From 2f896ee6f9cf6e693d70afad143d5d6b68852535 Mon Sep 17 00:00:00 2001 From: ipanov Date: Mon, 29 Dec 2025 12:51:44 +0100 Subject: [PATCH 1/3] feat(peer-review): Add Jira integration for AI-powered peer review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Initial implementation of peer review feature that validates PRs against linked Jira tickets: - Add PeerReviewIntegration class with ticket extraction and analysis - Add JiraMcpClient for MCP-based Jira communication - Add JiraSubAgent for AI-powered requirement validation - Add types for Jira tickets, acceptance criteria, and validation results - Extend analyze command with --peer-review flag - Update config loader to support peerReview configuration section The feature extracts ticket references from PR titles, branch names, and commit messages, then uses AI to validate that code changes satisfy the ticket's acceptance criteria. Work in progress - build verification pending. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- CLAUDE.md | 94 +++ src/agents/jira-sub-agent.ts | 569 +++++++++++++++ src/cli/commands/analyze.command.ts | 142 ++++ src/cli/utils/config-loader.ts | 31 + src/issue-tracker/index.ts | 34 + src/issue-tracker/jira-mcp-client.ts | 640 ++++++++++++++++ src/issue-tracker/peer-review-integration.ts | 729 +++++++++++++++++++ src/types/issue-tracker.types.ts | 211 ++++++ src/types/jira.types.ts | 278 +++++++ 9 files changed, 2728 insertions(+) create mode 100644 CLAUDE.md create mode 100644 src/agents/jira-sub-agent.ts create mode 100644 src/issue-tracker/index.ts create mode 100644 src/issue-tracker/jira-mcp-client.ts create mode 100644 src/issue-tracker/peer-review-integration.ts create mode 100644 src/types/issue-tracker.types.ts create mode 100644 src/types/jira.types.ts diff --git a/CLAUDE.md b/CLAUDE.md new file mode 100644 index 0000000..96c5d6b --- /dev/null +++ b/CLAUDE.md @@ -0,0 +1,94 @@ +# CLAUDE.md + +This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository. + +## Project Overview + +PR Agent is an AI-powered pull request analyzer available as both a CLI tool and a GitHub Action. It analyzes code changes using multiple AI providers (Anthropic Claude, OpenAI GPT, Google Gemini) and provides summaries, risk detection, complexity scoring, and architecture-aware recommendations. + +## Build & Development Commands + +```bash +# Install dependencies (--legacy-peer-deps required for LangChain peer dependency conflicts) +npm install --legacy-peer-deps + +# Build everything (TypeScript + GitHub Action bundle) +npm run build + +# Build TypeScript only +npm run build:tsc + +# Build GitHub Action only (uses @vercel/ncc) +npm run build:action + +# Clean and rebuild +npm run build:clean + +# Run tests +npm test +npm test -- --watch # Watch mode +npm test -- --coverage # With coverage + +# Run single test file +npm test -- tests/config-loader.test.ts + +# Development mode (no build needed) +npm run dev + +# Run CLI from built dist +npm run cli +``` + +## Architecture + +The project follows a modular monolith pattern with four layers: + +### Entry Points +- `src/cli/index.ts` - CLI entry point using Commander.js +- `src/action.ts` - GitHub Action entry point +- `src/index.ts` - Probot app integration + +### Core Analysis Engine +- `src/agents/pr-analyzer-agent.ts` - Main LangChain-based analysis workflow +- `src/agents/base-pr-agent-workflow.ts` - LangGraph workflow orchestration + +### AI Provider Layer +- `src/providers/` - Provider implementations (Anthropic, OpenAI, Google) +- `src/providers/provider.factory.ts` - Factory pattern for instantiation +- `src/providers/provider.interface.ts` - Common interface all providers implement + +### Tools & Utilities +- `src/tools/pr-analysis-tools.ts` - Diff parsing and analysis tools +- `src/utils/arch-docs-parser.ts` - Parse `.arch-docs` documentation folder +- `src/utils/arch-docs-rag.ts` - RAG (Retrieval-Augmented Generation) for architecture context +- `src/utils/branch-resolver.ts` - Git branch detection and resolution +- `src/cli/utils/config-loader.ts` - Configuration file management + +### Data Flow +``` +User Input → CLI/Action Interface → Config Loader → PRAnalyzerAgent + → Parse Diff → Load Architecture Docs (optional) → Build RAG Context + → Provider Factory → AI Provider → Structured Analysis Results + → Format Output (CLI terminal or GitHub PR comment) +``` + +## Key Configuration Files + +- `.pragent.config.json` - User configuration (AI provider, model, API keys, analysis settings) +- `.pr-analyzer.yml` - GitHub Action configuration +- `action.yml` - GitHub Action manifest + +## Technology Stack + +- **Framework**: TypeScript/Node.js (ES Modules), requires Node.js >=18.0.0 +- **AI Orchestration**: LangChain v1.x with LangGraph for workflow management +- **CLI Framework**: Commander.js with Inquirer for interactive prompts +- **Testing**: Jest with ts-jest +- **Action Bundling**: @vercel/ncc bundles the GitHub Action into a single file + +## Important Notes + +- Large diffs (>50KB) automatically use agent-based chunking (configurable via `analysis.agentThreshold`) +- The GitHub Action bundle in `dist/` must be committed after changes to action code +- Environment variables `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or `GOOGLE_API_KEY` can be used instead of config file +- Default branch detection uses: config file → GitHub API → git commands → fallback to `origin/main` diff --git a/src/agents/jira-sub-agent.ts b/src/agents/jira-sub-agent.ts new file mode 100644 index 0000000..d72596b --- /dev/null +++ b/src/agents/jira-sub-agent.ts @@ -0,0 +1,569 @@ +/** + * Jira Sub-Agent (Peer Review Agent) + * + * This agent acts like an experienced senior developer reviewing a PR. + * It understands not just the code, but the business context from the Jira ticket. + * + * KEY PHILOSOPHY: + * Like a senior developer who deeply knows the codebase, this agent: + * 1. Mentally constructs test scenarios and edge cases (INTERNAL reasoning) + * 2. Uses those mental models to EVALUATE if the implementation is complete + * 3. Checks if changes might break other parts of the application + * 4. Reports FINDINGS, not suggestions for tests + * + * The test scenarios are the agent's internal thought process - like how a + * senior dev thinks "what about when X happens?" while reviewing code. + * The OUTPUT is the conclusion: "This doesn't handle X" or "X case is covered". + */ + +import { ChatPromptTemplate } from '@langchain/core/prompts'; +import { StructuredOutputParser } from 'langchain/output_parsers'; +import { z } from 'zod'; +import { IssueTicket } from '../types/issue-tracker.types.js'; +import { BaseLanguageModel } from '@langchain/core/language_models/base'; + +// ========== Output Schemas ========== + +const TicketQualitySchema = z.object({ + overallScore: z.number().min(0).max(100).describe('Overall ticket quality score'), + dimensions: z.object({ + descriptionClarity: z.number().min(0).max(100), + acceptanceCriteriaQuality: z.number().min(0).max(100), + testabilityScore: z.number().min(0).max(100), + scopeDefinition: z.number().min(0).max(100), + technicalContext: z.number().min(0).max(100), + visualDocumentation: z.number().min(0).max(100), + completeness: z.number().min(0).max(100), + }), + feedback: z.object({ + strengths: z.array(z.string()), + weaknesses: z.array(z.string()), + suggestions: z.array(z.string()), + }), + tier: z.enum(['excellent', 'good', 'adequate', 'poor', 'insufficient']), + reviewable: z.boolean(), + reviewabilityReason: z.string(), +}); + +/** + * Acceptance Criteria Validation - focuses on what IS and ISN'T covered + * + * IMPORTANT: The agent DERIVES its own acceptance criteria by analyzing: + * - The full ticket description + * - Any explicit AC field (if present, but don't rely on it) + * - The ticket type (bug vs feature has different expectations) + * - Technical context and constraints mentioned + * + * Like a senior dev who reads the whole ticket and thinks: + * "To implement this properly, I'd need to: 1) do X, 2) handle Y, 3) ensure Z" + */ +const AcceptanceCriteriaValidationSchema = z.object({ + // The agent's derived understanding of what needs to be implemented + derivedRequirements: z.array( + z.object({ + id: z.string(), + requirement: z.string().describe('What the agent derived needs to be done'), + source: z.enum(['description', 'explicit_ac', 'implied', 'ticket_type', 'technical_context']) + .describe('Where this requirement was derived from'), + importance: z.enum(['essential', 'expected', 'nice_to_have']), + }) + ).describe('Requirements derived by analyzing the full ticket, not just AC field'), + + // Analysis of each derived requirement against the PR + criteriaAnalysis: z.array( + z.object({ + criteriaId: z.string(), + criteriaText: z.string(), + status: z.enum(['met', 'unmet', 'partial', 'unclear']), + confidence: z.number().min(0).max(100), + evidence: z.array(z.string()).describe('Code evidence showing coverage or lack thereof'), + explanation: z.string().describe('Why this criteria is/isnt met'), + relatedFiles: z.array(z.string()), + }) + ), + compliancePercentage: z.number().min(0).max(100), + gaps: z.array( + z.object({ + criteriaText: z.string(), + gapDescription: z.string().describe('What specific functionality is missing'), + severity: z.enum(['critical', 'major', 'minor']), + impact: z.string().describe('What will happen if this gap is not addressed'), + }) + ), + // Internal reasoning exposed as findings, not suggestions + missingBehaviors: z.array(z.string()).describe('Behaviors that should exist but dont'), + partialImplementations: z.array(z.string()).describe('Features that are started but incomplete'), +}); + +/** + * Peer Review Analysis - the senior developer's verdict + */ +const PeerReviewAnalysisSchema = z.object({ + implementationCompleteness: z.number().min(0).max(100), + qualityScore: z.number().min(0).max(100), + readyForReview: z.boolean(), + + // Critical findings that block merge + blockers: z.array( + z.object({ + issue: z.string(), + reason: z.string(), + location: z.string().optional().describe('File or component affected'), + }) + ), + + // Important issues that should be fixed + warnings: z.array( + z.object({ + issue: z.string(), + reason: z.string(), + location: z.string().optional(), + }) + ), + + // Nice-to-have improvements + recommendations: z.array(z.string()), + + // Scope analysis + scopeAnalysis: z.object({ + inScope: z.array(z.string()), + outOfScope: z.array(z.string()), + scopeCreepRisk: z.boolean(), + scopeCreepDetails: z.string().optional(), + }), + + // Potential regression analysis - what might break + regressionRisks: z.array( + z.object({ + risk: z.string().describe('What could break'), + affectedArea: z.string().describe('Part of the app that might be affected'), + likelihood: z.enum(['high', 'medium', 'low']), + reasoning: z.string().describe('Why this might happen'), + }) + ), + + // Uncovered scenarios identified during review (findings, not suggestions) + uncoveredScenarios: z.array( + z.object({ + scenario: z.string().describe('A scenario that isnt handled'), + impact: z.enum(['critical', 'major', 'minor']), + relatedCriteria: z.string().optional(), + }) + ), + + // Final verdict + verdict: z.object({ + summary: z.string().describe('One paragraph summary of the review'), + recommendation: z.enum(['approve', 'request_changes', 'needs_discussion']), + confidenceLevel: z.number().min(0).max(100), + }), +}); + +// ========== Types ========== + +export type TicketQualityRating = z.infer; +export type AcceptanceCriteriaValidation = z.infer; +export type PeerReviewAnalysis = z.infer; + +export interface JiraSubAgentResult { + ticketQuality: TicketQualityRating; + acValidation?: AcceptanceCriteriaValidation; + peerReview: PeerReviewAnalysis; +} + +export interface JiraSubAgentContext { + ticket: IssueTicket; + prTitle: string; + prDescription?: string; + diff: string; + files: Array<{ + path: string; + additions: number; + deletions: number; + status: string; + }>; + prSummary?: string; + prRisks?: string[]; +} + +// ========== Prompts ========== + +const TICKET_QUALITY_PROMPT = `You are an expert at evaluating Jira tickets and user stories. +Analyze the following ticket and rate its quality based on industry best practices. + +TICKET INFORMATION: +Key: {ticketKey} +Type: {ticketType} +Title: {ticketTitle} +Description: +{ticketDescription} + +Acceptance Criteria: +{acceptanceCriteria} + +Test Scenarios Defined: {testScenarios} +Has Screenshots/Mockups: {hasScreenshots} +Has Diagrams: {hasDiagrams} +Story Points: {storyPoints} +Labels: {labels} +Components: {components} + +EVALUATION CRITERIA: +1. Description Clarity (0-100): Is the description clear, complete, and unambiguous? +2. Acceptance Criteria Quality (0-100): Are ACs specific, measurable, achievable, and testable (SMART)? +3. Testability Score (0-100): Can this ticket be tested? Are expected behaviors clear? +4. Scope Definition (0-100): Is the scope well-defined and bounded? No scope creep potential? +5. Technical Context (0-100): Are technical requirements, constraints, and dependencies clear? +6. Visual Documentation (0-100): Are there screenshots, mockups, or diagrams where needed? +7. Completeness (0-100): Overall ticket completeness - nothing critical missing? + +QUALITY TIERS: +- excellent (85-100): Exemplary ticket, can be implemented with high confidence +- good (70-84): Well-written ticket with minor gaps +- adequate (50-69): Passable but has notable gaps that may cause issues +- poor (25-49): Significant issues, needs improvement before implementation +- insufficient (0-24): Cannot be implemented reliably, needs major rework + +REVIEWABILITY: +A ticket is "reviewable" if there's enough information to meaningfully derive what needs +to be implemented. This does NOT require an explicit acceptance criteria field! + +A ticket is REVIEWABLE if: +- The description explains what needs to be done (even briefly) +- The title + type give enough context to understand the goal +- A senior developer could reasonably derive requirements from it + +A ticket is NOT REVIEWABLE if: +- It's just a title with no description (e.g., "Fix bug" with nothing else) +- It's too vague to derive any concrete requirements +- There's literally not enough info to know what "done" looks like + +Remember: Many good tickets have detailed descriptions but empty AC fields. +The key is whether YOU can derive what needs to be built. + +{format_instructions}`; + +const AC_VALIDATION_PROMPT = `You are a SENIOR DEVELOPER with deep knowledge of this codebase reviewing a PR. + +Your task: Understand what this ticket requires, then evaluate if the PR implements it correctly. + +CRITICAL: DO NOT just rely on the "Acceptance Criteria" field. Many tickets have empty AC or +poorly written AC. You must DERIVE your own understanding of what needs to be done by reading: +- The full description +- The ticket type (bug fix has different needs than a feature) +- Any technical context mentioned +- The implicit requirements (what any experienced dev would know is needed) + +Think like an experienced dev who reads a ticket and thinks: +"Okay, to implement this properly I need to: handle X, add Y, make sure Z works..." + +JIRA TICKET: +Key: {ticketKey} +Type: {ticketType} +Title: {ticketTitle} + +FULL DESCRIPTION (analyze this carefully): +{ticketDescription} + +EXPLICIT ACCEPTANCE CRITERIA (may be empty or incomplete - don't rely solely on this): +{acceptanceCriteria} + +PR INFORMATION: +Title: {prTitle} +Description: {prDescription} + +FILES CHANGED: +{filesChanged} + +CODE DIFF: +{diff} + +PREVIOUS PR ANALYSIS SUMMARY: +{prSummary} + +YOUR TASK: + +1. DERIVE REQUIREMENTS: + First, read the entire ticket and derive what actually needs to be implemented. + For each requirement you identify, note: + - What the requirement is + - Where you derived it from (description, explicit AC, implied by ticket type, technical context) + - How essential it is (essential, expected, nice-to-have) + + Don't just copy the AC field - THINK about what's really needed. + A ticket saying "Add login button" implies: the button should be visible, clickable, + trigger auth flow, handle errors, etc. + +2. VALIDATE EACH REQUIREMENT: + For each derived requirement: + - Is it MET, UNMET, PARTIAL, or UNCLEAR in the code? + - Provide CODE EVIDENCE + - Explain your reasoning + +3. IDENTIFY GAPS: + What's missing? What behaviors should exist but don't? + Think through scenarios: "What if the user does X?" "What about error case Y?" + +Report FINDINGS, not suggestions. Like a senior dev saying: +"This doesn't handle the case when the user is logged out" + +{format_instructions}`; + +const PEER_REVIEW_PROMPT = `You are a SENIOR DEVELOPER doing a thorough peer review. + +You've been with this team for years. You know where the bodies are buried. +You think about: +- Does this actually solve the problem in the ticket? +- What might this break in other parts of the app? +- Are there scenarios the developer didn't consider? +- Is this ready for production? + +JIRA TICKET: +Key: {ticketKey} +Type: {ticketType} +Title: {ticketTitle} +Description: {ticketDescription} +Acceptance Criteria: {acceptanceCriteria} + +PR INFORMATION: +Title: {prTitle} +Description: {prDescription} + +FILES CHANGED: +{filesChanged} + +DIFF SUMMARY: +{diff} + +EXISTING PR ANALYSIS: +Summary: {prSummary} +Risks Identified: {prRisks} + +TICKET QUALITY ASSESSMENT: +Overall Score: {ticketQualityScore}/100 +Reviewable: {isReviewable} + +AC VALIDATION RESULTS: +Compliance: {acCompliancePercentage}% +Gaps Found: {gapsFound} + +YOUR PEER REVIEW TASK: + +1. IMPLEMENTATION COMPLETENESS (0-100): + Does this PR fully implement what the ticket asks for? + +2. QUALITY SCORE (0-100): + Code quality + requirements adherence combined + +3. READY FOR REVIEW: + Would you approve this or request changes? + +4. BLOCKERS: + Critical issues - things that MUST be fixed before merge + (missing functionality, bugs, security issues) + +5. WARNINGS: + Important issues - things that SHOULD be fixed + (edge cases not handled, potential bugs) + +6. RECOMMENDATIONS: + Nice-to-haves for improvement + +7. SCOPE ANALYSIS: + - What's in scope vs out of scope? + - Is there scope creep? + +8. REGRESSION RISKS: + Think: "What else in the app might this break?" + - Consider dependencies, shared code, side effects + - Think about how this interacts with existing features + +9. UNCOVERED SCENARIOS: + As a senior dev, you mentally run through scenarios: + - "What if the user does X?" + - "What about when Y is null?" + - "What happens during Z error condition?" + + Report which scenarios you identified that AREN'T handled. + Don't suggest tests - just flag what's missing. + +10. FINAL VERDICT: + Give your honest assessment: + - APPROVE: Ready to merge (maybe minor nits) + - REQUEST_CHANGES: Needs work before merge + - NEEDS_DISCUSSION: Architectural concerns to discuss + +{format_instructions}`; + +// ========== Agent Class ========== + +export class JiraSubAgent { + private llm: BaseLanguageModel; + + constructor(llm: BaseLanguageModel) { + this.llm = llm; + } + + /** + * Analyze a ticket and PR, providing comprehensive peer review + */ + async analyze(context: JiraSubAgentContext): Promise { + // Step 1: Rate ticket quality + const ticketQuality = await this.rateTicketQuality(context.ticket); + + // Step 2: Derive requirements and validate against PR + // NOTE: We analyze even if there's no explicit AC field - the agent derives + // requirements from the full ticket (description, title, type, context) + let acValidation: AcceptanceCriteriaValidation | undefined; + if (ticketQuality.reviewable) { + // The agent will derive its own requirements from the ticket + // Don't skip just because acceptanceCriteriaList is empty + acValidation = await this.validateAcceptanceCriteria(context); + } + + // Step 3: Generate peer review analysis + const peerReview = await this.generatePeerReview(context, ticketQuality, acValidation); + + return { + ticketQuality, + acValidation, + peerReview, + }; + } + + /** + * Rate the quality of a Jira ticket + */ + async rateTicketQuality(ticket: IssueTicket): Promise { + const parser = StructuredOutputParser.fromZodSchema(TicketQualitySchema); + + const prompt = ChatPromptTemplate.fromTemplate(TICKET_QUALITY_PROMPT); + + const chain = prompt.pipe(this.llm); + + const response = await chain.invoke({ + ticketKey: ticket.key, + ticketType: ticket.type, + ticketTitle: ticket.title, + ticketDescription: ticket.description || 'No description provided', + acceptanceCriteria: ticket.acceptanceCriteria || + ticket.acceptanceCriteriaList?.join('\n') || + 'No acceptance criteria defined', + testScenarios: ticket.testScenarios?.join(', ') || 'None defined', + hasScreenshots: ticket.hasScreenshots ? 'Yes' : 'No', + hasDiagrams: ticket.hasDiagrams ? 'Yes' : 'No', + storyPoints: ticket.storyPoints?.toString() || 'Not estimated', + labels: ticket.labels.join(', ') || 'None', + components: ticket.components.join(', ') || 'None', + format_instructions: parser.getFormatInstructions(), + }); + + const content = typeof response === 'string' ? response : response.content?.toString() || ''; + return parser.parse(content); + } + + /** + * Validate acceptance criteria against PR changes + */ + async validateAcceptanceCriteria( + context: JiraSubAgentContext + ): Promise { + const parser = StructuredOutputParser.fromZodSchema(AcceptanceCriteriaValidationSchema); + + const prompt = ChatPromptTemplate.fromTemplate(AC_VALIDATION_PROMPT); + + const chain = prompt.pipe(this.llm); + + // Format acceptance criteria with IDs + const acList = context.ticket.acceptanceCriteriaList || []; + const formattedAC = acList + .map((ac, i) => `AC-${i + 1}: ${ac}`) + .join('\n'); + + // Format files changed + const filesChanged = context.files + .map((f) => `${f.path} (+${f.additions}/-${f.deletions}) [${f.status}]`) + .join('\n'); + + // Truncate diff if too long + const maxDiffLength = 15000; + const truncatedDiff = + context.diff.length > maxDiffLength + ? context.diff.substring(0, maxDiffLength) + '\n... [diff truncated]' + : context.diff; + + const response = await chain.invoke({ + ticketKey: context.ticket.key, + ticketType: context.ticket.type, + ticketTitle: context.ticket.title, + ticketDescription: context.ticket.description?.substring(0, 2000) || 'No description', + acceptanceCriteria: formattedAC || 'No acceptance criteria defined', + prTitle: context.prTitle, + prDescription: context.prDescription || 'No description', + filesChanged, + diff: truncatedDiff, + prSummary: context.prSummary || 'No summary available', + format_instructions: parser.getFormatInstructions(), + }); + + const content = typeof response === 'string' ? response : response.content?.toString() || ''; + return parser.parse(content); + } + + /** + * Generate comprehensive peer review analysis + */ + async generatePeerReview( + context: JiraSubAgentContext, + ticketQuality: TicketQualityRating, + acValidation?: AcceptanceCriteriaValidation + ): Promise { + const parser = StructuredOutputParser.fromZodSchema(PeerReviewAnalysisSchema); + + const prompt = ChatPromptTemplate.fromTemplate(PEER_REVIEW_PROMPT); + + const chain = prompt.pipe(this.llm); + + // Format files changed + const filesChanged = context.files + .map((f) => `${f.path} (+${f.additions}/-${f.deletions}) [${f.status}]`) + .join('\n'); + + // Truncate diff if too long + const maxDiffLength = 10000; + const truncatedDiff = + context.diff.length > maxDiffLength + ? context.diff.substring(0, maxDiffLength) + '\n... [diff truncated]' + : context.diff; + + // Format gaps found + const gapsFound = acValidation?.gaps + .map((g) => `- ${g.criteriaText}: ${g.gapDescription}`) + .join('\n') || 'None identified'; + + const response = await chain.invoke({ + ticketKey: context.ticket.key, + ticketType: context.ticket.type, + ticketTitle: context.ticket.title, + ticketDescription: context.ticket.description?.substring(0, 2000) || 'No description', + acceptanceCriteria: + context.ticket.acceptanceCriteria || + context.ticket.acceptanceCriteriaList?.join('\n') || + 'None defined', + prTitle: context.prTitle, + prDescription: context.prDescription || 'No description', + filesChanged, + diff: truncatedDiff, + prSummary: context.prSummary || 'No summary available', + prRisks: context.prRisks?.join(', ') || 'None identified', + ticketQualityScore: ticketQuality.overallScore, + isReviewable: ticketQuality.reviewable ? 'Yes' : 'No', + acCompliancePercentage: acValidation?.compliancePercentage ?? 'N/A', + gapsFound, + format_instructions: parser.getFormatInstructions(), + }); + + const content = typeof response === 'string' ? response : response.content?.toString() || ''; + return parser.parse(content); + } +} diff --git a/src/cli/commands/analyze.command.ts b/src/cli/commands/analyze.command.ts index ba82f01..0a26cb7 100644 --- a/src/cli/commands/analyze.command.ts +++ b/src/cli/commands/analyze.command.ts @@ -7,6 +7,11 @@ import { loadUserConfig, getApiKey } from '../utils/config-loader.js'; import { archDocsExists } from '../../utils/arch-docs-parser.js'; import { resolveDefaultBranch } from '../../utils/branch-resolver.js'; import { ConfigurationError, GitHubAPIError, GitError } from '../../utils/errors.js'; +import { + createPeerReviewIntegration, + formatPeerReviewOutput, + type PeerReviewResult, +} from '../../issue-tracker/index.js'; interface AnalyzeOptions { diff?: string; @@ -24,6 +29,7 @@ interface AnalyzeOptions { verbose?: boolean; maxCost?: number; archDocs?: boolean; + peerReview?: boolean; // Enable Jira peer review integration } interface AnalysisMode { @@ -410,6 +416,12 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { // Display results displayAgentResults(result, mode, options.verbose || false); + + // Run Peer Review if enabled (via flag or config) + const peerReviewEnabled = options.peerReview || config.peerReview?.enabled; + if (peerReviewEnabled) { + await runPeerReview(config, diff, title, result, options.verbose || false); + } } catch (error: any) { spinner.fail('Analysis failed'); @@ -612,4 +624,134 @@ function displayAgentResults(result: any, mode: AnalysisMode, verbose: boolean): console.log(chalk.gray('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n')); } +/** + * Run Peer Review analysis against linked Jira tickets + * + * This extends the PR analysis with business context validation: + * - Fetches linked Jira tickets from PR title/branch + * - Rates ticket quality + * - Validates implementation against derived requirements + * - Provides senior-dev style verdict + */ +async function runPeerReview( + config: any, + diff: string, + title: string | undefined, + prAnalysisResult: any, + verbose: boolean +): Promise { + const spinner = ora('Running Peer Review analysis...').start(); + + try { + // Create peer review integration from config + const peerReviewConfig = config.peerReview || {}; + const integration = createPeerReviewIntegration(peerReviewConfig); + + if (!integration.isEnabled()) { + spinner.warn('Peer Review enabled but not configured. Add Jira settings to config.'); + console.log(chalk.gray(' Run: pr-agent config --set peerReview.instanceUrl=https://your.atlassian.net')); + console.log(chalk.gray(' Or configure MCP: peerReview.useMcp=true')); + return; + } + + // Get branch name for ticket extraction + let branchName: string | undefined; + try { + branchName = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf-8' }).trim(); + } catch { + // Ignore - branch name is optional + } + + // Get commit messages for ticket extraction + let commitMessages: string[] = []; + try { + const commits = execSync('git log --oneline -10', { encoding: 'utf-8' }); + commitMessages = commits.trim().split('\n'); + } catch { + // Ignore + } + + // Parse diff to get file info + const files = parseDiffFiles(diff); + + spinner.text = 'Extracting ticket references...'; + + // Run peer review analysis + const result = await integration.analyze({ + prTitle: title || 'Untitled PR', + prDescription: undefined, // Could extract from git commit body + branchName, + commitMessages, + diff, + files, + prSummary: prAnalysisResult.summary, + prRisks: prAnalysisResult.overallRisks, + prComplexity: prAnalysisResult.overallComplexity, + }); + spinner.succeed('Peer Review analysis complete'); + + // Display peer review results + const output = formatPeerReviewOutput(result); + if (output) { + console.log(output); + } + + if (verbose && result.ticketReferences.length > 0) { + console.log(chalk.gray('Ticket references found:')); + result.ticketReferences.forEach((ref) => { + console.log(chalk.gray(` - ${ref.key} (from ${ref.source}, confidence: ${ref.confidence}%)`)); + }); + } + } catch (error: any) { + spinner.fail('Peer Review analysis failed'); + console.error(chalk.yellow(`⚠️ ${error.message || 'Unknown error'}`)); + console.log(chalk.gray(' The main PR analysis completed successfully.')); + console.log(chalk.gray(' Peer Review is an optional enhancement - check Jira configuration.')); + } +} + +/** + * Parse diff to extract file information + */ +function parseDiffFiles(diff: string): Array<{ + path: string; + additions: number; + deletions: number; + status: string; +}> { + const files: Array<{ + path: string; + additions: number; + deletions: number; + status: string; + }> = []; + + const filePattern = /^diff --git a\/(.+?) b\/(.+?)$/gm; + let match; + + while ((match = filePattern.exec(diff)) !== null) { + const filePath = match[2] !== '/dev/null' ? match[2] : match[1]; + const isNew = match[1] === '/dev/null' || match[1].startsWith('dev/null'); + const isDeleted = match[2] === '/dev/null'; + + // Count additions and deletions (simplified) + const fileStart = match.index; + const nextFileMatch = filePattern.exec(diff); + const fileEnd = nextFileMatch ? nextFileMatch.index : diff.length; + filePattern.lastIndex = match.index + 1; // Reset to continue from after current match + + const fileContent = diff.substring(fileStart, fileEnd); + const additions = (fileContent.match(/^\+[^+]/gm) || []).length; + const deletions = (fileContent.match(/^-[^-]/gm) || []).length; + + files.push({ + path: filePath, + additions, + deletions, + status: isNew ? 'added' : isDeleted ? 'deleted' : 'modified', + }); + } + + return files; +} diff --git a/src/cli/utils/config-loader.ts b/src/cli/utils/config-loader.ts index 4937347..d18ca2b 100644 --- a/src/cli/utils/config-loader.ts +++ b/src/cli/utils/config-loader.ts @@ -34,6 +34,37 @@ export interface UserConfig { showStrategy?: boolean; showRecommendations?: boolean; }; + /** + * Peer Review configuration - integrates with issue trackers (Jira, etc.) + * to validate PRs against tickets and acceptance criteria + */ + peerReview?: { + // Enable/disable peer review feature + enabled?: boolean; + // Issue tracker provider: 'jira' | 'linear' | 'azure-devops' | 'github-issues' + provider?: string; + // Use MCP server for Jira access (recommended) + useMcp?: boolean; + // Direct API access settings (fallback if MCP not available) + instanceUrl?: string; + email?: string; + apiToken?: string; + // Default project key + defaultProject?: string; + // Custom field IDs (Jira-specific) + acceptanceCriteriaField?: string; + storyPointsField?: string; + // Custom ticket patterns (regex) - defaults to PROJ-123 format + ticketPatterns?: string[]; + // Analysis options + analyzeAcceptanceCriteria?: boolean; + rateTicketQuality?: boolean; + generateTestSuggestions?: boolean; + checkScopeCreep?: boolean; + // Output options + includeTicketDetails?: boolean; + verbose?: boolean; + }; } /** diff --git a/src/issue-tracker/index.ts b/src/issue-tracker/index.ts new file mode 100644 index 0000000..013f13e --- /dev/null +++ b/src/issue-tracker/index.ts @@ -0,0 +1,34 @@ +/** + * Issue Tracker Module + * + * Provides integration with issue tracking systems (Jira, Linear, etc.) + * for context-aware PR reviews. + */ + +// Types +export * from '../types/issue-tracker.types.js'; + +// Jira Client +export { JiraMcpClient, type JiraConfig } from './jira-mcp-client.js'; + +// Integration +export { + PeerReviewIntegration, + createPeerReviewIntegration, + formatPeerReviewOutput, + formatPeerReviewMarkdown, + type PeerReviewConfig, + type PeerReviewContext, + type PeerReviewResult, + type PeerReviewUserConfig, +} from './peer-review-integration.js'; + +// Sub-Agent +export { + JiraSubAgent, + type JiraSubAgentResult, + type JiraSubAgentContext, + type TicketQualityRating, + type AcceptanceCriteriaValidation, + type PeerReviewAnalysis, +} from '../agents/jira-sub-agent.js'; diff --git a/src/issue-tracker/jira-mcp-client.ts b/src/issue-tracker/jira-mcp-client.ts new file mode 100644 index 0000000..89302f4 --- /dev/null +++ b/src/issue-tracker/jira-mcp-client.ts @@ -0,0 +1,640 @@ +/** + * Jira MCP Client + * + * Implements IssueTrackerProvider interface using the Atlassian MCP server. + * This client fetches Jira tickets and extracts ticket references from PR metadata. + * + * The MCP server is expected to provide Jira access through its tools. + * For environments without MCP, falls back to direct Jira API (if configured). + */ + +import { + IssueTrackerProvider, + IssueTrackerType, + IssueTicket, + IssueType, + IssuePriority, + TicketReference, + TicketExtractionContext, + IssueComment, + LinkedIssue, + SubtaskInfo, +} from '../types/issue-tracker.types.js'; + +// Jira-specific configuration +export interface JiraConfig { + // MCP-based access (preferred) + useMcp: boolean; + + // Direct API access (fallback) + instanceUrl?: string; + email?: string; + apiToken?: string; + + // Project settings + defaultProject?: string; + + // Custom field mappings + acceptanceCriteriaField?: string; // Custom field ID for AC + storyPointsField?: string; // Custom field ID for story points + + // Ticket patterns for extraction + ticketPatterns?: string[]; +} + +// Default patterns to match Jira ticket keys +const DEFAULT_TICKET_PATTERNS = [ + /([A-Z][A-Z0-9]+-\d+)/g, // Standard Jira format: PROJ-123 +]; + +export class JiraMcpClient implements IssueTrackerProvider { + readonly name = 'Jira'; + readonly type: IssueTrackerType = 'jira'; + + private config: JiraConfig; + private ticketPatterns: RegExp[]; + + // MCP callback for making MCP tool calls + // This is injected at runtime when MCP is available + private mcpCallback?: ( + tool: string, + params: Record + ) => Promise; + + constructor(config: JiraConfig) { + this.config = config; + this.ticketPatterns = this.buildTicketPatterns(); + } + + /** + * Set the MCP callback function for making MCP tool calls + */ + setMcpCallback( + callback: ( + tool: string, + params: Record + ) => Promise + ): void { + this.mcpCallback = callback; + } + + /** + * Check if the client is properly configured + */ + isConfigured(): boolean { + if (this.config.useMcp) { + return !!this.mcpCallback; + } + // Direct API requires instance URL and credentials + return !!( + this.config.instanceUrl && + this.config.email && + this.config.apiToken + ); + } + + /** + * Test connection to Jira + */ + async testConnection(): Promise { + try { + // Try to fetch any ticket to verify connection + if (this.config.useMcp && this.mcpCallback) { + // Use MCP to test connection + const result = await this.mcpCallback('atlassian:search-company-knowledge', { + query: 'test connection', + limit: 1, + }); + return !!result; + } else if (this.config.instanceUrl) { + // Direct API test + const response = await this.fetchJiraApi('/rest/api/3/myself'); + return response.ok; + } + return false; + } catch { + return false; + } + } + + /** + * Extract ticket references from PR metadata + */ + extractTicketReferences(context: TicketExtractionContext): TicketReference[] { + const references: Map = new Map(); + + // Extract from title (highest confidence) + this.extractFromText(context.prTitle, 'title', 95, references); + + // Extract from branch name (high confidence) + if (context.branchName) { + this.extractFromText(context.branchName, 'branch', 90, references); + } + + // Extract from description (medium confidence) + if (context.prDescription) { + this.extractFromText(context.prDescription, 'description', 80, references); + } + + // Extract from commit messages (lower confidence due to potential noise) + if (context.commitMessages) { + for (const msg of context.commitMessages) { + this.extractFromText(msg, 'commit', 70, references); + } + } + + // Sort by confidence (highest first) + return Array.from(references.values()).sort( + (a, b) => b.confidence - a.confidence + ); + } + + /** + * Fetch a single ticket by key + */ + async getTicket(key: string): Promise { + try { + const rawTicket = await this.fetchJiraTicket(key); + if (!rawTicket) return null; + return this.normalizeTicket(rawTicket); + } catch (error) { + console.error(`Failed to fetch ticket ${key}:`, error); + return null; + } + } + + /** + * Fetch multiple tickets by keys + */ + async getTickets(keys: string[]): Promise { + const tickets: IssueTicket[] = []; + + // Fetch in parallel with concurrency limit + const batchSize = 5; + for (let i = 0; i < keys.length; i += batchSize) { + const batch = keys.slice(i, i + batchSize); + const results = await Promise.all( + batch.map((key) => this.getTicket(key)) + ); + tickets.push(...results.filter((t): t is IssueTicket => t !== null)); + } + + return tickets; + } + + /** + * Search for tickets matching a query + */ + async searchTickets(query: string, limit = 10): Promise { + try { + if (this.config.useMcp && this.mcpCallback) { + // Use MCP search + const result = await this.mcpCallback('atlassian:search-company-knowledge', { + query, + limit, + }); + // Parse and normalize results + if (Array.isArray(result)) { + return result.map((r) => this.normalizeTicket(r)); + } + } else { + // Direct JQL search + const jql = `text ~ "${query}" ORDER BY updated DESC`; + const response = await this.fetchJiraApi( + `/rest/api/3/search?jql=${encodeURIComponent(jql)}&maxResults=${limit}` + ); + if (response.ok) { + const data = await response.json(); + return (data.issues || []).map((issue: JiraApiIssue) => + this.normalizeTicket(issue) + ); + } + } + } catch (error) { + console.error('Failed to search tickets:', error); + } + return []; + } + + /** + * Get comments for a ticket + */ + async getComments(ticketKey: string): Promise { + try { + const response = await this.fetchJiraApi( + `/rest/api/3/issue/${ticketKey}/comment` + ); + if (response.ok) { + const data = await response.json(); + return (data.comments || []).map((c: JiraApiComment) => ({ + id: c.id, + author: c.author?.displayName || 'Unknown', + body: c.body?.content?.[0]?.content?.[0]?.text || c.body || '', + createdAt: c.created, + })); + } + } catch (error) { + console.error(`Failed to get comments for ${ticketKey}:`, error); + } + return []; + } + + // ========== Private Helper Methods ========== + + private buildTicketPatterns(): RegExp[] { + if (this.config.ticketPatterns?.length) { + return this.config.ticketPatterns.map((p) => new RegExp(p, 'g')); + } + return DEFAULT_TICKET_PATTERNS; + } + + private extractFromText( + text: string, + source: TicketReference['source'], + baseConfidence: number, + references: Map + ): void { + for (const pattern of this.ticketPatterns) { + // Reset lastIndex for global patterns + pattern.lastIndex = 0; + let match; + while ((match = pattern.exec(text)) !== null) { + const key = match[1] || match[0]; + const upperKey = key.toUpperCase(); + + // Skip if we already have this reference with higher confidence + const existing = references.get(upperKey); + if (existing && existing.confidence >= baseConfidence) { + continue; + } + + references.set(upperKey, { + key: upperKey, + source, + rawMatch: match[0], + confidence: baseConfidence, + }); + } + } + } + + private async fetchJiraTicket(key: string): Promise { + if (this.config.useMcp && this.mcpCallback) { + // Use MCP to fetch ticket + // The MCP server should have a tool for fetching individual issues + try { + const result = await this.mcpCallback('atlassian:get-issue', { + issueKey: key, + }); + return result as JiraApiIssue; + } catch { + // If specific tool not available, try search + const searchResult = await this.mcpCallback('atlassian:search-company-knowledge', { + query: `key:${key}`, + limit: 1, + }); + if (Array.isArray(searchResult) && searchResult.length > 0) { + return searchResult[0] as JiraApiIssue; + } + } + } + + // Direct API fetch + const response = await this.fetchJiraApi(`/rest/api/3/issue/${key}?expand=renderedFields`); + if (response.ok) { + return response.json(); + } + return null; + } + + private async fetchJiraApi(path: string): Promise { + if (!this.config.instanceUrl || !this.config.email || !this.config.apiToken) { + throw new Error('Jira API credentials not configured'); + } + + const url = `${this.config.instanceUrl}${path}`; + const auth = Buffer.from(`${this.config.email}:${this.config.apiToken}`).toString('base64'); + + return fetch(url, { + headers: { + Authorization: `Basic ${auth}`, + Accept: 'application/json', + }, + }); + } + + private normalizeTicket(raw: JiraApiIssue): IssueTicket { + const fields = raw.fields || {}; + + // Extract acceptance criteria from description or custom field + const acceptanceCriteria = this.extractAcceptanceCriteria(fields); + + // Normalize issue type + const issueType = this.normalizeIssueType(fields.issuetype?.name); + + // Normalize priority + const priority = this.normalizePriority(fields.priority?.name); + + // Extract linked issues + const linkedIssues = this.extractLinkedIssues(fields); + + // Extract subtasks + const subtasks = this.extractSubtasks(fields); + + // Check for visual documentation + const attachments = fields.attachment || []; + const hasScreenshots = attachments.some((a: JiraApiAttachment) => + a.mimeType?.startsWith('image/') + ); + const hasDiagrams = attachments.some( + (a: JiraApiAttachment) => + a.filename?.includes('diagram') || + a.filename?.includes('flow') || + a.mimeType?.includes('svg') + ); + + return { + id: raw.id, + key: raw.key, + url: `${this.config.instanceUrl || ''}/browse/${raw.key}`, + title: fields.summary || '', + description: this.extractDescription(fields), + type: issueType, + status: fields.status?.name || 'Unknown', + priority, + assignee: fields.assignee?.displayName, + reporter: fields.reporter?.displayName, + labels: fields.labels || [], + components: (fields.components || []).map((c: { name: string }) => c.name), + project: fields.project?.key, + storyPoints: this.extractStoryPoints(fields), + acceptanceCriteria: acceptanceCriteria.text, + acceptanceCriteriaList: acceptanceCriteria.list, + testScenarios: this.extractTestScenarios(fields), + linkedTestCases: [], // Would need Zephyr/Xray integration + hasScreenshots, + hasDiagrams, + attachmentCount: attachments.length, + parentKey: fields.parent?.key, + epicKey: fields.epic?.key || fields.customfield_10014, // Common epic link field + linkedIssues, + subtasks, + createdAt: fields.created || '', + updatedAt: fields.updated || '', + rawData: raw, + }; + } + + private extractDescription(fields: JiraApiFields): string { + // Handle Atlassian Document Format (ADF) or plain text + if (typeof fields.description === 'string') { + return fields.description; + } + if (fields.description?.content) { + return this.adfToText(fields.description); + } + return ''; + } + + private adfToText(adf: JiraAdfDocument): string { + // Simple ADF to text conversion + const extractText = (node: JiraAdfNode): string => { + if (node.type === 'text') { + return node.text || ''; + } + if (node.content) { + return node.content.map(extractText).join(''); + } + return ''; + }; + + return (adf.content || []) + .map((node) => { + const text = extractText(node); + // Add newlines for block elements + if (['paragraph', 'heading', 'bulletList', 'orderedList', 'listItem'].includes(node.type)) { + return text + '\n'; + } + return text; + }) + .join('') + .trim(); + } + + private extractAcceptanceCriteria(fields: JiraApiFields): { + text: string; + list: string[]; + } { + // Try custom field first + if (this.config.acceptanceCriteriaField) { + const customField = fields[this.config.acceptanceCriteriaField]; + if (customField) { + const text = typeof customField === 'string' ? customField : this.adfToText(customField); + return { text, list: this.parseAcceptanceCriteriaList(text) }; + } + } + + // Extract from description - look for common AC patterns + const description = this.extractDescription(fields); + const acPatterns = [ + /acceptance\s*criteria[:\s]*\n([\s\S]*?)(?=\n\n|\n#|$)/i, + /definition\s*of\s*done[:\s]*\n([\s\S]*?)(?=\n\n|\n#|$)/i, + /requirements[:\s]*\n([\s\S]*?)(?=\n\n|\n#|$)/i, + /given[\s\S]*?when[\s\S]*?then/gi, // Gherkin-style + ]; + + for (const pattern of acPatterns) { + const match = description.match(pattern); + if (match) { + const text = match[1] || match[0]; + return { text, list: this.parseAcceptanceCriteriaList(text) }; + } + } + + return { text: '', list: [] }; + } + + private parseAcceptanceCriteriaList(text: string): string[] { + const items: string[] = []; + + // Parse bullet points + const bulletMatches = text.match(/^[\s]*[-*•]\s*(.+)$/gm); + if (bulletMatches) { + items.push(...bulletMatches.map((m) => m.replace(/^[\s]*[-*•]\s*/, '').trim())); + } + + // Parse numbered items + const numberedMatches = text.match(/^[\s]*\d+[.)]\s*(.+)$/gm); + if (numberedMatches) { + items.push(...numberedMatches.map((m) => m.replace(/^[\s]*\d+[.)]\s*/, '').trim())); + } + + // Parse checkboxes + const checkboxMatches = text.match(/^[\s]*\[[ x]\]\s*(.+)$/gim); + if (checkboxMatches) { + items.push(...checkboxMatches.map((m) => m.replace(/^[\s]*\[[ x]\]\s*/i, '').trim())); + } + + // If no structured items found, split by newlines + if (items.length === 0 && text.trim()) { + const lines = text.split('\n').filter((l) => l.trim().length > 10); + items.push(...lines.map((l) => l.trim())); + } + + return [...new Set(items)]; // Remove duplicates + } + + private extractStoryPoints(fields: JiraApiFields): number | undefined { + // Try common story point field IDs + const spFields = [ + this.config.storyPointsField, + 'customfield_10016', // Common Jira Cloud + 'customfield_10004', // Another common one + 'storyPoints', + ].filter(Boolean); + + for (const field of spFields) { + if (field && fields[field] !== undefined) { + const value = fields[field]; + if (typeof value === 'number') return value; + if (typeof value === 'string') return parseFloat(value) || undefined; + } + } + return undefined; + } + + private extractTestScenarios(fields: JiraApiFields): string[] { + const description = this.extractDescription(fields); + const scenarios: string[] = []; + + // Look for test scenario patterns + const testPatterns = [ + /test\s*scenario[s]?[:\s]*\n([\s\S]*?)(?=\n\n|\n#|$)/i, + /test\s*cases?[:\s]*\n([\s\S]*?)(?=\n\n|\n#|$)/i, + /scenario[:\s]+(.+)/gi, + ]; + + for (const pattern of testPatterns) { + const matches = description.match(pattern); + if (matches) { + scenarios.push(...this.parseAcceptanceCriteriaList(matches[1] || matches[0])); + } + } + + return [...new Set(scenarios)]; + } + + private normalizeIssueType(typeName?: string): IssueType { + if (!typeName) return 'other'; + const lower = typeName.toLowerCase(); + if (lower.includes('bug')) return 'bug'; + if (lower.includes('feature')) return 'feature'; + if (lower.includes('story')) return 'story'; + if (lower.includes('epic')) return 'epic'; + if (lower.includes('subtask') || lower.includes('sub-task')) return 'subtask'; + if (lower.includes('task')) return 'task'; + if (lower.includes('improvement')) return 'improvement'; + if (lower.includes('spike')) return 'spike'; + return 'other'; + } + + private normalizePriority(priorityName?: string): IssuePriority { + if (!priorityName) return 'none'; + const lower = priorityName.toLowerCase(); + if (lower.includes('critical') || lower.includes('blocker') || lower.includes('highest')) { + return 'critical'; + } + if (lower.includes('high')) return 'high'; + if (lower.includes('medium') || lower.includes('normal')) return 'medium'; + if (lower.includes('low') || lower.includes('minor')) return 'low'; + return 'none'; + } + + private extractLinkedIssues(fields: JiraApiFields): LinkedIssue[] { + const links = fields.issuelinks || []; + return links.map((link: JiraApiIssueLink) => { + const linkedIssue = link.inwardIssue || link.outwardIssue; + const linkType = link.inwardIssue ? link.type?.inward : link.type?.outward; + return { + key: linkedIssue?.key || '', + type: linkType || 'relates to', + title: linkedIssue?.fields?.summary || '', + status: linkedIssue?.fields?.status?.name || '', + }; + }); + } + + private extractSubtasks(fields: JiraApiFields): SubtaskInfo[] { + const subtasks = fields.subtasks || []; + return subtasks.map((st: JiraApiSubtask) => ({ + key: st.key, + title: st.fields?.summary || '', + status: st.fields?.status?.name || '', + })); + } +} + +// ========== Jira API Types ========== + +interface JiraApiIssue { + id: string; + key: string; + fields: JiraApiFields; +} + +interface JiraApiFields { + summary?: string; + description?: string | JiraAdfDocument; + issuetype?: { name: string }; + status?: { name: string }; + priority?: { name: string }; + assignee?: { displayName: string }; + reporter?: { displayName: string }; + labels?: string[]; + components?: Array<{ name: string }>; + project?: { key: string }; + parent?: { key: string }; + epic?: { key: string }; + created?: string; + updated?: string; + attachment?: JiraApiAttachment[]; + issuelinks?: JiraApiIssueLink[]; + subtasks?: JiraApiSubtask[]; + [key: string]: unknown; // Custom fields +} + +interface JiraAdfDocument { + type: string; + version: number; + content?: JiraAdfNode[]; +} + +interface JiraAdfNode { + type: string; + text?: string; + content?: JiraAdfNode[]; +} + +interface JiraApiAttachment { + id: string; + filename: string; + mimeType: string; +} + +interface JiraApiIssueLink { + type?: { inward: string; outward: string }; + inwardIssue?: { key: string; fields?: { summary?: string; status?: { name: string } } }; + outwardIssue?: { key: string; fields?: { summary?: string; status?: { name: string } } }; +} + +interface JiraApiSubtask { + key: string; + fields?: { summary?: string; status?: { name: string } }; +} + +interface JiraApiComment { + id: string; + author?: { displayName: string }; + body?: string | JiraAdfDocument; + created: string; +} diff --git a/src/issue-tracker/peer-review-integration.ts b/src/issue-tracker/peer-review-integration.ts new file mode 100644 index 0000000..24808b5 --- /dev/null +++ b/src/issue-tracker/peer-review-integration.ts @@ -0,0 +1,729 @@ +/** + * Peer Review Integration + * + * This module integrates the Jira sub-agent with the main PR analysis workflow. + * It handles: + * - Extracting ticket references from PR metadata + * - Fetching tickets from issue trackers + * - Running the Jira sub-agent analysis + * - Formatting the combined output + */ + +import { JiraMcpClient, JiraConfig } from './jira-mcp-client.js'; +import { JiraSubAgent, JiraSubAgentResult, JiraSubAgentContext } from '../agents/jira-sub-agent.js'; +import { + IssueTrackerProvider, + IssueTrackerConfig, + IssueTrackerType, + IssueTicket, + TicketReference, +} from '../types/issue-tracker.types.js'; +import { BaseLanguageModel } from '@langchain/core/language_models/base'; + +// ========== Types ========== + +export interface PeerReviewConfig { + issueTracker: IssueTrackerConfig; +} + +export interface PeerReviewContext { + prTitle: string; + prDescription?: string; + branchName?: string; + commitMessages?: string[]; + diff: string; + files: Array<{ + path: string; + additions: number; + deletions: number; + status: string; + }>; + // From existing PR analysis + prSummary?: string; + prRisks?: string[]; + prComplexity?: number; +} + +export interface PeerReviewResult { + enabled: boolean; + ticketReferences: TicketReference[]; + linkedTickets: IssueTicket[]; + primaryTicket?: IssueTicket; + analysis?: JiraSubAgentResult; + error?: string; +} + +// ========== Main Integration Class ========== + +export class PeerReviewIntegration { + private provider: IssueTrackerProvider | null = null; + private subAgent: JiraSubAgent | null = null; + private config: IssueTrackerConfig; + + constructor(config: IssueTrackerConfig, llm?: BaseLanguageModel) { + this.config = config; + this.initializeProvider(); + if (llm) { + this.subAgent = new JiraSubAgent(llm); + } + } + + /** + * Set the LLM for the sub-agent + */ + setLLM(llm: BaseLanguageModel): void { + this.subAgent = new JiraSubAgent(llm); + } + + /** + * Set MCP callback for the Jira client + */ + setMcpCallback( + callback: (tool: string, params: Record) => Promise + ): void { + if (this.provider && this.provider instanceof JiraMcpClient) { + (this.provider as JiraMcpClient).setMcpCallback(callback); + } + } + + /** + * Check if peer review is enabled and properly configured + */ + isEnabled(): boolean { + return this.config.enabled && this.provider !== null && this.provider.isConfigured(); + } + + /** + * Run peer review analysis + */ + async analyze(context: PeerReviewContext): Promise { + if (!this.config.enabled) { + return { + enabled: false, + ticketReferences: [], + linkedTickets: [], + }; + } + + if (!this.provider) { + return { + enabled: true, + ticketReferences: [], + linkedTickets: [], + error: 'Issue tracker provider not configured', + }; + } + + try { + // Step 1: Extract ticket references from PR metadata + const ticketReferences = this.provider.extractTicketReferences({ + prTitle: context.prTitle, + prDescription: context.prDescription, + branchName: context.branchName, + commitMessages: context.commitMessages, + }); + + if (ticketReferences.length === 0) { + return { + enabled: true, + ticketReferences: [], + linkedTickets: [], + error: 'No ticket references found in PR title, description, or branch name', + }; + } + + // Step 2: Fetch tickets + const ticketKeys = [...new Set(ticketReferences.map((r) => r.key))]; + const linkedTickets = await this.provider.getTickets(ticketKeys); + + if (linkedTickets.length === 0) { + return { + enabled: true, + ticketReferences, + linkedTickets: [], + error: `Could not fetch tickets: ${ticketKeys.join(', ')}`, + }; + } + + // Primary ticket is the one with highest confidence reference + const primaryTicket = linkedTickets[0]; + + // Step 3: Run sub-agent analysis (if configured) + let analysis: JiraSubAgentResult | undefined; + if (this.subAgent && primaryTicket) { + const subAgentContext: JiraSubAgentContext = { + ticket: primaryTicket, + prTitle: context.prTitle, + prDescription: context.prDescription, + diff: context.diff, + files: context.files, + prSummary: context.prSummary, + prRisks: context.prRisks, + }; + + analysis = await this.subAgent.analyze(subAgentContext); + } + + return { + enabled: true, + ticketReferences, + linkedTickets, + primaryTicket, + analysis, + }; + } catch (error) { + return { + enabled: true, + ticketReferences: [], + linkedTickets: [], + error: `Peer review analysis failed: ${error instanceof Error ? error.message : String(error)}`, + }; + } + } + + // ========== Private Methods ========== + + private initializeProvider(): void { + if (!this.config.enabled) return; + + switch (this.config.provider) { + case 'jira': + this.provider = new JiraMcpClient(this.config.providerConfig as JiraConfig); + break; + + // Future providers + case 'linear': + case 'azure-devops': + case 'github-issues': + case 'gitlab-issues': + console.warn(`Provider ${this.config.provider} not yet implemented, using Jira fallback`); + break; + + default: + console.warn(`Unknown provider: ${this.config.provider}`); + } + } +} + +// ========== Factory Function ========== + +/** + * Create a PeerReviewIntegration from user config + */ +export function createPeerReviewIntegration( + userConfig: PeerReviewUserConfig, + llm?: BaseLanguageModel +): PeerReviewIntegration { + const issueTrackerConfig: IssueTrackerConfig = { + enabled: userConfig.enabled ?? false, + provider: (userConfig.provider as IssueTrackerType) || 'jira', + providerConfig: { + useMcp: userConfig.useMcp ?? true, + instanceUrl: userConfig.instanceUrl, + email: userConfig.email, + apiToken: userConfig.apiToken, + defaultProject: userConfig.defaultProject, + acceptanceCriteriaField: userConfig.acceptanceCriteriaField, + storyPointsField: userConfig.storyPointsField, + ticketPatterns: userConfig.ticketPatterns, + }, + analyzeAcceptanceCriteria: userConfig.analyzeAcceptanceCriteria ?? true, + rateTicketQuality: userConfig.rateTicketQuality ?? true, + generateTestSuggestions: userConfig.generateTestSuggestions ?? true, + checkScopeCreep: userConfig.checkScopeCreep ?? true, + ticketPatterns: userConfig.ticketPatterns, + includeTicketDetails: userConfig.includeTicketDetails ?? true, + verbose: userConfig.verbose ?? false, + }; + + return new PeerReviewIntegration(issueTrackerConfig, llm); +} + +// ========== User Config Type ========== + +/** + * User-facing configuration for peer review + * This is what goes in .pragent.config.json + */ +export interface PeerReviewUserConfig { + // Enable/disable peer review feature + enabled?: boolean; + + // Issue tracker provider + provider?: string; // 'jira' | 'linear' | 'azure-devops' | 'github-issues' + + // MCP-based access (preferred for Jira) + useMcp?: boolean; + + // Direct API access (fallback) + instanceUrl?: string; // e.g., "https://company.atlassian.net" + email?: string; + apiToken?: string; + + // Project settings + defaultProject?: string; + + // Custom field mappings (Jira-specific) + acceptanceCriteriaField?: string; + storyPointsField?: string; + + // Ticket patterns for extraction (regex) + ticketPatterns?: string[]; + + // Analysis settings + analyzeAcceptanceCriteria?: boolean; + rateTicketQuality?: boolean; + generateTestSuggestions?: boolean; + checkScopeCreep?: boolean; + + // Output settings + includeTicketDetails?: boolean; + verbose?: boolean; +} + +// ========== Output Formatting ========== + +/** + * Format peer review results for CLI output + */ +export function formatPeerReviewOutput(result: PeerReviewResult): string { + const lines: string[] = []; + + if (!result.enabled) { + return ''; // Silently skip if not enabled + } + + lines.push(''); + lines.push('═══════════════════════════════════════════════════════════════'); + lines.push(' 🔍 PEER REVIEW ANALYSIS'); + lines.push('═══════════════════════════════════════════════════════════════'); + lines.push(''); + + if (result.error) { + lines.push(`⚠️ ${result.error}`); + lines.push(''); + return lines.join('\n'); + } + + // Ticket Information + if (result.primaryTicket) { + const ticket = result.primaryTicket; + lines.push('📋 LINKED TICKET'); + lines.push('───────────────────────────────────────────────────────────────'); + lines.push(` Key: ${ticket.key}`); + lines.push(` Title: ${ticket.title}`); + lines.push(` Type: ${ticket.type.toUpperCase()}`); + lines.push(` Status: ${ticket.status}`); + if (ticket.storyPoints) { + lines.push(` Points: ${ticket.storyPoints}`); + } + lines.push(''); + } + + // Ticket Quality Rating + if (result.analysis?.ticketQuality) { + const quality = result.analysis.ticketQuality; + const scoreEmoji = getScoreEmoji(quality.overallScore); + + lines.push('📊 TICKET QUALITY RATING'); + lines.push('───────────────────────────────────────────────────────────────'); + lines.push(` Overall Score: ${scoreEmoji} ${quality.overallScore}/100 (${quality.tier.toUpperCase()})`); + lines.push(''); + lines.push(' Dimension Scores:'); + lines.push(` • Description Clarity: ${formatScore(quality.dimensions.descriptionClarity)}`); + lines.push(` • Acceptance Criteria: ${formatScore(quality.dimensions.acceptanceCriteriaQuality)}`); + lines.push(` • Testability: ${formatScore(quality.dimensions.testabilityScore)}`); + lines.push(` • Scope Definition: ${formatScore(quality.dimensions.scopeDefinition)}`); + lines.push(` • Technical Context: ${formatScore(quality.dimensions.technicalContext)}`); + lines.push(` • Visual Documentation: ${formatScore(quality.dimensions.visualDocumentation)}`); + lines.push(` • Completeness: ${formatScore(quality.dimensions.completeness)}`); + lines.push(''); + + if (!quality.reviewable) { + lines.push(` ⚠️ Ticket Not Reviewable: ${quality.reviewabilityReason}`); + lines.push(''); + } + + if (quality.feedback.weaknesses.length > 0) { + lines.push(' ⚠️ Ticket Weaknesses:'); + quality.feedback.weaknesses.forEach((w) => lines.push(` • ${w}`)); + lines.push(''); + } + } + + // Requirements Validation (derived from ticket analysis) + if (result.analysis?.acValidation) { + const validation = result.analysis.acValidation; + const complianceEmoji = getScoreEmoji(validation.compliancePercentage); + + lines.push('✅ REQUIREMENTS VALIDATION'); + lines.push('───────────────────────────────────────────────────────────────'); + lines.push(` Compliance: ${complianceEmoji} ${validation.compliancePercentage}%`); + lines.push(''); + + // Show derived requirements (what the agent understood from the ticket) + if (validation.derivedRequirements && validation.derivedRequirements.length > 0) { + lines.push(' 📋 DERIVED REQUIREMENTS (from ticket analysis):'); + validation.derivedRequirements.forEach((req) => { + const importanceIcon = { + essential: '🔴', + expected: '🟡', + nice_to_have: '🟢', + }[req.importance]; + const sourceLabel = { + description: 'desc', + explicit_ac: 'AC', + implied: 'implied', + ticket_type: 'type', + technical_context: 'tech', + }[req.source]; + lines.push(` ${importanceIcon} [${sourceLabel}] ${req.requirement}`); + }); + lines.push(''); + } + + // Show each requirement's validation status + lines.push(' 📊 REQUIREMENT STATUS:'); + validation.criteriaAnalysis.forEach((c) => { + const statusEmoji = { + met: '✅', + partial: '🟡', + unmet: '❌', + unclear: '❓', + }[c.status]; + lines.push(` ${statusEmoji} ${c.criteriaText.substring(0, 60)}${c.criteriaText.length > 60 ? '...' : ''}`); + if (c.status !== 'met') { + lines.push(` └─ ${c.explanation.substring(0, 70)}${c.explanation.length > 70 ? '...' : ''}`); + } + }); + lines.push(''); + + // Show gaps with impact + if (validation.gaps.length > 0) { + lines.push(' ❌ COVERAGE GAPS:'); + validation.gaps.forEach((gap) => { + const severityEmoji = { critical: '🔴', major: '🟠', minor: '🟡' }[gap.severity]; + lines.push(` ${severityEmoji} [${gap.severity.toUpperCase()}] ${gap.gapDescription}`); + lines.push(` └─ Impact: ${gap.impact}`); + }); + lines.push(''); + } + + // Show missing behaviors identified by the agent + if (validation.missingBehaviors && validation.missingBehaviors.length > 0) { + lines.push(' ⚠️ MISSING BEHAVIORS:'); + validation.missingBehaviors.forEach((b) => lines.push(` • ${b}`)); + lines.push(''); + } + } + + // Overall Peer Review Assessment + if (result.analysis?.peerReview) { + const review = result.analysis.peerReview; + + // Final verdict banner + const verdictEmoji = { + approve: '✅', + request_changes: '❌', + needs_discussion: '💬', + }[review.verdict.recommendation]; + const verdictText = { + approve: 'APPROVED', + request_changes: 'CHANGES REQUESTED', + needs_discussion: 'NEEDS DISCUSSION', + }[review.verdict.recommendation]; + + lines.push('🎯 PEER REVIEW VERDICT'); + lines.push('───────────────────────────────────────────────────────────────'); + lines.push(` ${verdictEmoji} ${verdictText} (Confidence: ${review.verdict.confidenceLevel}%)`); + lines.push(''); + lines.push(` ${review.verdict.summary}`); + lines.push(''); + + lines.push(' Scores:'); + lines.push(` • Implementation Completeness: ${formatScore(review.implementationCompleteness)}`); + lines.push(` • Quality Score: ${formatScore(review.qualityScore)}`); + lines.push(''); + + // Blockers with details + if (review.blockers.length > 0) { + lines.push(' 🚫 BLOCKERS (must fix before merge):'); + review.blockers.forEach((b) => { + lines.push(` • ${b.issue}`); + lines.push(` Reason: ${b.reason}`); + if (b.location) { + lines.push(` Location: ${b.location}`); + } + }); + lines.push(''); + } + + // Warnings with details + if (review.warnings.length > 0) { + lines.push(' ⚠️ WARNINGS (should address):'); + review.warnings.forEach((w) => { + lines.push(` • ${w.issue}`); + if (w.reason) { + lines.push(` Reason: ${w.reason}`); + } + }); + lines.push(''); + } + + // Regression risks - critical for senior dev perspective + if (review.regressionRisks && review.regressionRisks.length > 0) { + lines.push(' ⚡ POTENTIAL REGRESSION RISKS:'); + review.regressionRisks.forEach((r) => { + const likelihoodEmoji = { high: '🔴', medium: '🟠', low: '🟡' }[r.likelihood]; + lines.push(` ${likelihoodEmoji} ${r.risk}`); + lines.push(` Affected: ${r.affectedArea}`); + lines.push(` Why: ${r.reasoning}`); + }); + lines.push(''); + } + + // Uncovered scenarios - what the senior dev noticed isn't handled + if (review.uncoveredScenarios && review.uncoveredScenarios.length > 0) { + lines.push(' 🔍 SCENARIOS NOT HANDLED:'); + review.uncoveredScenarios.forEach((s) => { + const impactEmoji = { critical: '🔴', major: '🟠', minor: '🟡' }[s.impact]; + lines.push(` ${impactEmoji} ${s.scenario}`); + if (s.relatedCriteria) { + lines.push(` Related to: ${s.relatedCriteria}`); + } + }); + lines.push(''); + } + + // Scope analysis + if (review.scopeAnalysis.scopeCreepRisk) { + lines.push(' ⚠️ SCOPE CREEP DETECTED:'); + lines.push(` ${review.scopeAnalysis.scopeCreepDetails || 'Changes may exceed ticket scope'}`); + if (review.scopeAnalysis.outOfScope.length > 0) { + lines.push(' Out of scope changes:'); + review.scopeAnalysis.outOfScope.slice(0, 3).forEach((s) => lines.push(` • ${s}`)); + } + lines.push(''); + } + + // Recommendations + if (review.recommendations.length > 0) { + lines.push(' 💡 RECOMMENDATIONS:'); + review.recommendations.slice(0, 3).forEach((r) => lines.push(` • ${r}`)); + lines.push(''); + } + } + + lines.push('═══════════════════════════════════════════════════════════════'); + lines.push(''); + + return lines.join('\n'); +} + +function getScoreEmoji(score: number): string { + if (score >= 85) return '🟢'; + if (score >= 70) return '🟡'; + if (score >= 50) return '🟠'; + return '🔴'; +} + +function formatScore(score: number): string { + const emoji = getScoreEmoji(score); + const bar = '█'.repeat(Math.floor(score / 10)) + '░'.repeat(10 - Math.floor(score / 10)); + return `${emoji} ${bar} ${score}`; +} + +/** + * Format peer review results for GitHub PR comment + */ +export function formatPeerReviewMarkdown(result: PeerReviewResult): string { + if (!result.enabled || result.error) { + return ''; + } + + const lines: string[] = []; + + lines.push('## 🔍 Peer Review Analysis'); + lines.push(''); + + // Verdict banner at the top + if (result.analysis?.peerReview) { + const review = result.analysis.peerReview; + const verdictEmoji = { + approve: '✅', + request_changes: '❌', + needs_discussion: '💬', + }[review.verdict.recommendation]; + const verdictText = { + approve: 'APPROVED', + request_changes: 'CHANGES REQUESTED', + needs_discussion: 'NEEDS DISCUSSION', + }[review.verdict.recommendation]; + + lines.push(`### ${verdictEmoji} Verdict: ${verdictText}`); + lines.push(''); + lines.push(`> ${review.verdict.summary}`); + lines.push(''); + } + + // Ticket Information + if (result.primaryTicket) { + const ticket = result.primaryTicket; + lines.push(`### 📋 Linked Ticket: [${ticket.key}](${ticket.url})`); + lines.push(''); + lines.push(`**${ticket.title}**`); + lines.push(''); + lines.push(`| Property | Value |`); + lines.push(`|----------|-------|`); + lines.push(`| Type | ${ticket.type} |`); + lines.push(`| Status | ${ticket.status} |`); + if (ticket.storyPoints) { + lines.push(`| Story Points | ${ticket.storyPoints} |`); + } + lines.push(''); + } + + // Ticket Quality + if (result.analysis?.ticketQuality) { + const quality = result.analysis.ticketQuality; + lines.push('### 📊 Ticket Quality'); + lines.push(''); + lines.push(`**Overall Score: ${quality.overallScore}/100** (${quality.tier})`); + lines.push(''); + + if (!quality.reviewable) { + lines.push(`> ⚠️ **Warning:** ${quality.reviewabilityReason}`); + lines.push(''); + } + + if (quality.feedback.weaknesses.length > 0) { + lines.push('
'); + lines.push('Ticket Weaknesses'); + lines.push(''); + quality.feedback.weaknesses.forEach((w) => lines.push(`- ${w}`)); + lines.push(''); + lines.push('
'); + lines.push(''); + } + } + + // Requirements Validation (derived from ticket) + if (result.analysis?.acValidation) { + const validation = result.analysis.acValidation; + lines.push('### ✅ Requirements Validation'); + lines.push(''); + lines.push(`**Compliance: ${validation.compliancePercentage}%**`); + lines.push(''); + + // Show derived requirements + if (validation.derivedRequirements && validation.derivedRequirements.length > 0) { + lines.push('
'); + lines.push('📋 Derived Requirements (from ticket analysis)'); + lines.push(''); + lines.push('| Importance | Source | Requirement |'); + lines.push('|------------|--------|-------------|'); + validation.derivedRequirements.forEach((req) => { + const importanceEmoji = { essential: '🔴', expected: '🟡', nice_to_have: '🟢' }[req.importance]; + lines.push(`| ${importanceEmoji} ${req.importance} | ${req.source} | ${req.requirement} |`); + }); + lines.push(''); + lines.push('
'); + lines.push(''); + } + + lines.push('| Status | Requirement |'); + lines.push('|--------|-------------|'); + validation.criteriaAnalysis.forEach((c) => { + const statusEmoji = { met: '✅', partial: '🟡', unmet: '❌', unclear: '❓' }[c.status]; + lines.push(`| ${statusEmoji} ${c.status} | ${c.criteriaText.substring(0, 80)}${c.criteriaText.length > 80 ? '...' : ''} |`); + }); + lines.push(''); + + if (validation.gaps.length > 0) { + lines.push('#### ❌ Coverage Gaps'); + lines.push(''); + validation.gaps.forEach((gap) => { + lines.push(`- **[${gap.severity}]** ${gap.gapDescription}`); + lines.push(` - _Impact:_ ${gap.impact}`); + }); + lines.push(''); + } + } + + // Peer Review Details + if (result.analysis?.peerReview) { + const review = result.analysis.peerReview; + lines.push('### 🎯 Assessment Details'); + lines.push(''); + lines.push(`| Metric | Score |`); + lines.push(`|--------|-------|`); + lines.push(`| Implementation Completeness | ${review.implementationCompleteness}% |`); + lines.push(`| Quality Score | ${review.qualityScore}% |`); + lines.push(`| Confidence | ${review.verdict.confidenceLevel}% |`); + lines.push(''); + + if (review.blockers.length > 0) { + lines.push('#### 🚫 Blockers (Must Fix)'); + lines.push(''); + review.blockers.forEach((b) => { + lines.push(`- **${b.issue}**`); + lines.push(` - ${b.reason}`); + if (b.location) { + lines.push(` - 📍 ${b.location}`); + } + }); + lines.push(''); + } + + if (review.warnings.length > 0) { + lines.push('#### ⚠️ Warnings (Should Address)'); + lines.push(''); + review.warnings.forEach((w) => { + lines.push(`- **${w.issue}**`); + if (w.reason) { + lines.push(` - ${w.reason}`); + } + }); + lines.push(''); + } + + // Regression risks + if (review.regressionRisks && review.regressionRisks.length > 0) { + lines.push('
'); + lines.push('⚡ Potential Regression Risks'); + lines.push(''); + review.regressionRisks.forEach((r) => { + lines.push(`- **${r.risk}** (${r.likelihood} likelihood)`); + lines.push(` - Affects: ${r.affectedArea}`); + lines.push(` - Reason: ${r.reasoning}`); + }); + lines.push(''); + lines.push('
'); + lines.push(''); + } + + // Uncovered scenarios + if (review.uncoveredScenarios && review.uncoveredScenarios.length > 0) { + lines.push('
'); + lines.push('🔍 Scenarios Not Handled'); + lines.push(''); + review.uncoveredScenarios.forEach((s) => { + lines.push(`- **[${s.impact}]** ${s.scenario}`); + if (s.relatedCriteria) { + lines.push(` - Related to: ${s.relatedCriteria}`); + } + }); + lines.push(''); + lines.push('
'); + lines.push(''); + } + + // Scope creep + if (review.scopeAnalysis.scopeCreepRisk) { + lines.push('> ⚠️ **Scope Creep Detected:** ' + (review.scopeAnalysis.scopeCreepDetails || 'Changes may exceed ticket scope')); + lines.push(''); + } + } + + return lines.join('\n'); +} diff --git a/src/types/issue-tracker.types.ts b/src/types/issue-tracker.types.ts new file mode 100644 index 0000000..6577ef5 --- /dev/null +++ b/src/types/issue-tracker.types.ts @@ -0,0 +1,211 @@ +/** + * Generic Issue Tracker Provider Interface + * + * This abstraction allows PR Agent to work with different issue tracking systems + * (Jira, Linear, Azure DevOps, GitHub Issues, etc.) through a unified interface. + * + * MVP: Jira implementation via Atlassian MCP + * Future: Linear, Azure DevOps, GitHub Issues, etc. + */ + +/** + * Normalized ticket/issue representation across all providers + */ +export interface IssueTicket { + // Core identifiers + id: string; // Provider-specific ID + key: string; // Human-readable key (e.g., "PROJ-123", "#456") + url: string; // Direct link to the ticket + + // Basic info + title: string; + description: string; + type: IssueType; + status: string; + priority: IssuePriority; + + // People + assignee?: string; + reporter?: string; + + // Categorization + labels: string[]; + components: string[]; + project?: string; + + // Estimates + storyPoints?: number; + estimate?: string; + + // Acceptance criteria - the key field for Peer Review Agent + acceptanceCriteria?: string; + acceptanceCriteriaList?: string[]; + + // Test information + testScenarios?: string[]; + linkedTestCases?: string[]; + + // Attachments and context + hasScreenshots: boolean; + hasDiagrams: boolean; + attachmentCount: number; + + // Relations + parentKey?: string; + epicKey?: string; + linkedIssues: LinkedIssue[]; + subtasks: SubtaskInfo[]; + + // Timestamps + createdAt: string; + updatedAt: string; + + // Raw provider-specific data for edge cases + rawData?: Record; +} + +export type IssueType = + | 'bug' + | 'feature' + | 'story' + | 'task' + | 'epic' + | 'subtask' + | 'improvement' + | 'spike' + | 'other'; + +export type IssuePriority = + | 'critical' + | 'high' + | 'medium' + | 'low' + | 'none'; + +export interface LinkedIssue { + key: string; + type: string; // "blocks", "is blocked by", "relates to", "duplicates", etc. + title: string; + status: string; +} + +export interface SubtaskInfo { + key: string; + title: string; + status: string; +} + +/** + * Reference to a ticket found in PR metadata + */ +export interface TicketReference { + key: string; + source: 'title' | 'description' | 'branch' | 'commit' | 'manual'; + rawMatch: string; // The actual text that matched + confidence: number; // 0-100 +} + +/** + * Issue tracker provider interface - implement this for each provider + */ +export interface IssueTrackerProvider { + /** + * Provider name for display and configuration + */ + readonly name: string; + + /** + * Provider type identifier + */ + readonly type: IssueTrackerType; + + /** + * Check if the provider is properly configured and accessible + */ + isConfigured(): boolean; + + /** + * Test connection to the provider + */ + testConnection(): Promise; + + /** + * Fetch a single ticket by key + */ + getTicket(key: string): Promise; + + /** + * Fetch multiple tickets by keys + */ + getTickets(keys: string[]): Promise; + + /** + * Extract ticket references from PR metadata + */ + extractTicketReferences(context: TicketExtractionContext): TicketReference[]; + + /** + * Search for tickets matching a query + */ + searchTickets?(query: string, limit?: number): Promise; + + /** + * Get ticket comments (if supported) + */ + getComments?(ticketKey: string): Promise; +} + +export type IssueTrackerType = + | 'jira' + | 'linear' + | 'azure-devops' + | 'github-issues' + | 'gitlab-issues' + | 'shortcut' + | 'asana' + | 'other'; + +export interface TicketExtractionContext { + prTitle: string; + prDescription?: string; + branchName?: string; + commitMessages?: string[]; +} + +export interface IssueComment { + id: string; + author: string; + body: string; + createdAt: string; +} + +/** + * Configuration for issue tracker integration + */ +export interface IssueTrackerConfig { + enabled: boolean; + provider: IssueTrackerType; + + // Provider-specific settings (varies by provider) + providerConfig: Record; + + // Analysis settings (common across providers) + analyzeAcceptanceCriteria: boolean; + rateTicketQuality: boolean; + generateTestSuggestions: boolean; + checkScopeCreep: boolean; + + // Ticket extraction patterns (regex) + ticketPatterns?: string[]; + + // Output settings + includeTicketDetails: boolean; + verbose: boolean; +} + +/** + * Factory function type for creating providers + */ +export type IssueTrackerProviderFactory = ( + config: IssueTrackerConfig +) => IssueTrackerProvider | null; diff --git a/src/types/jira.types.ts b/src/types/jira.types.ts new file mode 100644 index 0000000..3205d74 --- /dev/null +++ b/src/types/jira.types.ts @@ -0,0 +1,278 @@ +/** + * Jira types and interfaces for Peer Review Agent + * Provides structures for Jira ticket analysis and acceptance criteria validation + */ + +/** + * Jira ticket from the Atlassian API/MCP + */ +export interface JiraTicket { + key: string; // e.g., "PROJ-123" + id: string; // Jira internal ID + summary: string; // Ticket title + description: string; // Full description (may contain markdown/rich text) + status: string; // e.g., "In Progress", "In Review", "Done" + type: JiraTicketType; // bug, feature, task, story, epic + priority: string; // e.g., "High", "Medium", "Low" + assignee?: string; // Assignee display name + reporter?: string; // Reporter display name + labels: string[]; // Labels/tags + components: string[]; // Affected components + fixVersions: string[]; // Target release versions + storyPoints?: number; // Story points estimate + createdAt: string; // ISO date string + updatedAt: string; // ISO date string + + // Acceptance criteria - can be in description or custom field + acceptanceCriteria?: string; // Extracted AC text + acceptanceCriteriaItems?: AcceptanceCriteriaItem[]; + + // Test-related fields + testScenarios?: string[]; // Listed test scenarios + testCases?: string[]; // Linked test cases + + // Additional context + attachments?: JiraAttachment[]; + linkedIssues?: JiraLinkedIssue[]; + comments?: JiraComment[]; + subtasks?: JiraSubtask[]; + parentKey?: string; // If this is a subtask + epicKey?: string; // Parent epic + + // Raw fields for custom field access + customFields?: Record; +} + +export type JiraTicketType = 'bug' | 'feature' | 'task' | 'story' | 'epic' | 'subtask' | 'improvement' | 'other'; + +export interface AcceptanceCriteriaItem { + id: string; // Generated ID for tracking + text: string; // The AC text + isMet?: boolean; // Whether this AC is covered by the PR + coverageDetails?: string; // Explanation of how it's covered + relatedFiles?: string[]; // Files that implement this AC + confidence: number; // 0-100 confidence in assessment +} + +export interface JiraAttachment { + id: string; + filename: string; + mimeType: string; + url: string; + createdAt: string; + isScreenshot: boolean; +} + +export interface JiraLinkedIssue { + key: string; + type: string; // "blocks", "is blocked by", "relates to", etc. + summary: string; + status: string; +} + +export interface JiraComment { + id: string; + author: string; + body: string; + createdAt: string; +} + +export interface JiraSubtask { + key: string; + summary: string; + status: string; +} + +/** + * Ticket quality rating based on best practices + */ +export interface TicketQualityRating { + overallScore: number; // 0-100 composite score + + // Individual dimension scores (0-100) + dimensions: { + descriptionClarity: number; // Is the description clear and complete? + acceptanceCriteriaQuality: number; // Are ACs specific, measurable, testable? + testabilityScore: number; // Are test scenarios/cases defined? + scopeDefinition: number; // Is scope well-defined and bounded? + technicalContext: number; // Are technical details/constraints provided? + visualDocumentation: number; // Screenshots, diagrams, mockups? + estimationQuality: number; // Story points reasonable for scope? + completeness: number; // Overall ticket completeness + }; + + // Detailed feedback for each dimension + feedback: { + strengths: string[]; // What's good about the ticket + weaknesses: string[]; // What's missing or unclear + suggestions: string[]; // How to improve the ticket + }; + + // Quality tier based on score + tier: 'excellent' | 'good' | 'adequate' | 'poor' | 'insufficient'; + + // Can we provide meaningful PR review with this ticket? + reviewable: boolean; + reviewabilityReason: string; +} + +/** + * Result of acceptance criteria validation against PR changes + */ +export interface AcceptanceCriteriaValidation { + ticketKey: string; + totalCriteria: number; + metCriteria: number; + unmetCriteria: number; + partialCriteria: number; + + // Detailed per-criteria analysis + criteriaAnalysis: CriteriaAnalysisItem[]; + + // Overall compliance percentage + compliancePercentage: number; + + // Summary of gaps + gaps: AcceptanceCriteriaGap[]; + + // Suggested test scenarios for uncovered cases + suggestedTestScenarios: TestScenarioSuggestion[]; +} + +export interface CriteriaAnalysisItem { + criteriaId: string; + criteriaText: string; + status: 'met' | 'unmet' | 'partial' | 'unclear'; + confidence: number; // 0-100 + evidence: string[]; // Code snippets or file references that show coverage + explanation: string; // Why we think it's met/unmet + relatedFiles: string[]; // Files that relate to this criteria +} + +export interface AcceptanceCriteriaGap { + criteriaText: string; + gapDescription: string; + severity: 'critical' | 'major' | 'minor'; + suggestedAction: string; +} + +export interface TestScenarioSuggestion { + scenario: string; // Test scenario description + type: 'unit' | 'integration' | 'e2e' | 'manual'; + priority: 'high' | 'medium' | 'low'; + relatedCriteria: string[]; // Which AC this tests + suggestedApproach: string; // How to implement the test +} + +/** + * Complete Jira analysis result for a PR + */ +export interface JiraAnalysisResult { + // Linked tickets found in PR + linkedTickets: JiraTicket[]; + primaryTicket?: JiraTicket; // Main ticket (first found or specified) + + // Ticket quality assessment + ticketQuality?: TicketQualityRating; + + // Acceptance criteria validation + acValidation?: AcceptanceCriteriaValidation; + + // Cross-reference with PR changes + scopeAnalysis: { + inScope: string[]; // Changes that align with ticket scope + outOfScope: string[]; // Changes that seem unrelated + scopeCreepRisk: boolean; + scopeCreepDetails?: string; + }; + + // Edge cases and test coverage + edgeCaseAnalysis: { + identifiedEdgeCases: string[]; + coveredEdgeCases: string[]; + uncoveredEdgeCases: string[]; + testSuggestions: TestScenarioSuggestion[]; + }; + + // Overall assessment + overallAssessment: { + implementationCompleteness: number; // 0-100 + qualityScore: number; // 0-100 + readyForReview: boolean; + blockers: string[]; + warnings: string[]; + recommendations: string[]; + }; + + // Metrics summary + metrics: { + ticketsCovered: number; + criteriaTotal: number; + criteriaMet: number; + criteriaPartial: number; + criteriaUnmet: number; + testScenariosGenerated: number; + }; +} + +/** + * Configuration for Jira integration + */ +export interface JiraConfig { + enabled: boolean; + + // MCP connection settings + mcpServerUrl?: string; // If using custom MCP server + + // Jira instance settings (for direct API if needed) + instanceUrl?: string; // e.g., "https://company.atlassian.net" + projectKey?: string; // Default project key + + // Authentication (via MCP or direct) + apiToken?: string; // Jira API token + email?: string; // Jira account email + + // Analysis settings + analyzeAcceptanceCriteria: boolean; + rateTicketQuality: boolean; + generateTestSuggestions: boolean; + checkScopeCreep: boolean; + + // Output settings + includeTicketDetailsInOutput: boolean; + verboseOutput: boolean; +} + +/** + * Ticket reference extracted from PR title/description/branch + */ +export interface TicketReference { + key: string; // e.g., "PROJ-123" + source: 'title' | 'description' | 'branch' | 'commit'; + confidence: number; // How confident we are this is the right ticket +} + +/** + * Context passed to Jira sub-agent + */ +export interface JiraAnalysisContext { + prTitle: string; + prDescription?: string; + branchName?: string; + commitMessages?: string[]; + diff: string; + files: Array<{ + path: string; + additions: number; + deletions: number; + status: string; + }>; + + // Pre-analyzed PR data + prSummary?: string; + prRisks?: string[]; + prComplexity?: number; + + // Jira config + config: JiraConfig; +} From 6fb77741a202c8f00cb6f80fda8d14130c56f1e8 Mon Sep 17 00:00:00 2001 From: ipanov Date: Mon, 29 Dec 2025 13:42:43 +0100 Subject: [PATCH 2/3] fix: TypeScript errors and multi-provider support for peer review MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Fix LangChain import path (langchain/output_parsers -> @langchain/core/output_parsers) - Fix TypeScript type casting issues in jira-mcp-client.ts - Refactor peer review to use ProviderFactory for multi-provider support - Peer review now uses the same provider/model as the main PR analysis 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- dist/agents/jira-sub-agent.d.ts | 199 + dist/agents/jira-sub-agent.js | 473 + dist/agents/jira-sub-agent.js.map | 1 + dist/cli/commands/analyze.command.d.ts | 1 + dist/cli/commands/analyze.command.js | 123 +- dist/cli/commands/analyze.command.js.map | 2 +- dist/cli/utils/config-loader.d.ts | 22 + dist/cli/utils/config-loader.js.map | 2 +- dist/index.js | 125011 +++++++++++++++- dist/types/issue-tracker.types.d.ts | 138 + dist/types/issue-tracker.types.js | 11 + dist/types/issue-tracker.types.js.map | 1 + dist/types/jira.types.d.ts | 211 + dist/types/jira.types.js | 6 + dist/types/jira.types.js.map | 1 + src/agents/jira-sub-agent.ts | 2 +- src/cli/commands/analyze.command.ts | 54 +- src/issue-tracker/jira-mcp-client.ts | 44 +- src/issue-tracker/peer-review-integration.ts | 2 +- 19 files changed, 126183 insertions(+), 121 deletions(-) create mode 100644 dist/agents/jira-sub-agent.d.ts create mode 100644 dist/agents/jira-sub-agent.js create mode 100644 dist/agents/jira-sub-agent.js.map create mode 100644 dist/types/issue-tracker.types.d.ts create mode 100644 dist/types/issue-tracker.types.js create mode 100644 dist/types/issue-tracker.types.js.map create mode 100644 dist/types/jira.types.d.ts create mode 100644 dist/types/jira.types.js create mode 100644 dist/types/jira.types.js.map diff --git a/dist/agents/jira-sub-agent.d.ts b/dist/agents/jira-sub-agent.d.ts new file mode 100644 index 0000000..c8d12e0 --- /dev/null +++ b/dist/agents/jira-sub-agent.d.ts @@ -0,0 +1,199 @@ +/** + * Jira Sub-Agent (Peer Review Agent) + * + * This agent acts like an experienced senior developer reviewing a PR. + * It understands not just the code, but the business context from the Jira ticket. + * + * KEY PHILOSOPHY: + * Like a senior developer who deeply knows the codebase, this agent: + * 1. Mentally constructs test scenarios and edge cases (INTERNAL reasoning) + * 2. Uses those mental models to EVALUATE if the implementation is complete + * 3. Checks if changes might break other parts of the application + * 4. Reports FINDINGS, not suggestions for tests + * + * The test scenarios are the agent's internal thought process - like how a + * senior dev thinks "what about when X happens?" while reviewing code. + * The OUTPUT is the conclusion: "This doesn't handle X" or "X case is covered". + */ +import { z } from 'zod'; +import { IssueTicket } from '../types/issue-tracker.types.js'; +import { BaseLanguageModel } from '@langchain/core/language_models/base'; +declare const TicketQualitySchema: z.ZodObject<{ + overallScore: z.ZodNumber; + dimensions: z.ZodObject<{ + descriptionClarity: z.ZodNumber; + acceptanceCriteriaQuality: z.ZodNumber; + testabilityScore: z.ZodNumber; + scopeDefinition: z.ZodNumber; + technicalContext: z.ZodNumber; + visualDocumentation: z.ZodNumber; + completeness: z.ZodNumber; + }, z.core.$strip>; + feedback: z.ZodObject<{ + strengths: z.ZodArray; + weaknesses: z.ZodArray; + suggestions: z.ZodArray; + }, z.core.$strip>; + tier: z.ZodEnum<{ + excellent: "excellent"; + good: "good"; + adequate: "adequate"; + poor: "poor"; + insufficient: "insufficient"; + }>; + reviewable: z.ZodBoolean; + reviewabilityReason: z.ZodString; +}, z.core.$strip>; +/** + * Acceptance Criteria Validation - focuses on what IS and ISN'T covered + * + * IMPORTANT: The agent DERIVES its own acceptance criteria by analyzing: + * - The full ticket description + * - Any explicit AC field (if present, but don't rely on it) + * - The ticket type (bug vs feature has different expectations) + * - Technical context and constraints mentioned + * + * Like a senior dev who reads the whole ticket and thinks: + * "To implement this properly, I'd need to: 1) do X, 2) handle Y, 3) ensure Z" + */ +declare const AcceptanceCriteriaValidationSchema: z.ZodObject<{ + derivedRequirements: z.ZodArray; + importance: z.ZodEnum<{ + expected: "expected"; + essential: "essential"; + nice_to_have: "nice_to_have"; + }>; + }, z.core.$strip>>; + criteriaAnalysis: z.ZodArray; + confidence: z.ZodNumber; + evidence: z.ZodArray; + explanation: z.ZodString; + relatedFiles: z.ZodArray; + }, z.core.$strip>>; + compliancePercentage: z.ZodNumber; + gaps: z.ZodArray; + impact: z.ZodString; + }, z.core.$strip>>; + missingBehaviors: z.ZodArray; + partialImplementations: z.ZodArray; +}, z.core.$strip>; +/** + * Peer Review Analysis - the senior developer's verdict + */ +declare const PeerReviewAnalysisSchema: z.ZodObject<{ + implementationCompleteness: z.ZodNumber; + qualityScore: z.ZodNumber; + readyForReview: z.ZodBoolean; + blockers: z.ZodArray; + }, z.core.$strip>>; + warnings: z.ZodArray; + }, z.core.$strip>>; + recommendations: z.ZodArray; + scopeAnalysis: z.ZodObject<{ + inScope: z.ZodArray; + outOfScope: z.ZodArray; + scopeCreepRisk: z.ZodBoolean; + scopeCreepDetails: z.ZodOptional; + }, z.core.$strip>; + regressionRisks: z.ZodArray; + reasoning: z.ZodString; + }, z.core.$strip>>; + uncoveredScenarios: z.ZodArray; + relatedCriteria: z.ZodOptional; + }, z.core.$strip>>; + verdict: z.ZodObject<{ + summary: z.ZodString; + recommendation: z.ZodEnum<{ + approve: "approve"; + request_changes: "request_changes"; + needs_discussion: "needs_discussion"; + }>; + confidenceLevel: z.ZodNumber; + }, z.core.$strip>; +}, z.core.$strip>; +export type TicketQualityRating = z.infer; +export type AcceptanceCriteriaValidation = z.infer; +export type PeerReviewAnalysis = z.infer; +export interface JiraSubAgentResult { + ticketQuality: TicketQualityRating; + acValidation?: AcceptanceCriteriaValidation; + peerReview: PeerReviewAnalysis; +} +export interface JiraSubAgentContext { + ticket: IssueTicket; + prTitle: string; + prDescription?: string; + diff: string; + files: Array<{ + path: string; + additions: number; + deletions: number; + status: string; + }>; + prSummary?: string; + prRisks?: string[]; +} +export declare class JiraSubAgent { + private llm; + constructor(llm: BaseLanguageModel); + /** + * Analyze a ticket and PR, providing comprehensive peer review + */ + analyze(context: JiraSubAgentContext): Promise; + /** + * Rate the quality of a Jira ticket + */ + rateTicketQuality(ticket: IssueTicket): Promise; + /** + * Validate acceptance criteria against PR changes + */ + validateAcceptanceCriteria(context: JiraSubAgentContext): Promise; + /** + * Generate comprehensive peer review analysis + */ + generatePeerReview(context: JiraSubAgentContext, ticketQuality: TicketQualityRating, acValidation?: AcceptanceCriteriaValidation): Promise; +} +export {}; diff --git a/dist/agents/jira-sub-agent.js b/dist/agents/jira-sub-agent.js new file mode 100644 index 0000000..a851f1b --- /dev/null +++ b/dist/agents/jira-sub-agent.js @@ -0,0 +1,473 @@ +/** + * Jira Sub-Agent (Peer Review Agent) + * + * This agent acts like an experienced senior developer reviewing a PR. + * It understands not just the code, but the business context from the Jira ticket. + * + * KEY PHILOSOPHY: + * Like a senior developer who deeply knows the codebase, this agent: + * 1. Mentally constructs test scenarios and edge cases (INTERNAL reasoning) + * 2. Uses those mental models to EVALUATE if the implementation is complete + * 3. Checks if changes might break other parts of the application + * 4. Reports FINDINGS, not suggestions for tests + * + * The test scenarios are the agent's internal thought process - like how a + * senior dev thinks "what about when X happens?" while reviewing code. + * The OUTPUT is the conclusion: "This doesn't handle X" or "X case is covered". + */ +import { ChatPromptTemplate } from '@langchain/core/prompts'; +import { StructuredOutputParser } from '@langchain/core/output_parsers'; +import { z } from 'zod'; +// ========== Output Schemas ========== +const TicketQualitySchema = z.object({ + overallScore: z.number().min(0).max(100).describe('Overall ticket quality score'), + dimensions: z.object({ + descriptionClarity: z.number().min(0).max(100), + acceptanceCriteriaQuality: z.number().min(0).max(100), + testabilityScore: z.number().min(0).max(100), + scopeDefinition: z.number().min(0).max(100), + technicalContext: z.number().min(0).max(100), + visualDocumentation: z.number().min(0).max(100), + completeness: z.number().min(0).max(100), + }), + feedback: z.object({ + strengths: z.array(z.string()), + weaknesses: z.array(z.string()), + suggestions: z.array(z.string()), + }), + tier: z.enum(['excellent', 'good', 'adequate', 'poor', 'insufficient']), + reviewable: z.boolean(), + reviewabilityReason: z.string(), +}); +/** + * Acceptance Criteria Validation - focuses on what IS and ISN'T covered + * + * IMPORTANT: The agent DERIVES its own acceptance criteria by analyzing: + * - The full ticket description + * - Any explicit AC field (if present, but don't rely on it) + * - The ticket type (bug vs feature has different expectations) + * - Technical context and constraints mentioned + * + * Like a senior dev who reads the whole ticket and thinks: + * "To implement this properly, I'd need to: 1) do X, 2) handle Y, 3) ensure Z" + */ +const AcceptanceCriteriaValidationSchema = z.object({ + // The agent's derived understanding of what needs to be implemented + derivedRequirements: z.array(z.object({ + id: z.string(), + requirement: z.string().describe('What the agent derived needs to be done'), + source: z.enum(['description', 'explicit_ac', 'implied', 'ticket_type', 'technical_context']) + .describe('Where this requirement was derived from'), + importance: z.enum(['essential', 'expected', 'nice_to_have']), + })).describe('Requirements derived by analyzing the full ticket, not just AC field'), + // Analysis of each derived requirement against the PR + criteriaAnalysis: z.array(z.object({ + criteriaId: z.string(), + criteriaText: z.string(), + status: z.enum(['met', 'unmet', 'partial', 'unclear']), + confidence: z.number().min(0).max(100), + evidence: z.array(z.string()).describe('Code evidence showing coverage or lack thereof'), + explanation: z.string().describe('Why this criteria is/isnt met'), + relatedFiles: z.array(z.string()), + })), + compliancePercentage: z.number().min(0).max(100), + gaps: z.array(z.object({ + criteriaText: z.string(), + gapDescription: z.string().describe('What specific functionality is missing'), + severity: z.enum(['critical', 'major', 'minor']), + impact: z.string().describe('What will happen if this gap is not addressed'), + })), + // Internal reasoning exposed as findings, not suggestions + missingBehaviors: z.array(z.string()).describe('Behaviors that should exist but dont'), + partialImplementations: z.array(z.string()).describe('Features that are started but incomplete'), +}); +/** + * Peer Review Analysis - the senior developer's verdict + */ +const PeerReviewAnalysisSchema = z.object({ + implementationCompleteness: z.number().min(0).max(100), + qualityScore: z.number().min(0).max(100), + readyForReview: z.boolean(), + // Critical findings that block merge + blockers: z.array(z.object({ + issue: z.string(), + reason: z.string(), + location: z.string().optional().describe('File or component affected'), + })), + // Important issues that should be fixed + warnings: z.array(z.object({ + issue: z.string(), + reason: z.string(), + location: z.string().optional(), + })), + // Nice-to-have improvements + recommendations: z.array(z.string()), + // Scope analysis + scopeAnalysis: z.object({ + inScope: z.array(z.string()), + outOfScope: z.array(z.string()), + scopeCreepRisk: z.boolean(), + scopeCreepDetails: z.string().optional(), + }), + // Potential regression analysis - what might break + regressionRisks: z.array(z.object({ + risk: z.string().describe('What could break'), + affectedArea: z.string().describe('Part of the app that might be affected'), + likelihood: z.enum(['high', 'medium', 'low']), + reasoning: z.string().describe('Why this might happen'), + })), + // Uncovered scenarios identified during review (findings, not suggestions) + uncoveredScenarios: z.array(z.object({ + scenario: z.string().describe('A scenario that isnt handled'), + impact: z.enum(['critical', 'major', 'minor']), + relatedCriteria: z.string().optional(), + })), + // Final verdict + verdict: z.object({ + summary: z.string().describe('One paragraph summary of the review'), + recommendation: z.enum(['approve', 'request_changes', 'needs_discussion']), + confidenceLevel: z.number().min(0).max(100), + }), +}); +// ========== Prompts ========== +const TICKET_QUALITY_PROMPT = `You are an expert at evaluating Jira tickets and user stories. +Analyze the following ticket and rate its quality based on industry best practices. + +TICKET INFORMATION: +Key: {ticketKey} +Type: {ticketType} +Title: {ticketTitle} +Description: +{ticketDescription} + +Acceptance Criteria: +{acceptanceCriteria} + +Test Scenarios Defined: {testScenarios} +Has Screenshots/Mockups: {hasScreenshots} +Has Diagrams: {hasDiagrams} +Story Points: {storyPoints} +Labels: {labels} +Components: {components} + +EVALUATION CRITERIA: +1. Description Clarity (0-100): Is the description clear, complete, and unambiguous? +2. Acceptance Criteria Quality (0-100): Are ACs specific, measurable, achievable, and testable (SMART)? +3. Testability Score (0-100): Can this ticket be tested? Are expected behaviors clear? +4. Scope Definition (0-100): Is the scope well-defined and bounded? No scope creep potential? +5. Technical Context (0-100): Are technical requirements, constraints, and dependencies clear? +6. Visual Documentation (0-100): Are there screenshots, mockups, or diagrams where needed? +7. Completeness (0-100): Overall ticket completeness - nothing critical missing? + +QUALITY TIERS: +- excellent (85-100): Exemplary ticket, can be implemented with high confidence +- good (70-84): Well-written ticket with minor gaps +- adequate (50-69): Passable but has notable gaps that may cause issues +- poor (25-49): Significant issues, needs improvement before implementation +- insufficient (0-24): Cannot be implemented reliably, needs major rework + +REVIEWABILITY: +A ticket is "reviewable" if there's enough information to meaningfully derive what needs +to be implemented. This does NOT require an explicit acceptance criteria field! + +A ticket is REVIEWABLE if: +- The description explains what needs to be done (even briefly) +- The title + type give enough context to understand the goal +- A senior developer could reasonably derive requirements from it + +A ticket is NOT REVIEWABLE if: +- It's just a title with no description (e.g., "Fix bug" with nothing else) +- It's too vague to derive any concrete requirements +- There's literally not enough info to know what "done" looks like + +Remember: Many good tickets have detailed descriptions but empty AC fields. +The key is whether YOU can derive what needs to be built. + +{format_instructions}`; +const AC_VALIDATION_PROMPT = `You are a SENIOR DEVELOPER with deep knowledge of this codebase reviewing a PR. + +Your task: Understand what this ticket requires, then evaluate if the PR implements it correctly. + +CRITICAL: DO NOT just rely on the "Acceptance Criteria" field. Many tickets have empty AC or +poorly written AC. You must DERIVE your own understanding of what needs to be done by reading: +- The full description +- The ticket type (bug fix has different needs than a feature) +- Any technical context mentioned +- The implicit requirements (what any experienced dev would know is needed) + +Think like an experienced dev who reads a ticket and thinks: +"Okay, to implement this properly I need to: handle X, add Y, make sure Z works..." + +JIRA TICKET: +Key: {ticketKey} +Type: {ticketType} +Title: {ticketTitle} + +FULL DESCRIPTION (analyze this carefully): +{ticketDescription} + +EXPLICIT ACCEPTANCE CRITERIA (may be empty or incomplete - don't rely solely on this): +{acceptanceCriteria} + +PR INFORMATION: +Title: {prTitle} +Description: {prDescription} + +FILES CHANGED: +{filesChanged} + +CODE DIFF: +{diff} + +PREVIOUS PR ANALYSIS SUMMARY: +{prSummary} + +YOUR TASK: + +1. DERIVE REQUIREMENTS: + First, read the entire ticket and derive what actually needs to be implemented. + For each requirement you identify, note: + - What the requirement is + - Where you derived it from (description, explicit AC, implied by ticket type, technical context) + - How essential it is (essential, expected, nice-to-have) + + Don't just copy the AC field - THINK about what's really needed. + A ticket saying "Add login button" implies: the button should be visible, clickable, + trigger auth flow, handle errors, etc. + +2. VALIDATE EACH REQUIREMENT: + For each derived requirement: + - Is it MET, UNMET, PARTIAL, or UNCLEAR in the code? + - Provide CODE EVIDENCE + - Explain your reasoning + +3. IDENTIFY GAPS: + What's missing? What behaviors should exist but don't? + Think through scenarios: "What if the user does X?" "What about error case Y?" + +Report FINDINGS, not suggestions. Like a senior dev saying: +"This doesn't handle the case when the user is logged out" + +{format_instructions}`; +const PEER_REVIEW_PROMPT = `You are a SENIOR DEVELOPER doing a thorough peer review. + +You've been with this team for years. You know where the bodies are buried. +You think about: +- Does this actually solve the problem in the ticket? +- What might this break in other parts of the app? +- Are there scenarios the developer didn't consider? +- Is this ready for production? + +JIRA TICKET: +Key: {ticketKey} +Type: {ticketType} +Title: {ticketTitle} +Description: {ticketDescription} +Acceptance Criteria: {acceptanceCriteria} + +PR INFORMATION: +Title: {prTitle} +Description: {prDescription} + +FILES CHANGED: +{filesChanged} + +DIFF SUMMARY: +{diff} + +EXISTING PR ANALYSIS: +Summary: {prSummary} +Risks Identified: {prRisks} + +TICKET QUALITY ASSESSMENT: +Overall Score: {ticketQualityScore}/100 +Reviewable: {isReviewable} + +AC VALIDATION RESULTS: +Compliance: {acCompliancePercentage}% +Gaps Found: {gapsFound} + +YOUR PEER REVIEW TASK: + +1. IMPLEMENTATION COMPLETENESS (0-100): + Does this PR fully implement what the ticket asks for? + +2. QUALITY SCORE (0-100): + Code quality + requirements adherence combined + +3. READY FOR REVIEW: + Would you approve this or request changes? + +4. BLOCKERS: + Critical issues - things that MUST be fixed before merge + (missing functionality, bugs, security issues) + +5. WARNINGS: + Important issues - things that SHOULD be fixed + (edge cases not handled, potential bugs) + +6. RECOMMENDATIONS: + Nice-to-haves for improvement + +7. SCOPE ANALYSIS: + - What's in scope vs out of scope? + - Is there scope creep? + +8. REGRESSION RISKS: + Think: "What else in the app might this break?" + - Consider dependencies, shared code, side effects + - Think about how this interacts with existing features + +9. UNCOVERED SCENARIOS: + As a senior dev, you mentally run through scenarios: + - "What if the user does X?" + - "What about when Y is null?" + - "What happens during Z error condition?" + + Report which scenarios you identified that AREN'T handled. + Don't suggest tests - just flag what's missing. + +10. FINAL VERDICT: + Give your honest assessment: + - APPROVE: Ready to merge (maybe minor nits) + - REQUEST_CHANGES: Needs work before merge + - NEEDS_DISCUSSION: Architectural concerns to discuss + +{format_instructions}`; +// ========== Agent Class ========== +export class JiraSubAgent { + llm; + constructor(llm) { + this.llm = llm; + } + /** + * Analyze a ticket and PR, providing comprehensive peer review + */ + async analyze(context) { + // Step 1: Rate ticket quality + const ticketQuality = await this.rateTicketQuality(context.ticket); + // Step 2: Derive requirements and validate against PR + // NOTE: We analyze even if there's no explicit AC field - the agent derives + // requirements from the full ticket (description, title, type, context) + let acValidation; + if (ticketQuality.reviewable) { + // The agent will derive its own requirements from the ticket + // Don't skip just because acceptanceCriteriaList is empty + acValidation = await this.validateAcceptanceCriteria(context); + } + // Step 3: Generate peer review analysis + const peerReview = await this.generatePeerReview(context, ticketQuality, acValidation); + return { + ticketQuality, + acValidation, + peerReview, + }; + } + /** + * Rate the quality of a Jira ticket + */ + async rateTicketQuality(ticket) { + const parser = StructuredOutputParser.fromZodSchema(TicketQualitySchema); + const prompt = ChatPromptTemplate.fromTemplate(TICKET_QUALITY_PROMPT); + const chain = prompt.pipe(this.llm); + const response = await chain.invoke({ + ticketKey: ticket.key, + ticketType: ticket.type, + ticketTitle: ticket.title, + ticketDescription: ticket.description || 'No description provided', + acceptanceCriteria: ticket.acceptanceCriteria || + ticket.acceptanceCriteriaList?.join('\n') || + 'No acceptance criteria defined', + testScenarios: ticket.testScenarios?.join(', ') || 'None defined', + hasScreenshots: ticket.hasScreenshots ? 'Yes' : 'No', + hasDiagrams: ticket.hasDiagrams ? 'Yes' : 'No', + storyPoints: ticket.storyPoints?.toString() || 'Not estimated', + labels: ticket.labels.join(', ') || 'None', + components: ticket.components.join(', ') || 'None', + format_instructions: parser.getFormatInstructions(), + }); + const content = typeof response === 'string' ? response : response.content?.toString() || ''; + return parser.parse(content); + } + /** + * Validate acceptance criteria against PR changes + */ + async validateAcceptanceCriteria(context) { + const parser = StructuredOutputParser.fromZodSchema(AcceptanceCriteriaValidationSchema); + const prompt = ChatPromptTemplate.fromTemplate(AC_VALIDATION_PROMPT); + const chain = prompt.pipe(this.llm); + // Format acceptance criteria with IDs + const acList = context.ticket.acceptanceCriteriaList || []; + const formattedAC = acList + .map((ac, i) => `AC-${i + 1}: ${ac}`) + .join('\n'); + // Format files changed + const filesChanged = context.files + .map((f) => `${f.path} (+${f.additions}/-${f.deletions}) [${f.status}]`) + .join('\n'); + // Truncate diff if too long + const maxDiffLength = 15000; + const truncatedDiff = context.diff.length > maxDiffLength + ? context.diff.substring(0, maxDiffLength) + '\n... [diff truncated]' + : context.diff; + const response = await chain.invoke({ + ticketKey: context.ticket.key, + ticketType: context.ticket.type, + ticketTitle: context.ticket.title, + ticketDescription: context.ticket.description?.substring(0, 2000) || 'No description', + acceptanceCriteria: formattedAC || 'No acceptance criteria defined', + prTitle: context.prTitle, + prDescription: context.prDescription || 'No description', + filesChanged, + diff: truncatedDiff, + prSummary: context.prSummary || 'No summary available', + format_instructions: parser.getFormatInstructions(), + }); + const content = typeof response === 'string' ? response : response.content?.toString() || ''; + return parser.parse(content); + } + /** + * Generate comprehensive peer review analysis + */ + async generatePeerReview(context, ticketQuality, acValidation) { + const parser = StructuredOutputParser.fromZodSchema(PeerReviewAnalysisSchema); + const prompt = ChatPromptTemplate.fromTemplate(PEER_REVIEW_PROMPT); + const chain = prompt.pipe(this.llm); + // Format files changed + const filesChanged = context.files + .map((f) => `${f.path} (+${f.additions}/-${f.deletions}) [${f.status}]`) + .join('\n'); + // Truncate diff if too long + const maxDiffLength = 10000; + const truncatedDiff = context.diff.length > maxDiffLength + ? context.diff.substring(0, maxDiffLength) + '\n... [diff truncated]' + : context.diff; + // Format gaps found + const gapsFound = acValidation?.gaps + .map((g) => `- ${g.criteriaText}: ${g.gapDescription}`) + .join('\n') || 'None identified'; + const response = await chain.invoke({ + ticketKey: context.ticket.key, + ticketType: context.ticket.type, + ticketTitle: context.ticket.title, + ticketDescription: context.ticket.description?.substring(0, 2000) || 'No description', + acceptanceCriteria: context.ticket.acceptanceCriteria || + context.ticket.acceptanceCriteriaList?.join('\n') || + 'None defined', + prTitle: context.prTitle, + prDescription: context.prDescription || 'No description', + filesChanged, + diff: truncatedDiff, + prSummary: context.prSummary || 'No summary available', + prRisks: context.prRisks?.join(', ') || 'None identified', + ticketQualityScore: ticketQuality.overallScore, + isReviewable: ticketQuality.reviewable ? 'Yes' : 'No', + acCompliancePercentage: acValidation?.compliancePercentage ?? 'N/A', + gapsFound, + format_instructions: parser.getFormatInstructions(), + }); + const content = typeof response === 'string' ? response : response.content?.toString() || ''; + return parser.parse(content); + } +} +//# sourceMappingURL=jira-sub-agent.js.map \ No newline at end of file diff --git a/dist/agents/jira-sub-agent.js.map b/dist/agents/jira-sub-agent.js.map new file mode 100644 index 0000000..15e2e5d --- /dev/null +++ b/dist/agents/jira-sub-agent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jira-sub-agent.js","sourceRoot":"","sources":["../../src/agents/jira-sub-agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,uCAAuC;AAEvC,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACnC,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,8BAA8B,CAAC;IACjF,UAAU,EAAE,CAAC,CAAC,MAAM,CAAC;QACnB,kBAAkB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;QAC9C,yBAAyB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;QACrD,gBAAgB,EAAE,CAAC,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EAAE,OAAO,CAAC,aAAa,IAAI,gBAAgB;YACxD,YAAY;YACZ,IAAI,EAAE,aAAa;YACnB,SAAS,EAAE,OAAO,CAAC,SAAS,IAAI,sBAAsB;YACtD,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,iBAAiB;YACzD,kBAAkB,EAAE,aAAa,CAAC,YAAY;YAC9C,YAAY,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;YACrD,sBAAsB,EAAE,YAAY,EAAE,oBAAoB,IAAI,KAAK;YACnE,SAAS;YACT,mBAAmB,EAAE,MAAM,CAAC,qBAAqB,EAAE;SACpD,CAAC,CAAC;QAEH,MAAM,OAAO,GAAG,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;QAC7F,OAAO,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC;CACF"} \ No newline at end of file diff --git a/dist/cli/commands/analyze.command.d.ts b/dist/cli/commands/analyze.command.d.ts index d18214c..4b963c2 100644 --- a/dist/cli/commands/analyze.command.d.ts +++ b/dist/cli/commands/analyze.command.d.ts @@ -14,6 +14,7 @@ interface AnalyzeOptions { verbose?: boolean; maxCost?: number; archDocs?: boolean; + peerReview?: boolean; } /** * Analyze command - analyze PR diffs with AI diff --git a/dist/cli/commands/analyze.command.js b/dist/cli/commands/analyze.command.js index b6e7cf3..7852aab 100644 --- a/dist/cli/commands/analyze.command.js +++ b/dist/cli/commands/analyze.command.js @@ -7,6 +7,8 @@ import { loadUserConfig, getApiKey } from '../utils/config-loader.js'; import { archDocsExists } from '../../utils/arch-docs-parser.js'; import { resolveDefaultBranch } from '../../utils/branch-resolver.js'; import { ConfigurationError, GitHubAPIError, GitError } from '../../utils/errors.js'; +import { createPeerReviewIntegration, formatPeerReviewOutput, } from '../../issue-tracker/index.js'; +import { ProviderFactory } from '../../providers/index.js'; /** * Determine which files should be skipped during analysis */ @@ -232,6 +234,7 @@ export async function analyzePR(options = {}) { } const provider = (options.provider || config.ai?.provider || 'anthropic').toLowerCase(); const apiKey = getApiKey(provider, config); + const model = options.model || config.ai?.model; if (!apiKey) { spinner.fail('No API key found'); console.error(chalk.yellow('💡 Please set it in one of these ways:')); @@ -345,7 +348,6 @@ export async function analyzePR(options = {}) { else if (options.archDocs && !hasArchDocs) { console.log(chalk.yellow('⚠️ --arch-docs flag specified but no .arch-docs folder found\n')); } - const model = options.model || config.ai?.model; const agent = new PRAnalyzerAgent({ provider: provider, apiKey, @@ -357,6 +359,16 @@ export async function analyzePR(options = {}) { }); // Display results displayAgentResults(result, mode, options.verbose || false); + // Run Peer Review if enabled (via flag or config) + const peerReviewEnabled = options.peerReview || config.peerReview?.enabled; + if (peerReviewEnabled) { + // Pass the same provider config to peer review so it uses the same LLM + await runPeerReview(config, diff, title, result, options.verbose || false, { + provider, + apiKey, + model, + }); + } } catch (error) { spinner.fail('Analysis failed'); @@ -544,4 +556,113 @@ function displayAgentResults(result, mode, verbose) { } console.log(chalk.gray('\n━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n')); } +/** + * Run Peer Review analysis against linked Jira tickets + * + * This extends the PR analysis with business context validation: + * - Fetches linked Jira tickets from PR title/branch + * - Rates ticket quality + * - Validates implementation against derived requirements + * - Provides senior-dev style verdict + */ +async function runPeerReview(config, diff, title, prAnalysisResult, verbose, providerOptions) { + const spinner = ora('Running Peer Review analysis...').start(); + try { + // Create LLM using the same provider as main analysis + const llm = ProviderFactory.createChatModel({ + provider: providerOptions.provider, + apiKey: providerOptions.apiKey, + model: providerOptions.model, + temperature: 0.2, + maxTokens: 4000, + }); + // Create peer review integration from config, passing the LLM + const peerReviewConfig = config.peerReview || {}; + const integration = createPeerReviewIntegration(peerReviewConfig, llm); + if (!integration.isEnabled()) { + spinner.warn('Peer Review enabled but not configured. Add Jira settings to config.'); + console.log(chalk.gray(' Run: pr-agent config --set peerReview.instanceUrl=https://your.atlassian.net')); + console.log(chalk.gray(' Or configure MCP: peerReview.useMcp=true')); + return; + } + // Get branch name for ticket extraction + let branchName; + try { + branchName = execSync('git rev-parse --abbrev-ref HEAD', { encoding: 'utf-8' }).trim(); + } + catch { + // Ignore - branch name is optional + } + // Get commit messages for ticket extraction + let commitMessages = []; + try { + const commits = execSync('git log --oneline -10', { encoding: 'utf-8' }); + commitMessages = commits.trim().split('\n'); + } + catch { + // Ignore + } + // Parse diff to get file info + const files = parseDiffFiles(diff); + spinner.text = 'Extracting ticket references...'; + // Run peer review analysis + const result = await integration.analyze({ + prTitle: title || 'Untitled PR', + prDescription: undefined, // Could extract from git commit body + branchName, + commitMessages, + diff, + files, + prSummary: prAnalysisResult.summary, + prRisks: prAnalysisResult.overallRisks, + prComplexity: prAnalysisResult.overallComplexity, + }); + spinner.succeed('Peer Review analysis complete'); + // Display peer review results + const output = formatPeerReviewOutput(result); + if (output) { + console.log(output); + } + if (verbose && result.ticketReferences.length > 0) { + console.log(chalk.gray('Ticket references found:')); + result.ticketReferences.forEach((ref) => { + console.log(chalk.gray(` - ${ref.key} (from ${ref.source}, confidence: ${ref.confidence}%)`)); + }); + } + } + catch (error) { + spinner.fail('Peer Review analysis failed'); + console.error(chalk.yellow(`⚠️ ${error.message || 'Unknown error'}`)); + console.log(chalk.gray(' The main PR analysis completed successfully.')); + console.log(chalk.gray(' Peer Review is an optional enhancement - check Jira configuration.')); + } +} +/** + * Parse diff to extract file information + */ +function parseDiffFiles(diff) { + const files = []; + const filePattern = /^diff --git a\/(.+?) b\/(.+?)$/gm; + let match; + while ((match = filePattern.exec(diff)) !== null) { + const filePath = match[2] !== '/dev/null' ? match[2] : match[1]; + const isNew = match[1] === '/dev/null' || match[1].startsWith('dev/null'); + const isDeleted = match[2] === '/dev/null'; + // Count additions and deletions (simplified) + const fileStart = match.index; + const nextFileMatch = filePattern.exec(diff); + const fileEnd = nextFileMatch ? nextFileMatch.index : diff.length; + filePattern.lastIndex = match.index + 1; // Reset to continue from after current match + const fileContent = diff.substring(fileStart, fileEnd); + const additions = (fileContent.match(/^\+[^+]/gm) || []).length; + const deletions = (fileContent.match(/^-[^-]/gm) || []).length; + files.push({ + path: filePath, + additions, + deletions, + status: isNew ? 'added' : isDeleted ? 'deleted' : 'modified', + }); + } + return files; +} //# sourceMappingURL=analyze.command.js.map \ No newline at end of file diff --git a/dist/cli/commands/analyze.command.js.map b/dist/cli/commands/analyze.command.js.map index 08e352d..068375d 100644 --- a/dist/cli/commands/analyze.command.js.map +++ b/dist/cli/commands/analyze.command.js.map @@ -1 +1 @@ -{"version":3,"file":"analyze.command.js","sourceRoot":"","sources":["../../../src/cli/commands/analyze.command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AA0BrF;;GAEG;AACH,SAAS,cAAc,CAAC,QAAgB;IACtC,4CAA4C;IAC5C,IAAI,QAAQ,CAAC,UAAU,CAAC,OAAO,CAAC,IAAI,QAAQ,CAAC,QAAQ,CAAC,QAAQ,CAAC,EAAE,CAAC;QAChE,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,QAAQ,CAAC,UAAU,CAAC,eAAe,CA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C,CAAC,CAAC,IAAI,CAAC,CAAC;4BAC3C,KAAK,KAAK,oBAAoB,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC;gCACvC,KAAK,KAAK,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,CAAC,CAAC,GAAG,CAAC;gBACtD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,UAAU,IAAI,KAAK,EAAE,CAAC,CAAC,CAAC;YACvD,CAAC,CAAC,CAAC;YACH,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAClB,CAAC;QAED,IAAI,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACjD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,4CAA4C,CAAC,CAAC,CAAC;YACtE,MAAM,CAAC,cAAc,CAAC,WAAW,CAAC,OAAO,CAAC,CAAC,OAAe,EAAE,CAAS,EAAE,EAAE;gBACvE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,KAAK,CAAC,GAAG,CAAC,KAAK,OAAO,EAAE,CAAC,CAAC,CAAC;YACrD,CAAC,CAAC,CAAC;YACH,OAAO,CAAC,GAAG,CAAC,EAAE,CAAC,CAAC;QAClB,CAAC;IACH,CAAC;IAED,IAAI,MAAM,CAAC,eAAe,EAAE,CAAC;QAC3B,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,wBAAwB,MAAM,CAAC,eAAe,CAAC,cAAc,EAAE,EAAE,CAAC,CAAC,CAAC;IAC7F,CAAC;IAED,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,8CAA8C,CAAC,CAAC,CAAC;AAC1E,CAAC"} \ No newline at end of file +{"version":3,"file":"analyze.command.js","sourceRoot":"","sources":["../../../src/cli/commands/analyze.command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAA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MAAM,SAAS,GAAG,CAAC,WAAW,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;QAE/D,KAAK,CAAC,IAAI,CAAC;YACT,IAAI,EAAE,QAAQ;YACd,SAAS;YACT,SAAS;YACT,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU;SAC7D,CAAC,CAAC;IACL,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/dist/cli/utils/config-loader.d.ts b/dist/cli/utils/config-loader.d.ts index 384a0b1..87fd34f 100644 --- a/dist/cli/utils/config-loader.d.ts +++ b/dist/cli/utils/config-loader.d.ts @@ -26,6 +26,28 @@ export interface UserConfig { showStrategy?: boolean; showRecommendations?: boolean; }; + /** + * Peer Review configuration - integrates with issue trackers (Jira, etc.) + * to validate PRs against tickets and acceptance criteria + */ + peerReview?: { + enabled?: boolean; + provider?: string; + useMcp?: boolean; + instanceUrl?: string; + email?: string; + apiToken?: string; + defaultProject?: string; + acceptanceCriteriaField?: string; + storyPointsField?: string; + ticketPatterns?: string[]; + analyzeAcceptanceCriteria?: boolean; + rateTicketQuality?: boolean; + generateTestSuggestions?: boolean; + checkScopeCreep?: boolean; + includeTicketDetails?: boolean; + verbose?: boolean; + }; } /** * Find config file in current directory or parent directories diff --git a/dist/cli/utils/config-loader.js.map b/dist/cli/utils/config-loader.js.map index ffcea2d..e1e8469 100644 --- a/dist/cli/utils/config-loader.js.map +++ b/dist/cli/utils/config-loader.js.map @@ -1 +1 @@ -{"version":3,"file":"config-loader.js","sourceRoot":"","sources":["../../../src/cli/utils/config-loader.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B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QAAgB,EAAE,MAAmB;IAC7D,qBAAqB;IACrB,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;QACpB,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,QAAuC,CAAC,CAAC;QACpE,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACjC,OAAO,GAAG,CAAC;QACb,CAAC;IACH,CAAC;IAED,qCAAqC;IACrC,MAAM,SAAS,GAA2B;QACxC,SAAS,EAAE,mBAAmB;QAC9B,MAAM,EAAE,gBAAgB;QACxB,MAAM,EAAE,gBAAgB;KACzB,CAAC;IAEF,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IACjD,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACnC,IAAI,MAAM,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACvC,OAAO,MAAM,CAAC;QAChB,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,UAAU,CAAC,MAAkB,EAAE,UAAmB;IAChE,MAAM,UAAU,GAAG,UAAU,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,WAAW,CAAC,CAAC;IACvE,EAAE,CAAC,aAAa,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;AACzE,CAAC"} \ No newline at end of file +{"version":3,"file":"config-loader.js","sourceRoot":"","sources":["../../../src/cli/utils/config-loader.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO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G;AACH,MAAM,UAAU,SAAS,CAAC,QAAgB,EAAE,MAAmB;IAC7D,qBAAqB;IACrB,IAAI,MAAM,EAAE,OAAO,EAAE,CAAC;QACpB,MAAM,GAAG,GAAG,MAAM,CAAC,OAAO,CAAC,QAAuC,CAAC,CAAC;QACpE,IAAI,GAAG,IAAI,GAAG,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACjC,OAAO,GAAG,CAAC;QACb,CAAC;IACH,CAAC;IAED,qCAAqC;IACrC,MAAM,SAAS,GAA2B;QACxC,SAAS,EAAE,mBAAmB;QAC9B,MAAM,EAAE,gBAAgB;QACxB,MAAM,EAAE,gBAAgB;KACzB,CAAC;IAEF,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IACjD,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACnC,IAAI,MAAM,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACvC,OAAO,MAAM,CAAC;QAChB,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,UAAU,CAAC,MAAkB,EAAE,UAAmB;IAChE,MAAM,UAAU,GAAG,UAAU,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,WAAW,CAAC,CAAC;IACvE,EAAE,CAAC,aAAa,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;AACzE,CAAC"} \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index b2087ba..7dbb248 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,111 +1,124954 @@ -import { PRAnalyzerAgent } from './agents/pr-analyzer-agent.js'; -const provider = (process.env.AI_PROVIDER || 'anthropic').toLowerCase(); -const apiKey = process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY || process.env.GOOGLE_API_KEY; -const model = process.env.AI_MODEL; +import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module"; +/******/ var __webpack_modules__ = ({ + +/***/ 4914: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.issue = exports.issueCommand = void 0; +const os = __importStar(__nccwpck_require__(857)); +const utils_1 = __nccwpck_require__(302); +/** + * Commands + * + * Command Format: + * ::name key=value,key=value::message + * + * Examples: + * ::warning::This is the message + * ::set-env name=MY_VAR::some value + */ +function issueCommand(command, properties, message) { + const cmd = new Command(command, properties, message); + process.stdout.write(cmd.toString() + os.EOL); +} +exports.issueCommand = issueCommand; +function issue(name, message = '') { + issueCommand(name, {}, message); +} +exports.issue = issue; +const CMD_STRING = '::'; +class Command { + constructor(command, properties, message) { + if (!command) { + command = 'missing.command'; + } + this.command = command; + this.properties = properties; + this.message = message; + } + toString() { + let cmdStr = CMD_STRING + this.command; + if (this.properties && Object.keys(this.properties).length > 0) { + cmdStr += ' '; + let first = true; + for (const key in this.properties) { + if (this.properties.hasOwnProperty(key)) { + const val = this.properties[key]; + if (val) { + if (first) { + first = false; + } + else { + cmdStr += ','; + } + cmdStr += `${key}=${escapeProperty(val)}`; + } + } + } + } + cmdStr += `${CMD_STRING}${escapeData(this.message)}`; + return cmdStr; + } +} +function escapeData(s) { + return (0, utils_1.toCommandValue)(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A'); +} +function escapeProperty(s) { + return (0, utils_1.toCommandValue)(s) + .replace(/%/g, '%25') + .replace(/\r/g, '%0D') + .replace(/\n/g, '%0A') + .replace(/:/g, '%3A') + .replace(/,/g, '%2C'); +} +//# sourceMappingURL=command.js.map + +/***/ }), + +/***/ 7484: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; +const command_1 = __nccwpck_require__(4914); +const file_command_1 = __nccwpck_require__(4753); +const utils_1 = __nccwpck_require__(302); +const os = __importStar(__nccwpck_require__(857)); +const path = __importStar(__nccwpck_require__(6928)); +const oidc_utils_1 = __nccwpck_require__(5306); +/** + * The code to exit an action + */ +var ExitCode; +(function (ExitCode) { + /** + * A code indicating that the action was successful + */ + ExitCode[ExitCode["Success"] = 0] = "Success"; + /** + * A code indicating that the action was a failure + */ + ExitCode[ExitCode["Failure"] = 1] = "Failure"; +})(ExitCode || (exports.ExitCode = ExitCode = {})); +//----------------------------------------------------------------------- +// Variables +//----------------------------------------------------------------------- +/** + * Sets env variable for this action and future actions in the job + * @param name the name of the variable to set + * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function exportVariable(name, val) { + const convertedVal = (0, utils_1.toCommandValue)(val); + process.env[name] = convertedVal; + const filePath = process.env['GITHUB_ENV'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); + } + (0, command_1.issueCommand)('set-env', { name }, convertedVal); +} +exports.exportVariable = exportVariable; +/** + * Registers a secret which will get masked from logs + * @param secret value of the secret + */ +function setSecret(secret) { + (0, command_1.issueCommand)('add-mask', {}, secret); +} +exports.setSecret = setSecret; +/** + * Prepends inputPath to the PATH (for this action and future actions) + * @param inputPath + */ +function addPath(inputPath) { + const filePath = process.env['GITHUB_PATH'] || ''; + if (filePath) { + (0, file_command_1.issueFileCommand)('PATH', inputPath); + } + else { + (0, command_1.issueCommand)('add-path', {}, inputPath); + } + process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; +} +exports.addPath = addPath; +/** + * Gets the value of an input. + * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. + * Returns an empty string if the value is not defined. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string + */ +function getInput(name, options) { + const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; + if (options && options.required && !val) { + throw new Error(`Input required and not supplied: ${name}`); + } + if (options && options.trimWhitespace === false) { + return val; + } + return val.trim(); +} +exports.getInput = getInput; +/** + * Gets the values of an multiline input. Each value is also trimmed. + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns string[] + * + */ +function getMultilineInput(name, options) { + const inputs = getInput(name, options) + .split('\n') + .filter(x => x !== ''); + if (options && options.trimWhitespace === false) { + return inputs; + } + return inputs.map(input => input.trim()); +} +exports.getMultilineInput = getMultilineInput; +/** + * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. + * Support boolean input list: `true | True | TRUE | false | False | FALSE` . + * The return value is also in boolean type. + * ref: https://yaml.org/spec/1.2/spec.html#id2804923 + * + * @param name name of the input to get + * @param options optional. See InputOptions. + * @returns boolean + */ +function getBooleanInput(name, options) { + const trueValue = ['true', 'True', 'TRUE']; + const falseValue = ['false', 'False', 'FALSE']; + const val = getInput(name, options); + if (trueValue.includes(val)) + return true; + if (falseValue.includes(val)) + return false; + throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + + `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); +} +exports.getBooleanInput = getBooleanInput; +/** + * Sets the value of an output. + * + * @param name name of the output to set + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function setOutput(name, value) { + const filePath = process.env['GITHUB_OUTPUT'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } + process.stdout.write(os.EOL); + (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); +} +exports.setOutput = setOutput; +/** + * Enables or disables the echoing of commands into stdout for the rest of the step. + * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. + * + */ +function setCommandEcho(enabled) { + (0, command_1.issue)('echo', enabled ? 'on' : 'off'); +} +exports.setCommandEcho = setCommandEcho; +//----------------------------------------------------------------------- +// Results +//----------------------------------------------------------------------- +/** + * Sets the action status to failed. + * When the action exits it will be with an exit code of 1 + * @param message add error issue message + */ +function setFailed(message) { + process.exitCode = ExitCode.Failure; + error(message); +} +exports.setFailed = setFailed; +//----------------------------------------------------------------------- +// Logging Commands +//----------------------------------------------------------------------- +/** + * Gets whether Actions Step Debug is on or not + */ +function isDebug() { + return process.env['RUNNER_DEBUG'] === '1'; +} +exports.isDebug = isDebug; +/** + * Writes debug message to user log + * @param message debug message + */ +function debug(message) { + (0, command_1.issueCommand)('debug', {}, message); +} +exports.debug = debug; +/** + * Adds an error issue + * @param message error issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function error(message, properties = {}) { + (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.error = error; +/** + * Adds a warning issue + * @param message warning issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function warning(message, properties = {}) { + (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.warning = warning; +/** + * Adds a notice issue + * @param message notice issue message. Errors will be converted to string via toString() + * @param properties optional properties to add to the annotation. + */ +function notice(message, properties = {}) { + (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); +} +exports.notice = notice; +/** + * Writes info to log with console.log. + * @param message info message + */ +function info(message) { + process.stdout.write(message + os.EOL); +} +exports.info = info; +/** + * Begin an output group. + * + * Output until the next `groupEnd` will be foldable in this group + * + * @param name The name of the output group + */ +function startGroup(name) { + (0, command_1.issue)('group', name); +} +exports.startGroup = startGroup; +/** + * End an output group. + */ +function endGroup() { + (0, command_1.issue)('endgroup'); +} +exports.endGroup = endGroup; +/** + * Wrap an asynchronous function call in a group. + * + * Returns the same type as the function itself. + * + * @param name The name of the group + * @param fn The function to wrap in the group + */ +function group(name, fn) { + return __awaiter(this, void 0, void 0, function* () { + startGroup(name); + let result; + try { + result = yield fn(); + } + finally { + endGroup(); + } + return result; + }); +} +exports.group = group; +//----------------------------------------------------------------------- +// Wrapper action state +//----------------------------------------------------------------------- +/** + * Saves state for current action, the state can only be retrieved by this action's post job execution. + * + * @param name name of the state to store + * @param value value to store. Non-string values will be converted to a string via JSON.stringify + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function saveState(name, value) { + const filePath = process.env['GITHUB_STATE'] || ''; + if (filePath) { + return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); + } + (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); +} +exports.saveState = saveState; +/** + * Gets the value of an state set by this action's main execution. + * + * @param name name of the state to get + * @returns string + */ +function getState(name) { + return process.env[`STATE_${name}`] || ''; +} +exports.getState = getState; +function getIDToken(aud) { + return __awaiter(this, void 0, void 0, function* () { + return yield oidc_utils_1.OidcClient.getIDToken(aud); + }); +} +exports.getIDToken = getIDToken; +/** + * Summary exports + */ +var summary_1 = __nccwpck_require__(1847); +Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); +/** + * @deprecated use core.summary + */ +var summary_2 = __nccwpck_require__(1847); +Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); +/** + * Path exports + */ +var path_utils_1 = __nccwpck_require__(1976); +Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); +Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); +Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); +/** + * Platform utilities exports + */ +exports.platform = __importStar(__nccwpck_require__(8968)); +//# sourceMappingURL=core.js.map + +/***/ }), + +/***/ 4753: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +// For internal use, subject to change. +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +const crypto = __importStar(__nccwpck_require__(6982)); +const fs = __importStar(__nccwpck_require__(9896)); +const os = __importStar(__nccwpck_require__(857)); +const utils_1 = __nccwpck_require__(302); +function issueFileCommand(command, message) { + const filePath = process.env[`GITHUB_${command}`]; + if (!filePath) { + throw new Error(`Unable to find environment variable for file command ${command}`); + } + if (!fs.existsSync(filePath)) { + throw new Error(`Missing file at path: ${filePath}`); + } + fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { + encoding: 'utf8' + }); +} +exports.issueFileCommand = issueFileCommand; +function prepareKeyValueMessage(key, value) { + const delimiter = `ghadelimiter_${crypto.randomUUID()}`; + const convertedValue = (0, utils_1.toCommandValue)(value); + // These should realistically never happen, but just in case someone finds a + // way to exploit uuid generation let's not allow keys or values that contain + // the delimiter. + if (key.includes(delimiter)) { + throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); + } + if (convertedValue.includes(delimiter)) { + throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); + } + return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; +} +exports.prepareKeyValueMessage = prepareKeyValueMessage; +//# sourceMappingURL=file-command.js.map + +/***/ }), + +/***/ 5306: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.OidcClient = void 0; +const http_client_1 = __nccwpck_require__(4844); +const auth_1 = __nccwpck_require__(4552); +const core_1 = __nccwpck_require__(7484); +class OidcClient { + static createHttpClient(allowRetry = true, maxRetry = 10) { + const requestOptions = { + allowRetries: allowRetry, + maxRetries: maxRetry + }; + return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); + } + static getRequestToken() { + const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; + if (!token) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); + } + return token; + } + static getIDTokenUrl() { + const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; + if (!runtimeUrl) { + throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); + } + return runtimeUrl; + } + static getCall(id_token_url) { + var _a; + return __awaiter(this, void 0, void 0, function* () { + const httpclient = OidcClient.createHttpClient(); + const res = yield httpclient + .getJson(id_token_url) + .catch(error => { + throw new Error(`Failed to get ID Token. \n + Error Code : ${error.statusCode}\n + Error Message: ${error.message}`); + }); + const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; + if (!id_token) { + throw new Error('Response json body do not have ID Token field'); + } + return id_token; + }); + } + static getIDToken(audience) { + return __awaiter(this, void 0, void 0, function* () { + try { + // New ID Token is requested from action service + let id_token_url = OidcClient.getIDTokenUrl(); + if (audience) { + const encodedAudience = encodeURIComponent(audience); + id_token_url = `${id_token_url}&audience=${encodedAudience}`; + } + (0, core_1.debug)(`ID token url is ${id_token_url}`); + const id_token = yield OidcClient.getCall(id_token_url); + (0, core_1.setSecret)(id_token); + return id_token; + } + catch (error) { + throw new Error(`Error message: ${error.message}`); + } + }); + } +} +exports.OidcClient = OidcClient; +//# sourceMappingURL=oidc-utils.js.map + +/***/ }), + +/***/ 1976: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; +const path = __importStar(__nccwpck_require__(6928)); +/** + * toPosixPath converts the given path to the posix form. On Windows, \\ will be + * replaced with /. + * + * @param pth. Path to transform. + * @return string Posix path. + */ +function toPosixPath(pth) { + return pth.replace(/[\\]/g, '/'); +} +exports.toPosixPath = toPosixPath; +/** + * toWin32Path converts the given path to the win32 form. On Linux, / will be + * replaced with \\. + * + * @param pth. Path to transform. + * @return string Win32 path. + */ +function toWin32Path(pth) { + return pth.replace(/[/]/g, '\\'); +} +exports.toWin32Path = toWin32Path; +/** + * toPlatformPath converts the given path to a platform-specific path. It does + * this by replacing instances of / and \ with the platform-specific path + * separator. + * + * @param pth The path to platformize. + * @return string The platform-specific path. + */ +function toPlatformPath(pth) { + return pth.replace(/[/\\]/g, path.sep); +} +exports.toPlatformPath = toPlatformPath; +//# sourceMappingURL=path-utils.js.map + +/***/ }), + +/***/ 8968: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var __importDefault = (this && this.__importDefault) || function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; +const os_1 = __importDefault(__nccwpck_require__(857)); +const exec = __importStar(__nccwpck_require__(5236)); +const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { + silent: true + }); + const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { + silent: true + }); + return { + name: name.trim(), + version: version.trim() + }; +}); +const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { + var _a, _b, _c, _d; + const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { + silent: true + }); + const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; + const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; + return { + name, + version + }; +}); +const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { + const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { + silent: true + }); + const [name, version] = stdout.trim().split('\n'); + return { + name, + version + }; +}); +exports.platform = os_1.default.platform(); +exports.arch = os_1.default.arch(); +exports.isWindows = exports.platform === 'win32'; +exports.isMacOS = exports.platform === 'darwin'; +exports.isLinux = exports.platform === 'linux'; +function getDetails() { + return __awaiter(this, void 0, void 0, function* () { + return Object.assign(Object.assign({}, (yield (exports.isWindows + ? getWindowsInfo() + : exports.isMacOS + ? getMacOsInfo() + : getLinuxInfo()))), { platform: exports.platform, + arch: exports.arch, + isWindows: exports.isWindows, + isMacOS: exports.isMacOS, + isLinux: exports.isLinux }); + }); +} +exports.getDetails = getDetails; +//# sourceMappingURL=platform.js.map + +/***/ }), + +/***/ 1847: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; +const os_1 = __nccwpck_require__(857); +const fs_1 = __nccwpck_require__(9896); +const { access, appendFile, writeFile } = fs_1.promises; +exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; +exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; +class Summary { + constructor() { + this._buffer = ''; + } + /** + * Finds the summary file path from the environment, rejects if env var is not found or file does not exist + * Also checks r/w permissions. + * + * @returns step summary file path + */ + filePath() { + return __awaiter(this, void 0, void 0, function* () { + if (this._filePath) { + return this._filePath; + } + const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; + if (!pathFromEnv) { + throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); + } + try { + yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); + } + catch (_a) { + throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); + } + this._filePath = pathFromEnv; + return this._filePath; + }); + } + /** + * Wraps content in an HTML tag, adding any HTML attributes + * + * @param {string} tag HTML tag to wrap + * @param {string | null} content content within the tag + * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add + * + * @returns {string} content wrapped in HTML element + */ + wrap(tag, content, attrs = {}) { + const htmlAttrs = Object.entries(attrs) + .map(([key, value]) => ` ${key}="${value}"`) + .join(''); + if (!content) { + return `<${tag}${htmlAttrs}>`; + } + return `<${tag}${htmlAttrs}>${content}`; + } + /** + * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. + * + * @param {SummaryWriteOptions} [options] (optional) options for write operation + * + * @returns {Promise} summary instance + */ + write(options) { + return __awaiter(this, void 0, void 0, function* () { + const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); + const filePath = yield this.filePath(); + const writeFunc = overwrite ? writeFile : appendFile; + yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); + return this.emptyBuffer(); + }); + } + /** + * Clears the summary buffer and wipes the summary file + * + * @returns {Summary} summary instance + */ + clear() { + return __awaiter(this, void 0, void 0, function* () { + return this.emptyBuffer().write({ overwrite: true }); + }); + } + /** + * Returns the current summary buffer as a string + * + * @returns {string} string of summary buffer + */ + stringify() { + return this._buffer; + } + /** + * If the summary buffer is empty + * + * @returns {boolen} true if the buffer is empty + */ + isEmptyBuffer() { + return this._buffer.length === 0; + } + /** + * Resets the summary buffer without writing to summary file + * + * @returns {Summary} summary instance + */ + emptyBuffer() { + this._buffer = ''; + return this; + } + /** + * Adds raw text to the summary buffer + * + * @param {string} text content to add + * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) + * + * @returns {Summary} summary instance + */ + addRaw(text, addEOL = false) { + this._buffer += text; + return addEOL ? this.addEOL() : this; + } + /** + * Adds the operating system-specific end-of-line marker to the buffer + * + * @returns {Summary} summary instance + */ + addEOL() { + return this.addRaw(os_1.EOL); + } + /** + * Adds an HTML codeblock to the summary buffer + * + * @param {string} code content to render within fenced code block + * @param {string} lang (optional) language to syntax highlight code + * + * @returns {Summary} summary instance + */ + addCodeBlock(code, lang) { + const attrs = Object.assign({}, (lang && { lang })); + const element = this.wrap('pre', this.wrap('code', code), attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML list to the summary buffer + * + * @param {string[]} items list of items to render + * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) + * + * @returns {Summary} summary instance + */ + addList(items, ordered = false) { + const tag = ordered ? 'ol' : 'ul'; + const listItems = items.map(item => this.wrap('li', item)).join(''); + const element = this.wrap(tag, listItems); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML table to the summary buffer + * + * @param {SummaryTableCell[]} rows table rows + * + * @returns {Summary} summary instance + */ + addTable(rows) { + const tableBody = rows + .map(row => { + const cells = row + .map(cell => { + if (typeof cell === 'string') { + return this.wrap('td', cell); + } + const { header, data, colspan, rowspan } = cell; + const tag = header ? 'th' : 'td'; + const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); + return this.wrap(tag, data, attrs); + }) + .join(''); + return this.wrap('tr', cells); + }) + .join(''); + const element = this.wrap('table', tableBody); + return this.addRaw(element).addEOL(); + } + /** + * Adds a collapsable HTML details element to the summary buffer + * + * @param {string} label text for the closed state + * @param {string} content collapsable content + * + * @returns {Summary} summary instance + */ + addDetails(label, content) { + const element = this.wrap('details', this.wrap('summary', label) + content); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML image tag to the summary buffer + * + * @param {string} src path to the image you to embed + * @param {string} alt text description of the image + * @param {SummaryImageOptions} options (optional) addition image attributes + * + * @returns {Summary} summary instance + */ + addImage(src, alt, options) { + const { width, height } = options || {}; + const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); + const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML section heading element + * + * @param {string} text heading text + * @param {number | string} [level=1] (optional) the heading level, default: 1 + * + * @returns {Summary} summary instance + */ + addHeading(text, level) { + const tag = `h${level}`; + const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) + ? tag + : 'h1'; + const element = this.wrap(allowedTag, text); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML thematic break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addSeparator() { + const element = this.wrap('hr', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML line break (
) to the summary buffer + * + * @returns {Summary} summary instance + */ + addBreak() { + const element = this.wrap('br', null); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML blockquote to the summary buffer + * + * @param {string} text quote text + * @param {string} cite (optional) citation url + * + * @returns {Summary} summary instance + */ + addQuote(text, cite) { + const attrs = Object.assign({}, (cite && { cite })); + const element = this.wrap('blockquote', text, attrs); + return this.addRaw(element).addEOL(); + } + /** + * Adds an HTML anchor tag to the summary buffer + * + * @param {string} text link text/content + * @param {string} href hyperlink + * + * @returns {Summary} summary instance + */ + addLink(text, href) { + const element = this.wrap('a', text, { href }); + return this.addRaw(element).addEOL(); + } +} +const _summary = new Summary(); +/** + * @deprecated use `core.summary` + */ +exports.markdownSummary = _summary; +exports.summary = _summary; +//# sourceMappingURL=summary.js.map + +/***/ }), + +/***/ 302: +/***/ ((__unused_webpack_module, exports) => { + + +// We use any as a valid input type +/* eslint-disable @typescript-eslint/no-explicit-any */ +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.toCommandProperties = exports.toCommandValue = void 0; +/** + * Sanitizes an input into a string so it can be passed into issueCommand safely + * @param input input to sanitize into a string + */ +function toCommandValue(input) { + if (input === null || input === undefined) { + return ''; + } + else if (typeof input === 'string' || input instanceof String) { + return input; + } + return JSON.stringify(input); +} +exports.toCommandValue = toCommandValue; +/** + * + * @param annotationProperties + * @returns The command properties to send with the actual annotation command + * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 + */ +function toCommandProperties(annotationProperties) { + if (!Object.keys(annotationProperties).length) { + return {}; + } + return { + title: annotationProperties.title, + file: annotationProperties.file, + line: annotationProperties.startLine, + endLine: annotationProperties.endLine, + col: annotationProperties.startColumn, + endColumn: annotationProperties.endColumn + }; +} +exports.toCommandProperties = toCommandProperties; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 5236: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getExecOutput = exports.exec = void 0; +const string_decoder_1 = __nccwpck_require__(3193); +const tr = __importStar(__nccwpck_require__(6665)); +/** + * Exec a command. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code + */ +function exec(commandLine, args, options) { + return __awaiter(this, void 0, void 0, function* () { + const commandArgs = tr.argStringToArray(commandLine); + if (commandArgs.length === 0) { + throw new Error(`Parameter 'commandLine' cannot be null or empty.`); + } + // Path to tool to execute should be first arg + const toolPath = commandArgs[0]; + args = commandArgs.slice(1).concat(args || []); + const runner = new tr.ToolRunner(toolPath, args, options); + return runner.exec(); + }); +} +exports.exec = exec; +/** + * Exec a command and get the output. + * Output will be streamed to the live console. + * Returns promise with the exit code and collected stdout and stderr + * + * @param commandLine command to execute (can include additional args). Must be correctly escaped. + * @param args optional arguments for tool. Escaping is handled by the lib. + * @param options optional exec options. See ExecOptions + * @returns Promise exit code, stdout, and stderr + */ +function getExecOutput(commandLine, args, options) { + var _a, _b; + return __awaiter(this, void 0, void 0, function* () { + let stdout = ''; + let stderr = ''; + //Using string decoder covers the case where a mult-byte character is split + const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); + const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); + const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; + const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; + const stdErrListener = (data) => { + stderr += stderrDecoder.write(data); + if (originalStdErrListener) { + originalStdErrListener(data); + } + }; + const stdOutListener = (data) => { + stdout += stdoutDecoder.write(data); + if (originalStdoutListener) { + originalStdoutListener(data); + } + }; + const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); + const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); + //flush any remaining characters + stdout += stdoutDecoder.end(); + stderr += stderrDecoder.end(); + return { + exitCode, + stdout, + stderr + }; + }); +} +exports.getExecOutput = getExecOutput; +//# sourceMappingURL=exec.js.map + +/***/ }), + +/***/ 6665: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.argStringToArray = exports.ToolRunner = void 0; +const os = __importStar(__nccwpck_require__(857)); +const events = __importStar(__nccwpck_require__(4434)); +const child = __importStar(__nccwpck_require__(5317)); +const path = __importStar(__nccwpck_require__(6928)); +const io = __importStar(__nccwpck_require__(4994)); +const ioUtil = __importStar(__nccwpck_require__(5207)); +const timers_1 = __nccwpck_require__(3557); +/* eslint-disable @typescript-eslint/unbound-method */ +const IS_WINDOWS = process.platform === 'win32'; +/* + * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. + */ +class ToolRunner extends events.EventEmitter { + constructor(toolPath, args, options) { + super(); + if (!toolPath) { + throw new Error("Parameter 'toolPath' cannot be null or empty."); + } + this.toolPath = toolPath; + this.args = args || []; + this.options = options || {}; + } + _debug(message) { + if (this.options.listeners && this.options.listeners.debug) { + this.options.listeners.debug(message); + } + } + _getCommandString(options, noPrefix) { + const toolPath = this._getSpawnFileName(); + const args = this._getSpawnArgs(options); + let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool + if (IS_WINDOWS) { + // Windows + cmd file + if (this._isCmdFile()) { + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } + } + // Windows + verbatim + else if (options.windowsVerbatimArguments) { + cmd += `"${toolPath}"`; + for (const a of args) { + cmd += ` ${a}`; + } + } + // Windows (regular) + else { + cmd += this._windowsQuoteCmdArg(toolPath); + for (const a of args) { + cmd += ` ${this._windowsQuoteCmdArg(a)}`; + } + } + } + else { + // OSX/Linux - this can likely be improved with some form of quoting. + // creating processes on Unix is fundamentally different than Windows. + // on Unix, execvp() takes an arg array. + cmd += toolPath; + for (const a of args) { + cmd += ` ${a}`; + } + } + return cmd; + } + _processLineBuffer(data, strBuffer, onLine) { + try { + let s = strBuffer + data.toString(); + let n = s.indexOf(os.EOL); + while (n > -1) { + const line = s.substring(0, n); + onLine(line); + // the rest of the string ... + s = s.substring(n + os.EOL.length); + n = s.indexOf(os.EOL); + } + return s; + } + catch (err) { + // streaming lines to console is best effort. Don't fail a build. + this._debug(`error processing line. Failed with error ${err}`); + return ''; + } + } + _getSpawnFileName() { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + return process.env['COMSPEC'] || 'cmd.exe'; + } + } + return this.toolPath; + } + _getSpawnArgs(options) { + if (IS_WINDOWS) { + if (this._isCmdFile()) { + let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; + for (const a of this.args) { + argline += ' '; + argline += options.windowsVerbatimArguments + ? a + : this._windowsQuoteCmdArg(a); + } + argline += '"'; + return [argline]; + } + } + return this.args; + } + _endsWith(str, end) { + return str.endsWith(end); + } + _isCmdFile() { + const upperToolPath = this.toolPath.toUpperCase(); + return (this._endsWith(upperToolPath, '.CMD') || + this._endsWith(upperToolPath, '.BAT')); + } + _windowsQuoteCmdArg(arg) { + // for .exe, apply the normal quoting rules that libuv applies + if (!this._isCmdFile()) { + return this._uvQuoteCmdArg(arg); + } + // otherwise apply quoting rules specific to the cmd.exe command line parser. + // the libuv rules are generic and are not designed specifically for cmd.exe + // command line parser. + // + // for a detailed description of the cmd.exe command line parser, refer to + // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 + // need quotes for empty arg + if (!arg) { + return '""'; + } + // determine whether the arg needs to be quoted + const cmdSpecialChars = [ + ' ', + '\t', + '&', + '(', + ')', + '[', + ']', + '{', + '}', + '^', + '=', + ';', + '!', + "'", + '+', + ',', + '`', + '~', + '|', + '<', + '>', + '"' + ]; + let needsQuotes = false; + for (const char of arg) { + if (cmdSpecialChars.some(x => x === char)) { + needsQuotes = true; + break; + } + } + // short-circuit if quotes not needed + if (!needsQuotes) { + return arg; + } + // the following quoting rules are very similar to the rules that by libuv applies. + // + // 1) wrap the string in quotes + // + // 2) double-up quotes - i.e. " => "" + // + // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately + // doesn't work well with a cmd.exe command line. + // + // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. + // for example, the command line: + // foo.exe "myarg:""my val""" + // is parsed by a .NET console app into an arg array: + // [ "myarg:\"my val\"" ] + // which is the same end result when applying libuv quoting rules. although the actual + // command line from libuv quoting rules would look like: + // foo.exe "myarg:\"my val\"" + // + // 3) double-up slashes that precede a quote, + // e.g. hello \world => "hello \world" + // hello\"world => "hello\\""world" + // hello\\"world => "hello\\\\""world" + // hello world\ => "hello world\\" + // + // technically this is not required for a cmd.exe command line, or the batch argument parser. + // the reasons for including this as a .cmd quoting rule are: + // + // a) this is optimized for the scenario where the argument is passed from the .cmd file to an + // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. + // + // b) it's what we've been doing previously (by deferring to node default behavior) and we + // haven't heard any complaints about that aspect. + // + // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be + // escaped when used on the command line directly - even though within a .cmd file % can be escaped + // by using %%. + // + // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts + // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. + // + // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would + // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the + // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args + // to an external program. + // + // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. + // % can be escaped within a .cmd file. + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; // double the slash + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '"'; // double the quote + } + else { + quoteHit = false; + } + } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); + } + _uvQuoteCmdArg(arg) { + // Tool runner wraps child_process.spawn() and needs to apply the same quoting as + // Node in certain cases where the undocumented spawn option windowsVerbatimArguments + // is used. + // + // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, + // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), + // pasting copyright notice from Node within this function: + // + // Copyright Joyent, Inc. and other Node contributors. All rights reserved. + // + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the "Software"), to + // deal in the Software without restriction, including without limitation the + // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + // sell copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // + // The above copyright notice and this permission notice shall be included in + // all copies or substantial portions of the Software. + // + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + // IN THE SOFTWARE. + if (!arg) { + // Need double quotation for empty argument + return '""'; + } + if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { + // No quotation needed + return arg; + } + if (!arg.includes('"') && !arg.includes('\\')) { + // No embedded double quotes or backslashes, so I can just wrap + // quote marks around the whole thing. + return `"${arg}"`; + } + // Expected input/output: + // input : hello"world + // output: "hello\"world" + // input : hello""world + // output: "hello\"\"world" + // input : hello\world + // output: hello\world + // input : hello\\world + // output: hello\\world + // input : hello\"world + // output: "hello\\\"world" + // input : hello\\"world + // output: "hello\\\\\"world" + // input : hello world\ + // output: "hello world\\" - note the comment in libuv actually reads "hello world\" + // but it appears the comment is wrong, it should be "hello world\\" + let reverse = '"'; + let quoteHit = true; + for (let i = arg.length; i > 0; i--) { + // walk the string in reverse + reverse += arg[i - 1]; + if (quoteHit && arg[i - 1] === '\\') { + reverse += '\\'; + } + else if (arg[i - 1] === '"') { + quoteHit = true; + reverse += '\\'; + } + else { + quoteHit = false; + } + } + reverse += '"'; + return reverse + .split('') + .reverse() + .join(''); + } + _cloneExecOptions(options) { + options = options || {}; + const result = { + cwd: options.cwd || process.cwd(), + env: options.env || process.env, + silent: options.silent || false, + windowsVerbatimArguments: options.windowsVerbatimArguments || false, + failOnStdErr: options.failOnStdErr || false, + ignoreReturnCode: options.ignoreReturnCode || false, + delay: options.delay || 10000 + }; + result.outStream = options.outStream || process.stdout; + result.errStream = options.errStream || process.stderr; + return result; + } + _getSpawnOptions(options, toolPath) { + options = options || {}; + const result = {}; + result.cwd = options.cwd; + result.env = options.env; + result['windowsVerbatimArguments'] = + options.windowsVerbatimArguments || this._isCmdFile(); + if (options.windowsVerbatimArguments) { + result.argv0 = `"${toolPath}"`; + } + return result; + } + /** + * Exec a tool. + * Output will be streamed to the live console. + * Returns promise with return code + * + * @param tool path to tool to exec + * @param options optional exec options. See ExecOptions + * @returns number + */ + exec() { + return __awaiter(this, void 0, void 0, function* () { + // root the tool path if it is unrooted and contains relative pathing + if (!ioUtil.isRooted(this.toolPath) && + (this.toolPath.includes('/') || + (IS_WINDOWS && this.toolPath.includes('\\')))) { + // prefer options.cwd if it is specified, however options.cwd may also need to be rooted + this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + } + // if the tool is only a file name, then resolve it from the PATH + // otherwise verify it exists (add extension on Windows if necessary) + this.toolPath = yield io.which(this.toolPath, true); + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + this._debug(`exec tool: ${this.toolPath}`); + this._debug('arguments:'); + for (const arg of this.args) { + this._debug(` ${arg}`); + } + const optionsNonNull = this._cloneExecOptions(this.options); + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); + } + const state = new ExecState(optionsNonNull, this.toolPath); + state.on('debug', (message) => { + this._debug(message); + }); + if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { + return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); + } + const fileName = this._getSpawnFileName(); + const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); + let stdbuffer = ''; + if (cp.stdout) { + cp.stdout.on('data', (data) => { + if (this.options.listeners && this.options.listeners.stdout) { + this.options.listeners.stdout(data); + } + if (!optionsNonNull.silent && optionsNonNull.outStream) { + optionsNonNull.outStream.write(data); + } + stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { + if (this.options.listeners && this.options.listeners.stdline) { + this.options.listeners.stdline(line); + } + }); + }); + } + let errbuffer = ''; + if (cp.stderr) { + cp.stderr.on('data', (data) => { + state.processStderr = true; + if (this.options.listeners && this.options.listeners.stderr) { + this.options.listeners.stderr(data); + } + if (!optionsNonNull.silent && + optionsNonNull.errStream && + optionsNonNull.outStream) { + const s = optionsNonNull.failOnStdErr + ? optionsNonNull.errStream + : optionsNonNull.outStream; + s.write(data); + } + errbuffer = this._processLineBuffer(data, errbuffer, (line) => { + if (this.options.listeners && this.options.listeners.errline) { + this.options.listeners.errline(line); + } + }); + }); + } + cp.on('error', (err) => { + state.processError = err.message; + state.processExited = true; + state.processClosed = true; + state.CheckComplete(); + }); + cp.on('exit', (code) => { + state.processExitCode = code; + state.processExited = true; + this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); + state.CheckComplete(); + }); + cp.on('close', (code) => { + state.processExitCode = code; + state.processExited = true; + state.processClosed = true; + this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); + state.CheckComplete(); + }); + state.on('done', (error, exitCode) => { + if (stdbuffer.length > 0) { + this.emit('stdline', stdbuffer); + } + if (errbuffer.length > 0) { + this.emit('errline', errbuffer); + } + cp.removeAllListeners(); + if (error) { + reject(error); + } + else { + resolve(exitCode); + } + }); + if (this.options.input) { + if (!cp.stdin) { + throw new Error('child process missing stdin'); + } + cp.stdin.end(this.options.input); + } + })); + }); + } +} +exports.ToolRunner = ToolRunner; +/** + * Convert an arg string to an array of args. Handles escaping + * + * @param argString string of arguments + * @returns string[] array of arguments + */ +function argStringToArray(argString) { + const args = []; + let inQuotes = false; + let escaped = false; + let arg = ''; + function append(c) { + // we only escape double quotes. + if (escaped && c !== '"') { + arg += '\\'; + } + arg += c; + escaped = false; + } + for (let i = 0; i < argString.length; i++) { + const c = argString.charAt(i); + if (c === '"') { + if (!escaped) { + inQuotes = !inQuotes; + } + else { + append(c); + } + continue; + } + if (c === '\\' && escaped) { + append(c); + continue; + } + if (c === '\\' && inQuotes) { + escaped = true; + continue; + } + if (c === ' ' && !inQuotes) { + if (arg.length > 0) { + args.push(arg); + arg = ''; + } + continue; + } + append(c); + } + if (arg.length > 0) { + args.push(arg.trim()); + } + return args; +} +exports.argStringToArray = argStringToArray; +class ExecState extends events.EventEmitter { + constructor(options, toolPath) { + super(); + this.processClosed = false; // tracks whether the process has exited and stdio is closed + this.processError = ''; + this.processExitCode = 0; + this.processExited = false; // tracks whether the process has exited + this.processStderr = false; // tracks whether stderr was written to + this.delay = 10000; // 10 seconds + this.done = false; + this.timeout = null; + if (!toolPath) { + throw new Error('toolPath must not be empty'); + } + this.options = options; + this.toolPath = toolPath; + if (options.delay) { + this.delay = options.delay; + } + } + CheckComplete() { + if (this.done) { + return; + } + if (this.processClosed) { + this._setResult(); + } + else if (this.processExited) { + this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); + } + } + _debug(message) { + this.emit('debug', message); + } + _setResult() { + // determine whether there is an error + let error; + if (this.processExited) { + if (this.processError) { + error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); + } + else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { + error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); + } + else if (this.processStderr && this.options.failOnStdErr) { + error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); + } + } + // clear the timeout + if (this.timeout) { + clearTimeout(this.timeout); + this.timeout = null; + } + this.done = true; + this.emit('done', error, this.processExitCode); + } + static HandleTimeout(state) { + if (state.done) { + return; + } + if (!state.processClosed && state.processExited) { + const message = `The STDIO streams did not close within ${state.delay / + 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; + state._debug(message); + } + state._setResult(); + } +} +//# sourceMappingURL=toolrunner.js.map + +/***/ }), + +/***/ 1648: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.Context = void 0; +const fs_1 = __nccwpck_require__(9896); +const os_1 = __nccwpck_require__(857); +class Context { + /** + * Hydrate the context from the environment + */ + constructor() { + var _a, _b, _c; + this.payload = {}; + if (process.env.GITHUB_EVENT_PATH) { + if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { + this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); + } + else { + const path = process.env.GITHUB_EVENT_PATH; + process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); + } + } + this.eventName = process.env.GITHUB_EVENT_NAME; + this.sha = process.env.GITHUB_SHA; + this.ref = process.env.GITHUB_REF; + this.workflow = process.env.GITHUB_WORKFLOW; + this.action = process.env.GITHUB_ACTION; + this.actor = process.env.GITHUB_ACTOR; + this.job = process.env.GITHUB_JOB; + this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); + this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); + this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); + this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; + this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; + this.graphqlUrl = + (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; + } + get issue() { + const payload = this.payload; + return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); + } + get repo() { + if (process.env.GITHUB_REPOSITORY) { + const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); + return { owner, repo }; + } + if (this.payload.repository) { + return { + owner: this.payload.repository.owner.login, + repo: this.payload.repository.name + }; + } + throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); + } +} +exports.Context = Context; +//# sourceMappingURL=context.js.map + +/***/ }), + +/***/ 3228: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokit = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(1648)); +const utils_1 = __nccwpck_require__(8006); +exports.context = new Context.Context(); +/** + * Returns a hydrated octokit ready to use for GitHub Actions + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokit(token, options, ...additionalPlugins) { + const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); + return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options)); +} +exports.getOctokit = getOctokit; +//# sourceMappingURL=github.js.map + +/***/ }), + +/***/ 5156: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0; +const httpClient = __importStar(__nccwpck_require__(4844)); +const undici_1 = __nccwpck_require__(6752); +function getAuthString(token, options) { + if (!token && !options.auth) { + throw new Error('Parameter token or opts.auth is required'); + } + else if (token && options.auth) { + throw new Error('Parameters token and opts.auth may not both be specified'); + } + return typeof options.auth === 'string' ? options.auth : `token ${token}`; +} +exports.getAuthString = getAuthString; +function getProxyAgent(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgent(destinationUrl); +} +exports.getProxyAgent = getProxyAgent; +function getProxyAgentDispatcher(destinationUrl) { + const hc = new httpClient.HttpClient(); + return hc.getAgentDispatcher(destinationUrl); +} +exports.getProxyAgentDispatcher = getProxyAgentDispatcher; +function getProxyFetch(destinationUrl) { + const httpDispatcher = getProxyAgentDispatcher(destinationUrl); + const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { + return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); + }); + return proxyFetch; +} +exports.getProxyFetch = getProxyFetch; +function getApiBaseUrl() { + return process.env['GITHUB_API_URL'] || 'https://api.github.com'; +} +exports.getApiBaseUrl = getApiBaseUrl; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 8006: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; +const Context = __importStar(__nccwpck_require__(1648)); +const Utils = __importStar(__nccwpck_require__(5156)); +// octokit + plugins +const core_1 = __nccwpck_require__(1897); +const plugin_rest_endpoint_methods_1 = __nccwpck_require__(4935); +const plugin_paginate_rest_1 = __nccwpck_require__(8082); +exports.context = new Context.Context(); +const baseUrl = Utils.getApiBaseUrl(); +exports.defaults = { + baseUrl, + request: { + agent: Utils.getProxyAgent(baseUrl), + fetch: Utils.getProxyFetch(baseUrl) + } +}; +exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); +/** + * Convience function to correctly format Octokit Options to pass into the constructor. + * + * @param token the repo PAT or GITHUB_TOKEN + * @param options other options to set + */ +function getOctokitOptions(token, options) { + const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller + // Auth + const auth = Utils.getAuthString(token, opts); + if (auth) { + opts.auth = auth; + } + return opts; +} +exports.getOctokitOptions = getOctokitOptions; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 4552: +/***/ (function(__unused_webpack_module, exports) { + + +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; +class BasicCredentialHandler { + constructor(username, password) { + this.username = username; + this.password = password; + } + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BasicCredentialHandler = BasicCredentialHandler; +class BearerCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Bearer ${this.token}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.BearerCredentialHandler = BearerCredentialHandler; +class PersonalAccessTokenCredentialHandler { + constructor(token) { + this.token = token; + } + // currently implements pre-authorization + // TODO: support preAuth = false where it hooks on 401 + prepareRequest(options) { + if (!options.headers) { + throw Error('The request has no headers'); + } + options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; + } + // This handler cannot handle 401 + canHandleAuthentication() { + return false; + } + handleAuthentication() { + return __awaiter(this, void 0, void 0, function* () { + throw new Error('not implemented'); + }); + } +} +exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; +//# sourceMappingURL=auth.js.map + +/***/ }), + +/***/ 4844: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +/* eslint-disable @typescript-eslint/no-explicit-any */ +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; +const http = __importStar(__nccwpck_require__(8611)); +const https = __importStar(__nccwpck_require__(5692)); +const pm = __importStar(__nccwpck_require__(4988)); +const tunnel = __importStar(__nccwpck_require__(770)); +const undici_1 = __nccwpck_require__(6752); +var HttpCodes; +(function (HttpCodes) { + HttpCodes[HttpCodes["OK"] = 200] = "OK"; + HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; + HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; + HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; + HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; + HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; + HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; + HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; + HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; + HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; + HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; + HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; + HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; + HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; + HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; + HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; + HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; + HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; + HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; + HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; + HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; + HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; + HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; + HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; + HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; + HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; + HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; +})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); +var Headers; +(function (Headers) { + Headers["Accept"] = "accept"; + Headers["ContentType"] = "content-type"; +})(Headers || (exports.Headers = Headers = {})); +var MediaTypes; +(function (MediaTypes) { + MediaTypes["ApplicationJson"] = "application/json"; +})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); +/** + * Returns the proxy URL, depending upon the supplied url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ +function getProxyUrl(serverUrl) { + const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); + return proxyUrl ? proxyUrl.href : ''; +} +exports.getProxyUrl = getProxyUrl; +const HttpRedirectCodes = [ + HttpCodes.MovedPermanently, + HttpCodes.ResourceMoved, + HttpCodes.SeeOther, + HttpCodes.TemporaryRedirect, + HttpCodes.PermanentRedirect +]; +const HttpResponseRetryCodes = [ + HttpCodes.BadGateway, + HttpCodes.ServiceUnavailable, + HttpCodes.GatewayTimeout +]; +const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; +const ExponentialBackoffCeiling = 10; +const ExponentialBackoffTimeSlice = 5; +class HttpClientError extends Error { + constructor(message, statusCode) { + super(message); + this.name = 'HttpClientError'; + this.statusCode = statusCode; + Object.setPrototypeOf(this, HttpClientError.prototype); + } +} +exports.HttpClientError = HttpClientError; +class HttpClientResponse { + constructor(message) { + this.message = message; + } + readBody() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + let output = Buffer.alloc(0); + this.message.on('data', (chunk) => { + output = Buffer.concat([output, chunk]); + }); + this.message.on('end', () => { + resolve(output.toString()); + }); + })); + }); + } + readBodyBuffer() { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { + const chunks = []; + this.message.on('data', (chunk) => { + chunks.push(chunk); + }); + this.message.on('end', () => { + resolve(Buffer.concat(chunks)); + }); + })); + }); + } +} +exports.HttpClientResponse = HttpClientResponse; +function isHttps(requestUrl) { + const parsedUrl = new URL(requestUrl); + return parsedUrl.protocol === 'https:'; +} +exports.isHttps = isHttps; +class HttpClient { + constructor(userAgent, handlers, requestOptions) { + this._ignoreSslError = false; + this._allowRedirects = true; + this._allowRedirectDowngrade = false; + this._maxRedirects = 50; + this._allowRetries = false; + this._maxRetries = 1; + this._keepAlive = false; + this._disposed = false; + this.userAgent = userAgent; + this.handlers = handlers || []; + this.requestOptions = requestOptions; + if (requestOptions) { + if (requestOptions.ignoreSslError != null) { + this._ignoreSslError = requestOptions.ignoreSslError; + } + this._socketTimeout = requestOptions.socketTimeout; + if (requestOptions.allowRedirects != null) { + this._allowRedirects = requestOptions.allowRedirects; + } + if (requestOptions.allowRedirectDowngrade != null) { + this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; + } + if (requestOptions.maxRedirects != null) { + this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); + } + if (requestOptions.keepAlive != null) { + this._keepAlive = requestOptions.keepAlive; + } + if (requestOptions.allowRetries != null) { + this._allowRetries = requestOptions.allowRetries; + } + if (requestOptions.maxRetries != null) { + this._maxRetries = requestOptions.maxRetries; + } + } + } + options(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); + }); + } + get(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('GET', requestUrl, null, additionalHeaders || {}); + }); + } + del(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('DELETE', requestUrl, null, additionalHeaders || {}); + }); + } + post(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('POST', requestUrl, data, additionalHeaders || {}); + }); + } + patch(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PATCH', requestUrl, data, additionalHeaders || {}); + }); + } + put(requestUrl, data, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('PUT', requestUrl, data, additionalHeaders || {}); + }); + } + head(requestUrl, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request('HEAD', requestUrl, null, additionalHeaders || {}); + }); + } + sendStream(verb, requestUrl, stream, additionalHeaders) { + return __awaiter(this, void 0, void 0, function* () { + return this.request(verb, requestUrl, stream, additionalHeaders); + }); + } + /** + * Gets a typed object from an endpoint + * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise + */ + getJson(requestUrl, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + const res = yield this.get(requestUrl, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + postJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.post(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + putJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.put(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + patchJson(requestUrl, obj, additionalHeaders = {}) { + return __awaiter(this, void 0, void 0, function* () { + const data = JSON.stringify(obj, null, 2); + additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); + additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); + const res = yield this.patch(requestUrl, data, additionalHeaders); + return this._processResponse(res, this.requestOptions); + }); + } + /** + * Makes a raw http request. + * All other methods such as get, post, patch, and request ultimately call this. + * Prefer get, del, post and patch + */ + request(verb, requestUrl, data, headers) { + return __awaiter(this, void 0, void 0, function* () { + if (this._disposed) { + throw new Error('Client has already been disposed.'); + } + const parsedUrl = new URL(requestUrl); + let info = this._prepareRequest(verb, parsedUrl, headers); + // Only perform retries on reads since writes may not be idempotent. + const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) + ? this._maxRetries + 1 + : 1; + let numTries = 0; + let response; + do { + response = yield this.requestRaw(info, data); + // Check if it's an authentication challenge + if (response && + response.message && + response.message.statusCode === HttpCodes.Unauthorized) { + let authenticationHandler; + for (const handler of this.handlers) { + if (handler.canHandleAuthentication(response)) { + authenticationHandler = handler; + break; + } + } + if (authenticationHandler) { + return authenticationHandler.handleAuthentication(this, info, data); + } + else { + // We have received an unauthorized response but have no handlers to handle it. + // Let the response return to the caller. + return response; + } + } + let redirectsRemaining = this._maxRedirects; + while (response.message.statusCode && + HttpRedirectCodes.includes(response.message.statusCode) && + this._allowRedirects && + redirectsRemaining > 0) { + const redirectUrl = response.message.headers['location']; + if (!redirectUrl) { + // if there's no location to redirect to, we won't + break; + } + const parsedRedirectUrl = new URL(redirectUrl); + if (parsedUrl.protocol === 'https:' && + parsedUrl.protocol !== parsedRedirectUrl.protocol && + !this._allowRedirectDowngrade) { + throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); + } + // we need to finish reading the response before reassigning response + // which will leak the open socket. + yield response.readBody(); + // strip authorization header if redirected to a different hostname + if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { + for (const header in headers) { + // header names are case insensitive + if (header.toLowerCase() === 'authorization') { + delete headers[header]; + } + } + } + // let's make the request with the new redirectUrl + info = this._prepareRequest(verb, parsedRedirectUrl, headers); + response = yield this.requestRaw(info, data); + redirectsRemaining--; + } + if (!response.message.statusCode || + !HttpResponseRetryCodes.includes(response.message.statusCode)) { + // If not a retry code, return immediately instead of retrying + return response; + } + numTries += 1; + if (numTries < maxTries) { + yield response.readBody(); + yield this._performExponentialBackoff(numTries); + } + } while (numTries < maxTries); + return response; + }); + } + /** + * Needs to be called if keepAlive is set to true in request options. + */ + dispose() { + if (this._agent) { + this._agent.destroy(); + } + this._disposed = true; + } + /** + * Raw request. + * @param info + * @param data + */ + requestRaw(info, data) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => { + function callbackForResult(err, res) { + if (err) { + reject(err); + } + else if (!res) { + // If `err` is not passed, then `res` must be passed. + reject(new Error('Unknown error')); + } + else { + resolve(res); + } + } + this.requestRawWithCallback(info, data, callbackForResult); + }); + }); + } + /** + * Raw request with callback. + * @param info + * @param data + * @param onResult + */ + requestRawWithCallback(info, data, onResult) { + if (typeof data === 'string') { + if (!info.options.headers) { + info.options.headers = {}; + } + info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); + } + let callbackCalled = false; + function handleResult(err, res) { + if (!callbackCalled) { + callbackCalled = true; + onResult(err, res); + } + } + const req = info.httpModule.request(info.options, (msg) => { + const res = new HttpClientResponse(msg); + handleResult(undefined, res); + }); + let socket; + req.on('socket', sock => { + socket = sock; + }); + // If we ever get disconnected, we want the socket to timeout eventually + req.setTimeout(this._socketTimeout || 3 * 60000, () => { + if (socket) { + socket.end(); + } + handleResult(new Error(`Request timeout: ${info.options.path}`)); + }); + req.on('error', function (err) { + // err has statusCode property + // res should have headers + handleResult(err); + }); + if (data && typeof data === 'string') { + req.write(data, 'utf8'); + } + if (data && typeof data !== 'string') { + data.on('close', function () { + req.end(); + }); + data.pipe(req); + } + else { + req.end(); + } + } + /** + * Gets an http agent. This function is useful when you need an http agent that handles + * routing through a proxy server - depending upon the url and proxy environment variables. + * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com + */ + getAgent(serverUrl) { + const parsedUrl = new URL(serverUrl); + return this._getAgent(parsedUrl); + } + getAgentDispatcher(serverUrl) { + const parsedUrl = new URL(serverUrl); + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (!useProxy) { + return; + } + return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); + } + _prepareRequest(method, requestUrl, headers) { + const info = {}; + info.parsedUrl = requestUrl; + const usingSsl = info.parsedUrl.protocol === 'https:'; + info.httpModule = usingSsl ? https : http; + const defaultPort = usingSsl ? 443 : 80; + info.options = {}; + info.options.host = info.parsedUrl.hostname; + info.options.port = info.parsedUrl.port + ? parseInt(info.parsedUrl.port) + : defaultPort; + info.options.path = + (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); + info.options.method = method; + info.options.headers = this._mergeHeaders(headers); + if (this.userAgent != null) { + info.options.headers['user-agent'] = this.userAgent; + } + info.options.agent = this._getAgent(info.parsedUrl); + // gives handlers an opportunity to participate + if (this.handlers) { + for (const handler of this.handlers) { + handler.prepareRequest(info.options); + } + } + return info; + } + _mergeHeaders(headers) { + if (this.requestOptions && this.requestOptions.headers) { + return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); + } + return lowercaseKeys(headers || {}); + } + _getExistingOrDefaultHeader(additionalHeaders, header, _default) { + let clientHeader; + if (this.requestOptions && this.requestOptions.headers) { + clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; + } + return additionalHeaders[header] || clientHeader || _default; + } + _getAgent(parsedUrl) { + let agent; + const proxyUrl = pm.getProxyUrl(parsedUrl); + const useProxy = proxyUrl && proxyUrl.hostname; + if (this._keepAlive && useProxy) { + agent = this._proxyAgent; + } + if (!useProxy) { + agent = this._agent; + } + // if agent is already assigned use that agent. + if (agent) { + return agent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + let maxSockets = 100; + if (this.requestOptions) { + maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; + } + // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. + if (proxyUrl && proxyUrl.hostname) { + const agentOptions = { + maxSockets, + keepAlive: this._keepAlive, + proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { + proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` + })), { host: proxyUrl.hostname, port: proxyUrl.port }) + }; + let tunnelAgent; + const overHttps = proxyUrl.protocol === 'https:'; + if (usingSsl) { + tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; + } + else { + tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; + } + agent = tunnelAgent(agentOptions); + this._proxyAgent = agent; + } + // if tunneling agent isn't assigned create a new agent + if (!agent) { + const options = { keepAlive: this._keepAlive, maxSockets }; + agent = usingSsl ? new https.Agent(options) : new http.Agent(options); + this._agent = agent; + } + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + agent.options = Object.assign(agent.options || {}, { + rejectUnauthorized: false + }); + } + return agent; + } + _getProxyAgentDispatcher(parsedUrl, proxyUrl) { + let proxyAgent; + if (this._keepAlive) { + proxyAgent = this._proxyAgentDispatcher; + } + // if agent is already assigned use that agent. + if (proxyAgent) { + return proxyAgent; + } + const usingSsl = parsedUrl.protocol === 'https:'; + proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { + token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` + }))); + this._proxyAgentDispatcher = proxyAgent; + if (usingSsl && this._ignoreSslError) { + // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process + // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options + // we have to cast it to any and change it directly + proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { + rejectUnauthorized: false + }); + } + return proxyAgent; + } + _performExponentialBackoff(retryNumber) { + return __awaiter(this, void 0, void 0, function* () { + retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); + const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); + return new Promise(resolve => setTimeout(() => resolve(), ms)); + }); + } + _processResponse(res, options) { + return __awaiter(this, void 0, void 0, function* () { + return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { + const statusCode = res.message.statusCode || 0; + const response = { + statusCode, + result: null, + headers: {} + }; + // not found leads to null obj returned + if (statusCode === HttpCodes.NotFound) { + resolve(response); + } + // get the result from the body + function dateTimeDeserializer(key, value) { + if (typeof value === 'string') { + const a = new Date(value); + if (!isNaN(a.valueOf())) { + return a; + } + } + return value; + } + let obj; + let contents; + try { + contents = yield res.readBody(); + if (contents && contents.length > 0) { + if (options && options.deserializeDates) { + obj = JSON.parse(contents, dateTimeDeserializer); + } + else { + obj = JSON.parse(contents); + } + response.result = obj; + } + response.headers = res.message.headers; + } + catch (err) { + // Invalid resource (contents not json); leaving result obj null + } + // note that 3xx redirects are handled by the http layer. + if (statusCode > 299) { + let msg; + // if exception/error in body, attempt to get better error + if (obj && obj.message) { + msg = obj.message; + } + else if (contents && contents.length > 0) { + // it may be the case that the exception is in the body message as string + msg = contents; + } + else { + msg = `Failed request: (${statusCode})`; + } + const err = new HttpClientError(msg, statusCode); + err.result = response.result; + reject(err); + } + else { + resolve(response); + } + })); + }); + } +} +exports.HttpClient = HttpClient; +const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); +//# sourceMappingURL=index.js.map + +/***/ }), + +/***/ 4988: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.checkBypass = exports.getProxyUrl = void 0; +function getProxyUrl(reqUrl) { + const usingSsl = reqUrl.protocol === 'https:'; + if (checkBypass(reqUrl)) { + return undefined; + } + const proxyVar = (() => { + if (usingSsl) { + return process.env['https_proxy'] || process.env['HTTPS_PROXY']; + } + else { + return process.env['http_proxy'] || process.env['HTTP_PROXY']; + } + })(); + if (proxyVar) { + try { + return new DecodedURL(proxyVar); + } + catch (_a) { + if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) + return new DecodedURL(`http://${proxyVar}`); + } + } + else { + return undefined; + } +} +exports.getProxyUrl = getProxyUrl; +function checkBypass(reqUrl) { + if (!reqUrl.hostname) { + return false; + } + const reqHost = reqUrl.hostname; + if (isLoopbackAddress(reqHost)) { + return true; + } + const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; + if (!noProxy) { + return false; + } + // Determine the request port + let reqPort; + if (reqUrl.port) { + reqPort = Number(reqUrl.port); + } + else if (reqUrl.protocol === 'http:') { + reqPort = 80; + } + else if (reqUrl.protocol === 'https:') { + reqPort = 443; + } + // Format the request hostname and hostname with port + const upperReqHosts = [reqUrl.hostname.toUpperCase()]; + if (typeof reqPort === 'number') { + upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); + } + // Compare request host against noproxy + for (const upperNoProxyItem of noProxy + .split(',') + .map(x => x.trim().toUpperCase()) + .filter(x => x)) { + if (upperNoProxyItem === '*' || + upperReqHosts.some(x => x === upperNoProxyItem || + x.endsWith(`.${upperNoProxyItem}`) || + (upperNoProxyItem.startsWith('.') && + x.endsWith(`${upperNoProxyItem}`)))) { + return true; + } + } + return false; +} +exports.checkBypass = checkBypass; +function isLoopbackAddress(host) { + const hostLower = host.toLowerCase(); + return (hostLower === 'localhost' || + hostLower.startsWith('127.') || + hostLower.startsWith('[::1]') || + hostLower.startsWith('[0:0:0:0:0:0:0:1]')); +} +class DecodedURL extends URL { + constructor(url, base) { + super(url, base); + this._decodedUsername = decodeURIComponent(super.username); + this._decodedPassword = decodeURIComponent(super.password); + } + get username() { + return this._decodedUsername; + } + get password() { + return this._decodedPassword; + } +} +//# sourceMappingURL=proxy.js.map + +/***/ }), + +/***/ 5207: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +var _a; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; +const fs = __importStar(__nccwpck_require__(9896)); +const path = __importStar(__nccwpck_require__(6928)); +_a = fs.promises +// export const {open} = 'fs' +, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; +// export const {open} = 'fs' +exports.IS_WINDOWS = process.platform === 'win32'; +// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 +exports.UV_FS_O_EXLOCK = 0x10000000; +exports.READONLY = fs.constants.O_RDONLY; +function exists(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + try { + yield exports.stat(fsPath); + } + catch (err) { + if (err.code === 'ENOENT') { + return false; + } + throw err; + } + return true; + }); +} +exports.exists = exists; +function isDirectory(fsPath, useStat = false) { + return __awaiter(this, void 0, void 0, function* () { + const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); + return stats.isDirectory(); + }); +} +exports.isDirectory = isDirectory; +/** + * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: + * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). + */ +function isRooted(p) { + p = normalizeSeparators(p); + if (!p) { + throw new Error('isRooted() parameter "p" cannot be empty'); + } + if (exports.IS_WINDOWS) { + return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello + ); // e.g. C: or C:\hello + } + return p.startsWith('/'); +} +exports.isRooted = isRooted; +/** + * Best effort attempt to determine whether a file exists and is executable. + * @param filePath file path to check + * @param extensions additional file extensions to try + * @return if file exists and is executable, returns the file path. otherwise empty string. + */ +function tryGetExecutablePath(filePath, extensions) { + return __awaiter(this, void 0, void 0, function* () { + let stats = undefined; + try { + // test file exists + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // on Windows, test for valid extension + const upperExt = path.extname(filePath).toUpperCase(); + if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { + return filePath; + } + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + // try each extension + const originalFilePath = filePath; + for (const extension of extensions) { + filePath = originalFilePath + extension; + stats = undefined; + try { + stats = yield exports.stat(filePath); + } + catch (err) { + if (err.code !== 'ENOENT') { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); + } + } + if (stats && stats.isFile()) { + if (exports.IS_WINDOWS) { + // preserve the case of the actual file (since an extension was appended) + try { + const directory = path.dirname(filePath); + const upperName = path.basename(filePath).toUpperCase(); + for (const actualName of yield exports.readdir(directory)) { + if (upperName === actualName.toUpperCase()) { + filePath = path.join(directory, actualName); + break; + } + } + } + catch (err) { + // eslint-disable-next-line no-console + console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); + } + return filePath; + } + else { + if (isUnixExecutable(stats)) { + return filePath; + } + } + } + } + return ''; + }); +} +exports.tryGetExecutablePath = tryGetExecutablePath; +function normalizeSeparators(p) { + p = p || ''; + if (exports.IS_WINDOWS) { + // convert slashes on Windows + p = p.replace(/\//g, '\\'); + // remove redundant slashes + return p.replace(/\\\\+/g, '\\'); + } + // remove redundant slashes + return p.replace(/\/\/+/g, '/'); +} +// on Mac/Linux, test the execute bit +// R W X R W X R W X +// 256 128 64 32 16 8 4 2 1 +function isUnixExecutable(stats) { + return ((stats.mode & 1) > 0 || + ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || + ((stats.mode & 64) > 0 && stats.uid === process.getuid())); +} +// Get the path of cmd.exe in windows +function getCmdPath() { + var _a; + return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; +} +exports.getCmdPath = getCmdPath; +//# sourceMappingURL=io-util.js.map + +/***/ }), + +/***/ 4994: +/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { + + +var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +})); +var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}); +var __importStar = (this && this.__importStar) || function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); + __setModuleDefault(result, mod); + return result; +}; +var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +}; +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; +const assert_1 = __nccwpck_require__(2613); +const path = __importStar(__nccwpck_require__(6928)); +const ioUtil = __importStar(__nccwpck_require__(5207)); +/** + * Copies a file or folder. + * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js + * + * @param source source path + * @param dest destination path + * @param options optional. See CopyOptions. + */ +function cp(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + const { force, recursive, copySourceDirectory } = readCopyOptions(options); + const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; + // Dest is an existing file, but not forcing + if (destStat && destStat.isFile() && !force) { + return; + } + // If dest is an existing directory, should copy inside. + const newDest = destStat && destStat.isDirectory() && copySourceDirectory + ? path.join(dest, path.basename(source)) + : dest; + if (!(yield ioUtil.exists(source))) { + throw new Error(`no such file or directory: ${source}`); + } + const sourceStat = yield ioUtil.stat(source); + if (sourceStat.isDirectory()) { + if (!recursive) { + throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); + } + else { + yield cpDirRecursive(source, newDest, 0, force); + } + } + else { + if (path.relative(source, newDest) === '') { + // a file cannot be copied to itself + throw new Error(`'${newDest}' and '${source}' are the same file`); + } + yield copyFile(source, newDest, force); + } + }); +} +exports.cp = cp; +/** + * Moves a path. + * + * @param source source path + * @param dest destination path + * @param options optional. See MoveOptions. + */ +function mv(source, dest, options = {}) { + return __awaiter(this, void 0, void 0, function* () { + if (yield ioUtil.exists(dest)) { + let destExists = true; + if (yield ioUtil.isDirectory(dest)) { + // If dest is directory copy src into dest + dest = path.join(dest, path.basename(source)); + destExists = yield ioUtil.exists(dest); + } + if (destExists) { + if (options.force == null || options.force) { + yield rmRF(dest); + } + else { + throw new Error('Destination already exists'); + } + } + } + yield mkdirP(path.dirname(dest)); + yield ioUtil.rename(source, dest); + }); +} +exports.mv = mv; +/** + * Remove a path recursively with force + * + * @param inputPath path to remove + */ +function rmRF(inputPath) { + return __awaiter(this, void 0, void 0, function* () { + if (ioUtil.IS_WINDOWS) { + // Check for invalid characters + // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file + if (/[*"<>|]/.test(inputPath)) { + throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); + } + } + try { + // note if path does not exist, error is silent + yield ioUtil.rm(inputPath, { + force: true, + maxRetries: 3, + recursive: true, + retryDelay: 300 + }); + } + catch (err) { + throw new Error(`File was unable to be removed ${err}`); + } + }); +} +exports.rmRF = rmRF; +/** + * Make a directory. Creates the full path with folders in between + * Will throw if it fails + * + * @param fsPath path to create + * @returns Promise + */ +function mkdirP(fsPath) { + return __awaiter(this, void 0, void 0, function* () { + assert_1.ok(fsPath, 'a path argument must be provided'); + yield ioUtil.mkdir(fsPath, { recursive: true }); + }); +} +exports.mkdirP = mkdirP; +/** + * Returns path of a tool had the tool actually been invoked. Resolves via paths. + * If you check and the tool does not exist, it will throw. + * + * @param tool name of the tool + * @param check whether to check if tool exists + * @returns Promise path to tool + */ +function which(tool, check) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + // recursive when check=true + if (check) { + const result = yield which(tool, false); + if (!result) { + if (ioUtil.IS_WINDOWS) { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); + } + else { + throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); + } + } + return result; + } + const matches = yield findInPath(tool); + if (matches && matches.length > 0) { + return matches[0]; + } + return ''; + }); +} +exports.which = which; +/** + * Returns a list of all occurrences of the given tool on the system path. + * + * @returns Promise the paths of the tool + */ +function findInPath(tool) { + return __awaiter(this, void 0, void 0, function* () { + if (!tool) { + throw new Error("parameter 'tool' is required"); + } + // build the list of extensions to try + const extensions = []; + if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { + for (const extension of process.env['PATHEXT'].split(path.delimiter)) { + if (extension) { + extensions.push(extension); + } + } + } + // if it's rooted, return it if exists. otherwise return empty. + if (ioUtil.isRooted(tool)) { + const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); + if (filePath) { + return [filePath]; + } + return []; + } + // if any path separators, return empty + if (tool.includes(path.sep)) { + return []; + } + // build the list of directories + // + // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, + // it feels like we should not do this. Checking the current directory seems like more of a use + // case of a shell, and the which() function exposed by the toolkit should strive for consistency + // across platforms. + const directories = []; + if (process.env.PATH) { + for (const p of process.env.PATH.split(path.delimiter)) { + if (p) { + directories.push(p); + } + } + } + // find all matches + const matches = []; + for (const directory of directories) { + const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); + if (filePath) { + matches.push(filePath); + } + } + return matches; + }); +} +exports.findInPath = findInPath; +function readCopyOptions(options) { + const force = options.force == null ? true : options.force; + const recursive = Boolean(options.recursive); + const copySourceDirectory = options.copySourceDirectory == null + ? true + : Boolean(options.copySourceDirectory); + return { force, recursive, copySourceDirectory }; +} +function cpDirRecursive(sourceDir, destDir, currentDepth, force) { + return __awaiter(this, void 0, void 0, function* () { + // Ensure there is not a run away recursive copy + if (currentDepth >= 255) + return; + currentDepth++; + yield mkdirP(destDir); + const files = yield ioUtil.readdir(sourceDir); + for (const fileName of files) { + const srcFile = `${sourceDir}/${fileName}`; + const destFile = `${destDir}/${fileName}`; + const srcFileStat = yield ioUtil.lstat(srcFile); + if (srcFileStat.isDirectory()) { + // Recurse + yield cpDirRecursive(srcFile, destFile, currentDepth, force); + } + else { + yield copyFile(srcFile, destFile, force); + } + } + // Change the mode for the newly created directory + yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); + }); +} +// Buffered file copy +function copyFile(srcFile, destFile, force) { + return __awaiter(this, void 0, void 0, function* () { + if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { + // unlink/re-link it + try { + yield ioUtil.lstat(destFile); + yield ioUtil.unlink(destFile); + } + catch (e) { + // Try to override file permission + if (e.code === 'EPERM') { + yield ioUtil.chmod(destFile, '0666'); + yield ioUtil.unlink(destFile); + } + // other errors = it doesn't exist, no work to do + } + // Copy over symlink + const symlinkFull = yield ioUtil.readlink(srcFile); + yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); + } + else if (!(yield ioUtil.exists(destFile)) || force) { + yield ioUtil.copyFile(srcFile, destFile); + } + }); +} +//# sourceMappingURL=io.js.map + +/***/ }), + +/***/ 7864: +/***/ ((module) => { + + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + createTokenAuth: () => createTokenAuth +}); +module.exports = __toCommonJS(dist_src_exports); + +// pkg/dist-src/auth.js +var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; +var REGEX_IS_INSTALLATION = /^ghs_/; +var REGEX_IS_USER_TO_SERVER = /^ghu_/; +async function auth(token) { + const isApp = token.split(/\./).length === 3; + const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); + const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); + const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; + return { + type: "token", + token, + tokenType + }; +} + +// pkg/dist-src/with-authorization-prefix.js +function withAuthorizationPrefix(token) { + if (token.split(/\./).length === 3) { + return `bearer ${token}`; + } + return `token ${token}`; +} + +// pkg/dist-src/hook.js +async function hook(token, request, route, parameters) { + const endpoint = request.endpoint.merge( + route, + parameters + ); + endpoint.headers.authorization = withAuthorizationPrefix(token); + return request(endpoint); +} + +// pkg/dist-src/index.js +var createTokenAuth = function createTokenAuth2(token) { + if (!token) { + throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); + } + if (typeof token !== "string") { + throw new Error( + "[@octokit/auth-token] Token passed to createTokenAuth is not a string" + ); + } + token = token.replace(/^(token|bearer) +/i, ""); + return Object.assign(auth.bind(null, token), { + hook: hook.bind(null, token) + }); +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 1897: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var index_exports = {}; +__export(index_exports, { + Octokit: () => Octokit +}); +module.exports = __toCommonJS(index_exports); +var import_universal_user_agent = __nccwpck_require__(3843); +var import_before_after_hook = __nccwpck_require__(2732); +var import_request = __nccwpck_require__(8636); +var import_graphql = __nccwpck_require__(7); +var import_auth_token = __nccwpck_require__(7864); + +// pkg/dist-src/version.js +var VERSION = "5.2.2"; + +// pkg/dist-src/index.js +var noop = () => { +}; +var consoleWarn = console.warn.bind(console); +var consoleError = console.error.bind(console); +function createLogger(logger = {}) { + if (typeof logger.debug !== "function") { + logger.debug = noop; + } + if (typeof logger.info !== "function") { + logger.info = noop; + } + if (typeof logger.warn !== "function") { + logger.warn = consoleWarn; + } + if (typeof logger.error !== "function") { + logger.error = consoleError; + } + return logger; +} +var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; +var Octokit = class { + static { + this.VERSION = VERSION; + } + static defaults(defaults) { + const OctokitWithDefaults = class extends this { + constructor(...args) { + const options = args[0] || {}; + if (typeof defaults === "function") { + super(defaults(options)); + return; + } + super( + Object.assign( + {}, + defaults, + options, + options.userAgent && defaults.userAgent ? { + userAgent: `${options.userAgent} ${defaults.userAgent}` + } : null + ) + ); + } + }; + return OctokitWithDefaults; + } + static { + this.plugins = []; + } + /** + * Attach a plugin (or many) to your Octokit instance. + * + * @example + * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) + */ + static plugin(...newPlugins) { + const currentPlugins = this.plugins; + const NewOctokit = class extends this { + static { + this.plugins = currentPlugins.concat( + newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) + ); + } + }; + return NewOctokit; + } + constructor(options = {}) { + const hook = new import_before_after_hook.Collection(); + const requestDefaults = { + baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl, + headers: {}, + request: Object.assign({}, options.request, { + // @ts-ignore internal usage only, no need to type + hook: hook.bind(null, "request") + }), + mediaType: { + previews: [], + format: "" + } + }; + requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; + if (options.baseUrl) { + requestDefaults.baseUrl = options.baseUrl; + } + if (options.previews) { + requestDefaults.mediaType.previews = options.previews; + } + if (options.timeZone) { + requestDefaults.headers["time-zone"] = options.timeZone; + } + this.request = import_request.request.defaults(requestDefaults); + this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); + this.log = createLogger(options.log); + this.hook = hook; + if (!options.authStrategy) { + if (!options.auth) { + this.auth = async () => ({ + type: "unauthenticated" + }); + } else { + const auth = (0, import_auth_token.createTokenAuth)(options.auth); + hook.wrap("request", auth.hook); + this.auth = auth; + } + } else { + const { authStrategy, ...otherOptions } = options; + const auth = authStrategy( + Object.assign( + { + request: this.request, + log: this.log, + // we pass the current octokit instance as well as its constructor options + // to allow for authentication strategies that return a new octokit instance + // that shares the same internal state as the current one. The original + // requirement for this was the "event-octokit" authentication strategy + // of https://github.com/probot/octokit-auth-probot. + octokit: this, + octokitOptions: otherOptions + }, + options.auth + ) + ); + hook.wrap("request", auth.hook); + this.auth = auth; + } + const classConstructor = this.constructor; + for (let i = 0; i < classConstructor.plugins.length; ++i) { + Object.assign(this, classConstructor.plugins[i](this, options)); + } + } +}; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 4471: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + endpoint: () => endpoint +}); +module.exports = __toCommonJS(dist_src_exports); + +// pkg/dist-src/defaults.js +var import_universal_user_agent = __nccwpck_require__(3843); + +// pkg/dist-src/version.js +var VERSION = "9.0.6"; + +// pkg/dist-src/defaults.js +var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; +var DEFAULTS = { + method: "GET", + baseUrl: "https://api.github.com", + headers: { + accept: "application/vnd.github.v3+json", + "user-agent": userAgent + }, + mediaType: { + format: "" + } +}; + +// pkg/dist-src/util/lowercase-keys.js +function lowercaseKeys(object) { + if (!object) { + return {}; + } + return Object.keys(object).reduce((newObj, key) => { + newObj[key.toLowerCase()] = object[key]; + return newObj; + }, {}); +} + +// pkg/dist-src/util/is-plain-object.js +function isPlainObject(value) { + if (typeof value !== "object" || value === null) + return false; + if (Object.prototype.toString.call(value) !== "[object Object]") + return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) + return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} + +// pkg/dist-src/util/merge-deep.js +function mergeDeep(defaults, options) { + const result = Object.assign({}, defaults); + Object.keys(options).forEach((key) => { + if (isPlainObject(options[key])) { + if (!(key in defaults)) + Object.assign(result, { [key]: options[key] }); + else + result[key] = mergeDeep(defaults[key], options[key]); + } else { + Object.assign(result, { [key]: options[key] }); + } + }); + return result; +} + +// pkg/dist-src/util/remove-undefined-properties.js +function removeUndefinedProperties(obj) { + for (const key in obj) { + if (obj[key] === void 0) { + delete obj[key]; + } + } + return obj; +} + +// pkg/dist-src/merge.js +function merge(defaults, route, options) { + if (typeof route === "string") { + let [method, url] = route.split(" "); + options = Object.assign(url ? { method, url } : { url: method }, options); + } else { + options = Object.assign({}, route); + } + options.headers = lowercaseKeys(options.headers); + removeUndefinedProperties(options); + removeUndefinedProperties(options.headers); + const mergedOptions = mergeDeep(defaults || {}, options); + if (options.url === "/graphql") { + if (defaults && defaults.mediaType.previews?.length) { + mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( + (preview) => !mergedOptions.mediaType.previews.includes(preview) + ).concat(mergedOptions.mediaType.previews); + } + mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); + } + return mergedOptions; +} + +// pkg/dist-src/util/add-query-parameters.js +function addQueryParameters(url, parameters) { + const separator = /\?/.test(url) ? "&" : "?"; + const names = Object.keys(parameters); + if (names.length === 0) { + return url; + } + return url + separator + names.map((name) => { + if (name === "q") { + return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); + } + return `${name}=${encodeURIComponent(parameters[name])}`; + }).join("&"); +} + +// pkg/dist-src/util/extract-url-variable-names.js +var urlVariableRegex = /\{[^{}}]+\}/g; +function removeNonChars(variableName) { + return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); +} + +// pkg/dist-src/util/omit.js +function omit(object, keysToOmit) { + const result = { __proto__: null }; + for (const key of Object.keys(object)) { + if (keysToOmit.indexOf(key) === -1) { + result[key] = object[key]; + } + } + return result; +} + +// pkg/dist-src/util/url-template.js +function encodeReserved(str) { + return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { + if (!/%[0-9A-Fa-f]/.test(part)) { + part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); + } + return part; + }).join(""); +} +function encodeUnreserved(str) { + return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { + return "%" + c.charCodeAt(0).toString(16).toUpperCase(); + }); +} +function encodeValue(operator, value, key) { + value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); + if (key) { + return encodeUnreserved(key) + "=" + value; + } else { + return value; + } +} +function isDefined(value) { + return value !== void 0 && value !== null; +} +function isKeyOperator(operator) { + return operator === ";" || operator === "&" || operator === "?"; +} +function getValues(context, operator, key, modifier) { + var value = context[key], result = []; + if (isDefined(value) && value !== "") { + if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { + value = value.toString(); + if (modifier && modifier !== "*") { + value = value.substring(0, parseInt(modifier, 10)); + } + result.push( + encodeValue(operator, value, isKeyOperator(operator) ? key : "") + ); + } else { + if (modifier === "*") { + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + result.push( + encodeValue(operator, value2, isKeyOperator(operator) ? key : "") + ); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + result.push(encodeValue(operator, value[k], k)); + } + }); + } + } else { + const tmp = []; + if (Array.isArray(value)) { + value.filter(isDefined).forEach(function(value2) { + tmp.push(encodeValue(operator, value2)); + }); + } else { + Object.keys(value).forEach(function(k) { + if (isDefined(value[k])) { + tmp.push(encodeUnreserved(k)); + tmp.push(encodeValue(operator, value[k].toString())); + } + }); + } + if (isKeyOperator(operator)) { + result.push(encodeUnreserved(key) + "=" + tmp.join(",")); + } else if (tmp.length !== 0) { + result.push(tmp.join(",")); + } + } + } + } else { + if (operator === ";") { + if (isDefined(value)) { + result.push(encodeUnreserved(key)); + } + } else if (value === "" && (operator === "&" || operator === "?")) { + result.push(encodeUnreserved(key) + "="); + } else if (value === "") { + result.push(""); + } + } + return result; +} +function parseUrl(template) { + return { + expand: expand.bind(null, template) + }; +} +function expand(template, context) { + var operators = ["+", "#", ".", "/", ";", "?", "&"]; + template = template.replace( + /\{([^\{\}]+)\}|([^\{\}]+)/g, + function(_, expression, literal) { + if (expression) { + let operator = ""; + const values = []; + if (operators.indexOf(expression.charAt(0)) !== -1) { + operator = expression.charAt(0); + expression = expression.substr(1); + } + expression.split(/,/g).forEach(function(variable) { + var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); + values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); + }); + if (operator && operator !== "+") { + var separator = ","; + if (operator === "?") { + separator = "&"; + } else if (operator !== "#") { + separator = operator; + } + return (values.length !== 0 ? operator : "") + values.join(separator); + } else { + return values.join(","); + } + } else { + return encodeReserved(literal); + } + } + ); + if (template === "/") { + return template; + } else { + return template.replace(/\/$/, ""); + } +} + +// pkg/dist-src/parse.js +function parse(options) { + let method = options.method.toUpperCase(); + let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); + let headers = Object.assign({}, options.headers); + let body; + let parameters = omit(options, [ + "method", + "baseUrl", + "url", + "headers", + "request", + "mediaType" + ]); + const urlVariableNames = extractUrlVariableNames(url); + url = parseUrl(url).expand(parameters); + if (!/^http/.test(url)) { + url = options.baseUrl + url; + } + const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); + const remainingParameters = omit(parameters, omittedParameters); + const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); + if (!isBinaryRequest) { + if (options.mediaType.format) { + headers.accept = headers.accept.split(/,/).map( + (format) => format.replace( + /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, + `application/vnd$1$2.${options.mediaType.format}` + ) + ).join(","); + } + if (url.endsWith("/graphql")) { + if (options.mediaType.previews?.length) { + const previewsFromAcceptHeader = headers.accept.match(/(? { + const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; + return `application/vnd.github.${preview}-preview${format}`; + }).join(","); + } + } + } + if (["GET", "HEAD"].includes(method)) { + url = addQueryParameters(url, remainingParameters); + } else { + if ("data" in remainingParameters) { + body = remainingParameters.data; + } else { + if (Object.keys(remainingParameters).length) { + body = remainingParameters; + } + } + } + if (!headers["content-type"] && typeof body !== "undefined") { + headers["content-type"] = "application/json; charset=utf-8"; + } + if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { + body = ""; + } + return Object.assign( + { method, url, headers }, + typeof body !== "undefined" ? { body } : null, + options.request ? { request: options.request } : null + ); +} + +// pkg/dist-src/endpoint-with-defaults.js +function endpointWithDefaults(defaults, route, options) { + return parse(merge(defaults, route, options)); +} + +// pkg/dist-src/with-defaults.js +function withDefaults(oldDefaults, newDefaults) { + const DEFAULTS2 = merge(oldDefaults, newDefaults); + const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); + return Object.assign(endpoint2, { + DEFAULTS: DEFAULTS2, + defaults: withDefaults.bind(null, DEFAULTS2), + merge: merge.bind(null, DEFAULTS2), + parse + }); +} + +// pkg/dist-src/index.js +var endpoint = withDefaults(null, DEFAULTS); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 7: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var index_exports = {}; +__export(index_exports, { + GraphqlResponseError: () => GraphqlResponseError, + graphql: () => graphql2, + withCustomRequest: () => withCustomRequest +}); +module.exports = __toCommonJS(index_exports); +var import_request3 = __nccwpck_require__(8636); +var import_universal_user_agent = __nccwpck_require__(3843); + +// pkg/dist-src/version.js +var VERSION = "7.1.1"; + +// pkg/dist-src/with-defaults.js +var import_request2 = __nccwpck_require__(8636); + +// pkg/dist-src/graphql.js +var import_request = __nccwpck_require__(8636); + +// pkg/dist-src/error.js +function _buildMessageForResponseErrors(data) { + return `Request failed due to following response errors: +` + data.errors.map((e) => ` - ${e.message}`).join("\n"); +} +var GraphqlResponseError = class extends Error { + constructor(request2, headers, response) { + super(_buildMessageForResponseErrors(response)); + this.request = request2; + this.headers = headers; + this.response = response; + this.name = "GraphqlResponseError"; + this.errors = response.errors; + this.data = response.data; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + } +}; + +// pkg/dist-src/graphql.js +var NON_VARIABLE_OPTIONS = [ + "method", + "baseUrl", + "url", + "headers", + "request", + "query", + "mediaType" +]; +var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; +var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; +function graphql(request2, query, options) { + if (options) { + if (typeof query === "string" && "query" in options) { + return Promise.reject( + new Error(`[@octokit/graphql] "query" cannot be used as variable name`) + ); + } + for (const key in options) { + if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; + return Promise.reject( + new Error( + `[@octokit/graphql] "${key}" cannot be used as variable name` + ) + ); + } + } + const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; + const requestOptions = Object.keys( + parsedOptions + ).reduce((result, key) => { + if (NON_VARIABLE_OPTIONS.includes(key)) { + result[key] = parsedOptions[key]; + return result; + } + if (!result.variables) { + result.variables = {}; + } + result.variables[key] = parsedOptions[key]; + return result; + }, {}); + const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; + if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { + requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); + } + return request2(requestOptions).then((response) => { + if (response.data.errors) { + const headers = {}; + for (const key of Object.keys(response.headers)) { + headers[key] = response.headers[key]; + } + throw new GraphqlResponseError( + requestOptions, + headers, + response.data + ); + } + return response.data.data; + }); +} + +// pkg/dist-src/with-defaults.js +function withDefaults(request2, newDefaults) { + const newRequest = request2.defaults(newDefaults); + const newApi = (query, options) => { + return graphql(newRequest, query, options); + }; + return Object.assign(newApi, { + defaults: withDefaults.bind(null, newRequest), + endpoint: newRequest.endpoint + }); +} + +// pkg/dist-src/index.js +var graphql2 = withDefaults(import_request3.request, { + headers: { + "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + }, + method: "POST", + url: "/graphql" +}); +function withCustomRequest(customRequest) { + return withDefaults(customRequest, { + method: "POST", + url: "/graphql" + }); +} +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 8082: +/***/ ((module) => { + + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + composePaginateRest: () => composePaginateRest, + isPaginatingEndpoint: () => isPaginatingEndpoint, + paginateRest: () => paginateRest, + paginatingEndpoints: () => paginatingEndpoints +}); +module.exports = __toCommonJS(dist_src_exports); + +// pkg/dist-src/version.js +var VERSION = "9.2.2"; + +// pkg/dist-src/normalize-paginated-list-response.js +function normalizePaginatedListResponse(response) { + if (!response.data) { + return { + ...response, + data: [] + }; + } + const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); + if (!responseNeedsNormalization) + return response; + const incompleteResults = response.data.incomplete_results; + const repositorySelection = response.data.repository_selection; + const totalCount = response.data.total_count; + delete response.data.incomplete_results; + delete response.data.repository_selection; + delete response.data.total_count; + const namespaceKey = Object.keys(response.data)[0]; + const data = response.data[namespaceKey]; + response.data = data; + if (typeof incompleteResults !== "undefined") { + response.data.incomplete_results = incompleteResults; + } + if (typeof repositorySelection !== "undefined") { + response.data.repository_selection = repositorySelection; + } + response.data.total_count = totalCount; + return response; +} + +// pkg/dist-src/iterator.js +function iterator(octokit, route, parameters) { + const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); + const requestMethod = typeof route === "function" ? route : octokit.request; + const method = options.method; + const headers = options.headers; + let url = options.url; + return { + [Symbol.asyncIterator]: () => ({ + async next() { + if (!url) + return { done: true }; + try { + const response = await requestMethod({ method, url, headers }); + const normalizedResponse = normalizePaginatedListResponse(response); + url = ((normalizedResponse.headers.link || "").match( + /<([^<>]+)>;\s*rel="next"/ + ) || [])[1]; + return { value: normalizedResponse }; + } catch (error) { + if (error.status !== 409) + throw error; + url = ""; + return { + value: { + status: 200, + headers: {}, + data: [] + } + }; + } + } + }) + }; +} + +// pkg/dist-src/paginate.js +function paginate(octokit, route, parameters, mapFn) { + if (typeof parameters === "function") { + mapFn = parameters; + parameters = void 0; + } + return gather( + octokit, + [], + iterator(octokit, route, parameters)[Symbol.asyncIterator](), + mapFn + ); +} +function gather(octokit, results, iterator2, mapFn) { + return iterator2.next().then((result) => { + if (result.done) { + return results; + } + let earlyExit = false; + function done() { + earlyExit = true; + } + results = results.concat( + mapFn ? mapFn(result.value, done) : result.value.data + ); + if (earlyExit) { + return results; + } + return gather(octokit, results, iterator2, mapFn); + }); +} + +// pkg/dist-src/compose-paginate.js +var composePaginateRest = Object.assign(paginate, { + iterator +}); + +// pkg/dist-src/generated/paginating-endpoints.js +var paginatingEndpoints = [ + "GET /advisories", + "GET /app/hook/deliveries", + "GET /app/installation-requests", + "GET /app/installations", + "GET /assignments/{assignment_id}/accepted_assignments", + "GET /classrooms", + "GET /classrooms/{classroom_id}/assignments", + "GET /enterprises/{enterprise}/dependabot/alerts", + "GET /enterprises/{enterprise}/secret-scanning/alerts", + "GET /events", + "GET /gists", + "GET /gists/public", + "GET /gists/starred", + "GET /gists/{gist_id}/comments", + "GET /gists/{gist_id}/commits", + "GET /gists/{gist_id}/forks", + "GET /installation/repositories", + "GET /issues", + "GET /licenses", + "GET /marketplace_listing/plans", + "GET /marketplace_listing/plans/{plan_id}/accounts", + "GET /marketplace_listing/stubbed/plans", + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", + "GET /networks/{owner}/{repo}/events", + "GET /notifications", + "GET /organizations", + "GET /orgs/{org}/actions/cache/usage-by-repository", + "GET /orgs/{org}/actions/permissions/repositories", + "GET /orgs/{org}/actions/runners", + "GET /orgs/{org}/actions/secrets", + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", + "GET /orgs/{org}/actions/variables", + "GET /orgs/{org}/actions/variables/{name}/repositories", + "GET /orgs/{org}/blocks", + "GET /orgs/{org}/code-scanning/alerts", + "GET /orgs/{org}/codespaces", + "GET /orgs/{org}/codespaces/secrets", + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", + "GET /orgs/{org}/copilot/billing/seats", + "GET /orgs/{org}/dependabot/alerts", + "GET /orgs/{org}/dependabot/secrets", + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", + "GET /orgs/{org}/events", + "GET /orgs/{org}/failed_invitations", + "GET /orgs/{org}/hooks", + "GET /orgs/{org}/hooks/{hook_id}/deliveries", + "GET /orgs/{org}/installations", + "GET /orgs/{org}/invitations", + "GET /orgs/{org}/invitations/{invitation_id}/teams", + "GET /orgs/{org}/issues", + "GET /orgs/{org}/members", + "GET /orgs/{org}/members/{username}/codespaces", + "GET /orgs/{org}/migrations", + "GET /orgs/{org}/migrations/{migration_id}/repositories", + "GET /orgs/{org}/organization-roles/{role_id}/teams", + "GET /orgs/{org}/organization-roles/{role_id}/users", + "GET /orgs/{org}/outside_collaborators", + "GET /orgs/{org}/packages", + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + "GET /orgs/{org}/personal-access-token-requests", + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", + "GET /orgs/{org}/personal-access-tokens", + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", + "GET /orgs/{org}/projects", + "GET /orgs/{org}/properties/values", + "GET /orgs/{org}/public_members", + "GET /orgs/{org}/repos", + "GET /orgs/{org}/rulesets", + "GET /orgs/{org}/rulesets/rule-suites", + "GET /orgs/{org}/secret-scanning/alerts", + "GET /orgs/{org}/security-advisories", + "GET /orgs/{org}/teams", + "GET /orgs/{org}/teams/{team_slug}/discussions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", + "GET /orgs/{org}/teams/{team_slug}/invitations", + "GET /orgs/{org}/teams/{team_slug}/members", + "GET /orgs/{org}/teams/{team_slug}/projects", + "GET /orgs/{org}/teams/{team_slug}/repos", + "GET /orgs/{org}/teams/{team_slug}/teams", + "GET /projects/columns/{column_id}/cards", + "GET /projects/{project_id}/collaborators", + "GET /projects/{project_id}/columns", + "GET /repos/{owner}/{repo}/actions/artifacts", + "GET /repos/{owner}/{repo}/actions/caches", + "GET /repos/{owner}/{repo}/actions/organization-secrets", + "GET /repos/{owner}/{repo}/actions/organization-variables", + "GET /repos/{owner}/{repo}/actions/runners", + "GET /repos/{owner}/{repo}/actions/runs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", + "GET /repos/{owner}/{repo}/actions/secrets", + "GET /repos/{owner}/{repo}/actions/variables", + "GET /repos/{owner}/{repo}/actions/workflows", + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", + "GET /repos/{owner}/{repo}/activity", + "GET /repos/{owner}/{repo}/assignees", + "GET /repos/{owner}/{repo}/branches", + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", + "GET /repos/{owner}/{repo}/code-scanning/alerts", + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + "GET /repos/{owner}/{repo}/code-scanning/analyses", + "GET /repos/{owner}/{repo}/codespaces", + "GET /repos/{owner}/{repo}/codespaces/devcontainers", + "GET /repos/{owner}/{repo}/codespaces/secrets", + "GET /repos/{owner}/{repo}/collaborators", + "GET /repos/{owner}/{repo}/comments", + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/commits", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", + "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", + "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", + "GET /repos/{owner}/{repo}/commits/{ref}/status", + "GET /repos/{owner}/{repo}/commits/{ref}/statuses", + "GET /repos/{owner}/{repo}/contributors", + "GET /repos/{owner}/{repo}/dependabot/alerts", + "GET /repos/{owner}/{repo}/dependabot/secrets", + "GET /repos/{owner}/{repo}/deployments", + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", + "GET /repos/{owner}/{repo}/environments", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", + "GET /repos/{owner}/{repo}/events", + "GET /repos/{owner}/{repo}/forks", + "GET /repos/{owner}/{repo}/hooks", + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", + "GET /repos/{owner}/{repo}/invitations", + "GET /repos/{owner}/{repo}/issues", + "GET /repos/{owner}/{repo}/issues/comments", + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/issues/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", + "GET /repos/{owner}/{repo}/issues/{issue_number}/events", + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", + "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", + "GET /repos/{owner}/{repo}/keys", + "GET /repos/{owner}/{repo}/labels", + "GET /repos/{owner}/{repo}/milestones", + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", + "GET /repos/{owner}/{repo}/notifications", + "GET /repos/{owner}/{repo}/pages/builds", + "GET /repos/{owner}/{repo}/projects", + "GET /repos/{owner}/{repo}/pulls", + "GET /repos/{owner}/{repo}/pulls/comments", + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", + "GET /repos/{owner}/{repo}/releases", + "GET /repos/{owner}/{repo}/releases/{release_id}/assets", + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", + "GET /repos/{owner}/{repo}/rules/branches/{branch}", + "GET /repos/{owner}/{repo}/rulesets", + "GET /repos/{owner}/{repo}/rulesets/rule-suites", + "GET /repos/{owner}/{repo}/secret-scanning/alerts", + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", + "GET /repos/{owner}/{repo}/security-advisories", + "GET /repos/{owner}/{repo}/stargazers", + "GET /repos/{owner}/{repo}/subscribers", + "GET /repos/{owner}/{repo}/tags", + "GET /repos/{owner}/{repo}/teams", + "GET /repos/{owner}/{repo}/topics", + "GET /repositories", + "GET /repositories/{repository_id}/environments/{environment_name}/secrets", + "GET /repositories/{repository_id}/environments/{environment_name}/variables", + "GET /search/code", + "GET /search/commits", + "GET /search/issues", + "GET /search/labels", + "GET /search/repositories", + "GET /search/topics", + "GET /search/users", + "GET /teams/{team_id}/discussions", + "GET /teams/{team_id}/discussions/{discussion_number}/comments", + "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", + "GET /teams/{team_id}/discussions/{discussion_number}/reactions", + "GET /teams/{team_id}/invitations", + "GET /teams/{team_id}/members", + "GET /teams/{team_id}/projects", + "GET /teams/{team_id}/repos", + "GET /teams/{team_id}/teams", + "GET /user/blocks", + "GET /user/codespaces", + "GET /user/codespaces/secrets", + "GET /user/emails", + "GET /user/followers", + "GET /user/following", + "GET /user/gpg_keys", + "GET /user/installations", + "GET /user/installations/{installation_id}/repositories", + "GET /user/issues", + "GET /user/keys", + "GET /user/marketplace_purchases", + "GET /user/marketplace_purchases/stubbed", + "GET /user/memberships/orgs", + "GET /user/migrations", + "GET /user/migrations/{migration_id}/repositories", + "GET /user/orgs", + "GET /user/packages", + "GET /user/packages/{package_type}/{package_name}/versions", + "GET /user/public_emails", + "GET /user/repos", + "GET /user/repository_invitations", + "GET /user/social_accounts", + "GET /user/ssh_signing_keys", + "GET /user/starred", + "GET /user/subscriptions", + "GET /user/teams", + "GET /users", + "GET /users/{username}/events", + "GET /users/{username}/events/orgs/{org}", + "GET /users/{username}/events/public", + "GET /users/{username}/followers", + "GET /users/{username}/following", + "GET /users/{username}/gists", + "GET /users/{username}/gpg_keys", + "GET /users/{username}/keys", + "GET /users/{username}/orgs", + "GET /users/{username}/packages", + "GET /users/{username}/projects", + "GET /users/{username}/received_events", + "GET /users/{username}/received_events/public", + "GET /users/{username}/repos", + "GET /users/{username}/social_accounts", + "GET /users/{username}/ssh_signing_keys", + "GET /users/{username}/starred", + "GET /users/{username}/subscriptions" +]; + +// pkg/dist-src/paginating-endpoints.js +function isPaginatingEndpoint(arg) { + if (typeof arg === "string") { + return paginatingEndpoints.includes(arg); + } else { + return false; + } +} + +// pkg/dist-src/index.js +function paginateRest(octokit) { + return { + paginate: Object.assign(paginate.bind(null, octokit), { + iterator: iterator.bind(null, octokit) + }) + }; +} +paginateRest.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 4935: +/***/ ((module) => { + + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + legacyRestEndpointMethods: () => legacyRestEndpointMethods, + restEndpointMethods: () => restEndpointMethods +}); +module.exports = __toCommonJS(dist_src_exports); + +// pkg/dist-src/version.js +var VERSION = "10.4.1"; + +// pkg/dist-src/generated/endpoints.js +var Endpoints = { + actions: { + addCustomLabelsToSelfHostedRunnerForOrg: [ + "POST /orgs/{org}/actions/runners/{runner_id}/labels" + ], + addCustomLabelsToSelfHostedRunnerForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + approveWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" + ], + cancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" + ], + createEnvironmentVariable: [ + "POST /repositories/{repository_id}/environments/{environment_name}/variables" + ], + createOrUpdateEnvironmentSecret: [ + "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + createOrgVariable: ["POST /orgs/{org}/actions/variables"], + createRegistrationTokenForOrg: [ + "POST /orgs/{org}/actions/runners/registration-token" + ], + createRegistrationTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/registration-token" + ], + createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], + createRemoveTokenForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/remove-token" + ], + createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], + createWorkflowDispatch: [ + "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" + ], + deleteActionsCacheById: [ + "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" + ], + deleteActionsCacheByKey: [ + "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" + ], + deleteArtifact: [ + "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" + ], + deleteEnvironmentSecret: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + deleteEnvironmentVariable: [ + "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], + deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" + ], + deleteRepoVariable: [ + "DELETE /repos/{owner}/{repo}/actions/variables/{name}" + ], + deleteSelfHostedRunnerFromOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}" + ], + deleteSelfHostedRunnerFromRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], + deleteWorkflowRunLogs: [ + "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + disableSelectedRepositoryGithubActionsOrganization: [ + "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + disableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" + ], + downloadArtifact: [ + "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" + ], + downloadJobLogsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" + ], + downloadWorkflowRunAttemptLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" + ], + downloadWorkflowRunLogs: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" + ], + enableSelectedRepositoryGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" + ], + enableWorkflow: [ + "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" + ], + forceCancelWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" + ], + generateRunnerJitconfigForOrg: [ + "POST /orgs/{org}/actions/runners/generate-jitconfig" + ], + generateRunnerJitconfigForRepo: [ + "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" + ], + getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], + getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], + getActionsCacheUsageByRepoForOrg: [ + "GET /orgs/{org}/actions/cache/usage-by-repository" + ], + getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], + getAllowedActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/selected-actions" + ], + getAllowedActionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], + getCustomOidcSubClaimForRepo: [ + "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + getEnvironmentPublicKey: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" + ], + getEnvironmentSecret: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" + ], + getEnvironmentVariable: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + getGithubActionsDefaultWorkflowPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions/workflow" + ], + getGithubActionsDefaultWorkflowPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/workflow" + ], + getGithubActionsPermissionsOrganization: [ + "GET /orgs/{org}/actions/permissions" + ], + getGithubActionsPermissionsRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions" + ], + getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], + getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], + getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], + getPendingDeploymentsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + getRepoPermissions: [ + "GET /repos/{owner}/{repo}/actions/permissions", + {}, + { renamed: ["actions", "getGithubActionsPermissionsRepository"] } + ], + getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], + getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], + getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], + getReviewsForRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" + ], + getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], + getSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" + ], + getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], + getWorkflowAccessToRepository: [ + "GET /repos/{owner}/{repo}/actions/permissions/access" + ], + getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], + getWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" + ], + getWorkflowRunUsage: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" + ], + getWorkflowUsage: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" + ], + listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], + listEnvironmentSecrets: [ + "GET /repositories/{repository_id}/environments/{environment_name}/secrets" + ], + listEnvironmentVariables: [ + "GET /repositories/{repository_id}/environments/{environment_name}/variables" + ], + listJobsForWorkflowRun: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" + ], + listJobsForWorkflowRunAttempt: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" + ], + listLabelsForSelfHostedRunnerForOrg: [ + "GET /orgs/{org}/actions/runners/{runner_id}/labels" + ], + listLabelsForSelfHostedRunnerForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], + listOrgVariables: ["GET /orgs/{org}/actions/variables"], + listRepoOrganizationSecrets: [ + "GET /repos/{owner}/{repo}/actions/organization-secrets" + ], + listRepoOrganizationVariables: [ + "GET /repos/{owner}/{repo}/actions/organization-variables" + ], + listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], + listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], + listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], + listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], + listRunnerApplicationsForRepo: [ + "GET /repos/{owner}/{repo}/actions/runners/downloads" + ], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + listSelectedReposForOrgVariable: [ + "GET /orgs/{org}/actions/variables/{name}/repositories" + ], + listSelectedRepositoriesEnabledGithubActionsOrganization: [ + "GET /orgs/{org}/actions/permissions/repositories" + ], + listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], + listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], + listWorkflowRunArtifacts: [ + "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" + ], + listWorkflowRuns: [ + "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" + ], + listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], + reRunJobForWorkflowRun: [ + "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" + ], + reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], + reRunWorkflowFailedJobs: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" + ], + removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" + ], + removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + removeCustomLabelFromSelfHostedRunnerForOrg: [ + "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" + ], + removeCustomLabelFromSelfHostedRunnerForRepo: [ + "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgVariable: [ + "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" + ], + reviewCustomGatesForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" + ], + reviewPendingDeploymentsForRun: [ + "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" + ], + setAllowedActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/selected-actions" + ], + setAllowedActionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" + ], + setCustomLabelsForSelfHostedRunnerForOrg: [ + "PUT /orgs/{org}/actions/runners/{runner_id}/labels" + ], + setCustomLabelsForSelfHostedRunnerForRepo: [ + "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" + ], + setCustomOidcSubClaimForRepo: [ + "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" + ], + setGithubActionsDefaultWorkflowPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/workflow" + ], + setGithubActionsDefaultWorkflowPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/workflow" + ], + setGithubActionsPermissionsOrganization: [ + "PUT /orgs/{org}/actions/permissions" + ], + setGithubActionsPermissionsRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgVariable: [ + "PUT /orgs/{org}/actions/variables/{name}/repositories" + ], + setSelectedRepositoriesEnabledGithubActionsOrganization: [ + "PUT /orgs/{org}/actions/permissions/repositories" + ], + setWorkflowAccessToRepository: [ + "PUT /repos/{owner}/{repo}/actions/permissions/access" + ], + updateEnvironmentVariable: [ + "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" + ], + updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], + updateRepoVariable: [ + "PATCH /repos/{owner}/{repo}/actions/variables/{name}" + ] + }, + activity: { + checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], + deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], + deleteThreadSubscription: [ + "DELETE /notifications/threads/{thread_id}/subscription" + ], + getFeeds: ["GET /feeds"], + getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], + getThread: ["GET /notifications/threads/{thread_id}"], + getThreadSubscriptionForAuthenticatedUser: [ + "GET /notifications/threads/{thread_id}/subscription" + ], + listEventsForAuthenticatedUser: ["GET /users/{username}/events"], + listNotificationsForAuthenticatedUser: ["GET /notifications"], + listOrgEventsForAuthenticatedUser: [ + "GET /users/{username}/events/orgs/{org}" + ], + listPublicEvents: ["GET /events"], + listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], + listPublicEventsForUser: ["GET /users/{username}/events/public"], + listPublicOrgEvents: ["GET /orgs/{org}/events"], + listReceivedEventsForUser: ["GET /users/{username}/received_events"], + listReceivedPublicEventsForUser: [ + "GET /users/{username}/received_events/public" + ], + listRepoEvents: ["GET /repos/{owner}/{repo}/events"], + listRepoNotificationsForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/notifications" + ], + listReposStarredByAuthenticatedUser: ["GET /user/starred"], + listReposStarredByUser: ["GET /users/{username}/starred"], + listReposWatchedByUser: ["GET /users/{username}/subscriptions"], + listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], + listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], + listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], + markNotificationsAsRead: ["PUT /notifications"], + markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], + markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], + markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], + setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], + setThreadSubscription: [ + "PUT /notifications/threads/{thread_id}/subscription" + ], + starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], + unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] + }, + apps: { + addRepoToInstallation: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } + ], + addRepoToInstallationForAuthenticatedUser: [ + "PUT /user/installations/{installation_id}/repositories/{repository_id}" + ], + checkToken: ["POST /applications/{client_id}/token"], + createFromManifest: ["POST /app-manifests/{code}/conversions"], + createInstallationAccessToken: [ + "POST /app/installations/{installation_id}/access_tokens" + ], + deleteAuthorization: ["DELETE /applications/{client_id}/grant"], + deleteInstallation: ["DELETE /app/installations/{installation_id}"], + deleteToken: ["DELETE /applications/{client_id}/token"], + getAuthenticated: ["GET /app"], + getBySlug: ["GET /apps/{app_slug}"], + getInstallation: ["GET /app/installations/{installation_id}"], + getOrgInstallation: ["GET /orgs/{org}/installation"], + getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], + getSubscriptionPlanForAccount: [ + "GET /marketplace_listing/accounts/{account_id}" + ], + getSubscriptionPlanForAccountStubbed: [ + "GET /marketplace_listing/stubbed/accounts/{account_id}" + ], + getUserInstallation: ["GET /users/{username}/installation"], + getWebhookConfigForApp: ["GET /app/hook/config"], + getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], + listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], + listAccountsForPlanStubbed: [ + "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" + ], + listInstallationReposForAuthenticatedUser: [ + "GET /user/installations/{installation_id}/repositories" + ], + listInstallationRequestsForAuthenticatedApp: [ + "GET /app/installation-requests" + ], + listInstallations: ["GET /app/installations"], + listInstallationsForAuthenticatedUser: ["GET /user/installations"], + listPlans: ["GET /marketplace_listing/plans"], + listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], + listReposAccessibleToInstallation: ["GET /installation/repositories"], + listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], + listSubscriptionsForAuthenticatedUserStubbed: [ + "GET /user/marketplace_purchases/stubbed" + ], + listWebhookDeliveries: ["GET /app/hook/deliveries"], + redeliverWebhookDelivery: [ + "POST /app/hook/deliveries/{delivery_id}/attempts" + ], + removeRepoFromInstallation: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}", + {}, + { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } + ], + removeRepoFromInstallationForAuthenticatedUser: [ + "DELETE /user/installations/{installation_id}/repositories/{repository_id}" + ], + resetToken: ["PATCH /applications/{client_id}/token"], + revokeInstallationAccessToken: ["DELETE /installation/token"], + scopeToken: ["POST /applications/{client_id}/token/scoped"], + suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], + unsuspendInstallation: [ + "DELETE /app/installations/{installation_id}/suspended" + ], + updateWebhookConfigForApp: ["PATCH /app/hook/config"] + }, + billing: { + getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], + getGithubActionsBillingUser: [ + "GET /users/{username}/settings/billing/actions" + ], + getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], + getGithubPackagesBillingUser: [ + "GET /users/{username}/settings/billing/packages" + ], + getSharedStorageBillingOrg: [ + "GET /orgs/{org}/settings/billing/shared-storage" + ], + getSharedStorageBillingUser: [ + "GET /users/{username}/settings/billing/shared-storage" + ] + }, + checks: { + create: ["POST /repos/{owner}/{repo}/check-runs"], + createSuite: ["POST /repos/{owner}/{repo}/check-suites"], + get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], + getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], + listAnnotations: [ + "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" + ], + listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], + listForSuite: [ + "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" + ], + listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], + rerequestRun: [ + "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" + ], + rerequestSuite: [ + "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" + ], + setSuitesPreferences: [ + "PATCH /repos/{owner}/{repo}/check-suites/preferences" + ], + update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] + }, + codeScanning: { + deleteAnalysis: [ + "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" + ], + getAlert: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", + {}, + { renamedParameters: { alert_id: "alert_number" } } + ], + getAnalysis: [ + "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" + ], + getCodeqlDatabase: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" + ], + getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], + getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], + listAlertInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" + ], + listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], + listAlertsInstances: [ + "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", + {}, + { renamed: ["codeScanning", "listAlertInstances"] } + ], + listCodeqlDatabases: [ + "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" + ], + listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" + ], + updateDefaultSetup: [ + "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" + ], + uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] + }, + codesOfConduct: { + getAllCodesOfConduct: ["GET /codes_of_conduct"], + getConductCode: ["GET /codes_of_conduct/{key}"] + }, + codespaces: { + addRepositoryForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + checkPermissionsForDevcontainer: [ + "GET /repos/{owner}/{repo}/codespaces/permissions_check" + ], + codespaceMachinesForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/machines" + ], + createForAuthenticatedUser: ["POST /user/codespaces"], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + createOrUpdateSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}" + ], + createWithPrForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" + ], + createWithRepoForAuthenticatedUser: [ + "POST /repos/{owner}/{repo}/codespaces" + ], + deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], + deleteFromOrganization: [ + "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + deleteSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}" + ], + exportForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/exports" + ], + getCodespacesForUserInOrg: [ + "GET /orgs/{org}/members/{username}/codespaces" + ], + getExportDetailsForAuthenticatedUser: [ + "GET /user/codespaces/{codespace_name}/exports/{export_id}" + ], + getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], + getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], + getPublicKeyForAuthenticatedUser: [ + "GET /user/codespaces/secrets/public-key" + ], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" + ], + getSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}" + ], + listDevcontainersInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/devcontainers" + ], + listForAuthenticatedUser: ["GET /user/codespaces"], + listInOrganization: [ + "GET /orgs/{org}/codespaces", + {}, + { renamedParameters: { org_id: "org" } } + ], + listInRepositoryForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces" + ], + listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], + listRepositoriesForSecretForAuthenticatedUser: [ + "GET /user/codespaces/secrets/{secret_name}/repositories" + ], + listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + preFlightWithRepoForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/new" + ], + publishForAuthenticatedUser: [ + "POST /user/codespaces/{codespace_name}/publish" + ], + removeRepositoryForSecretForAuthenticatedUser: [ + "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" + ], + repoMachinesForAuthenticatedUser: [ + "GET /repos/{owner}/{repo}/codespaces/machines" + ], + setRepositoriesForSecretForAuthenticatedUser: [ + "PUT /user/codespaces/secrets/{secret_name}/repositories" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" + ], + startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], + stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], + stopInOrganization: [ + "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" + ], + updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] + }, + copilot: { + addCopilotSeatsForTeams: [ + "POST /orgs/{org}/copilot/billing/selected_teams" + ], + addCopilotSeatsForUsers: [ + "POST /orgs/{org}/copilot/billing/selected_users" + ], + cancelCopilotSeatAssignmentForTeams: [ + "DELETE /orgs/{org}/copilot/billing/selected_teams" + ], + cancelCopilotSeatAssignmentForUsers: [ + "DELETE /orgs/{org}/copilot/billing/selected_users" + ], + getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], + getCopilotSeatDetailsForUser: [ + "GET /orgs/{org}/members/{username}/copilot" + ], + listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] + }, + dependabot: { + addSelectedRepoToOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + createOrUpdateOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}" + ], + createOrUpdateRepoSecret: [ + "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], + deleteRepoSecret: [ + "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], + getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], + getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], + getRepoPublicKey: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" + ], + getRepoSecret: [ + "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/dependabot/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], + listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], + listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], + listSelectedReposForOrgSecret: [ + "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + removeSelectedRepoFromOrgSecret: [ + "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" + ], + setSelectedReposForOrgSecret: [ + "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" + ] + }, + dependencyGraph: { + createRepositorySnapshot: [ + "POST /repos/{owner}/{repo}/dependency-graph/snapshots" + ], + diffRange: [ + "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" + ], + exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] + }, + emojis: { get: ["GET /emojis"] }, + gists: { + checkIsStarred: ["GET /gists/{gist_id}/star"], + create: ["POST /gists"], + createComment: ["POST /gists/{gist_id}/comments"], + delete: ["DELETE /gists/{gist_id}"], + deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], + fork: ["POST /gists/{gist_id}/forks"], + get: ["GET /gists/{gist_id}"], + getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], + getRevision: ["GET /gists/{gist_id}/{sha}"], + list: ["GET /gists"], + listComments: ["GET /gists/{gist_id}/comments"], + listCommits: ["GET /gists/{gist_id}/commits"], + listForUser: ["GET /users/{username}/gists"], + listForks: ["GET /gists/{gist_id}/forks"], + listPublic: ["GET /gists/public"], + listStarred: ["GET /gists/starred"], + star: ["PUT /gists/{gist_id}/star"], + unstar: ["DELETE /gists/{gist_id}/star"], + update: ["PATCH /gists/{gist_id}"], + updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] + }, + git: { + createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], + createCommit: ["POST /repos/{owner}/{repo}/git/commits"], + createRef: ["POST /repos/{owner}/{repo}/git/refs"], + createTag: ["POST /repos/{owner}/{repo}/git/tags"], + createTree: ["POST /repos/{owner}/{repo}/git/trees"], + deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], + getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], + getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], + getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], + getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], + getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], + listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], + updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] + }, + gitignore: { + getAllTemplates: ["GET /gitignore/templates"], + getTemplate: ["GET /gitignore/templates/{name}"] + }, + interactions: { + getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], + getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], + getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], + getRestrictionsForYourPublicRepos: [ + "GET /user/interaction-limits", + {}, + { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } + ], + removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], + removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], + removeRestrictionsForRepo: [ + "DELETE /repos/{owner}/{repo}/interaction-limits" + ], + removeRestrictionsForYourPublicRepos: [ + "DELETE /user/interaction-limits", + {}, + { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } + ], + setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], + setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], + setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], + setRestrictionsForYourPublicRepos: [ + "PUT /user/interaction-limits", + {}, + { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } + ] + }, + issues: { + addAssignees: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], + checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], + checkUserCanBeAssignedToIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" + ], + create: ["POST /repos/{owner}/{repo}/issues"], + createComment: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" + ], + createLabel: ["POST /repos/{owner}/{repo}/labels"], + createMilestone: ["POST /repos/{owner}/{repo}/milestones"], + deleteComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" + ], + deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], + deleteMilestone: [ + "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" + ], + get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], + getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], + getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], + getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], + getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], + list: ["GET /issues"], + listAssignees: ["GET /repos/{owner}/{repo}/assignees"], + listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], + listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], + listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], + listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], + listEventsForTimeline: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" + ], + listForAuthenticatedUser: ["GET /user/issues"], + listForOrg: ["GET /orgs/{org}/issues"], + listForRepo: ["GET /repos/{owner}/{repo}/issues"], + listLabelsForMilestone: [ + "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" + ], + listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], + listLabelsOnIssue: [ + "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + listMilestones: ["GET /repos/{owner}/{repo}/milestones"], + lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], + removeAllLabels: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" + ], + removeAssignees: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" + ], + removeLabel: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" + ], + setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], + unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], + update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], + updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], + updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], + updateMilestone: [ + "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" + ] + }, + licenses: { + get: ["GET /licenses/{license}"], + getAllCommonlyUsed: ["GET /licenses"], + getForRepo: ["GET /repos/{owner}/{repo}/license"] + }, + markdown: { + render: ["POST /markdown"], + renderRaw: [ + "POST /markdown/raw", + { headers: { "content-type": "text/plain; charset=utf-8" } } + ] + }, + meta: { + get: ["GET /meta"], + getAllVersions: ["GET /versions"], + getOctocat: ["GET /octocat"], + getZen: ["GET /zen"], + root: ["GET /"] + }, + migrations: { + cancelImport: [ + "DELETE /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" + } + ], + deleteArchiveForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/archive" + ], + deleteArchiveForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/archive" + ], + downloadArchiveForOrg: [ + "GET /orgs/{org}/migrations/{migration_id}/archive" + ], + getArchiveForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/archive" + ], + getCommitAuthors: [ + "GET /repos/{owner}/{repo}/import/authors", + {}, + { + deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" + } + ], + getImportStatus: [ + "GET /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" + } + ], + getLargeFiles: [ + "GET /repos/{owner}/{repo}/import/large_files", + {}, + { + deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" + } + ], + getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], + getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], + listForAuthenticatedUser: ["GET /user/migrations"], + listForOrg: ["GET /orgs/{org}/migrations"], + listReposForAuthenticatedUser: [ + "GET /user/migrations/{migration_id}/repositories" + ], + listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], + listReposForUser: [ + "GET /user/migrations/{migration_id}/repositories", + {}, + { renamed: ["migrations", "listReposForAuthenticatedUser"] } + ], + mapCommitAuthor: [ + "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", + {}, + { + deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" + } + ], + setLfsPreference: [ + "PATCH /repos/{owner}/{repo}/import/lfs", + {}, + { + deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" + } + ], + startForAuthenticatedUser: ["POST /user/migrations"], + startForOrg: ["POST /orgs/{org}/migrations"], + startImport: [ + "PUT /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" + } + ], + unlockRepoForAuthenticatedUser: [ + "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" + ], + unlockRepoForOrg: [ + "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" + ], + updateImport: [ + "PATCH /repos/{owner}/{repo}/import", + {}, + { + deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" + } + ] + }, + oidc: { + getOidcCustomSubTemplateForOrg: [ + "GET /orgs/{org}/actions/oidc/customization/sub" + ], + updateOidcCustomSubTemplateForOrg: [ + "PUT /orgs/{org}/actions/oidc/customization/sub" + ] + }, + orgs: { + addSecurityManagerTeam: [ + "PUT /orgs/{org}/security-managers/teams/{team_slug}" + ], + assignTeamToOrgRole: [ + "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + assignUserToOrgRole: [ + "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + blockUser: ["PUT /orgs/{org}/blocks/{username}"], + cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], + checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], + checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], + checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], + convertMemberToOutsideCollaborator: [ + "PUT /orgs/{org}/outside_collaborators/{username}" + ], + createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], + createInvitation: ["POST /orgs/{org}/invitations"], + createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], + createOrUpdateCustomPropertiesValuesForRepos: [ + "PATCH /orgs/{org}/properties/values" + ], + createOrUpdateCustomProperty: [ + "PUT /orgs/{org}/properties/schema/{custom_property_name}" + ], + createWebhook: ["POST /orgs/{org}/hooks"], + delete: ["DELETE /orgs/{org}"], + deleteCustomOrganizationRole: [ + "DELETE /orgs/{org}/organization-roles/{role_id}" + ], + deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], + enableOrDisableSecurityProductOnAllOrgRepos: [ + "POST /orgs/{org}/{security_product}/{enablement}" + ], + get: ["GET /orgs/{org}"], + getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], + getCustomProperty: [ + "GET /orgs/{org}/properties/schema/{custom_property_name}" + ], + getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], + getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], + getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], + getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], + getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], + getWebhookDelivery: [ + "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + list: ["GET /organizations"], + listAppInstallations: ["GET /orgs/{org}/installations"], + listBlockedUsers: ["GET /orgs/{org}/blocks"], + listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], + listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], + listForAuthenticatedUser: ["GET /user/orgs"], + listForUser: ["GET /users/{username}/orgs"], + listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], + listMembers: ["GET /orgs/{org}/members"], + listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], + listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], + listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], + listOrgRoles: ["GET /orgs/{org}/organization-roles"], + listOrganizationFineGrainedPermissions: [ + "GET /orgs/{org}/organization-fine-grained-permissions" + ], + listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], + listPatGrantRepositories: [ + "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" + ], + listPatGrantRequestRepositories: [ + "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" + ], + listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], + listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], + listPendingInvitations: ["GET /orgs/{org}/invitations"], + listPublicMembers: ["GET /orgs/{org}/public_members"], + listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], + listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], + listWebhooks: ["GET /orgs/{org}/hooks"], + patchCustomOrganizationRole: [ + "PATCH /orgs/{org}/organization-roles/{role_id}" + ], + pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeCustomProperty: [ + "DELETE /orgs/{org}/properties/schema/{custom_property_name}" + ], + removeMember: ["DELETE /orgs/{org}/members/{username}"], + removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], + removeOutsideCollaborator: [ + "DELETE /orgs/{org}/outside_collaborators/{username}" + ], + removePublicMembershipForAuthenticatedUser: [ + "DELETE /orgs/{org}/public_members/{username}" + ], + removeSecurityManagerTeam: [ + "DELETE /orgs/{org}/security-managers/teams/{team_slug}" + ], + reviewPatGrantRequest: [ + "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" + ], + reviewPatGrantRequestsInBulk: [ + "POST /orgs/{org}/personal-access-token-requests" + ], + revokeAllOrgRolesTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" + ], + revokeAllOrgRolesUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}" + ], + revokeOrgRoleTeam: [ + "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" + ], + revokeOrgRoleUser: [ + "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" + ], + setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], + setPublicMembershipForAuthenticatedUser: [ + "PUT /orgs/{org}/public_members/{username}" + ], + unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], + update: ["PATCH /orgs/{org}"], + updateMembershipForAuthenticatedUser: [ + "PATCH /user/memberships/orgs/{org}" + ], + updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], + updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], + updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], + updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] + }, + packages: { + deletePackageForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}" + ], + deletePackageForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}" + ], + deletePackageForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}" + ], + deletePackageVersionForAuthenticatedUser: [ + "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForOrg: [ + "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + deletePackageVersionForUser: [ + "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getAllPackageVersionsForAPackageOwnedByAnOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", + {}, + { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } + ], + getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions", + {}, + { + renamed: [ + "packages", + "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" + ] + } + ], + getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByOrg: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" + ], + getAllPackageVersionsForPackageOwnedByUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions" + ], + getPackageForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}" + ], + getPackageForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}" + ], + getPackageForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}" + ], + getPackageVersionForAuthenticatedUser: [ + "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForOrganization: [ + "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + getPackageVersionForUser: [ + "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" + ], + listDockerMigrationConflictingPackagesForAuthenticatedUser: [ + "GET /user/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForOrganization: [ + "GET /orgs/{org}/docker/conflicts" + ], + listDockerMigrationConflictingPackagesForUser: [ + "GET /users/{username}/docker/conflicts" + ], + listPackagesForAuthenticatedUser: ["GET /user/packages"], + listPackagesForOrganization: ["GET /orgs/{org}/packages"], + listPackagesForUser: ["GET /users/{username}/packages"], + restorePackageForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" + ], + restorePackageVersionForAuthenticatedUser: [ + "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForOrg: [ + "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ], + restorePackageVersionForUser: [ + "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" + ] + }, + projects: { + addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], + createCard: ["POST /projects/columns/{column_id}/cards"], + createColumn: ["POST /projects/{project_id}/columns"], + createForAuthenticatedUser: ["POST /user/projects"], + createForOrg: ["POST /orgs/{org}/projects"], + createForRepo: ["POST /repos/{owner}/{repo}/projects"], + delete: ["DELETE /projects/{project_id}"], + deleteCard: ["DELETE /projects/columns/cards/{card_id}"], + deleteColumn: ["DELETE /projects/columns/{column_id}"], + get: ["GET /projects/{project_id}"], + getCard: ["GET /projects/columns/cards/{card_id}"], + getColumn: ["GET /projects/columns/{column_id}"], + getPermissionForUser: [ + "GET /projects/{project_id}/collaborators/{username}/permission" + ], + listCards: ["GET /projects/columns/{column_id}/cards"], + listCollaborators: ["GET /projects/{project_id}/collaborators"], + listColumns: ["GET /projects/{project_id}/columns"], + listForOrg: ["GET /orgs/{org}/projects"], + listForRepo: ["GET /repos/{owner}/{repo}/projects"], + listForUser: ["GET /users/{username}/projects"], + moveCard: ["POST /projects/columns/cards/{card_id}/moves"], + moveColumn: ["POST /projects/columns/{column_id}/moves"], + removeCollaborator: [ + "DELETE /projects/{project_id}/collaborators/{username}" + ], + update: ["PATCH /projects/{project_id}"], + updateCard: ["PATCH /projects/columns/cards/{card_id}"], + updateColumn: ["PATCH /projects/columns/{column_id}"] + }, + pulls: { + checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + create: ["POST /repos/{owner}/{repo}/pulls"], + createReplyForReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" + ], + createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + createReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + deletePendingReview: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + deleteReviewComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ], + dismissReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" + ], + get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], + getReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], + list: ["GET /repos/{owner}/{repo}/pulls"], + listCommentsForReview: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" + ], + listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], + listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], + listRequestedReviewers: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + listReviewComments: [ + "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" + ], + listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], + listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], + merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], + removeRequestedReviewers: [ + "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + requestReviewers: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" + ], + submitReview: [ + "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" + ], + update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], + updateBranch: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" + ], + updateReview: [ + "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" + ], + updateReviewComment: [ + "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" + ] + }, + rateLimit: { get: ["GET /rate_limit"] }, + reactions: { + createForCommitComment: [ + "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + createForIssue: [ + "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" + ], + createForIssueComment: [ + "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + createForPullRequestReviewComment: [ + "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + createForRelease: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + createForTeamDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + createForTeamDiscussionInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ], + deleteForCommitComment: [ + "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForIssue: [ + "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" + ], + deleteForIssueComment: [ + "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForPullRequestComment: [ + "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" + ], + deleteForRelease: [ + "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" + ], + deleteForTeamDiscussion: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" + ], + deleteForTeamDiscussionComment: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" + ], + listForCommitComment: [ + "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" + ], + listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], + listForIssueComment: [ + "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" + ], + listForPullRequestReviewComment: [ + "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" + ], + listForRelease: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" + ], + listForTeamDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" + ], + listForTeamDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" + ] + }, + repos: { + acceptInvitation: [ + "PATCH /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } + ], + acceptInvitationForAuthenticatedUser: [ + "PATCH /user/repository_invitations/{invitation_id}" + ], + addAppAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], + addStatusCheckContexts: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + addTeamAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + addUserAccessRestrictions: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + cancelPagesDeployment: [ + "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" + ], + checkAutomatedSecurityFixes: [ + "GET /repos/{owner}/{repo}/automated-security-fixes" + ], + checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], + checkVulnerabilityAlerts: [ + "GET /repos/{owner}/{repo}/vulnerability-alerts" + ], + codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], + compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], + compareCommitsWithBasehead: [ + "GET /repos/{owner}/{repo}/compare/{basehead}" + ], + createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], + createCommitComment: [ + "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + createCommitSignatureProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], + createDeployKey: ["POST /repos/{owner}/{repo}/keys"], + createDeployment: ["POST /repos/{owner}/{repo}/deployments"], + createDeploymentBranchPolicy: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + createDeploymentProtectionRule: [ + "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + createDeploymentStatus: [ + "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], + createForAuthenticatedUser: ["POST /user/repos"], + createFork: ["POST /repos/{owner}/{repo}/forks"], + createInOrg: ["POST /orgs/{org}/repos"], + createOrUpdateCustomPropertiesValues: [ + "PATCH /repos/{owner}/{repo}/properties/values" + ], + createOrUpdateEnvironment: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}" + ], + createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], + createOrgRuleset: ["POST /orgs/{org}/rulesets"], + createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], + createPagesSite: ["POST /repos/{owner}/{repo}/pages"], + createRelease: ["POST /repos/{owner}/{repo}/releases"], + createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], + createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], + createUsingTemplate: [ + "POST /repos/{template_owner}/{template_repo}/generate" + ], + createWebhook: ["POST /repos/{owner}/{repo}/hooks"], + declineInvitation: [ + "DELETE /user/repository_invitations/{invitation_id}", + {}, + { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } + ], + declineInvitationForAuthenticatedUser: [ + "DELETE /user/repository_invitations/{invitation_id}" + ], + delete: ["DELETE /repos/{owner}/{repo}"], + deleteAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + deleteAdminBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + deleteAnEnvironment: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}" + ], + deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], + deleteBranchProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" + ], + deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], + deleteCommitSignatureProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], + deleteDeployment: [ + "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" + ], + deleteDeploymentBranchPolicy: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], + deleteInvitation: [ + "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], + deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], + deletePullRequestReviewProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], + deleteReleaseAsset: [ + "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + deleteTagProtection: [ + "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" + ], + deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], + disableAutomatedSecurityFixes: [ + "DELETE /repos/{owner}/{repo}/automated-security-fixes" + ], + disableDeploymentProtectionRule: [ + "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + disablePrivateVulnerabilityReporting: [ + "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + disableVulnerabilityAlerts: [ + "DELETE /repos/{owner}/{repo}/vulnerability-alerts" + ], + downloadArchive: [ + "GET /repos/{owner}/{repo}/zipball/{ref}", + {}, + { renamed: ["repos", "downloadZipballArchive"] } + ], + downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], + downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], + enableAutomatedSecurityFixes: [ + "PUT /repos/{owner}/{repo}/automated-security-fixes" + ], + enablePrivateVulnerabilityReporting: [ + "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" + ], + enableVulnerabilityAlerts: [ + "PUT /repos/{owner}/{repo}/vulnerability-alerts" + ], + generateReleaseNotes: [ + "POST /repos/{owner}/{repo}/releases/generate-notes" + ], + get: ["GET /repos/{owner}/{repo}"], + getAccessRestrictions: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" + ], + getAdminBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + getAllDeploymentProtectionRules: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" + ], + getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], + getAllStatusCheckContexts: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" + ], + getAllTopics: ["GET /repos/{owner}/{repo}/topics"], + getAppsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" + ], + getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], + getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], + getBranchProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection" + ], + getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], + getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], + getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], + getCollaboratorPermissionLevel: [ + "GET /repos/{owner}/{repo}/collaborators/{username}/permission" + ], + getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], + getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], + getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], + getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], + getCommitSignatureProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" + ], + getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], + getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], + getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], + getCustomDeploymentProtectionRule: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" + ], + getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], + getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], + getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], + getDeploymentBranchPolicy: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + getDeploymentStatus: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" + ], + getEnvironment: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}" + ], + getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], + getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], + getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], + getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], + getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], + getOrgRulesets: ["GET /orgs/{org}/rulesets"], + getPages: ["GET /repos/{owner}/{repo}/pages"], + getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], + getPagesDeployment: [ + "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" + ], + getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], + getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], + getPullRequestReviewProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], + getReadme: ["GET /repos/{owner}/{repo}/readme"], + getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], + getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], + getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], + getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], + getRepoRuleSuite: [ + "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" + ], + getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], + getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], + getStatusChecksProtection: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + getTeamsWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" + ], + getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], + getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], + getUsersWithAccessToProtectedBranch: [ + "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" + ], + getViews: ["GET /repos/{owner}/{repo}/traffic/views"], + getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], + getWebhookConfigForRepo: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + getWebhookDelivery: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" + ], + listActivities: ["GET /repos/{owner}/{repo}/activity"], + listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], + listBranches: ["GET /repos/{owner}/{repo}/branches"], + listBranchesForHeadCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" + ], + listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], + listCommentsForCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" + ], + listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], + listCommitStatusesForRef: [ + "GET /repos/{owner}/{repo}/commits/{ref}/statuses" + ], + listCommits: ["GET /repos/{owner}/{repo}/commits"], + listContributors: ["GET /repos/{owner}/{repo}/contributors"], + listCustomDeploymentRuleIntegrations: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" + ], + listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], + listDeploymentBranchPolicies: [ + "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" + ], + listDeploymentStatuses: [ + "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" + ], + listDeployments: ["GET /repos/{owner}/{repo}/deployments"], + listForAuthenticatedUser: ["GET /user/repos"], + listForOrg: ["GET /orgs/{org}/repos"], + listForUser: ["GET /users/{username}/repos"], + listForks: ["GET /repos/{owner}/{repo}/forks"], + listInvitations: ["GET /repos/{owner}/{repo}/invitations"], + listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], + listLanguages: ["GET /repos/{owner}/{repo}/languages"], + listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], + listPublic: ["GET /repositories"], + listPullRequestsAssociatedWithCommit: [ + "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" + ], + listReleaseAssets: [ + "GET /repos/{owner}/{repo}/releases/{release_id}/assets" + ], + listReleases: ["GET /repos/{owner}/{repo}/releases"], + listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], + listTags: ["GET /repos/{owner}/{repo}/tags"], + listTeams: ["GET /repos/{owner}/{repo}/teams"], + listWebhookDeliveries: [ + "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" + ], + listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], + merge: ["POST /repos/{owner}/{repo}/merges"], + mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], + pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], + redeliverWebhookDelivery: [ + "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" + ], + removeAppAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + removeCollaborator: [ + "DELETE /repos/{owner}/{repo}/collaborators/{username}" + ], + removeStatusCheckContexts: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + removeStatusCheckProtection: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + removeTeamAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + removeUserAccessRestrictions: [ + "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], + replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], + requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], + setAdminBranchProtection: [ + "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" + ], + setAppAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", + {}, + { mapToData: "apps" } + ], + setStatusCheckContexts: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", + {}, + { mapToData: "contexts" } + ], + setTeamAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", + {}, + { mapToData: "teams" } + ], + setUserAccessRestrictions: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", + {}, + { mapToData: "users" } + ], + testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], + transfer: ["POST /repos/{owner}/{repo}/transfer"], + update: ["PATCH /repos/{owner}/{repo}"], + updateBranchProtection: [ + "PUT /repos/{owner}/{repo}/branches/{branch}/protection" + ], + updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], + updateDeploymentBranchPolicy: [ + "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" + ], + updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], + updateInvitation: [ + "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" + ], + updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], + updatePullRequestReviewProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" + ], + updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], + updateReleaseAsset: [ + "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" + ], + updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], + updateStatusCheckPotection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", + {}, + { renamed: ["repos", "updateStatusCheckProtection"] } + ], + updateStatusCheckProtection: [ + "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" + ], + updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], + updateWebhookConfigForRepo: [ + "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" + ], + uploadReleaseAsset: [ + "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", + { baseUrl: "https://uploads.github.com" } + ] + }, + search: { + code: ["GET /search/code"], + commits: ["GET /search/commits"], + issuesAndPullRequests: ["GET /search/issues"], + labels: ["GET /search/labels"], + repos: ["GET /search/repositories"], + topics: ["GET /search/topics"], + users: ["GET /search/users"] + }, + secretScanning: { + getAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ], + listAlertsForEnterprise: [ + "GET /enterprises/{enterprise}/secret-scanning/alerts" + ], + listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], + listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], + listLocationsForAlert: [ + "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" + ], + updateAlert: [ + "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" + ] + }, + securityAdvisories: { + createFork: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" + ], + createPrivateVulnerabilityReport: [ + "POST /repos/{owner}/{repo}/security-advisories/reports" + ], + createRepositoryAdvisory: [ + "POST /repos/{owner}/{repo}/security-advisories" + ], + createRepositoryAdvisoryCveRequest: [ + "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" + ], + getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], + getRepositoryAdvisory: [ + "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ], + listGlobalAdvisories: ["GET /advisories"], + listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], + listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], + updateRepositoryAdvisory: [ + "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" + ] + }, + teams: { + addOrUpdateMembershipForUserInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + addOrUpdateProjectPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + addOrUpdateRepoPermissionsInOrg: [ + "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + checkPermissionsForProjectInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + checkPermissionsForRepoInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + create: ["POST /orgs/{org}/teams"], + createDiscussionCommentInOrg: [ + "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], + deleteDiscussionCommentInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + deleteDiscussionInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], + getByName: ["GET /orgs/{org}/teams/{team_slug}"], + getDiscussionCommentInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + getDiscussionInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + getMembershipForUserInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + list: ["GET /orgs/{org}/teams"], + listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], + listDiscussionCommentsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" + ], + listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], + listForAuthenticatedUser: ["GET /user/teams"], + listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], + listPendingInvitationsInOrg: [ + "GET /orgs/{org}/teams/{team_slug}/invitations" + ], + listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], + listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], + removeMembershipForUserInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" + ], + removeProjectInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" + ], + removeRepoInOrg: [ + "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" + ], + updateDiscussionCommentInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" + ], + updateDiscussionInOrg: [ + "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" + ], + updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] + }, + users: { + addEmailForAuthenticated: [ + "POST /user/emails", + {}, + { renamed: ["users", "addEmailForAuthenticatedUser"] } + ], + addEmailForAuthenticatedUser: ["POST /user/emails"], + addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], + block: ["PUT /user/blocks/{username}"], + checkBlocked: ["GET /user/blocks/{username}"], + checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], + checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], + createGpgKeyForAuthenticated: [ + "POST /user/gpg_keys", + {}, + { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } + ], + createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], + createPublicSshKeyForAuthenticated: [ + "POST /user/keys", + {}, + { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } + ], + createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], + createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], + deleteEmailForAuthenticated: [ + "DELETE /user/emails", + {}, + { renamed: ["users", "deleteEmailForAuthenticatedUser"] } + ], + deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], + deleteGpgKeyForAuthenticated: [ + "DELETE /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } + ], + deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], + deletePublicSshKeyForAuthenticated: [ + "DELETE /user/keys/{key_id}", + {}, + { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } + ], + deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], + deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], + deleteSshSigningKeyForAuthenticatedUser: [ + "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + follow: ["PUT /user/following/{username}"], + getAuthenticated: ["GET /user"], + getByUsername: ["GET /users/{username}"], + getContextForUser: ["GET /users/{username}/hovercard"], + getGpgKeyForAuthenticated: [ + "GET /user/gpg_keys/{gpg_key_id}", + {}, + { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } + ], + getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], + getPublicSshKeyForAuthenticated: [ + "GET /user/keys/{key_id}", + {}, + { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } + ], + getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], + getSshSigningKeyForAuthenticatedUser: [ + "GET /user/ssh_signing_keys/{ssh_signing_key_id}" + ], + list: ["GET /users"], + listBlockedByAuthenticated: [ + "GET /user/blocks", + {}, + { renamed: ["users", "listBlockedByAuthenticatedUser"] } + ], + listBlockedByAuthenticatedUser: ["GET /user/blocks"], + listEmailsForAuthenticated: [ + "GET /user/emails", + {}, + { renamed: ["users", "listEmailsForAuthenticatedUser"] } + ], + listEmailsForAuthenticatedUser: ["GET /user/emails"], + listFollowedByAuthenticated: [ + "GET /user/following", + {}, + { renamed: ["users", "listFollowedByAuthenticatedUser"] } + ], + listFollowedByAuthenticatedUser: ["GET /user/following"], + listFollowersForAuthenticatedUser: ["GET /user/followers"], + listFollowersForUser: ["GET /users/{username}/followers"], + listFollowingForUser: ["GET /users/{username}/following"], + listGpgKeysForAuthenticated: [ + "GET /user/gpg_keys", + {}, + { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } + ], + listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], + listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], + listPublicEmailsForAuthenticated: [ + "GET /user/public_emails", + {}, + { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } + ], + listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], + listPublicKeysForUser: ["GET /users/{username}/keys"], + listPublicSshKeysForAuthenticated: [ + "GET /user/keys", + {}, + { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } + ], + listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], + listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], + listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], + listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], + listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], + setPrimaryEmailVisibilityForAuthenticated: [ + "PATCH /user/email/visibility", + {}, + { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } + ], + setPrimaryEmailVisibilityForAuthenticatedUser: [ + "PATCH /user/email/visibility" + ], + unblock: ["DELETE /user/blocks/{username}"], + unfollow: ["DELETE /user/following/{username}"], + updateAuthenticated: ["PATCH /user"] + } +}; +var endpoints_default = Endpoints; + +// pkg/dist-src/endpoints-to-methods.js +var endpointMethodsMap = /* @__PURE__ */ new Map(); +for (const [scope, endpoints] of Object.entries(endpoints_default)) { + for (const [methodName, endpoint] of Object.entries(endpoints)) { + const [route, defaults, decorations] = endpoint; + const [method, url] = route.split(/ /); + const endpointDefaults = Object.assign( + { + method, + url + }, + defaults + ); + if (!endpointMethodsMap.has(scope)) { + endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); + } + endpointMethodsMap.get(scope).set(methodName, { + scope, + methodName, + endpointDefaults, + decorations + }); + } +} +var handler = { + has({ scope }, methodName) { + return endpointMethodsMap.get(scope).has(methodName); + }, + getOwnPropertyDescriptor(target, methodName) { + return { + value: this.get(target, methodName), + // ensures method is in the cache + configurable: true, + writable: true, + enumerable: true + }; + }, + defineProperty(target, methodName, descriptor) { + Object.defineProperty(target.cache, methodName, descriptor); + return true; + }, + deleteProperty(target, methodName) { + delete target.cache[methodName]; + return true; + }, + ownKeys({ scope }) { + return [...endpointMethodsMap.get(scope).keys()]; + }, + set(target, methodName, value) { + return target.cache[methodName] = value; + }, + get({ octokit, scope, cache }, methodName) { + if (cache[methodName]) { + return cache[methodName]; + } + const method = endpointMethodsMap.get(scope).get(methodName); + if (!method) { + return void 0; + } + const { endpointDefaults, decorations } = method; + if (decorations) { + cache[methodName] = decorate( + octokit, + scope, + methodName, + endpointDefaults, + decorations + ); + } else { + cache[methodName] = octokit.request.defaults(endpointDefaults); + } + return cache[methodName]; + } +}; +function endpointsToMethods(octokit) { + const newMethods = {}; + for (const scope of endpointMethodsMap.keys()) { + newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); + } + return newMethods; +} +function decorate(octokit, scope, methodName, defaults, decorations) { + const requestWithDefaults = octokit.request.defaults(defaults); + function withDecorations(...args) { + let options = requestWithDefaults.endpoint.merge(...args); + if (decorations.mapToData) { + options = Object.assign({}, options, { + data: options[decorations.mapToData], + [decorations.mapToData]: void 0 + }); + return requestWithDefaults(options); + } + if (decorations.renamed) { + const [newScope, newMethodName] = decorations.renamed; + octokit.log.warn( + `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` + ); + } + if (decorations.deprecated) { + octokit.log.warn(decorations.deprecated); + } + if (decorations.renamedParameters) { + const options2 = requestWithDefaults.endpoint.merge(...args); + for (const [name, alias] of Object.entries( + decorations.renamedParameters + )) { + if (name in options2) { + octokit.log.warn( + `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` + ); + if (!(alias in options2)) { + options2[alias] = options2[name]; + } + delete options2[name]; + } + } + return requestWithDefaults(options2); + } + return requestWithDefaults(...args); + } + return Object.assign(withDecorations, requestWithDefaults); +} + +// pkg/dist-src/index.js +function restEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + rest: api + }; +} +restEndpointMethods.VERSION = VERSION; +function legacyRestEndpointMethods(octokit) { + const api = endpointsToMethods(octokit); + return { + ...api, + rest: api + }; +} +legacyRestEndpointMethods.VERSION = VERSION; +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 3708: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + RequestError: () => RequestError +}); +module.exports = __toCommonJS(dist_src_exports); +var import_deprecation = __nccwpck_require__(4150); +var import_once = __toESM(__nccwpck_require__(5560)); +var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); +var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); +var RequestError = class extends Error { + constructor(message, statusCode, options) { + super(message); + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + this.name = "HttpError"; + this.status = statusCode; + let headers; + if ("headers" in options && typeof options.headers !== "undefined") { + headers = options.headers; + } + if ("response" in options) { + this.response = options.response; + headers = options.response.headers; + } + const requestCopy = Object.assign({}, options.request); + if (options.request.headers.authorization) { + requestCopy.headers = Object.assign({}, options.request.headers, { + authorization: options.request.headers.authorization.replace( + /(? { + + +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// pkg/dist-src/index.js +var dist_src_exports = {}; +__export(dist_src_exports, { + request: () => request +}); +module.exports = __toCommonJS(dist_src_exports); +var import_endpoint = __nccwpck_require__(4471); +var import_universal_user_agent = __nccwpck_require__(3843); + +// pkg/dist-src/version.js +var VERSION = "8.4.1"; + +// pkg/dist-src/is-plain-object.js +function isPlainObject(value) { + if (typeof value !== "object" || value === null) + return false; + if (Object.prototype.toString.call(value) !== "[object Object]") + return false; + const proto = Object.getPrototypeOf(value); + if (proto === null) + return true; + const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; + return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); +} + +// pkg/dist-src/fetch-wrapper.js +var import_request_error = __nccwpck_require__(3708); + +// pkg/dist-src/get-buffer-response.js +function getBufferResponse(response) { + return response.arrayBuffer(); +} + +// pkg/dist-src/fetch-wrapper.js +function fetchWrapper(requestOptions) { + var _a, _b, _c, _d; + const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; + const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; + if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { + requestOptions.body = JSON.stringify(requestOptions.body); + } + let headers = {}; + let status; + let url; + let { fetch } = globalThis; + if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { + fetch = requestOptions.request.fetch; + } + if (!fetch) { + throw new Error( + "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" + ); + } + return fetch(requestOptions.url, { + method: requestOptions.method, + body: requestOptions.body, + redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, + headers: requestOptions.headers, + signal: (_d = requestOptions.request) == null ? void 0 : _d.signal, + // duplex must be set if request.body is ReadableStream or Async Iterables. + // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. + ...requestOptions.body && { duplex: "half" } + }).then(async (response) => { + url = response.url; + status = response.status; + for (const keyAndValue of response.headers) { + headers[keyAndValue[0]] = keyAndValue[1]; + } + if ("deprecation" in headers) { + const matches = headers.link && headers.link.match(/<([^<>]+)>; rel="deprecation"/); + const deprecationLink = matches && matches.pop(); + log.warn( + `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` + ); + } + if (status === 204 || status === 205) { + return; + } + if (requestOptions.method === "HEAD") { + if (status < 400) { + return; + } + throw new import_request_error.RequestError(response.statusText, status, { + response: { + url, + status, + headers, + data: void 0 + }, + request: requestOptions + }); + } + if (status === 304) { + throw new import_request_error.RequestError("Not modified", status, { + response: { + url, + status, + headers, + data: await getResponseData(response) + }, + request: requestOptions + }); + } + if (status >= 400) { + const data = await getResponseData(response); + const error = new import_request_error.RequestError(toErrorMessage(data), status, { + response: { + url, + status, + headers, + data + }, + request: requestOptions + }); + throw error; + } + return parseSuccessResponseBody ? await getResponseData(response) : response.body; + }).then((data) => { + return { + status, + url, + headers, + data + }; + }).catch((error) => { + if (error instanceof import_request_error.RequestError) + throw error; + else if (error.name === "AbortError") + throw error; + let message = error.message; + if (error.name === "TypeError" && "cause" in error) { + if (error.cause instanceof Error) { + message = error.cause.message; + } else if (typeof error.cause === "string") { + message = error.cause; + } + } + throw new import_request_error.RequestError(message, 500, { + request: requestOptions + }); + }); +} +async function getResponseData(response) { + const contentType = response.headers.get("content-type"); + if (/application\/json/.test(contentType)) { + return response.json().catch(() => response.text()).catch(() => ""); + } + if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { + return response.text(); + } + return getBufferResponse(response); +} +function toErrorMessage(data) { + if (typeof data === "string") + return data; + let suffix; + if ("documentation_url" in data) { + suffix = ` - ${data.documentation_url}`; + } else { + suffix = ""; + } + if ("message" in data) { + if (Array.isArray(data.errors)) { + return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; + } + return `${data.message}${suffix}`; + } + return `Unknown error: ${JSON.stringify(data)}`; +} + +// pkg/dist-src/with-defaults.js +function withDefaults(oldEndpoint, newDefaults) { + const endpoint2 = oldEndpoint.defaults(newDefaults); + const newApi = function(route, parameters) { + const endpointOptions = endpoint2.merge(route, parameters); + if (!endpointOptions.request || !endpointOptions.request.hook) { + return fetchWrapper(endpoint2.parse(endpointOptions)); + } + const request2 = (route2, parameters2) => { + return fetchWrapper( + endpoint2.parse(endpoint2.merge(route2, parameters2)) + ); + }; + Object.assign(request2, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); + return endpointOptions.request.hook(request2, endpointOptions); + }; + return Object.assign(newApi, { + endpoint: endpoint2, + defaults: withDefaults.bind(null, endpoint2) + }); +} + +// pkg/dist-src/index.js +var request = withDefaults(import_endpoint.endpoint, { + headers: { + "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` + } +}); +// Annotate the CommonJS export names for ESM import in node: +0 && (0); + + +/***/ }), + +/***/ 4412: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/* module decorator */ module = __nccwpck_require__.nmd(module); + + +const ANSI_BACKGROUND_OFFSET = 10; + +const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; + +const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; + +function assembleStyles() { + const codes = new Map(); + const styles = { + modifier: { + reset: [0, 0], + // 21 isn't widely supported and 22 does the same thing + bold: [1, 22], + dim: [2, 22], + italic: [3, 23], + underline: [4, 24], + overline: [53, 55], + inverse: [7, 27], + hidden: [8, 28], + strikethrough: [9, 29] + }, + color: { + black: [30, 39], + red: [31, 39], + green: [32, 39], + yellow: [33, 39], + blue: [34, 39], + magenta: [35, 39], + cyan: [36, 39], + white: [37, 39], + + // Bright color + blackBright: [90, 39], + redBright: [91, 39], + greenBright: [92, 39], + yellowBright: [93, 39], + blueBright: [94, 39], + magentaBright: [95, 39], + cyanBright: [96, 39], + whiteBright: [97, 39] + }, + bgColor: { + bgBlack: [40, 49], + bgRed: [41, 49], + bgGreen: [42, 49], + bgYellow: [43, 49], + bgBlue: [44, 49], + bgMagenta: [45, 49], + bgCyan: [46, 49], + bgWhite: [47, 49], + + // Bright color + bgBlackBright: [100, 49], + bgRedBright: [101, 49], + bgGreenBright: [102, 49], + bgYellowBright: [103, 49], + bgBlueBright: [104, 49], + bgMagentaBright: [105, 49], + bgCyanBright: [106, 49], + bgWhiteBright: [107, 49] + } + }; + + // Alias bright black as gray (and grey) + styles.color.gray = styles.color.blackBright; + styles.bgColor.bgGray = styles.bgColor.bgBlackBright; + styles.color.grey = styles.color.blackBright; + styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; + + for (const [groupName, group] of Object.entries(styles)) { + for (const [styleName, style] of Object.entries(group)) { + styles[styleName] = { + open: `\u001B[${style[0]}m`, + close: `\u001B[${style[1]}m` + }; + + group[styleName] = styles[styleName]; + + codes.set(style[0], style[1]); + } + + Object.defineProperty(styles, groupName, { + value: group, + enumerable: false + }); + } + + Object.defineProperty(styles, 'codes', { + value: codes, + enumerable: false + }); + + styles.color.close = '\u001B[39m'; + styles.bgColor.close = '\u001B[49m'; + + styles.color.ansi256 = wrapAnsi256(); + styles.color.ansi16m = wrapAnsi16m(); + styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); + styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); + + // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js + Object.defineProperties(styles, { + rgbToAnsi256: { + value: (red, green, blue) => { + // We use the extended greyscale palette here, with the exception of + // black and white. normal palette only has 4 greyscale shades. + if (red === green && green === blue) { + if (red < 8) { + return 16; + } + + if (red > 248) { + return 231; + } + + return Math.round(((red - 8) / 247) * 24) + 232; + } + + return 16 + + (36 * Math.round(red / 255 * 5)) + + (6 * Math.round(green / 255 * 5)) + + Math.round(blue / 255 * 5); + }, + enumerable: false + }, + hexToRgb: { + value: hex => { + const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); + if (!matches) { + return [0, 0, 0]; + } + + let {colorString} = matches.groups; + + if (colorString.length === 3) { + colorString = colorString.split('').map(character => character + character).join(''); + } + + const integer = Number.parseInt(colorString, 16); + + return [ + (integer >> 16) & 0xFF, + (integer >> 8) & 0xFF, + integer & 0xFF + ]; + }, + enumerable: false + }, + hexToAnsi256: { + value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), + enumerable: false + } + }); + + return styles; +} + +// Make the export immutable +Object.defineProperty(module, 'exports', { + enumerable: true, + get: assembleStyles +}); + + +/***/ }), + +/***/ 8793: +/***/ ((__unused_webpack_module, exports) => { + + + +exports.byteLength = byteLength +exports.toByteArray = toByteArray +exports.fromByteArray = fromByteArray + +var lookup = [] +var revLookup = [] +var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array + +var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' +for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i] + revLookup[code.charCodeAt(i)] = i +} + +// Support decoding URL-safe base64 strings, as Node.js does. +// See: https://en.wikipedia.org/wiki/Base64#URL_applications +revLookup['-'.charCodeAt(0)] = 62 +revLookup['_'.charCodeAt(0)] = 63 + +function getLens (b64) { + var len = b64.length + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('=') + if (validLen === -1) validLen = len + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4) + + return [validLen, placeHoldersLen] +} + +// base64 is 4/3 + up to two characters of the original data +function byteLength (b64) { + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen +} + +function toByteArray (b64) { + var tmp + var lens = getLens(b64) + var validLen = lens[0] + var placeHoldersLen = lens[1] + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) + + var curByte = 0 + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen + + var i + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)] + arr[curByte++] = (tmp >> 16) & 0xFF + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4) + arr[curByte++] = tmp & 0xFF + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2) + arr[curByte++] = (tmp >> 8) & 0xFF + arr[curByte++] = tmp & 0xFF + } + + return arr +} + +function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] +} + +function encodeChunk (uint8, start, end) { + var tmp + var output = [] + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF) + output.push(tripletToBase64(tmp)) + } + return output.join('') +} + +function fromByteArray (uint8) { + var tmp + var len = uint8.length + var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes + var parts = [] + var maxChunkLength = 16383 // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1] + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ) + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1] + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ) + } + + return parts.join('') +} + + +/***/ }), + +/***/ 2732: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var register = __nccwpck_require__(1063); +var addHook = __nccwpck_require__(2027); +var removeHook = __nccwpck_require__(9934); + +// bind with array of arguments: https://stackoverflow.com/a/21792913 +var bind = Function.bind; +var bindable = bind.bind(bind); + +function bindApi(hook, state, name) { + var removeHookRef = bindable(removeHook, null).apply( + null, + name ? [state, name] : [state] + ); + hook.api = { remove: removeHookRef }; + hook.remove = removeHookRef; + ["before", "error", "after", "wrap"].forEach(function (kind) { + var args = name ? [state, kind, name] : [state, kind]; + hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); + }); +} + +function HookSingular() { + var singularHookName = "h"; + var singularHookState = { + registry: {}, + }; + var singularHook = register.bind(null, singularHookState, singularHookName); + bindApi(singularHook, singularHookState, singularHookName); + return singularHook; +} + +function HookCollection() { + var state = { + registry: {}, + }; + + var hook = register.bind(null, state); + bindApi(hook, state); + + return hook; +} + +var collectionHookDeprecationMessageDisplayed = false; +function Hook() { + if (!collectionHookDeprecationMessageDisplayed) { + console.warn( + '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' + ); + collectionHookDeprecationMessageDisplayed = true; + } + return HookCollection(); +} + +Hook.Singular = HookSingular.bind(); +Hook.Collection = HookCollection.bind(); + +module.exports = Hook; +// expose constructors as a named property for TypeScript +module.exports.Hook = Hook; +module.exports.Singular = Hook.Singular; +module.exports.Collection = Hook.Collection; + + +/***/ }), + +/***/ 2027: +/***/ ((module) => { + +module.exports = addHook; + +function addHook(state, kind, name, hook) { + var orig = hook; + if (!state.registry[name]) { + state.registry[name] = []; + } + + if (kind === "before") { + hook = function (method, options) { + return Promise.resolve() + .then(orig.bind(null, options)) + .then(method.bind(null, options)); + }; + } + + if (kind === "after") { + hook = function (method, options) { + var result; + return Promise.resolve() + .then(method.bind(null, options)) + .then(function (result_) { + result = result_; + return orig(result, options); + }) + .then(function () { + return result; + }); + }; + } + + if (kind === "error") { + hook = function (method, options) { + return Promise.resolve() + .then(method.bind(null, options)) + .catch(function (error) { + return orig(error, options); + }); + }; + } + + state.registry[name].push({ + hook: hook, + orig: orig, + }); +} + + +/***/ }), + +/***/ 1063: +/***/ ((module) => { + +module.exports = register; + +function register(state, name, method, options) { + if (typeof method !== "function") { + throw new Error("method for before hook must be a function"); + } + + if (!options) { + options = {}; + } + + if (Array.isArray(name)) { + return name.reverse().reduce(function (callback, name) { + return register.bind(null, state, name, callback, options); + }, method)(); + } + + return Promise.resolve().then(function () { + if (!state.registry[name]) { + return method(options); + } + + return state.registry[name].reduce(function (method, registered) { + return registered.hook.bind(null, method, options); + }, method)(); + }); +} + + +/***/ }), + +/***/ 9934: +/***/ ((module) => { + +module.exports = removeHook; + +function removeHook(state, name, method) { + if (!state.registry[name]) { + return; + } + + var index = state.registry[name] + .map(function (registered) { + return registered.orig; + }) + .indexOf(method); + + if (index === -1) { + return; + } + + state.registry[name].splice(index, 1); +} + + +/***/ }), + +/***/ 9890: +/***/ ((module) => { + + + +const UPPERCASE = /[\p{Lu}]/u; +const LOWERCASE = /[\p{Ll}]/u; +const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; +const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; +const SEPARATORS = /[_.\- ]+/; + +const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source); +const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu'); +const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu'); + +const preserveCamelCase = (string, toLowerCase, toUpperCase) => { + let isLastCharLower = false; + let isLastCharUpper = false; + let isLastLastCharUpper = false; + + for (let i = 0; i < string.length; i++) { + const character = string[i]; + + if (isLastCharLower && UPPERCASE.test(character)) { + string = string.slice(0, i) + '-' + string.slice(i); + isLastCharLower = false; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = true; + i++; + } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { + string = string.slice(0, i - 1) + '-' + string.slice(i - 1); + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = false; + isLastCharLower = true; + } else { + isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; + isLastLastCharUpper = isLastCharUpper; + isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; + } + } + + return string; +}; + +const preserveConsecutiveUppercase = (input, toLowerCase) => { + LEADING_CAPITAL.lastIndex = 0; + + return input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1)); +}; + +const postProcess = (input, toUpperCase) => { + SEPARATORS_AND_IDENTIFIER.lastIndex = 0; + NUMBERS_AND_IDENTIFIER.lastIndex = 0; + + return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)) + .replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m)); +}; + +const camelCase = (input, options) => { + if (!(typeof input === 'string' || Array.isArray(input))) { + throw new TypeError('Expected the input to be `string | string[]`'); + } + + options = { + pascalCase: false, + preserveConsecutiveUppercase: false, + ...options + }; + + if (Array.isArray(input)) { + input = input.map(x => x.trim()) + .filter(x => x.length) + .join('-'); + } else { + input = input.trim(); + } + + if (input.length === 0) { + return ''; + } + + const toLowerCase = options.locale === false ? + string => string.toLowerCase() : + string => string.toLocaleLowerCase(options.locale); + const toUpperCase = options.locale === false ? + string => string.toUpperCase() : + string => string.toLocaleUpperCase(options.locale); + + if (input.length === 1) { + return options.pascalCase ? toUpperCase(input) : toLowerCase(input); + } + + const hasUpperCase = input !== toLowerCase(input); + + if (hasUpperCase) { + input = preserveCamelCase(input, toLowerCase, toUpperCase); + } + + input = input.replace(LEADING_SEPARATORS, ''); + + if (options.preserveConsecutiveUppercase) { + input = preserveConsecutiveUppercase(input, toLowerCase); + } else { + input = toLowerCase(input); + } + + if (options.pascalCase) { + input = toUpperCase(input.charAt(0)) + input.slice(1); + } + + return postProcess(input, toUpperCase); +}; + +module.exports = camelCase; +// TODO: Remove this for the next major release +module.exports["default"] = camelCase; + + +/***/ }), + +/***/ 8203: +/***/ ((module) => { + + +module.exports = function (str, sep) { + if (typeof str !== 'string') { + throw new TypeError('Expected a string'); + } + + sep = typeof sep === 'undefined' ? '_' : sep; + + return str + .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2') + .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2') + .toLowerCase(); +}; + + +/***/ }), + +/***/ 4150: +/***/ ((__unused_webpack_module, exports) => { + + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +class Deprecation extends Error { + constructor(message) { + super(message); // Maintains proper stack trace (only available on V8) + + /* istanbul ignore next */ + + if (Error.captureStackTrace) { + Error.captureStackTrace(this, this.constructor); + } + + this.name = 'Deprecation'; + } + +} + +exports.Deprecation = Deprecation; + + +/***/ }), + +/***/ 2415: +/***/ ((module) => { + + + +var has = Object.prototype.hasOwnProperty + , prefix = '~'; + +/** + * Constructor to create a storage for our `EE` objects. + * An `Events` instance is a plain object whose properties are event names. + * + * @constructor + * @private + */ +function Events() {} + +// +// We try to not inherit from `Object.prototype`. In some engines creating an +// instance in this way is faster than calling `Object.create(null)` directly. +// If `Object.create(null)` is not supported we prefix the event names with a +// character to make sure that the built-in object properties are not +// overridden or used as an attack vector. +// +if (Object.create) { + Events.prototype = Object.create(null); + + // + // This hack is needed because the `__proto__` property is still inherited in + // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. + // + if (!new Events().__proto__) prefix = false; +} + +/** + * Representation of a single event listener. + * + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} [once=false] Specify if the listener is a one-time listener. + * @constructor + * @private + */ +function EE(fn, context, once) { + this.fn = fn; + this.context = context; + this.once = once || false; +} + +/** + * Add a listener for a given event. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} context The context to invoke the listener with. + * @param {Boolean} once Specify if the listener is a one-time listener. + * @returns {EventEmitter} + * @private + */ +function addListener(emitter, event, fn, context, once) { + if (typeof fn !== 'function') { + throw new TypeError('The listener must be a function'); + } + + var listener = new EE(fn, context || emitter, once) + , evt = prefix ? prefix + event : event; + + if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; + else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); + else emitter._events[evt] = [emitter._events[evt], listener]; + + return emitter; +} + +/** + * Clear event by name. + * + * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. + * @param {(String|Symbol)} evt The Event name. + * @private + */ +function clearEvent(emitter, evt) { + if (--emitter._eventsCount === 0) emitter._events = new Events(); + else delete emitter._events[evt]; +} + +/** + * Minimal `EventEmitter` interface that is molded against the Node.js + * `EventEmitter` interface. + * + * @constructor + * @public + */ +function EventEmitter() { + this._events = new Events(); + this._eventsCount = 0; +} + +/** + * Return an array listing the events for which the emitter has registered + * listeners. + * + * @returns {Array} + * @public + */ +EventEmitter.prototype.eventNames = function eventNames() { + var names = [] + , events + , name; + + if (this._eventsCount === 0) return names; + + for (name in (events = this._events)) { + if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); + } + + if (Object.getOwnPropertySymbols) { + return names.concat(Object.getOwnPropertySymbols(events)); + } + + return names; +}; + +/** + * Return the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Array} The registered listeners. + * @public + */ +EventEmitter.prototype.listeners = function listeners(event) { + var evt = prefix ? prefix + event : event + , handlers = this._events[evt]; + + if (!handlers) return []; + if (handlers.fn) return [handlers.fn]; + + for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { + ee[i] = handlers[i].fn; + } + + return ee; +}; + +/** + * Return the number of listeners listening to a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Number} The number of listeners. + * @public + */ +EventEmitter.prototype.listenerCount = function listenerCount(event) { + var evt = prefix ? prefix + event : event + , listeners = this._events[evt]; + + if (!listeners) return 0; + if (listeners.fn) return 1; + return listeners.length; +}; + +/** + * Calls each of the listeners registered for a given event. + * + * @param {(String|Symbol)} event The event name. + * @returns {Boolean} `true` if the event had listeners, else `false`. + * @public + */ +EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return false; + + var listeners = this._events[evt] + , len = arguments.length + , args + , i; + + if (listeners.fn) { + if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); + + switch (len) { + case 1: return listeners.fn.call(listeners.context), true; + case 2: return listeners.fn.call(listeners.context, a1), true; + case 3: return listeners.fn.call(listeners.context, a1, a2), true; + case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; + case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; + case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; + } + + for (i = 1, args = new Array(len -1); i < len; i++) { + args[i - 1] = arguments[i]; + } + + listeners.fn.apply(listeners.context, args); + } else { + var length = listeners.length + , j; + + for (i = 0; i < length; i++) { + if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); + + switch (len) { + case 1: listeners[i].fn.call(listeners[i].context); break; + case 2: listeners[i].fn.call(listeners[i].context, a1); break; + case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; + case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; + default: + if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { + args[j - 1] = arguments[j]; + } + + listeners[i].fn.apply(listeners[i].context, args); + } + } + } + + return true; +}; + +/** + * Add a listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.on = function on(event, fn, context) { + return addListener(this, event, fn, context, false); +}; + +/** + * Add a one-time listener for a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn The listener function. + * @param {*} [context=this] The context to invoke the listener with. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.once = function once(event, fn, context) { + return addListener(this, event, fn, context, true); +}; + +/** + * Remove the listeners of a given event. + * + * @param {(String|Symbol)} event The event name. + * @param {Function} fn Only remove the listeners that match this function. + * @param {*} context Only remove the listeners that have this context. + * @param {Boolean} once Only remove one-time listeners. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { + var evt = prefix ? prefix + event : event; + + if (!this._events[evt]) return this; + if (!fn) { + clearEvent(this, evt); + return this; + } + + var listeners = this._events[evt]; + + if (listeners.fn) { + if ( + listeners.fn === fn && + (!once || listeners.once) && + (!context || listeners.context === context) + ) { + clearEvent(this, evt); + } + } else { + for (var i = 0, events = [], length = listeners.length; i < length; i++) { + if ( + listeners[i].fn !== fn || + (once && !listeners[i].once) || + (context && listeners[i].context !== context) + ) { + events.push(listeners[i]); + } + } + + // + // Reset the array, or remove it completely if we have no more listeners. + // + if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; + else clearEvent(this, evt); + } + + return this; +}; + +/** + * Remove all listeners, or those of the specified event. + * + * @param {(String|Symbol)} [event] The event name. + * @returns {EventEmitter} `this`. + * @public + */ +EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { + var evt; + + if (event) { + evt = prefix ? prefix + event : event; + if (this._events[evt]) clearEvent(this, evt); + } else { + this._events = new Events(); + this._eventsCount = 0; + } + + return this; +}; + +// +// Alias methods names because people roll like that. +// +EventEmitter.prototype.off = EventEmitter.prototype.removeListener; +EventEmitter.prototype.addListener = EventEmitter.prototype.on; + +// +// Expose the prefix. +// +EventEmitter.prefixed = prefix; + +// +// Allow `EventEmitter` to be imported as module namespace. +// +EventEmitter.EventEmitter = EventEmitter; + +// +// Expose the module. +// +if (true) { + module.exports = EventEmitter; +} + + +/***/ }), + +/***/ 9018: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const ANY = Symbol('SemVer ANY') +// hoisted class for cyclic dependency +class Comparator { + static get ANY () { + return ANY + } + + constructor (comp, options) { + options = parseOptions(options) + + if (comp instanceof Comparator) { + if (comp.loose === !!options.loose) { + return comp + } else { + comp = comp.value + } + } + + comp = comp.trim().split(/\s+/).join(' ') + debug('comparator', comp, options) + this.options = options + this.loose = !!options.loose + this.parse(comp) + + if (this.semver === ANY) { + this.value = '' + } else { + this.value = this.operator + this.semver.version + } + + debug('comp', this) + } + + parse (comp) { + const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] + const m = comp.match(r) + + if (!m) { + throw new TypeError(`Invalid comparator: ${comp}`) + } + + this.operator = m[1] !== undefined ? m[1] : '' + if (this.operator === '=') { + this.operator = '' + } + + // if it literally is just '>' or '' then allow anything. + if (!m[2]) { + this.semver = ANY + } else { + this.semver = new SemVer(m[2], this.options.loose) + } + } + + toString () { + return this.value + } + + test (version) { + debug('Comparator.test', version, this.options.loose) + + if (this.semver === ANY || version === ANY) { + return true + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + return cmp(version, this.operator, this.semver, this.options) + } + + intersects (comp, options) { + if (!(comp instanceof Comparator)) { + throw new TypeError('a Comparator is required') + } + + if (this.operator === '') { + if (this.value === '') { + return true + } + return new Range(comp.value, options).test(this.value) + } else if (comp.operator === '') { + if (comp.value === '') { + return true + } + return new Range(this.value, options).test(comp.semver) + } + + options = parseOptions(options) + + // Special cases where nothing can possibly be lower + if (options.includePrerelease && + (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { + return false + } + if (!options.includePrerelease && + (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { + return false + } + + // Same direction increasing (> or >=) + if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { + return true + } + // Same direction decreasing (< or <=) + if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { + return true + } + // same SemVer and both sides are inclusive (<= or >=) + if ( + (this.semver.version === comp.semver.version) && + this.operator.includes('=') && comp.operator.includes('=')) { + return true + } + // opposite directions less than + if (cmp(this.semver, '<', comp.semver, options) && + this.operator.startsWith('>') && comp.operator.startsWith('<')) { + return true + } + // opposite directions greater than + if (cmp(this.semver, '>', comp.semver, options) && + this.operator.startsWith('<') && comp.operator.startsWith('>')) { + return true + } + return false + } +} + +module.exports = Comparator + +const parseOptions = __nccwpck_require__(741) +const { safeRe: re, t } = __nccwpck_require__(3744) +const cmp = __nccwpck_require__(6845) +const debug = __nccwpck_require__(1370) +const SemVer = __nccwpck_require__(3542) +const Range = __nccwpck_require__(9005) + + +/***/ }), + +/***/ 9005: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SPACE_CHARACTERS = /\s+/g + +// hoisted class for cyclic dependency +class Range { + constructor (range, options) { + options = parseOptions(options) + + if (range instanceof Range) { + if ( + range.loose === !!options.loose && + range.includePrerelease === !!options.includePrerelease + ) { + return range + } else { + return new Range(range.raw, options) + } + } + + if (range instanceof Comparator) { + // just put it in the set and return + this.raw = range.value + this.set = [[range]] + this.formatted = undefined + return this + } + + this.options = options + this.loose = !!options.loose + this.includePrerelease = !!options.includePrerelease + + // First reduce all whitespace as much as possible so we do not have to rely + // on potentially slow regexes like \s*. This is then stored and used for + // future error messages as well. + this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') + + // First, split on || + this.set = this.raw + .split('||') + // map the range to a 2d array of comparators + .map(r => this.parseRange(r.trim())) + // throw out any comparator lists that are empty + // this generally means that it was not a valid range, which is allowed + // in loose mode, but will still throw if the WHOLE range is invalid. + .filter(c => c.length) + + if (!this.set.length) { + throw new TypeError(`Invalid SemVer Range: ${this.raw}`) + } + + // if we have any that are not the null set, throw out null sets. + if (this.set.length > 1) { + // keep the first one, in case they're all null sets + const first = this.set[0] + this.set = this.set.filter(c => !isNullSet(c[0])) + if (this.set.length === 0) { + this.set = [first] + } else if (this.set.length > 1) { + // if we have any that are *, then the range is just * + for (const c of this.set) { + if (c.length === 1 && isAny(c[0])) { + this.set = [c] + break + } + } + } + } + + this.formatted = undefined + } + + get range () { + if (this.formatted === undefined) { + this.formatted = '' + for (let i = 0; i < this.set.length; i++) { + if (i > 0) { + this.formatted += '||' + } + const comps = this.set[i] + for (let k = 0; k < comps.length; k++) { + if (k > 0) { + this.formatted += ' ' + } + this.formatted += comps[k].toString().trim() + } + } + } + return this.formatted + } + + format () { + return this.range + } + + toString () { + return this.range + } + + parseRange (range) { + // memoize range parsing for performance. + // this is a very hot path, and fully deterministic. + const memoOpts = + (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | + (this.options.loose && FLAG_LOOSE) + const memoKey = memoOpts + ':' + range + const cached = cache.get(memoKey) + if (cached) { + return cached + } + + const loose = this.options.loose + // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` + const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] + range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) + debug('hyphen replace', range) + + // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` + range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) + debug('comparator trim', range) + + // `~ 1.2.3` => `~1.2.3` + range = range.replace(re[t.TILDETRIM], tildeTrimReplace) + debug('tilde trim', range) + + // `^ 1.2.3` => `^1.2.3` + range = range.replace(re[t.CARETTRIM], caretTrimReplace) + debug('caret trim', range) + + // At this point, the range is completely trimmed and + // ready to be split into comparators. + + let rangeList = range + .split(' ') + .map(comp => parseComparator(comp, this.options)) + .join(' ') + .split(/\s+/) + // >=0.0.0 is equivalent to * + .map(comp => replaceGTE0(comp, this.options)) + + if (loose) { + // in loose mode, throw out any that are not valid comparators + rangeList = rangeList.filter(comp => { + debug('loose invalid filter', comp, this.options) + return !!comp.match(re[t.COMPARATORLOOSE]) + }) + } + debug('range list', rangeList) + + // if any comparators are the null set, then replace with JUST null set + // if more than one comparator, remove any * comparators + // also, don't include the same comparator more than once + const rangeMap = new Map() + const comparators = rangeList.map(comp => new Comparator(comp, this.options)) + for (const comp of comparators) { + if (isNullSet(comp)) { + return [comp] + } + rangeMap.set(comp.value, comp) + } + if (rangeMap.size > 1 && rangeMap.has('')) { + rangeMap.delete('') + } + + const result = [...rangeMap.values()] + cache.set(memoKey, result) + return result + } + + intersects (range, options) { + if (!(range instanceof Range)) { + throw new TypeError('a Range is required') + } + + return this.set.some((thisComparators) => { + return ( + isSatisfiable(thisComparators, options) && + range.set.some((rangeComparators) => { + return ( + isSatisfiable(rangeComparators, options) && + thisComparators.every((thisComparator) => { + return rangeComparators.every((rangeComparator) => { + return thisComparator.intersects(rangeComparator, options) + }) + }) + ) + }) + ) + }) + } + + // if ANY of the sets match ALL of its comparators, then pass + test (version) { + if (!version) { + return false + } + + if (typeof version === 'string') { + try { + version = new SemVer(version, this.options) + } catch (er) { + return false + } + } + + for (let i = 0; i < this.set.length; i++) { + if (testSet(this.set[i], version, this.options)) { + return true + } + } + return false + } +} + +module.exports = Range + +const LRU = __nccwpck_require__(9508) +const cache = new LRU() + +const parseOptions = __nccwpck_require__(741) +const Comparator = __nccwpck_require__(9018) +const debug = __nccwpck_require__(1370) +const SemVer = __nccwpck_require__(3542) +const { + safeRe: re, + t, + comparatorTrimReplace, + tildeTrimReplace, + caretTrimReplace, +} = __nccwpck_require__(3744) +const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(2780) + +const isNullSet = c => c.value === '<0.0.0-0' +const isAny = c => c.value === '' + +// take a set of comparators and determine whether there +// exists a version which can satisfy it +const isSatisfiable = (comparators, options) => { + let result = true + const remainingComparators = comparators.slice() + let testComparator = remainingComparators.pop() + + while (result && remainingComparators.length) { + result = remainingComparators.every((otherComparator) => { + return testComparator.intersects(otherComparator, options) + }) + + testComparator = remainingComparators.pop() + } + + return result +} + +// comprised of xranges, tildes, stars, and gtlt's at this point. +// already replaced the hyphen ranges +// turn into a set of JUST comparators. +const parseComparator = (comp, options) => { + comp = comp.replace(re[t.BUILD], '') + debug('comp', comp, options) + comp = replaceCarets(comp, options) + debug('caret', comp) + comp = replaceTildes(comp, options) + debug('tildes', comp) + comp = replaceXRanges(comp, options) + debug('xrange', comp) + comp = replaceStars(comp, options) + debug('stars', comp) + return comp +} + +const isX = id => !id || id.toLowerCase() === 'x' || id === '*' + +// ~, ~> --> * (any, kinda silly) +// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 +// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 +// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 +// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 +// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 +// ~0.0.1 --> >=0.0.1 <0.1.0-0 +const replaceTildes = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceTilde(c, options)) + .join(' ') +} + +const replaceTilde = (comp, options) => { + const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] + return comp.replace(r, (_, M, m, p, pr) => { + debug('tilde', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0 <${+M + 1}.0.0-0` + } else if (isX(p)) { + // ~1.2 == >=1.2.0 <1.3.0-0 + ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` + } else if (pr) { + debug('replaceTilde pr', pr) + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } else { + // ~1.2.3 == >=1.2.3 <1.3.0-0 + ret = `>=${M}.${m}.${p + } <${M}.${+m + 1}.0-0` + } + + debug('tilde return', ret) + return ret + }) +} + +// ^ --> * (any, kinda silly) +// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 +// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 +// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 +// ^1.2.3 --> >=1.2.3 <2.0.0-0 +// ^1.2.0 --> >=1.2.0 <2.0.0-0 +// ^0.0.1 --> >=0.0.1 <0.0.2-0 +// ^0.1.0 --> >=0.1.0 <0.2.0-0 +const replaceCarets = (comp, options) => { + return comp + .trim() + .split(/\s+/) + .map((c) => replaceCaret(c, options)) + .join(' ') +} + +const replaceCaret = (comp, options) => { + debug('caret', comp, options) + const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] + const z = options.includePrerelease ? '-0' : '' + return comp.replace(r, (_, M, m, p, pr) => { + debug('caret', comp, _, M, m, p, pr) + let ret + + if (isX(M)) { + ret = '' + } else if (isX(m)) { + ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` + } else if (isX(p)) { + if (M === '0') { + ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` + } else { + ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` + } + } else if (pr) { + debug('replaceCaret pr', pr) + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p}-${pr + } <${+M + 1}.0.0-0` + } + } else { + debug('no pr') + if (M === '0') { + if (m === '0') { + ret = `>=${M}.${m}.${p + }${z} <${M}.${m}.${+p + 1}-0` + } else { + ret = `>=${M}.${m}.${p + }${z} <${M}.${+m + 1}.0-0` + } + } else { + ret = `>=${M}.${m}.${p + } <${+M + 1}.0.0-0` + } + } + + debug('caret return', ret) + return ret + }) +} + +const replaceXRanges = (comp, options) => { + debug('replaceXRanges', comp, options) + return comp + .split(/\s+/) + .map((c) => replaceXRange(c, options)) + .join(' ') +} + +const replaceXRange = (comp, options) => { + comp = comp.trim() + const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] + return comp.replace(r, (ret, gtlt, M, m, p, pr) => { + debug('xRange', comp, ret, gtlt, M, m, p, pr) + const xM = isX(M) + const xm = xM || isX(m) + const xp = xm || isX(p) + const anyX = xp + + if (gtlt === '=' && anyX) { + gtlt = '' + } + + // if we're including prereleases in the match, then we need + // to fix this to -0, the lowest possible prerelease value + pr = options.includePrerelease ? '-0' : '' + + if (xM) { + if (gtlt === '>' || gtlt === '<') { + // nothing is allowed + ret = '<0.0.0-0' + } else { + // nothing is forbidden + ret = '*' + } + } else if (gtlt && anyX) { + // we know patch is an x, because we have any x at all. + // replace X with 0 + if (xm) { + m = 0 + } + p = 0 + + if (gtlt === '>') { + // >1 => >=2.0.0 + // >1.2 => >=1.3.0 + gtlt = '>=' + if (xm) { + M = +M + 1 + m = 0 + p = 0 + } else { + m = +m + 1 + p = 0 + } + } else if (gtlt === '<=') { + // <=0.7.x is actually <0.8.0, since any 0.7.x should + // pass. Similarly, <=7.x is actually <8.0.0, etc. + gtlt = '<' + if (xm) { + M = +M + 1 + } else { + m = +m + 1 + } + } + + if (gtlt === '<') { + pr = '-0' + } + + ret = `${gtlt + M}.${m}.${p}${pr}` + } else if (xm) { + ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` + } else if (xp) { + ret = `>=${M}.${m}.0${pr + } <${M}.${+m + 1}.0-0` + } + + debug('xRange return', ret) + + return ret + }) +} + +// Because * is AND-ed with everything else in the comparator, +// and '' means "any version", just remove the *s entirely. +const replaceStars = (comp, options) => { + debug('replaceStars', comp, options) + // Looseness is ignored here. star is always as loose as it gets! + return comp + .trim() + .replace(re[t.STAR], '') +} + +const replaceGTE0 = (comp, options) => { + debug('replaceGTE0', comp, options) + return comp + .trim() + .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') +} + +// This function is passed to string.replace(re[t.HYPHENRANGE]) +// M, m, patch, prerelease, build +// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 +// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do +// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 +// TODO build? +const hyphenReplace = incPr => ($0, + from, fM, fm, fp, fpr, fb, + to, tM, tm, tp, tpr) => { + if (isX(fM)) { + from = '' + } else if (isX(fm)) { + from = `>=${fM}.0.0${incPr ? '-0' : ''}` + } else if (isX(fp)) { + from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` + } else if (fpr) { + from = `>=${from}` + } else { + from = `>=${from}${incPr ? '-0' : ''}` + } + + if (isX(tM)) { + to = '' + } else if (isX(tm)) { + to = `<${+tM + 1}.0.0-0` + } else if (isX(tp)) { + to = `<${tM}.${+tm + 1}.0-0` + } else if (tpr) { + to = `<=${tM}.${tm}.${tp}-${tpr}` + } else if (incPr) { + to = `<${tM}.${tm}.${+tp + 1}-0` + } else { + to = `<=${to}` + } + + return `${from} ${to}`.trim() +} + +const testSet = (set, version, options) => { + for (let i = 0; i < set.length; i++) { + if (!set[i].test(version)) { + return false + } + } + + if (version.prerelease.length && !options.includePrerelease) { + // Find the set of versions that are allowed to have prereleases + // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 + // That should allow `1.2.3-pr.2` to pass. + // However, `1.2.4-alpha.notready` should NOT be allowed, + // even though it's within the range set by the comparators. + for (let i = 0; i < set.length; i++) { + debug(set[i].semver) + if (set[i].semver === Comparator.ANY) { + continue + } + + if (set[i].semver.prerelease.length > 0) { + const allowed = set[i].semver + if (allowed.major === version.major && + allowed.minor === version.minor && + allowed.patch === version.patch) { + return true + } + } + } + + // Version has a -pre, but it's not one of the ones we like. + return false + } + + return true +} + + +/***/ }), + +/***/ 3542: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const debug = __nccwpck_require__(1370) +const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(2780) +const { safeRe: re, t } = __nccwpck_require__(3744) + +const parseOptions = __nccwpck_require__(741) +const { compareIdentifiers } = __nccwpck_require__(5397) +class SemVer { + constructor (version, options) { + options = parseOptions(options) + + if (version instanceof SemVer) { + if (version.loose === !!options.loose && + version.includePrerelease === !!options.includePrerelease) { + return version + } else { + version = version.version + } + } else if (typeof version !== 'string') { + throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) + } + + if (version.length > MAX_LENGTH) { + throw new TypeError( + `version is longer than ${MAX_LENGTH} characters` + ) + } + + debug('SemVer', version, options) + this.options = options + this.loose = !!options.loose + // this isn't actually relevant for versions, but keep it so that we + // don't run into trouble passing this.options around. + this.includePrerelease = !!options.includePrerelease + + const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) + + if (!m) { + throw new TypeError(`Invalid Version: ${version}`) + } + + this.raw = version + + // these are actually numbers + this.major = +m[1] + this.minor = +m[2] + this.patch = +m[3] + + if (this.major > MAX_SAFE_INTEGER || this.major < 0) { + throw new TypeError('Invalid major version') + } + + if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { + throw new TypeError('Invalid minor version') + } + + if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { + throw new TypeError('Invalid patch version') + } + + // numberify any prerelease numeric ids + if (!m[4]) { + this.prerelease = [] + } else { + this.prerelease = m[4].split('.').map((id) => { + if (/^[0-9]+$/.test(id)) { + const num = +id + if (num >= 0 && num < MAX_SAFE_INTEGER) { + return num + } + } + return id + }) + } + + this.build = m[5] ? m[5].split('.') : [] + this.format() + } + + format () { + this.version = `${this.major}.${this.minor}.${this.patch}` + if (this.prerelease.length) { + this.version += `-${this.prerelease.join('.')}` + } + return this.version + } + + toString () { + return this.version + } + + compare (other) { + debug('SemVer.compare', this.version, this.options, other) + if (!(other instanceof SemVer)) { + if (typeof other === 'string' && other === this.version) { + return 0 + } + other = new SemVer(other, this.options) + } + + if (other.version === this.version) { + return 0 + } + + return this.compareMain(other) || this.comparePre(other) + } + + compareMain (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + if (this.major < other.major) { + return -1 + } + if (this.major > other.major) { + return 1 + } + if (this.minor < other.minor) { + return -1 + } + if (this.minor > other.minor) { + return 1 + } + if (this.patch < other.patch) { + return -1 + } + if (this.patch > other.patch) { + return 1 + } + return 0 + } + + comparePre (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + // NOT having a prerelease is > having one + if (this.prerelease.length && !other.prerelease.length) { + return -1 + } else if (!this.prerelease.length && other.prerelease.length) { + return 1 + } else if (!this.prerelease.length && !other.prerelease.length) { + return 0 + } + + let i = 0 + do { + const a = this.prerelease[i] + const b = other.prerelease[i] + debug('prerelease compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + compareBuild (other) { + if (!(other instanceof SemVer)) { + other = new SemVer(other, this.options) + } + + let i = 0 + do { + const a = this.build[i] + const b = other.build[i] + debug('build compare', i, a, b) + if (a === undefined && b === undefined) { + return 0 + } else if (b === undefined) { + return 1 + } else if (a === undefined) { + return -1 + } else if (a === b) { + continue + } else { + return compareIdentifiers(a, b) + } + } while (++i) + } + + // preminor will bump the version up to the next minor release, and immediately + // down to pre-release. premajor and prepatch work the same way. + inc (release, identifier, identifierBase) { + if (release.startsWith('pre')) { + if (!identifier && identifierBase === false) { + throw new Error('invalid increment argument: identifier is empty') + } + // Avoid an invalid semver results + if (identifier) { + const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) + if (!match || match[1] !== identifier) { + throw new Error(`invalid identifier: ${identifier}`) + } + } + } + + switch (release) { + case 'premajor': + this.prerelease.length = 0 + this.patch = 0 + this.minor = 0 + this.major++ + this.inc('pre', identifier, identifierBase) + break + case 'preminor': + this.prerelease.length = 0 + this.patch = 0 + this.minor++ + this.inc('pre', identifier, identifierBase) + break + case 'prepatch': + // If this is already a prerelease, it will bump to the next version + // drop any prereleases that might already exist, since they are not + // relevant at this point. + this.prerelease.length = 0 + this.inc('patch', identifier, identifierBase) + this.inc('pre', identifier, identifierBase) + break + // If the input is a non-prerelease version, this acts the same as + // prepatch. + case 'prerelease': + if (this.prerelease.length === 0) { + this.inc('patch', identifier, identifierBase) + } + this.inc('pre', identifier, identifierBase) + break + case 'release': + if (this.prerelease.length === 0) { + throw new Error(`version ${this.raw} is not a prerelease`) + } + this.prerelease.length = 0 + break + + case 'major': + // If this is a pre-major version, bump up to the same major version. + // Otherwise increment major. + // 1.0.0-5 bumps to 1.0.0 + // 1.1.0 bumps to 2.0.0 + if ( + this.minor !== 0 || + this.patch !== 0 || + this.prerelease.length === 0 + ) { + this.major++ + } + this.minor = 0 + this.patch = 0 + this.prerelease = [] + break + case 'minor': + // If this is a pre-minor version, bump up to the same minor version. + // Otherwise increment minor. + // 1.2.0-5 bumps to 1.2.0 + // 1.2.1 bumps to 1.3.0 + if (this.patch !== 0 || this.prerelease.length === 0) { + this.minor++ + } + this.patch = 0 + this.prerelease = [] + break + case 'patch': + // If this is not a pre-release version, it will increment the patch. + // If it is a pre-release it will bump up to the same patch version. + // 1.2.0-5 patches to 1.2.0 + // 1.2.0 patches to 1.2.1 + if (this.prerelease.length === 0) { + this.patch++ + } + this.prerelease = [] + break + // This probably shouldn't be used publicly. + // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. + case 'pre': { + const base = Number(identifierBase) ? 1 : 0 + + if (this.prerelease.length === 0) { + this.prerelease = [base] + } else { + let i = this.prerelease.length + while (--i >= 0) { + if (typeof this.prerelease[i] === 'number') { + this.prerelease[i]++ + i = -2 + } + } + if (i === -1) { + // didn't increment anything + if (identifier === this.prerelease.join('.') && identifierBase === false) { + throw new Error('invalid increment argument: identifier already exists') + } + this.prerelease.push(base) + } + } + if (identifier) { + // 1.2.0-beta.1 bumps to 1.2.0-beta.2, + // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 + let prerelease = [identifier, base] + if (identifierBase === false) { + prerelease = [identifier] + } + if (compareIdentifiers(this.prerelease[0], identifier) === 0) { + if (isNaN(this.prerelease[1])) { + this.prerelease = prerelease + } + } else { + this.prerelease = prerelease + } + } + break + } + default: + throw new Error(`invalid increment argument: ${release}`) + } + this.raw = this.format() + if (this.build.length) { + this.raw += `+${this.build.join('.')}` + } + return this + } +} + +module.exports = SemVer + + +/***/ }), + +/***/ 4944: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const parse = __nccwpck_require__(9354) +const clean = (version, options) => { + const s = parse(version.trim().replace(/^[=v]+/, ''), options) + return s ? s.version : null +} +module.exports = clean + + +/***/ }), + +/***/ 6845: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const eq = __nccwpck_require__(1095) +const neq = __nccwpck_require__(5) +const gt = __nccwpck_require__(4430) +const gte = __nccwpck_require__(4167) +const lt = __nccwpck_require__(401) +const lte = __nccwpck_require__(6162) + +const cmp = (a, op, b, loose) => { + switch (op) { + case '===': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a === b + + case '!==': + if (typeof a === 'object') { + a = a.version + } + if (typeof b === 'object') { + b = b.version + } + return a !== b + + case '': + case '=': + case '==': + return eq(a, b, loose) + + case '!=': + return neq(a, b, loose) + + case '>': + return gt(a, b, loose) + + case '>=': + return gte(a, b, loose) + + case '<': + return lt(a, b, loose) + + case '<=': + return lte(a, b, loose) + + default: + throw new TypeError(`Invalid operator: ${op}`) + } +} +module.exports = cmp + + +/***/ }), + +/***/ 9376: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) +const parse = __nccwpck_require__(9354) +const { safeRe: re, t } = __nccwpck_require__(3744) + +const coerce = (version, options) => { + if (version instanceof SemVer) { + return version + } + + if (typeof version === 'number') { + version = String(version) + } + + if (typeof version !== 'string') { + return null + } + + options = options || {} + + let match = null + if (!options.rtl) { + match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) + } else { + // Find the right-most coercible string that does not share + // a terminus with a more left-ward coercible string. + // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' + // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' + // + // Walk through the string checking with a /g regexp + // Manually set the index so as to pick up overlapping matches. + // Stop when we get a match that ends at the string end, since no + // coercible string can be more right-ward without the same terminus. + const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] + let next + while ((next = coerceRtlRegex.exec(version)) && + (!match || match.index + match[0].length !== version.length) + ) { + if (!match || + next.index + next[0].length !== match.index + match[0].length) { + match = next + } + coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length + } + // leave it in a clean state + coerceRtlRegex.lastIndex = -1 + } + + if (match === null) { + return null + } + + const major = match[2] + const minor = match[3] || '0' + const patch = match[4] || '0' + const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' + const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' + + return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) +} +module.exports = coerce + + +/***/ }), + +/***/ 5271: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) +const compareBuild = (a, b, loose) => { + const versionA = new SemVer(a, loose) + const versionB = new SemVer(b, loose) + return versionA.compare(versionB) || versionA.compareBuild(versionB) +} +module.exports = compareBuild + + +/***/ }), + +/***/ 5354: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const compare = __nccwpck_require__(8534) +const compareLoose = (a, b) => compare(a, b, true) +module.exports = compareLoose + + +/***/ }), + +/***/ 8534: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) +const compare = (a, b, loose) => + new SemVer(a, loose).compare(new SemVer(b, loose)) + +module.exports = compare + + +/***/ }), + +/***/ 9670: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const parse = __nccwpck_require__(9354) + +const diff = (version1, version2) => { + const v1 = parse(version1, null, true) + const v2 = parse(version2, null, true) + const comparison = v1.compare(v2) + + if (comparison === 0) { + return null + } + + const v1Higher = comparison > 0 + const highVersion = v1Higher ? v1 : v2 + const lowVersion = v1Higher ? v2 : v1 + const highHasPre = !!highVersion.prerelease.length + const lowHasPre = !!lowVersion.prerelease.length + + if (lowHasPre && !highHasPre) { + // Going from prerelease -> no prerelease requires some special casing + + // If the low version has only a major, then it will always be a major + // Some examples: + // 1.0.0-1 -> 1.0.0 + // 1.0.0-1 -> 1.1.1 + // 1.0.0-1 -> 2.0.0 + if (!lowVersion.patch && !lowVersion.minor) { + return 'major' + } + + // If the main part has no difference + if (lowVersion.compareMain(highVersion) === 0) { + if (lowVersion.minor && !lowVersion.patch) { + return 'minor' + } + return 'patch' + } + } + + // add the `pre` prefix if we are going to a prerelease version + const prefix = highHasPre ? 'pre' : '' + + if (v1.major !== v2.major) { + return prefix + 'major' + } + + if (v1.minor !== v2.minor) { + return prefix + 'minor' + } + + if (v1.patch !== v2.patch) { + return prefix + 'patch' + } + + // high and low are preleases + return 'prerelease' +} + +module.exports = diff + + +/***/ }), + +/***/ 1095: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const compare = __nccwpck_require__(8534) +const eq = (a, b, loose) => compare(a, b, loose) === 0 +module.exports = eq + + +/***/ }), + +/***/ 4430: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const compare = __nccwpck_require__(8534) +const gt = (a, b, loose) => compare(a, b, loose) > 0 +module.exports = gt + + +/***/ }), + +/***/ 4167: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const compare = __nccwpck_require__(8534) +const gte = (a, b, loose) => compare(a, b, loose) >= 0 +module.exports = gte + + +/***/ }), + +/***/ 1745: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) + +const inc = (version, release, options, identifier, identifierBase) => { + if (typeof (options) === 'string') { + identifierBase = identifier + identifier = options + options = undefined + } + + try { + return new SemVer( + version instanceof SemVer ? version.version : version, + options + ).inc(release, identifier, identifierBase).version + } catch (er) { + return null + } +} +module.exports = inc + + +/***/ }), + +/***/ 401: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const compare = __nccwpck_require__(8534) +const lt = (a, b, loose) => compare(a, b, loose) < 0 +module.exports = lt + + +/***/ }), + +/***/ 6162: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const compare = __nccwpck_require__(8534) +const lte = (a, b, loose) => compare(a, b, loose) <= 0 +module.exports = lte + + +/***/ }), + +/***/ 6264: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) +const major = (a, loose) => new SemVer(a, loose).major +module.exports = major + + +/***/ }), + +/***/ 8084: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) +const minor = (a, loose) => new SemVer(a, loose).minor +module.exports = minor + + +/***/ }), + +/***/ 5: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const compare = __nccwpck_require__(8534) +const neq = (a, b, loose) => compare(a, b, loose) !== 0 +module.exports = neq + + +/***/ }), + +/***/ 9354: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) +const parse = (version, options, throwErrors = false) => { + if (version instanceof SemVer) { + return version + } + try { + return new SemVer(version, options) + } catch (er) { + if (!throwErrors) { + return null + } + throw er + } +} + +module.exports = parse + + +/***/ }), + +/***/ 955: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) +const patch = (a, loose) => new SemVer(a, loose).patch +module.exports = patch + + +/***/ }), + +/***/ 7451: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const parse = __nccwpck_require__(9354) +const prerelease = (version, options) => { + const parsed = parse(version, options) + return (parsed && parsed.prerelease.length) ? parsed.prerelease : null +} +module.exports = prerelease + + +/***/ }), + +/***/ 1184: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const compare = __nccwpck_require__(8534) +const rcompare = (a, b, loose) => compare(b, a, loose) +module.exports = rcompare + + +/***/ }), + +/***/ 7895: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const compareBuild = __nccwpck_require__(5271) +const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) +module.exports = rsort + + +/***/ }), + +/***/ 5344: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Range = __nccwpck_require__(9005) +const satisfies = (version, range, options) => { + try { + range = new Range(range, options) + } catch (er) { + return false + } + return range.test(version) +} +module.exports = satisfies + + +/***/ }), + +/***/ 6425: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const compareBuild = __nccwpck_require__(5271) +const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) +module.exports = sort + + +/***/ }), + +/***/ 8799: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const parse = __nccwpck_require__(9354) +const valid = (version, options) => { + const v = parse(version, options) + return v ? v.version : null +} +module.exports = valid + + +/***/ }), + +/***/ 1727: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +// just pre-load all the stuff that index.js lazily exports +const internalRe = __nccwpck_require__(3744) +const constants = __nccwpck_require__(2780) +const SemVer = __nccwpck_require__(3542) +const identifiers = __nccwpck_require__(5397) +const parse = __nccwpck_require__(9354) +const valid = __nccwpck_require__(8799) +const clean = __nccwpck_require__(4944) +const inc = __nccwpck_require__(1745) +const diff = __nccwpck_require__(9670) +const major = __nccwpck_require__(6264) +const minor = __nccwpck_require__(8084) +const patch = __nccwpck_require__(955) +const prerelease = __nccwpck_require__(7451) +const compare = __nccwpck_require__(8534) +const rcompare = __nccwpck_require__(1184) +const compareLoose = __nccwpck_require__(5354) +const compareBuild = __nccwpck_require__(5271) +const sort = __nccwpck_require__(6425) +const rsort = __nccwpck_require__(7895) +const gt = __nccwpck_require__(4430) +const lt = __nccwpck_require__(401) +const eq = __nccwpck_require__(1095) +const neq = __nccwpck_require__(5) +const gte = __nccwpck_require__(4167) +const lte = __nccwpck_require__(6162) +const cmp = __nccwpck_require__(6845) +const coerce = __nccwpck_require__(9376) +const Comparator = __nccwpck_require__(9018) +const Range = __nccwpck_require__(9005) +const satisfies = __nccwpck_require__(5344) +const toComparators = __nccwpck_require__(6493) +const maxSatisfying = __nccwpck_require__(7890) +const minSatisfying = __nccwpck_require__(5320) +const minVersion = __nccwpck_require__(2067) +const validRange = __nccwpck_require__(8340) +const outside = __nccwpck_require__(2382) +const gtr = __nccwpck_require__(761) +const ltr = __nccwpck_require__(4624) +const intersects = __nccwpck_require__(7978) +const simplifyRange = __nccwpck_require__(9615) +const subset = __nccwpck_require__(7710) +module.exports = { + parse, + valid, + clean, + inc, + diff, + major, + minor, + patch, + prerelease, + compare, + rcompare, + compareLoose, + compareBuild, + sort, + rsort, + gt, + lt, + eq, + neq, + gte, + lte, + cmp, + coerce, + Comparator, + Range, + satisfies, + toComparators, + maxSatisfying, + minSatisfying, + minVersion, + validRange, + outside, + gtr, + ltr, + intersects, + simplifyRange, + subset, + SemVer, + re: internalRe.re, + src: internalRe.src, + tokens: internalRe.t, + SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, + RELEASE_TYPES: constants.RELEASE_TYPES, + compareIdentifiers: identifiers.compareIdentifiers, + rcompareIdentifiers: identifiers.rcompareIdentifiers, +} + + +/***/ }), + +/***/ 2780: +/***/ ((module) => { + + + +// Note: this is the semver.org version of the spec that it implements +// Not necessarily the package version of this code. +const SEMVER_SPEC_VERSION = '2.0.0' + +const MAX_LENGTH = 256 +const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || +/* istanbul ignore next */ 9007199254740991 + +// Max safe segment length for coercion. +const MAX_SAFE_COMPONENT_LENGTH = 16 + +// Max safe length for a build identifier. The max length minus 6 characters for +// the shortest version with a build 0.0.0+BUILD. +const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 + +const RELEASE_TYPES = [ + 'major', + 'premajor', + 'minor', + 'preminor', + 'patch', + 'prepatch', + 'prerelease', +] + +module.exports = { + MAX_LENGTH, + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_SAFE_INTEGER, + RELEASE_TYPES, + SEMVER_SPEC_VERSION, + FLAG_INCLUDE_PRERELEASE: 0b001, + FLAG_LOOSE: 0b010, +} + + +/***/ }), + +/***/ 1370: +/***/ ((module) => { + + + +const debug = ( + typeof process === 'object' && + process.env && + process.env.NODE_DEBUG && + /\bsemver\b/i.test(process.env.NODE_DEBUG) +) ? (...args) => console.error('SEMVER', ...args) + : () => {} + +module.exports = debug + + +/***/ }), + +/***/ 5397: +/***/ ((module) => { + + + +const numeric = /^[0-9]+$/ +const compareIdentifiers = (a, b) => { + if (typeof a === 'number' && typeof b === 'number') { + return a === b ? 0 : a < b ? -1 : 1 + } + + const anum = numeric.test(a) + const bnum = numeric.test(b) + + if (anum && bnum) { + a = +a + b = +b + } + + return a === b ? 0 + : (anum && !bnum) ? -1 + : (bnum && !anum) ? 1 + : a < b ? -1 + : 1 +} + +const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) + +module.exports = { + compareIdentifiers, + rcompareIdentifiers, +} + + +/***/ }), + +/***/ 9508: +/***/ ((module) => { + + + +class LRUCache { + constructor () { + this.max = 1000 + this.map = new Map() + } + + get (key) { + const value = this.map.get(key) + if (value === undefined) { + return undefined + } else { + // Remove the key from the map and add it to the end + this.map.delete(key) + this.map.set(key, value) + return value + } + } + + delete (key) { + return this.map.delete(key) + } + + set (key, value) { + const deleted = this.delete(key) + + if (!deleted && value !== undefined) { + // If cache is full, delete the least recently used item + if (this.map.size >= this.max) { + const firstKey = this.map.keys().next().value + this.delete(firstKey) + } + + this.map.set(key, value) + } + + return this + } +} + +module.exports = LRUCache + + +/***/ }), + +/***/ 741: +/***/ ((module) => { + + + +// parse out just the options we care about +const looseOption = Object.freeze({ loose: true }) +const emptyOpts = Object.freeze({ }) +const parseOptions = options => { + if (!options) { + return emptyOpts + } + + if (typeof options !== 'object') { + return looseOption + } + + return options +} +module.exports = parseOptions + + +/***/ }), + +/***/ 3744: +/***/ ((module, exports, __nccwpck_require__) => { + + + +const { + MAX_SAFE_COMPONENT_LENGTH, + MAX_SAFE_BUILD_LENGTH, + MAX_LENGTH, +} = __nccwpck_require__(2780) +const debug = __nccwpck_require__(1370) +exports = module.exports = {} + +// The actual regexps go on exports.re +const re = exports.re = [] +const safeRe = exports.safeRe = [] +const src = exports.src = [] +const safeSrc = exports.safeSrc = [] +const t = exports.t = {} +let R = 0 + +const LETTERDASHNUMBER = '[a-zA-Z0-9-]' + +// Replace some greedy regex tokens to prevent regex dos issues. These regex are +// used internally via the safeRe object since all inputs in this library get +// normalized first to trim and collapse all extra whitespace. The original +// regexes are exported for userland consumption and lower level usage. A +// future breaking change could export the safer regex only with a note that +// all input should have extra whitespace removed. +const safeRegexReplacements = [ + ['\\s', 1], + ['\\d', MAX_LENGTH], + [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], +] + +const makeSafeRegex = (value) => { + for (const [token, max] of safeRegexReplacements) { + value = value + .split(`${token}*`).join(`${token}{0,${max}}`) + .split(`${token}+`).join(`${token}{1,${max}}`) + } + return value +} + +const createToken = (name, value, isGlobal) => { + const safe = makeSafeRegex(value) + const index = R++ + debug(name, index, value) + t[name] = index + src[index] = value + safeSrc[index] = safe + re[index] = new RegExp(value, isGlobal ? 'g' : undefined) + safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) +} + +// The following Regular Expressions can be used for tokenizing, +// validating, and parsing SemVer version strings. + +// ## Numeric Identifier +// A single `0`, or a non-zero digit followed by zero or more digits. + +createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') +createToken('NUMERICIDENTIFIERLOOSE', '\\d+') + +// ## Non-numeric Identifier +// Zero or more digits, followed by a letter or hyphen, and then zero or +// more letters, digits, or hyphens. + +createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) + +// ## Main Version +// Three dot-separated numeric identifiers. + +createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})\\.` + + `(${src[t.NUMERICIDENTIFIER]})`) + +createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + + `(${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version Identifier +// A numeric identifier, or a non-numeric identifier. +// Non-numberic identifiers include numberic identifiers but can be longer. +// Therefore non-numberic identifiers must go first. + +createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIER]})`) + +createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] +}|${src[t.NUMERICIDENTIFIERLOOSE]})`) + +// ## Pre-release Version +// Hyphen, followed by one or more dot-separated pre-release version +// identifiers. + +createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] +}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) + +createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] +}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) + +// ## Build Metadata Identifier +// Any combination of digits, letters, or hyphens. + +createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) + +// ## Build Metadata +// Plus sign, followed by one or more period-separated build metadata +// identifiers. + +createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] +}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) + +// ## Full Version String +// A main version, followed optionally by a pre-release version and +// build metadata. + +// Note that the only major, minor, patch, and pre-release sections of +// the version string are capturing groups. The build metadata is not a +// capturing group, because it should not ever be used in version +// comparison. + +createToken('FULLPLAIN', `v?${src[t.MAINVERSION] +}${src[t.PRERELEASE]}?${ + src[t.BUILD]}?`) + +createToken('FULL', `^${src[t.FULLPLAIN]}$`) + +// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. +// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty +// common in the npm registry. +createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] +}${src[t.PRERELEASELOOSE]}?${ + src[t.BUILD]}?`) + +createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) + +createToken('GTLT', '((?:<|>)?=?)') + +// Something like "2.*" or "1.2.x". +// Note that "x.x" is a valid xRange identifer, meaning "any version" +// Only the first item is strictly required. +createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) +createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) + +createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + + `(?:${src[t.PRERELEASE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + + `(?:${src[t.PRERELEASELOOSE]})?${ + src[t.BUILD]}?` + + `)?)?`) + +createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) +createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) + +// Coercion. +// Extract anything that could conceivably be a part of a valid semver +createToken('COERCEPLAIN', `${'(^|[^\\d])' + + '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + + `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) +createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) +createToken('COERCEFULL', src[t.COERCEPLAIN] + + `(?:${src[t.PRERELEASE]})?` + + `(?:${src[t.BUILD]})?` + + `(?:$|[^\\d])`) +createToken('COERCERTL', src[t.COERCE], true) +createToken('COERCERTLFULL', src[t.COERCEFULL], true) + +// Tilde ranges. +// Meaning is "reasonably at or greater than" +createToken('LONETILDE', '(?:~>?)') + +createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) +exports.tildeTrimReplace = '$1~' + +createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) +createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) + +// Caret ranges. +// Meaning is "at least and backwards compatible with" +createToken('LONECARET', '(?:\\^)') + +createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) +exports.caretTrimReplace = '$1^' + +createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) +createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) + +// A simple gt/lt/eq thing, or just "" to indicate "any version" +createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) +createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) + +// An expression to strip any whitespace between the gtlt and the thing +// it modifies, so that `> 1.2.3` ==> `>1.2.3` +createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] +}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) +exports.comparatorTrimReplace = '$1$2$3' + +// Something like `1.2.3 - 1.2.4` +// Note that these all use the loose form, because they'll be +// checked against either the strict or loose comparator form +// later. +createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAIN]})` + + `\\s*$`) + +createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + + `\\s+-\\s+` + + `(${src[t.XRANGEPLAINLOOSE]})` + + `\\s*$`) + +// Star ranges basically just allow anything at all. +createToken('STAR', '(<|>)?=?\\s*\\*') +// >=0.0.0 is like a star +createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') +createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') + + +/***/ }), + +/***/ 761: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +// Determine if version is greater than all the versions possible in the range. +const outside = __nccwpck_require__(2382) +const gtr = (version, range, options) => outside(version, range, '>', options) +module.exports = gtr + + +/***/ }), + +/***/ 7978: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Range = __nccwpck_require__(9005) +const intersects = (r1, r2, options) => { + r1 = new Range(r1, options) + r2 = new Range(r2, options) + return r1.intersects(r2, options) +} +module.exports = intersects + + +/***/ }), + +/***/ 4624: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const outside = __nccwpck_require__(2382) +// Determine if version is less than all the versions possible in the range +const ltr = (version, range, options) => outside(version, range, '<', options) +module.exports = ltr + + +/***/ }), + +/***/ 7890: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) +const Range = __nccwpck_require__(9005) + +const maxSatisfying = (versions, range, options) => { + let max = null + let maxSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!max || maxSV.compare(v) === -1) { + // compare(max, v, true) + max = v + maxSV = new SemVer(max, options) + } + } + }) + return max +} +module.exports = maxSatisfying + + +/***/ }), + +/***/ 5320: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) +const Range = __nccwpck_require__(9005) +const minSatisfying = (versions, range, options) => { + let min = null + let minSV = null + let rangeObj = null + try { + rangeObj = new Range(range, options) + } catch (er) { + return null + } + versions.forEach((v) => { + if (rangeObj.test(v)) { + // satisfies(v, range, options) + if (!min || minSV.compare(v) === 1) { + // compare(min, v, true) + min = v + minSV = new SemVer(min, options) + } + } + }) + return min +} +module.exports = minSatisfying + + +/***/ }), + +/***/ 2067: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) +const Range = __nccwpck_require__(9005) +const gt = __nccwpck_require__(4430) + +const minVersion = (range, loose) => { + range = new Range(range, loose) + + let minver = new SemVer('0.0.0') + if (range.test(minver)) { + return minver + } + + minver = new SemVer('0.0.0-0') + if (range.test(minver)) { + return minver + } + + minver = null + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let setMin = null + comparators.forEach((comparator) => { + // Clone to avoid manipulating the comparator's semver object. + const compver = new SemVer(comparator.semver.version) + switch (comparator.operator) { + case '>': + if (compver.prerelease.length === 0) { + compver.patch++ + } else { + compver.prerelease.push(0) + } + compver.raw = compver.format() + /* fallthrough */ + case '': + case '>=': + if (!setMin || gt(compver, setMin)) { + setMin = compver + } + break + case '<': + case '<=': + /* Ignore maximum versions */ + break + /* istanbul ignore next */ + default: + throw new Error(`Unexpected operation: ${comparator.operator}`) + } + }) + if (setMin && (!minver || gt(minver, setMin))) { + minver = setMin + } + } + + if (minver && range.test(minver)) { + return minver + } + + return null +} +module.exports = minVersion + + +/***/ }), + +/***/ 2382: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const SemVer = __nccwpck_require__(3542) +const Comparator = __nccwpck_require__(9018) +const { ANY } = Comparator +const Range = __nccwpck_require__(9005) +const satisfies = __nccwpck_require__(5344) +const gt = __nccwpck_require__(4430) +const lt = __nccwpck_require__(401) +const lte = __nccwpck_require__(6162) +const gte = __nccwpck_require__(4167) + +const outside = (version, range, hilo, options) => { + version = new SemVer(version, options) + range = new Range(range, options) + + let gtfn, ltefn, ltfn, comp, ecomp + switch (hilo) { + case '>': + gtfn = gt + ltefn = lte + ltfn = lt + comp = '>' + ecomp = '>=' + break + case '<': + gtfn = lt + ltefn = gte + ltfn = gt + comp = '<' + ecomp = '<=' + break + default: + throw new TypeError('Must provide a hilo val of "<" or ">"') + } + + // If it satisfies the range it is not outside + if (satisfies(version, range, options)) { + return false + } + + // From now on, variable terms are as if we're in "gtr" mode. + // but note that everything is flipped for the "ltr" function. + + for (let i = 0; i < range.set.length; ++i) { + const comparators = range.set[i] + + let high = null + let low = null + + comparators.forEach((comparator) => { + if (comparator.semver === ANY) { + comparator = new Comparator('>=0.0.0') + } + high = high || comparator + low = low || comparator + if (gtfn(comparator.semver, high.semver, options)) { + high = comparator + } else if (ltfn(comparator.semver, low.semver, options)) { + low = comparator + } + }) + + // If the edge version comparator has a operator then our version + // isn't outside it + if (high.operator === comp || high.operator === ecomp) { + return false + } + + // If the lowest version comparator has an operator and our version + // is less than it then it isn't higher than the range + if ((!low.operator || low.operator === comp) && + ltefn(version, low.semver)) { + return false + } else if (low.operator === ecomp && ltfn(version, low.semver)) { + return false + } + } + return true +} + +module.exports = outside + + +/***/ }), + +/***/ 9615: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +// given a set of versions and a range, create a "simplified" range +// that includes the same versions that the original range does +// If the original range is shorter than the simplified one, return that. +const satisfies = __nccwpck_require__(5344) +const compare = __nccwpck_require__(8534) +module.exports = (versions, range, options) => { + const set = [] + let first = null + let prev = null + const v = versions.sort((a, b) => compare(a, b, options)) + for (const version of v) { + const included = satisfies(version, range, options) + if (included) { + prev = version + if (!first) { + first = version + } + } else { + if (prev) { + set.push([first, prev]) + } + prev = null + first = null + } + } + if (first) { + set.push([first, null]) + } + + const ranges = [] + for (const [min, max] of set) { + if (min === max) { + ranges.push(min) + } else if (!max && min === v[0]) { + ranges.push('*') + } else if (!max) { + ranges.push(`>=${min}`) + } else if (min === v[0]) { + ranges.push(`<=${max}`) + } else { + ranges.push(`${min} - ${max}`) + } + } + const simplified = ranges.join(' || ') + const original = typeof range.raw === 'string' ? range.raw : String(range) + return simplified.length < original.length ? simplified : range +} + + +/***/ }), + +/***/ 7710: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Range = __nccwpck_require__(9005) +const Comparator = __nccwpck_require__(9018) +const { ANY } = Comparator +const satisfies = __nccwpck_require__(5344) +const compare = __nccwpck_require__(8534) + +// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: +// - Every simple range `r1, r2, ...` is a null set, OR +// - Every simple range `r1, r2, ...` which is not a null set is a subset of +// some `R1, R2, ...` +// +// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: +// - If c is only the ANY comparator +// - If C is only the ANY comparator, return true +// - Else if in prerelease mode, return false +// - else replace c with `[>=0.0.0]` +// - If C is only the ANY comparator +// - if in prerelease mode, return true +// - else replace C with `[>=0.0.0]` +// - Let EQ be the set of = comparators in c +// - If EQ is more than one, return true (null set) +// - Let GT be the highest > or >= comparator in c +// - Let LT be the lowest < or <= comparator in c +// - If GT and LT, and GT.semver > LT.semver, return true (null set) +// - If any C is a = range, and GT or LT are set, return false +// - If EQ +// - If GT, and EQ does not satisfy GT, return true (null set) +// - If LT, and EQ does not satisfy LT, return true (null set) +// - If EQ satisfies every C, return true +// - Else return false +// - If GT +// - If GT.semver is lower than any > or >= comp in C, return false +// - If GT is >=, and GT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the GT.semver tuple, return false +// - If LT +// - If LT.semver is greater than any < or <= comp in C, return false +// - If LT is <=, and LT.semver does not satisfy every C, return false +// - If GT.semver has a prerelease, and not in prerelease mode +// - If no C has a prerelease and the LT.semver tuple, return false +// - Else return true + +const subset = (sub, dom, options = {}) => { + if (sub === dom) { + return true + } + + sub = new Range(sub, options) + dom = new Range(dom, options) + let sawNonNull = false + + OUTER: for (const simpleSub of sub.set) { + for (const simpleDom of dom.set) { + const isSub = simpleSubset(simpleSub, simpleDom, options) + sawNonNull = sawNonNull || isSub !== null + if (isSub) { + continue OUTER + } + } + // the null set is a subset of everything, but null simple ranges in + // a complex range should be ignored. so if we saw a non-null range, + // then we know this isn't a subset, but if EVERY simple range was null, + // then it is a subset. + if (sawNonNull) { + return false + } + } + return true +} + +const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] +const minimumVersion = [new Comparator('>=0.0.0')] + +const simpleSubset = (sub, dom, options) => { + if (sub === dom) { + return true + } + + if (sub.length === 1 && sub[0].semver === ANY) { + if (dom.length === 1 && dom[0].semver === ANY) { + return true + } else if (options.includePrerelease) { + sub = minimumVersionWithPreRelease + } else { + sub = minimumVersion + } + } + + if (dom.length === 1 && dom[0].semver === ANY) { + if (options.includePrerelease) { + return true + } else { + dom = minimumVersion + } + } + + const eqSet = new Set() + let gt, lt + for (const c of sub) { + if (c.operator === '>' || c.operator === '>=') { + gt = higherGT(gt, c, options) + } else if (c.operator === '<' || c.operator === '<=') { + lt = lowerLT(lt, c, options) + } else { + eqSet.add(c.semver) + } + } + + if (eqSet.size > 1) { + return null + } + + let gtltComp + if (gt && lt) { + gtltComp = compare(gt.semver, lt.semver, options) + if (gtltComp > 0) { + return null + } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { + return null + } + } + + // will iterate one or zero times + for (const eq of eqSet) { + if (gt && !satisfies(eq, String(gt), options)) { + return null + } + + if (lt && !satisfies(eq, String(lt), options)) { + return null + } + + for (const c of dom) { + if (!satisfies(eq, String(c), options)) { + return false + } + } + + return true + } + + let higher, lower + let hasDomLT, hasDomGT + // if the subset has a prerelease, we need a comparator in the superset + // with the same tuple and a prerelease, or it's not a subset + let needDomLTPre = lt && + !options.includePrerelease && + lt.semver.prerelease.length ? lt.semver : false + let needDomGTPre = gt && + !options.includePrerelease && + gt.semver.prerelease.length ? gt.semver : false + // exception: <1.2.3-0 is the same as <1.2.3 + if (needDomLTPre && needDomLTPre.prerelease.length === 1 && + lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { + needDomLTPre = false + } + + for (const c of dom) { + hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' + hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' + if (gt) { + if (needDomGTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomGTPre.major && + c.semver.minor === needDomGTPre.minor && + c.semver.patch === needDomGTPre.patch) { + needDomGTPre = false + } + } + if (c.operator === '>' || c.operator === '>=') { + higher = higherGT(gt, c, options) + if (higher === c && higher !== gt) { + return false + } + } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { + return false + } + } + if (lt) { + if (needDomLTPre) { + if (c.semver.prerelease && c.semver.prerelease.length && + c.semver.major === needDomLTPre.major && + c.semver.minor === needDomLTPre.minor && + c.semver.patch === needDomLTPre.patch) { + needDomLTPre = false + } + } + if (c.operator === '<' || c.operator === '<=') { + lower = lowerLT(lt, c, options) + if (lower === c && lower !== lt) { + return false + } + } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { + return false + } + } + if (!c.operator && (lt || gt) && gtltComp !== 0) { + return false + } + } + + // if there was a < or >, and nothing in the dom, then must be false + // UNLESS it was limited by another range in the other direction. + // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 + if (gt && hasDomLT && !lt && gtltComp !== 0) { + return false + } + + if (lt && hasDomGT && !gt && gtltComp !== 0) { + return false + } + + // we needed a prerelease range in a specific tuple, but didn't get one + // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, + // because it includes prereleases in the 1.2.3 tuple + if (needDomGTPre || needDomLTPre) { + return false + } + + return true +} + +// >=1.2.3 is lower than >1.2.3 +const higherGT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp > 0 ? a + : comp < 0 ? b + : b.operator === '>' && a.operator === '>=' ? b + : a +} + +// <=1.2.3 is higher than <1.2.3 +const lowerLT = (a, b, options) => { + if (!a) { + return b + } + const comp = compare(a.semver, b.semver, options) + return comp < 0 ? a + : comp > 0 ? b + : b.operator === '<' && a.operator === '<=' ? b + : a +} + +module.exports = subset + + +/***/ }), + +/***/ 6493: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Range = __nccwpck_require__(9005) + +// Mostly just for testing and legacy API reasons +const toComparators = (range, options) => + new Range(range, options).set + .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) + +module.exports = toComparators + + +/***/ }), + +/***/ 8340: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Range = __nccwpck_require__(9005) +const validRange = (range, options) => { + try { + // Return '*' instead of '' so that truthiness works. + // This will throw if it's invalid anyway + return new Range(range, options).range || '*' + } catch (er) { + return null + } +} +module.exports = validRange + + +/***/ }), + +/***/ 5560: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +var wrappy = __nccwpck_require__(8264) +module.exports = wrappy(once) +module.exports.strict = wrappy(onceStrict) + +once.proto = once(function () { + Object.defineProperty(Function.prototype, 'once', { + value: function () { + return once(this) + }, + configurable: true + }) + + Object.defineProperty(Function.prototype, 'onceStrict', { + value: function () { + return onceStrict(this) + }, + configurable: true + }) +}) + +function once (fn) { + var f = function () { + if (f.called) return f.value + f.called = true + return f.value = fn.apply(this, arguments) + } + f.called = false + return f +} + +function onceStrict (fn) { + var f = function () { + if (f.called) + throw new Error(f.onceError) + f.called = true + return f.value = fn.apply(this, arguments) + } + var name = fn.name || 'Function wrapped with `once`' + f.onceError = name + " shouldn't be called more than once" + f.called = false + return f +} + + +/***/ }), + +/***/ 2766: +/***/ ((module) => { + + +module.exports = (promise, onFinally) => { + onFinally = onFinally || (() => {}); + + return promise.then( + val => new Promise(resolve => { + resolve(onFinally()); + }).then(() => val), + err => new Promise(resolve => { + resolve(onFinally()); + }).then(() => { + throw err; + }) + ); +}; + + +/***/ }), + +/***/ 6459: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const EventEmitter = __nccwpck_require__(2415); +const p_timeout_1 = __nccwpck_require__(4802); +const priority_queue_1 = __nccwpck_require__(5905); +// eslint-disable-next-line @typescript-eslint/no-empty-function +const empty = () => { }; +const timeoutError = new p_timeout_1.TimeoutError(); +/** +Promise queue with concurrency control. +*/ +class PQueue extends EventEmitter { + constructor(options) { + var _a, _b, _c, _d; + super(); + this._intervalCount = 0; + this._intervalEnd = 0; + this._pendingCount = 0; + this._resolveEmpty = empty; + this._resolveIdle = empty; + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); + if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { + throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`); + } + if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { + throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`); + } + this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; + this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; + this._intervalCap = options.intervalCap; + this._interval = options.interval; + this._queue = new options.queueClass(); + this._queueClass = options.queueClass; + this.concurrency = options.concurrency; + this._timeout = options.timeout; + this._throwOnTimeout = options.throwOnTimeout === true; + this._isPaused = options.autoStart === false; + } + get _doesIntervalAllowAnother() { + return this._isIntervalIgnored || this._intervalCount < this._intervalCap; + } + get _doesConcurrentAllowAnother() { + return this._pendingCount < this._concurrency; + } + _next() { + this._pendingCount--; + this._tryToStartAnother(); + this.emit('next'); + } + _resolvePromises() { + this._resolveEmpty(); + this._resolveEmpty = empty; + if (this._pendingCount === 0) { + this._resolveIdle(); + this._resolveIdle = empty; + this.emit('idle'); + } + } + _onResumeInterval() { + this._onInterval(); + this._initializeIntervalIfNeeded(); + this._timeoutId = undefined; + } + _isIntervalPaused() { + const now = Date.now(); + if (this._intervalId === undefined) { + const delay = this._intervalEnd - now; + if (delay < 0) { + // Act as the interval was done + // We don't need to resume it here because it will be resumed on line 160 + this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0; + } + else { + // Act as the interval is pending + if (this._timeoutId === undefined) { + this._timeoutId = setTimeout(() => { + this._onResumeInterval(); + }, delay); + } + return true; + } + } + return false; + } + _tryToStartAnother() { + if (this._queue.size === 0) { + // We can clear the interval ("pause") + // Because we can redo it later ("resume") + if (this._intervalId) { + clearInterval(this._intervalId); + } + this._intervalId = undefined; + this._resolvePromises(); + return false; + } + if (!this._isPaused) { + const canInitializeInterval = !this._isIntervalPaused(); + if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { + const job = this._queue.dequeue(); + if (!job) { + return false; + } + this.emit('active'); + job(); + if (canInitializeInterval) { + this._initializeIntervalIfNeeded(); + } + return true; + } + } + return false; + } + _initializeIntervalIfNeeded() { + if (this._isIntervalIgnored || this._intervalId !== undefined) { + return; + } + this._intervalId = setInterval(() => { + this._onInterval(); + }, this._interval); + this._intervalEnd = Date.now() + this._interval; + } + _onInterval() { + if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { + clearInterval(this._intervalId); + this._intervalId = undefined; + } + this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; + this._processQueue(); + } + /** + Executes all queued functions until it reaches the limit. + */ + _processQueue() { + // eslint-disable-next-line no-empty + while (this._tryToStartAnother()) { } + } + get concurrency() { + return this._concurrency; + } + set concurrency(newConcurrency) { + if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) { + throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); + } + this._concurrency = newConcurrency; + this._processQueue(); + } + /** + Adds a sync or async task to the queue. Always returns a promise. + */ + async add(fn, options = {}) { + return new Promise((resolve, reject) => { + const run = async () => { + this._pendingCount++; + this._intervalCount++; + try { + const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => { + if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) { + reject(timeoutError); + } + return undefined; + }); + resolve(await operation); + } + catch (error) { + reject(error); + } + this._next(); + }; + this._queue.enqueue(run, options); + this._tryToStartAnother(); + this.emit('add'); + }); + } + /** + Same as `.add()`, but accepts an array of sync or async functions. + + @returns A promise that resolves when all functions are resolved. + */ + async addAll(functions, options) { + return Promise.all(functions.map(async (function_) => this.add(function_, options))); + } + /** + Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) + */ + start() { + if (!this._isPaused) { + return this; + } + this._isPaused = false; + this._processQueue(); + return this; + } + /** + Put queue execution on hold. + */ + pause() { + this._isPaused = true; + } + /** + Clear the queue. + */ + clear() { + this._queue = new this._queueClass(); + } + /** + Can be called multiple times. Useful if you for example add additional items at a later time. + + @returns A promise that settles when the queue becomes empty. + */ + async onEmpty() { + // Instantly resolve if the queue is empty + if (this._queue.size === 0) { + return; + } + return new Promise(resolve => { + const existingResolve = this._resolveEmpty; + this._resolveEmpty = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. + + @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. + */ + async onIdle() { + // Instantly resolve if none pending and if nothing else is queued + if (this._pendingCount === 0 && this._queue.size === 0) { + return; + } + return new Promise(resolve => { + const existingResolve = this._resolveIdle; + this._resolveIdle = () => { + existingResolve(); + resolve(); + }; + }); + } + /** + Size of the queue. + */ + get size() { + return this._queue.size; + } + /** + Size of the queue, filtered by the given options. + + For example, this can be used to find the number of items remaining in the queue with a specific priority level. + */ + sizeBy(options) { + // eslint-disable-next-line unicorn/no-fn-reference-in-iterator + return this._queue.filter(options).length; + } + /** + Number of pending promises. + */ + get pending() { + return this._pendingCount; + } + /** + Whether the queue is currently paused. + */ + get isPaused() { + return this._isPaused; + } + get timeout() { + return this._timeout; + } + /** + Set the timeout for future operations. + */ + set timeout(milliseconds) { + this._timeout = milliseconds; + } +} +exports["default"] = PQueue; + + +/***/ }), + +/***/ 9015: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound +// Used to compute insertion index to keep queue sorted after insertion +function lowerBound(array, value, comparator) { + let first = 0; + let count = array.length; + while (count > 0) { + const step = (count / 2) | 0; + let it = first + step; + if (comparator(array[it], value) <= 0) { + first = ++it; + count -= step + 1; + } + else { + count = step; + } + } + return first; +} +exports["default"] = lowerBound; + + +/***/ }), + +/***/ 5905: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +const lower_bound_1 = __nccwpck_require__(9015); +class PriorityQueue { + constructor() { + this._queue = []; + } + enqueue(run, options) { + options = Object.assign({ priority: 0 }, options); + const element = { + priority: options.priority, + run + }; + if (this.size && this._queue[this.size - 1].priority >= options.priority) { + this._queue.push(element); + return; + } + const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); + this._queue.splice(index, 0, element); + } + dequeue() { + const item = this._queue.shift(); + return item === null || item === void 0 ? void 0 : item.run; + } + filter(options) { + return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); + } + get size() { + return this._queue.length; + } +} +exports["default"] = PriorityQueue; + + +/***/ }), + +/***/ 4802: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const pFinally = __nccwpck_require__(2766); + +class TimeoutError extends Error { + constructor(message) { + super(message); + this.name = 'TimeoutError'; + } +} + +const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { + if (typeof milliseconds !== 'number' || milliseconds < 0) { + throw new TypeError('Expected `milliseconds` to be a positive number'); + } + + if (milliseconds === Infinity) { + resolve(promise); + return; + } + + const timer = setTimeout(() => { + if (typeof fallback === 'function') { + try { + resolve(fallback()); + } catch (error) { + reject(error); + } + + return; + } + + const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`; + const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); + + if (typeof promise.cancel === 'function') { + promise.cancel(); + } + + reject(timeoutError); + }, milliseconds); + + // TODO: Use native `finally` keyword when targeting Node.js 10 + pFinally( + // eslint-disable-next-line promise/prefer-await-to-then + promise.then(resolve, reject), + () => { + clearTimeout(timer); + } + ); +}); + +module.exports = pTimeout; +// TODO: Remove this for the next major release +module.exports["default"] = pTimeout; + +module.exports.TimeoutError = TimeoutError; + + +/***/ }), + +/***/ 770: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +module.exports = __nccwpck_require__(218); + + +/***/ }), + +/***/ 218: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +var net = __nccwpck_require__(9278); +var tls = __nccwpck_require__(4756); +var http = __nccwpck_require__(8611); +var https = __nccwpck_require__(5692); +var events = __nccwpck_require__(4434); +var assert = __nccwpck_require__(2613); +var util = __nccwpck_require__(9023); + + +exports.httpOverHttp = httpOverHttp; +exports.httpsOverHttp = httpsOverHttp; +exports.httpOverHttps = httpOverHttps; +exports.httpsOverHttps = httpsOverHttps; + + +function httpOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + return agent; +} + +function httpsOverHttp(options) { + var agent = new TunnelingAgent(options); + agent.request = http.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} + +function httpOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + return agent; +} + +function httpsOverHttps(options) { + var agent = new TunnelingAgent(options); + agent.request = https.request; + agent.createSocket = createSecureSocket; + agent.defaultPort = 443; + return agent; +} + + +function TunnelingAgent(options) { + var self = this; + self.options = options || {}; + self.proxyOptions = self.options.proxy || {}; + self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; + self.requests = []; + self.sockets = []; + + self.on('free', function onFree(socket, host, port, localAddress) { + var options = toOptions(host, port, localAddress); + for (var i = 0, len = self.requests.length; i < len; ++i) { + var pending = self.requests[i]; + if (pending.host === options.host && pending.port === options.port) { + // Detect the request to connect same origin server, + // reuse the connection. + self.requests.splice(i, 1); + pending.request.onSocket(socket); + return; + } + } + socket.destroy(); + self.removeSocket(socket); + }); +} +util.inherits(TunnelingAgent, events.EventEmitter); + +TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { + var self = this; + var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); + + if (self.sockets.length >= this.maxSockets) { + // We are over limit so we'll add it to the queue. + self.requests.push(options); + return; + } + + // If we are under maxSockets create a new one. + self.createSocket(options, function(socket) { + socket.on('free', onFree); + socket.on('close', onCloseOrRemove); + socket.on('agentRemove', onCloseOrRemove); + req.onSocket(socket); + + function onFree() { + self.emit('free', socket, options); + } + + function onCloseOrRemove(err) { + self.removeSocket(socket); + socket.removeListener('free', onFree); + socket.removeListener('close', onCloseOrRemove); + socket.removeListener('agentRemove', onCloseOrRemove); + } + }); +}; + +TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { + var self = this; + var placeholder = {}; + self.sockets.push(placeholder); + + var connectOptions = mergeOptions({}, self.proxyOptions, { + method: 'CONNECT', + path: options.host + ':' + options.port, + agent: false, + headers: { + host: options.host + ':' + options.port + } + }); + if (options.localAddress) { + connectOptions.localAddress = options.localAddress; + } + if (connectOptions.proxyAuth) { + connectOptions.headers = connectOptions.headers || {}; + connectOptions.headers['Proxy-Authorization'] = 'Basic ' + + new Buffer(connectOptions.proxyAuth).toString('base64'); + } + + debug('making CONNECT request'); + var connectReq = self.request(connectOptions); + connectReq.useChunkedEncodingByDefault = false; // for v0.6 + connectReq.once('response', onResponse); // for v0.6 + connectReq.once('upgrade', onUpgrade); // for v0.6 + connectReq.once('connect', onConnect); // for v0.7 or later + connectReq.once('error', onError); + connectReq.end(); + + function onResponse(res) { + // Very hacky. This is necessary to avoid http-parser leaks. + res.upgrade = true; + } + + function onUpgrade(res, socket, head) { + // Hacky. + process.nextTick(function() { + onConnect(res, socket, head); + }); + } + + function onConnect(res, socket, head) { + connectReq.removeAllListeners(); + socket.removeAllListeners(); + + if (res.statusCode !== 200) { + debug('tunneling socket could not be established, statusCode=%d', + res.statusCode); + socket.destroy(); + var error = new Error('tunneling socket could not be established, ' + + 'statusCode=' + res.statusCode); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + if (head.length > 0) { + debug('got illegal response body from proxy'); + socket.destroy(); + var error = new Error('got illegal response body from proxy'); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + return; + } + debug('tunneling connection has established'); + self.sockets[self.sockets.indexOf(placeholder)] = socket; + return cb(socket); + } + + function onError(cause) { + connectReq.removeAllListeners(); + + debug('tunneling socket could not be established, cause=%s\n', + cause.message, cause.stack); + var error = new Error('tunneling socket could not be established, ' + + 'cause=' + cause.message); + error.code = 'ECONNRESET'; + options.request.emit('error', error); + self.removeSocket(placeholder); + } +}; + +TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { + var pos = this.sockets.indexOf(socket) + if (pos === -1) { + return; + } + this.sockets.splice(pos, 1); + + var pending = this.requests.shift(); + if (pending) { + // If we have pending requests and a socket gets closed a new one + // needs to be created to take over in the pool for the one that closed. + this.createSocket(pending, function(socket) { + pending.request.onSocket(socket); + }); + } +}; + +function createSecureSocket(options, cb) { + var self = this; + TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { + var hostHeader = options.request.getHeader('host'); + var tlsOptions = mergeOptions({}, self.options, { + socket: socket, + servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host + }); + + // 0 is dummy port for v0.6 + var secureSocket = tls.connect(0, tlsOptions); + self.sockets[self.sockets.indexOf(socket)] = secureSocket; + cb(secureSocket); + }); +} + + +function toOptions(host, port, localAddress) { + if (typeof host === 'string') { // since v0.10 + return { + host: host, + port: port, + localAddress: localAddress + }; + } + return host; // for v0.11 or later +} + +function mergeOptions(target) { + for (var i = 1, len = arguments.length; i < len; ++i) { + var overrides = arguments[i]; + if (typeof overrides === 'object') { + var keys = Object.keys(overrides); + for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { + var k = keys[j]; + if (overrides[k] !== undefined) { + target[k] = overrides[k]; + } + } + } + } + return target; +} + + +var debug; +if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { + debug = function() { + var args = Array.prototype.slice.call(arguments); + if (typeof args[0] === 'string') { + args[0] = 'TUNNEL: ' + args[0]; + } else { + args.unshift('TUNNEL:'); + } + console.error.apply(console, args); + } +} else { + debug = function() {}; +} +exports.debug = debug; // for test + + +/***/ }), + +/***/ 6752: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Client = __nccwpck_require__(6197) +const Dispatcher = __nccwpck_require__(992) +const errors = __nccwpck_require__(8707) +const Pool = __nccwpck_require__(5076) +const BalancedPool = __nccwpck_require__(1093) +const Agent = __nccwpck_require__(9965) +const util = __nccwpck_require__(3440) +const { InvalidArgumentError } = errors +const api = __nccwpck_require__(6615) +const buildConnector = __nccwpck_require__(9136) +const MockClient = __nccwpck_require__(7365) +const MockAgent = __nccwpck_require__(7501) +const MockPool = __nccwpck_require__(4004) +const mockErrors = __nccwpck_require__(2429) +const ProxyAgent = __nccwpck_require__(2720) +const RetryHandler = __nccwpck_require__(3573) +const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(2581) +const DecoratorHandler = __nccwpck_require__(8840) +const RedirectHandler = __nccwpck_require__(8299) +const createRedirectInterceptor = __nccwpck_require__(4415) + +let hasCrypto +try { + __nccwpck_require__(6982) + hasCrypto = true +} catch { + hasCrypto = false +} + +Object.assign(Dispatcher.prototype, api) + +module.exports.Dispatcher = Dispatcher +module.exports.Client = Client +module.exports.Pool = Pool +module.exports.BalancedPool = BalancedPool +module.exports.Agent = Agent +module.exports.ProxyAgent = ProxyAgent +module.exports.RetryHandler = RetryHandler + +module.exports.DecoratorHandler = DecoratorHandler +module.exports.RedirectHandler = RedirectHandler +module.exports.createRedirectInterceptor = createRedirectInterceptor + +module.exports.buildConnector = buildConnector +module.exports.errors = errors + +function makeDispatcher (fn) { + return (url, opts, handler) => { + if (typeof opts === 'function') { + handler = opts + opts = null + } + + if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { + throw new InvalidArgumentError('invalid url') + } + + if (opts != null && typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (opts && opts.path != null) { + if (typeof opts.path !== 'string') { + throw new InvalidArgumentError('invalid opts.path') + } + + let path = opts.path + if (!opts.path.startsWith('/')) { + path = `/${path}` + } + + url = new URL(util.parseOrigin(url).origin + path) + } else { + if (!opts) { + opts = typeof url === 'object' ? url : {} + } + + url = util.parseURL(url) + } + + const { agent, dispatcher = getGlobalDispatcher() } = opts + + if (agent) { + throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') + } + + return fn.call(dispatcher, { + ...opts, + origin: url.origin, + path: url.search ? `${url.pathname}${url.search}` : url.pathname, + method: opts.method || (opts.body ? 'PUT' : 'GET') + }, handler) + } +} + +module.exports.setGlobalDispatcher = setGlobalDispatcher +module.exports.getGlobalDispatcher = getGlobalDispatcher + +if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { + let fetchImpl = null + module.exports.fetch = async function fetch (resource) { + if (!fetchImpl) { + fetchImpl = (__nccwpck_require__(2315).fetch) + } + + try { + return await fetchImpl(...arguments) + } catch (err) { + if (typeof err === 'object') { + Error.captureStackTrace(err, this) + } + + throw err + } + } + module.exports.Headers = __nccwpck_require__(6349).Headers + module.exports.Response = __nccwpck_require__(8676).Response + module.exports.Request = __nccwpck_require__(5194).Request + module.exports.FormData = __nccwpck_require__(3073).FormData + module.exports.File = __nccwpck_require__(3041).File + module.exports.FileReader = __nccwpck_require__(2160).FileReader + + const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(5628) + + module.exports.setGlobalOrigin = setGlobalOrigin + module.exports.getGlobalOrigin = getGlobalOrigin + + const { CacheStorage } = __nccwpck_require__(4738) + const { kConstruct } = __nccwpck_require__(296) + + // Cache & CacheStorage are tightly coupled with fetch. Even if it may run + // in an older version of Node, it doesn't have any use without fetch. + module.exports.caches = new CacheStorage(kConstruct) +} + +if (util.nodeMajor >= 16) { + const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(3168) + + module.exports.deleteCookie = deleteCookie + module.exports.getCookies = getCookies + module.exports.getSetCookies = getSetCookies + module.exports.setCookie = setCookie + + const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) + + module.exports.parseMIMEType = parseMIMEType + module.exports.serializeAMimeType = serializeAMimeType +} + +if (util.nodeMajor >= 18 && hasCrypto) { + const { WebSocket } = __nccwpck_require__(5171) + + module.exports.WebSocket = WebSocket +} + +module.exports.request = makeDispatcher(api.request) +module.exports.stream = makeDispatcher(api.stream) +module.exports.pipeline = makeDispatcher(api.pipeline) +module.exports.connect = makeDispatcher(api.connect) +module.exports.upgrade = makeDispatcher(api.upgrade) + +module.exports.MockClient = MockClient +module.exports.MockPool = MockPool +module.exports.MockAgent = MockAgent +module.exports.mockErrors = mockErrors + + +/***/ }), + +/***/ 9965: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { InvalidArgumentError } = __nccwpck_require__(8707) +const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443) +const DispatcherBase = __nccwpck_require__(1) +const Pool = __nccwpck_require__(5076) +const Client = __nccwpck_require__(6197) +const util = __nccwpck_require__(3440) +const createRedirectInterceptor = __nccwpck_require__(4415) +const { WeakRef, FinalizationRegistry } = __nccwpck_require__(3194)() + +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kMaxRedirections = Symbol('maxRedirections') +const kOnDrain = Symbol('onDrain') +const kFactory = Symbol('factory') +const kFinalizer = Symbol('finalizer') +const kOptions = Symbol('options') + +function defaultFactory (origin, opts) { + return opts && opts.connections === 1 + ? new Client(origin, opts) + : new Pool(origin, opts) +} + +class Agent extends DispatcherBase { + constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { + super() + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + if (connect && typeof connect !== 'function') { + connect = { ...connect } + } + + this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) + ? options.interceptors.Agent + : [createRedirectInterceptor({ maxRedirections })] + + this[kOptions] = { ...util.deepClone(options), connect } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kMaxRedirections] = maxRedirections + this[kFactory] = factory + this[kClients] = new Map() + this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { + const ref = this[kClients].get(key) + if (ref !== undefined && ref.deref() === undefined) { + this[kClients].delete(key) + } + }) + + const agent = this + + this[kOnDrain] = (origin, targets) => { + agent.emit('drain', origin, [agent, ...targets]) + } + + this[kOnConnect] = (origin, targets) => { + agent.emit('connect', origin, [agent, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + agent.emit('disconnect', origin, [agent, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + agent.emit('connectionError', origin, [agent, ...targets], err) + } + } + + get [kRunning] () { + let ret = 0 + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore next: gc is undeterministic */ + if (client) { + ret += client[kRunning] + } + } + return ret + } + + [kDispatch] (opts, handler) { + let key + if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { + key = String(opts.origin) + } else { + throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') + } + + const ref = this[kClients].get(key) + + let dispatcher = ref ? ref.deref() : null + if (!dispatcher) { + dispatcher = this[kFactory](opts.origin, this[kOptions]) + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].set(key, new WeakRef(dispatcher)) + this[kFinalizer].register(dispatcher, key) + } + + return dispatcher.dispatch(opts, handler) + } + + async [kClose] () { + const closePromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + closePromises.push(client.close()) + } + } + + await Promise.all(closePromises) + } + + async [kDestroy] (err) { + const destroyPromises = [] + for (const ref of this[kClients].values()) { + const client = ref.deref() + /* istanbul ignore else: gc is undeterministic */ + if (client) { + destroyPromises.push(client.destroy(err)) + } + } + + await Promise.all(destroyPromises) + } +} + +module.exports = Agent + + +/***/ }), + +/***/ 158: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { addAbortListener } = __nccwpck_require__(3440) +const { RequestAbortedError } = __nccwpck_require__(8707) + +const kListener = Symbol('kListener') +const kSignal = Symbol('kSignal') + +function abort (self) { + if (self.abort) { + self.abort() + } else { + self.onError(new RequestAbortedError()) + } +} + +function addSignal (self, signal) { + self[kSignal] = null + self[kListener] = null + + if (!signal) { + return + } + + if (signal.aborted) { + abort(self) + return + } + + self[kSignal] = signal + self[kListener] = () => { + abort(self) + } + + addAbortListener(self[kSignal], self[kListener]) +} + +function removeSignal (self) { + if (!self[kSignal]) { + return + } + + if ('removeEventListener' in self[kSignal]) { + self[kSignal].removeEventListener('abort', self[kListener]) + } else { + self[kSignal].removeListener('abort', self[kListener]) + } + + self[kSignal] = null + self[kListener] = null +} + +module.exports = { + addSignal, + removeSignal +} + + +/***/ }), + +/***/ 4660: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { AsyncResource } = __nccwpck_require__(290) +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { addSignal, removeSignal } = __nccwpck_require__(158) + +class ConnectHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_CONNECT') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.callback = callback + this.abort = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders () { + throw new SocketError('bad connect', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this + + removeSignal(this) + + this.callback = null + + let headers = rawHeaders + // Indicates is an HTTP2Session + if (headers != null) { + headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + } + + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function connect (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + connect.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const connectHandler = new ConnectHandler(opts, callback) + this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = connect + + +/***/ }), + +/***/ 6862: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { + Readable, + Duplex, + PassThrough +} = __nccwpck_require__(2203) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { AsyncResource } = __nccwpck_require__(290) +const { addSignal, removeSignal } = __nccwpck_require__(158) +const assert = __nccwpck_require__(2613) + +const kResume = Symbol('resume') + +class PipelineRequest extends Readable { + constructor () { + super({ autoDestroy: true }) + + this[kResume] = null + } + + _read () { + const { [kResume]: resume } = this + + if (resume) { + this[kResume] = null + resume() + } + } + + _destroy (err, callback) { + this._read() + + callback(err) + } +} + +class PipelineResponse extends Readable { + constructor (resume) { + super({ autoDestroy: true }) + this[kResume] = resume + } + + _read () { + this[kResume]() + } + + _destroy (err, callback) { + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + callback(err) + } +} + +class PipelineHandler extends AsyncResource { + constructor (opts, handler) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof handler !== 'function') { + throw new InvalidArgumentError('invalid handler') + } + + const { signal, method, opaque, onInfo, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_PIPELINE') + + this.opaque = opaque || null + this.responseHeaders = responseHeaders || null + this.handler = handler + this.abort = null + this.context = null + this.onInfo = onInfo || null + + this.req = new PipelineRequest().on('error', util.nop) + + this.ret = new Duplex({ + readableObjectMode: opts.objectMode, + autoDestroy: true, + read: () => { + const { body } = this + + if (body && body.resume) { + body.resume() + } + }, + write: (chunk, encoding, callback) => { + const { req } = this + + if (req.push(chunk, encoding) || req._readableState.destroyed) { + callback() + } else { + req[kResume] = callback + } + }, + destroy: (err, callback) => { + const { body, req, res, ret, abort } = this + + if (!err && !ret._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (abort && err) { + abort() + } + + util.destroy(body, err) + util.destroy(req, err) + util.destroy(res, err) + + removeSignal(this) + + callback(err) + } + }).on('prefinish', () => { + const { req } = this + + // Node < 15 does not call _final in same tick. + req.push(null) + }) + + this.res = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + const { ret, res } = this + + assert(!res, 'pipeline cannot be retried') + + if (ret.destroyed) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume) { + const { opaque, handler, context } = this + + if (statusCode < 200) { + if (this.onInfo) { + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.onInfo({ statusCode, headers }) + } + return + } + + this.res = new PipelineResponse(resume) + + let body + try { + this.handler = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + body = this.runInAsyncScope(handler, null, { + statusCode, + headers, + opaque, + body: this.res, + context + }) + } catch (err) { + this.res.on('error', util.nop) + throw err + } + + if (!body || typeof body.on !== 'function') { + throw new InvalidReturnValueError('expected Readable') + } + + body + .on('data', (chunk) => { + const { ret, body } = this + + if (!ret.push(chunk) && body.pause) { + body.pause() + } + }) + .on('error', (err) => { + const { ret } = this + + util.destroy(ret, err) + }) + .on('end', () => { + const { ret } = this + + ret.push(null) + }) + .on('close', () => { + const { ret } = this + + if (!ret._readableState.ended) { + util.destroy(ret, new RequestAbortedError()) + } + }) + + this.body = body + } + + onData (chunk) { + const { res } = this + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this + res.push(null) + } + + onError (err) { + const { ret } = this + this.handler = null + util.destroy(ret, err) + } +} + +function pipeline (opts, handler) { + try { + const pipelineHandler = new PipelineHandler(opts, handler) + this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) + return pipelineHandler.ret + } catch (err) { + return new PassThrough().destroy(err) + } +} + +module.exports = pipeline + + +/***/ }), + +/***/ 4043: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Readable = __nccwpck_require__(9927) +const { + InvalidArgumentError, + RequestAbortedError +} = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) +const { AsyncResource } = __nccwpck_require__(290) +const { addSignal, removeSignal } = __nccwpck_require__(158) + +class RequestHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { + throw new InvalidArgumentError('invalid highWaterMark') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_REQUEST') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.res = null + this.abort = null + this.body = body + this.trailers = {} + this.context = null + this.onInfo = onInfo || null + this.throwOnError = throwOnError + this.highWaterMark = highWaterMark + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + const body = new Readable({ resume, abort, contentType, highWaterMark }) + + this.callback = null + this.res = body + if (callback !== null) { + if (this.throwOnError && statusCode >= 400) { + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body, contentType, statusCode, statusMessage, headers } + ) + } else { + this.runInAsyncScope(callback, null, null, { + statusCode, + headers, + trailers: this.trailers, + opaque, + body, + context + }) + } + } + } + + onData (chunk) { + const { res } = this + return res.push(chunk) + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + util.parseHeaders(trailers, this.trailers) + + res.push(null) + } + + onError (err) { + const { res, callback, body, opaque } = this + + removeSignal(this) + + if (callback) { + // TODO: Does this need queueMicrotask? + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (res) { + this.res = null + // Ensure all queued handlers are invoked before destroying res. + queueMicrotask(() => { + util.destroy(res, err) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function request (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + request.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new RequestHandler(opts, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = request +module.exports.RequestHandler = RequestHandler + + +/***/ }), + +/***/ 3560: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { finished, PassThrough } = __nccwpck_require__(2203) +const { + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError +} = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) +const { AsyncResource } = __nccwpck_require__(290) +const { addSignal, removeSignal } = __nccwpck_require__(158) + +class StreamHandler extends AsyncResource { + constructor (opts, factory, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts + + try { + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('invalid factory') + } + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + if (method === 'CONNECT') { + throw new InvalidArgumentError('invalid method') + } + + if (onInfo && typeof onInfo !== 'function') { + throw new InvalidArgumentError('invalid onInfo callback') + } + + super('UNDICI_STREAM') + } catch (err) { + if (util.isStream(body)) { + util.destroy(body.on('error', util.nop), err) + } + throw err + } + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.factory = factory + this.callback = callback + this.res = null + this.abort = null + this.context = null + this.trailers = null + this.body = body + this.onInfo = onInfo || null + this.throwOnError = throwOnError || false + + if (util.isStream(body)) { + body.on('error', (err) => { + this.onError(err) + }) + } + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = context + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const { factory, opaque, context, callback, responseHeaders } = this + + const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + + if (statusCode < 200) { + if (this.onInfo) { + this.onInfo({ statusCode, headers }) + } + return + } + + this.factory = null + + let res + + if (this.throwOnError && statusCode >= 400) { + const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers + const contentType = parsedHeaders['content-type'] + res = new PassThrough() + + this.callback = null + this.runInAsyncScope(getResolveErrorBodyCallback, null, + { callback, body: res, contentType, statusCode, statusMessage, headers } + ) + } else { + if (factory === null) { + return + } + + res = this.runInAsyncScope(factory, null, { + statusCode, + headers, + opaque, + context + }) + + if ( + !res || + typeof res.write !== 'function' || + typeof res.end !== 'function' || + typeof res.on !== 'function' + ) { + throw new InvalidReturnValueError('expected Writable') + } + + // TODO: Avoid finished. It registers an unnecessary amount of listeners. + finished(res, { readable: false }, (err) => { + const { callback, res, opaque, trailers, abort } = this + + this.res = null + if (err || !res.readable) { + util.destroy(res, err) + } + + this.callback = null + this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) + + if (err) { + abort() + } + }) + } + + res.on('drain', resume) + + this.res = res + + const needDrain = res.writableNeedDrain !== undefined + ? res.writableNeedDrain + : res._writableState && res._writableState.needDrain + + return needDrain !== true + } + + onData (chunk) { + const { res } = this + + return res ? res.write(chunk) : true + } + + onComplete (trailers) { + const { res } = this + + removeSignal(this) + + if (!res) { + return + } + + this.trailers = util.parseHeaders(trailers) + + res.end() + } + + onError (err) { + const { res, callback, opaque, body } = this + + removeSignal(this) + + this.factory = null + + if (res) { + this.res = null + util.destroy(res, err) + } else if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + + if (body) { + this.body = null + util.destroy(body, err) + } + } +} + +function stream (opts, factory, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + stream.call(this, opts, factory, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + this.dispatch(opts, new StreamHandler(opts, factory, callback)) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = stream + + +/***/ }), + +/***/ 1882: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707) +const { AsyncResource } = __nccwpck_require__(290) +const util = __nccwpck_require__(3440) +const { addSignal, removeSignal } = __nccwpck_require__(158) +const assert = __nccwpck_require__(2613) + +class UpgradeHandler extends AsyncResource { + constructor (opts, callback) { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('invalid opts') + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + const { signal, opaque, responseHeaders } = opts + + if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { + throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') + } + + super('UNDICI_UPGRADE') + + this.responseHeaders = responseHeaders || null + this.opaque = opaque || null + this.callback = callback + this.abort = null + this.context = null + + addSignal(this, signal) + } + + onConnect (abort, context) { + if (!this.callback) { + throw new RequestAbortedError() + } + + this.abort = abort + this.context = null + } + + onHeaders () { + throw new SocketError('bad upgrade', null) + } + + onUpgrade (statusCode, rawHeaders, socket) { + const { callback, opaque, context } = this + + assert.strictEqual(statusCode, 101) + + removeSignal(this) + + this.callback = null + const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) + this.runInAsyncScope(callback, null, null, { + headers, + socket, + opaque, + context + }) + } + + onError (err) { + const { callback, opaque } = this + + removeSignal(this) + + if (callback) { + this.callback = null + queueMicrotask(() => { + this.runInAsyncScope(callback, null, err, { opaque }) + }) + } + } +} + +function upgrade (opts, callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + upgrade.call(this, opts, (err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + try { + const upgradeHandler = new UpgradeHandler(opts, callback) + this.dispatch({ + ...opts, + method: opts.method || 'GET', + upgrade: opts.protocol || 'Websocket' + }, upgradeHandler) + } catch (err) { + if (typeof callback !== 'function') { + throw err + } + const opaque = opts && opts.opaque + queueMicrotask(() => callback(err, { opaque })) + } +} + +module.exports = upgrade + + +/***/ }), + +/***/ 6615: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +module.exports.request = __nccwpck_require__(4043) +module.exports.stream = __nccwpck_require__(3560) +module.exports.pipeline = __nccwpck_require__(6862) +module.exports.upgrade = __nccwpck_require__(1882) +module.exports.connect = __nccwpck_require__(4660) + + +/***/ }), + +/***/ 9927: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// Ported from https://github.com/nodejs/undici/pull/907 + + + +const assert = __nccwpck_require__(2613) +const { Readable } = __nccwpck_require__(2203) +const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3440) + +let Blob + +const kConsume = Symbol('kConsume') +const kReading = Symbol('kReading') +const kBody = Symbol('kBody') +const kAbort = Symbol('abort') +const kContentType = Symbol('kContentType') + +const noop = () => {} + +module.exports = class BodyReadable extends Readable { + constructor ({ + resume, + abort, + contentType = '', + highWaterMark = 64 * 1024 // Same as nodejs fs streams. + }) { + super({ + autoDestroy: true, + read: resume, + highWaterMark + }) + + this._readableState.dataEmitted = false + + this[kAbort] = abort + this[kConsume] = null + this[kBody] = null + this[kContentType] = contentType + + // Is stream being consumed through Readable API? + // This is an optimization so that we avoid checking + // for 'data' and 'readable' listeners in the hot path + // inside push(). + this[kReading] = false + } + + destroy (err) { + if (this.destroyed) { + // Node < 16 + return this + } + + if (!err && !this._readableState.endEmitted) { + err = new RequestAbortedError() + } + + if (err) { + this[kAbort]() + } + + return super.destroy(err) + } + + emit (ev, ...args) { + if (ev === 'data') { + // Node < 16.7 + this._readableState.dataEmitted = true + } else if (ev === 'error') { + // Node < 16 + this._readableState.errorEmitted = true + } + return super.emit(ev, ...args) + } + + on (ev, ...args) { + if (ev === 'data' || ev === 'readable') { + this[kReading] = true + } + return super.on(ev, ...args) + } + + addListener (ev, ...args) { + return this.on(ev, ...args) + } + + off (ev, ...args) { + const ret = super.off(ev, ...args) + if (ev === 'data' || ev === 'readable') { + this[kReading] = ( + this.listenerCount('data') > 0 || + this.listenerCount('readable') > 0 + ) + } + return ret + } + + removeListener (ev, ...args) { + return this.off(ev, ...args) + } + + push (chunk) { + if (this[kConsume] && chunk !== null && this.readableLength === 0) { + consumePush(this[kConsume], chunk) + return this[kReading] ? super.push(chunk) : true + } + return super.push(chunk) + } + + // https://fetch.spec.whatwg.org/#dom-body-text + async text () { + return consume(this, 'text') + } + + // https://fetch.spec.whatwg.org/#dom-body-json + async json () { + return consume(this, 'json') + } + + // https://fetch.spec.whatwg.org/#dom-body-blob + async blob () { + return consume(this, 'blob') + } + + // https://fetch.spec.whatwg.org/#dom-body-arraybuffer + async arrayBuffer () { + return consume(this, 'arrayBuffer') + } + + // https://fetch.spec.whatwg.org/#dom-body-formdata + async formData () { + // TODO: Implement. + throw new NotSupportedError() + } + + // https://fetch.spec.whatwg.org/#dom-body-bodyused + get bodyUsed () { + return util.isDisturbed(this) + } + + // https://fetch.spec.whatwg.org/#dom-body-body + get body () { + if (!this[kBody]) { + this[kBody] = ReadableStreamFrom(this) + if (this[kConsume]) { + // TODO: Is this the best way to force a lock? + this[kBody].getReader() // Ensure stream is locked. + assert(this[kBody].locked) + } + } + return this[kBody] + } + + dump (opts) { + let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 + const signal = opts && opts.signal + + if (signal) { + try { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new InvalidArgumentError('signal must be an AbortSignal') + } + util.throwIfAborted(signal) + } catch (err) { + return Promise.reject(err) + } + } + + if (this.closed) { + return Promise.resolve(null) + } + + return new Promise((resolve, reject) => { + const signalListenerCleanup = signal + ? util.addAbortListener(signal, () => { + this.destroy() + }) + : noop + + this + .on('close', function () { + signalListenerCleanup() + if (signal && signal.aborted) { + reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) + } else { + resolve(null) + } + }) + .on('error', noop) + .on('data', function (chunk) { + limit -= chunk.length + if (limit <= 0) { + this.destroy() + } + }) + .resume() + }) + } +} + +// https://streams.spec.whatwg.org/#readablestream-locked +function isLocked (self) { + // Consume is an implicit lock. + return (self[kBody] && self[kBody].locked === true) || self[kConsume] +} + +// https://fetch.spec.whatwg.org/#body-unusable +function isUnusable (self) { + return util.isDisturbed(self) || isLocked(self) +} + +async function consume (stream, type) { + if (isUnusable(stream)) { + throw new TypeError('unusable') + } + + assert(!stream[kConsume]) + + return new Promise((resolve, reject) => { + stream[kConsume] = { + type, + stream, + resolve, + reject, + length: 0, + body: [] + } + + stream + .on('error', function (err) { + consumeFinish(this[kConsume], err) + }) + .on('close', function () { + if (this[kConsume].body !== null) { + consumeFinish(this[kConsume], new RequestAbortedError()) + } + }) + + process.nextTick(consumeStart, stream[kConsume]) + }) +} + +function consumeStart (consume) { + if (consume.body === null) { + return + } + + const { _readableState: state } = consume.stream + + for (const chunk of state.buffer) { + consumePush(consume, chunk) + } + + if (state.endEmitted) { + consumeEnd(this[kConsume]) + } else { + consume.stream.on('end', function () { + consumeEnd(this[kConsume]) + }) + } + + consume.stream.resume() + + while (consume.stream.read() != null) { + // Loop + } +} + +function consumeEnd (consume) { + const { type, body, resolve, stream, length } = consume + + try { + if (type === 'text') { + resolve(toUSVString(Buffer.concat(body))) + } else if (type === 'json') { + resolve(JSON.parse(Buffer.concat(body))) + } else if (type === 'arrayBuffer') { + const dst = new Uint8Array(length) + + let pos = 0 + for (const buf of body) { + dst.set(buf, pos) + pos += buf.byteLength + } + + resolve(dst.buffer) + } else if (type === 'blob') { + if (!Blob) { + Blob = (__nccwpck_require__(181).Blob) + } + resolve(new Blob(body, { type: stream[kContentType] })) + } + + consumeFinish(consume) + } catch (err) { + stream.destroy(err) + } +} + +function consumePush (consume, chunk) { + consume.length += chunk.length + consume.body.push(chunk) +} + +function consumeFinish (consume, err) { + if (consume.body === null) { + return + } + + if (err) { + consume.reject(err) + } else { + consume.resolve() + } + + consume.type = null + consume.stream = null + consume.resolve = null + consume.reject = null + consume.length = 0 + consume.body = null +} + + +/***/ }), + +/***/ 7655: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const assert = __nccwpck_require__(2613) +const { + ResponseStatusCodeError +} = __nccwpck_require__(8707) +const { toUSVString } = __nccwpck_require__(3440) + +async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { + assert(body) + + let chunks = [] + let limit = 0 + + for await (const chunk of body) { + chunks.push(chunk) + limit += chunk.length + if (limit > 128 * 1024) { + chunks = null + break + } + } + + if (statusCode === 204 || !contentType || !chunks) { + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) + return + } + + try { + if (contentType.startsWith('application/json')) { + const payload = JSON.parse(toUSVString(Buffer.concat(chunks))) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + + if (contentType.startsWith('text/')) { + const payload = toUSVString(Buffer.concat(chunks)) + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) + return + } + } catch (err) { + // Process in a fallback if error + } + + process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) +} + +module.exports = { getResolveErrorBodyCallback } + + +/***/ }), + +/***/ 1093: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { + BalancedPoolMissingUpstreamError, + InvalidArgumentError +} = __nccwpck_require__(8707) +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} = __nccwpck_require__(8640) +const Pool = __nccwpck_require__(5076) +const { kUrl, kInterceptors } = __nccwpck_require__(6443) +const { parseOrigin } = __nccwpck_require__(3440) +const kFactory = Symbol('factory') + +const kOptions = Symbol('options') +const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') +const kCurrentWeight = Symbol('kCurrentWeight') +const kIndex = Symbol('kIndex') +const kWeight = Symbol('kWeight') +const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') +const kErrorPenalty = Symbol('kErrorPenalty') + +function getGreatestCommonDivisor (a, b) { + if (b === 0) return a + return getGreatestCommonDivisor(b, a % b) +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class BalancedPool extends PoolBase { + constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { + super() + + this[kOptions] = opts + this[kIndex] = -1 + this[kCurrentWeight] = 0 + + this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 + this[kErrorPenalty] = this[kOptions].errorPenalty || 15 + + if (!Array.isArray(upstreams)) { + upstreams = [upstreams] + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) + ? opts.interceptors.BalancedPool + : [] + this[kFactory] = factory + + for (const upstream of upstreams) { + this.addUpstream(upstream) + } + this._updateBalancedPoolStats() + } + + addUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + if (this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + ))) { + return this + } + const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) + + this[kAddClient](pool) + pool.on('connect', () => { + pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) + }) + + pool.on('connectionError', () => { + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + }) + + pool.on('disconnect', (...args) => { + const err = args[2] + if (err && err.code === 'UND_ERR_SOCKET') { + // decrease the weight of the pool. + pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) + this._updateBalancedPoolStats() + } + }) + + for (const client of this[kClients]) { + client[kWeight] = this[kMaxWeightPerServer] + } + + this._updateBalancedPoolStats() + + return this + } + + _updateBalancedPoolStats () { + this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) + } + + removeUpstream (upstream) { + const upstreamOrigin = parseOrigin(upstream).origin + + const pool = this[kClients].find((pool) => ( + pool[kUrl].origin === upstreamOrigin && + pool.closed !== true && + pool.destroyed !== true + )) + + if (pool) { + this[kRemoveClient](pool) + } + + return this + } + + get upstreams () { + return this[kClients] + .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) + .map((p) => p[kUrl].origin) + } + + [kGetDispatcher] () { + // We validate that pools is greater than 0, + // otherwise we would have to wait until an upstream + // is added, which might never happen. + if (this[kClients].length === 0) { + throw new BalancedPoolMissingUpstreamError() + } + + const dispatcher = this[kClients].find(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + + if (!dispatcher) { + return + } + + const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) + + if (allClientsBusy) { + return + } + + let counter = 0 + + let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) + + while (counter++ < this[kClients].length) { + this[kIndex] = (this[kIndex] + 1) % this[kClients].length + const pool = this[kClients][this[kIndex]] + + // find pool index with the largest weight + if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { + maxWeightIndex = this[kIndex] + } + + // decrease the current weight every `this[kClients].length`. + if (this[kIndex] === 0) { + // Set the current weight to the next lower weight. + this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] + + if (this[kCurrentWeight] <= 0) { + this[kCurrentWeight] = this[kMaxWeightPerServer] + } + } + if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { + return pool + } + } + + this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] + this[kIndex] = maxWeightIndex + return this[kClients][maxWeightIndex] + } +} + +module.exports = BalancedPool + + +/***/ }), + +/***/ 479: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { kConstruct } = __nccwpck_require__(296) +const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(3993) +const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3440) +const { kHeadersList } = __nccwpck_require__(6443) +const { webidl } = __nccwpck_require__(4222) +const { Response, cloneResponse } = __nccwpck_require__(8676) +const { Request } = __nccwpck_require__(5194) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) +const { fetching } = __nccwpck_require__(2315) +const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(5523) +const assert = __nccwpck_require__(2613) +const { getGlobalDispatcher } = __nccwpck_require__(2581) + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation + * @typedef {Object} CacheBatchOperation + * @property {'delete' | 'put'} type + * @property {any} request + * @property {any} response + * @property {import('../../types/cache').CacheQueryOptions} options + */ + +/** + * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list + * @typedef {[any, any][]} requestResponseList + */ + +class Cache { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list + * @type {requestResponseList} + */ + #relevantRequestResponseList + + constructor () { + if (arguments[0] !== kConstruct) { + webidl.illegalConstructor() + } + + this.#relevantRequestResponseList = arguments[1] + } + + async match (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) + + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + const p = await this.matchAll(request, options) + + if (p.length === 0) { + return + } + + return p[0] + } + + async matchAll (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + // 1. + let r = null + + // 2. + if (request !== undefined) { + if (request instanceof Request) { + // 2.1.1 + r = request[kState] + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { + // 2.2.1 + r = new Request(request)[kState] + } + } + + // 5. + // 5.1 + const responses = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + responses.push(requestResponse[1]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + responses.push(requestResponse[1]) + } + } + + // 5.4 + // We don't implement CORs so we don't need to loop over the responses, yay! + + // 5.5.1 + const responseList = [] + + // 5.5.2 + for (const response of responses) { + // 5.5.2.1 + const responseObject = new Response(response.body?.source ?? null) + const body = responseObject[kState].body + responseObject[kState] = response + responseObject[kState].body = body + responseObject[kHeaders][kHeadersList] = response.headersList + responseObject[kHeaders][kGuard] = 'immutable' + + responseList.push(responseObject) + } + + // 6. + return Object.freeze(responseList) + } + + async add (request) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) + + request = webidl.converters.RequestInfo(request) + + // 1. + const requests = [request] + + // 2. + const responseArrayPromise = this.addAll(requests) + + // 3. + return await responseArrayPromise + } + + async addAll (requests) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) + + requests = webidl.converters['sequence'](requests) + + // 1. + const responsePromises = [] + + // 2. + const requestList = [] + + // 3. + for (const request of requests) { + if (typeof request === 'string') { + continue + } + + // 3.1 + const r = request[kState] + + // 3.2 + if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme when method is not GET.' + }) + } + } + + // 4. + /** @type {ReturnType[]} */ + const fetchControllers = [] + + // 5. + for (const request of requests) { + // 5.1 + const r = new Request(request)[kState] + + // 5.2 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Expected http/s scheme.' + }) + } + + // 5.4 + r.initiator = 'fetch' + r.destination = 'subresource' + + // 5.5 + requestList.push(r) + + // 5.6 + const responsePromise = createDeferredPromise() + + // 5.7 + fetchControllers.push(fetching({ + request: r, + dispatcher: getGlobalDispatcher(), + processResponse (response) { + // 1. + if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'Received an invalid status code or the request failed.' + })) + } else if (response.headersList.contains('vary')) { // 2. + // 2.1 + const fieldValues = getFieldValues(response.headersList.get('vary')) + + // 2.2 + for (const fieldValue of fieldValues) { + // 2.2.1 + if (fieldValue === '*') { + responsePromise.reject(webidl.errors.exception({ + header: 'Cache.addAll', + message: 'invalid vary field value' + })) + + for (const controller of fetchControllers) { + controller.abort() + } + + return + } + } + } + }, + processResponseEndOfBody (response) { + // 1. + if (response.aborted) { + responsePromise.reject(new DOMException('aborted', 'AbortError')) + return + } + + // 2. + responsePromise.resolve(response) + } + })) + + // 5.8 + responsePromises.push(responsePromise.promise) + } + + // 6. + const p = Promise.all(responsePromises) + + // 7. + const responses = await p + + // 7.1 + const operations = [] + + // 7.2 + let index = 0 + + // 7.3 + for (const response of responses) { + // 7.3.1 + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 7.3.2 + request: requestList[index], // 7.3.3 + response // 7.3.4 + } + + operations.push(operation) // 7.3.5 + + index++ // 7.3.6 + } + + // 7.5 + const cacheJobPromise = createDeferredPromise() + + // 7.6.1 + let errorData = null + + // 7.6.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 7.6.3 + queueMicrotask(() => { + // 7.6.3.1 + if (errorData === null) { + cacheJobPromise.resolve(undefined) + } else { + // 7.6.3.2 + cacheJobPromise.reject(errorData) + } + }) + + // 7.7 + return cacheJobPromise.promise + } + + async put (request, response) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) + + request = webidl.converters.RequestInfo(request) + response = webidl.converters.Response(response) + + // 1. + let innerRequest = null + + // 2. + if (request instanceof Request) { + innerRequest = request[kState] + } else { // 3. + innerRequest = new Request(request)[kState] + } + + // 4. + if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Expected an http/s scheme when method is not GET' + }) + } + + // 5. + const innerResponse = response[kState] + + // 6. + if (innerResponse.status === 206) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got 206 status' + }) + } + + // 7. + if (innerResponse.headersList.contains('vary')) { + // 7.1. + const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) + + // 7.2. + for (const fieldValue of fieldValues) { + // 7.2.1 + if (fieldValue === '*') { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Got * vary field value' + }) + } + } + } + + // 8. + if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { + throw webidl.errors.exception({ + header: 'Cache.put', + message: 'Response body is locked or disturbed' + }) + } + + // 9. + const clonedResponse = cloneResponse(innerResponse) + + // 10. + const bodyReadPromise = createDeferredPromise() + + // 11. + if (innerResponse.body != null) { + // 11.1 + const stream = innerResponse.body.stream + + // 11.2 + const reader = stream.getReader() + + // 11.3 + readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) + } else { + bodyReadPromise.resolve(undefined) + } + + // 12. + /** @type {CacheBatchOperation[]} */ + const operations = [] + + // 13. + /** @type {CacheBatchOperation} */ + const operation = { + type: 'put', // 14. + request: innerRequest, // 15. + response: clonedResponse // 16. + } + + // 17. + operations.push(operation) + + // 19. + const bytes = await bodyReadPromise.promise + + if (clonedResponse.body != null) { + clonedResponse.body.source = bytes + } + + // 19.1 + const cacheJobPromise = createDeferredPromise() + + // 19.2.1 + let errorData = null + + // 19.2.2 + try { + this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + // 19.2.3 + queueMicrotask(() => { + // 19.2.3.1 + if (errorData === null) { + cacheJobPromise.resolve() + } else { // 19.2.3.2 + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + async delete (request, options = {}) { + webidl.brandCheck(this, Cache) + webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) + + request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + /** + * @type {Request} + */ + let r = null + + if (request instanceof Request) { + r = request[kState] + + if (r.method !== 'GET' && !options.ignoreMethod) { + return false + } + } else { + assert(typeof request === 'string') + + r = new Request(request)[kState] + } + + /** @type {CacheBatchOperation[]} */ + const operations = [] + + /** @type {CacheBatchOperation} */ + const operation = { + type: 'delete', + request: r, + options + } + + operations.push(operation) + + const cacheJobPromise = createDeferredPromise() + + let errorData = null + let requestResponses + + try { + requestResponses = this.#batchCacheOperations(operations) + } catch (e) { + errorData = e + } + + queueMicrotask(() => { + if (errorData === null) { + cacheJobPromise.resolve(!!requestResponses?.length) + } else { + cacheJobPromise.reject(errorData) + } + }) + + return cacheJobPromise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys + * @param {any} request + * @param {import('../../types/cache').CacheQueryOptions} options + * @returns {readonly Request[]} + */ + async keys (request = undefined, options = {}) { + webidl.brandCheck(this, Cache) + + if (request !== undefined) request = webidl.converters.RequestInfo(request) + options = webidl.converters.CacheQueryOptions(options) + + // 1. + let r = null + + // 2. + if (request !== undefined) { + // 2.1 + if (request instanceof Request) { + // 2.1.1 + r = request[kState] + + // 2.1.2 + if (r.method !== 'GET' && !options.ignoreMethod) { + return [] + } + } else if (typeof request === 'string') { // 2.2 + r = new Request(request)[kState] + } + } + + // 4. + const promise = createDeferredPromise() + + // 5. + // 5.1 + const requests = [] + + // 5.2 + if (request === undefined) { + // 5.2.1 + for (const requestResponse of this.#relevantRequestResponseList) { + // 5.2.1.1 + requests.push(requestResponse[0]) + } + } else { // 5.3 + // 5.3.1 + const requestResponses = this.#queryCache(r, options) + + // 5.3.2 + for (const requestResponse of requestResponses) { + // 5.3.2.1 + requests.push(requestResponse[0]) + } + } + + // 5.4 + queueMicrotask(() => { + // 5.4.1 + const requestList = [] + + // 5.4.2 + for (const request of requests) { + const requestObject = new Request('https://a') + requestObject[kState] = request + requestObject[kHeaders][kHeadersList] = request.headersList + requestObject[kHeaders][kGuard] = 'immutable' + requestObject[kRealm] = request.client + + // 5.4.2.1 + requestList.push(requestObject) + } + + // 5.4.3 + promise.resolve(Object.freeze(requestList)) + }) + + return promise.promise + } + + /** + * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm + * @param {CacheBatchOperation[]} operations + * @returns {requestResponseList} + */ + #batchCacheOperations (operations) { + // 1. + const cache = this.#relevantRequestResponseList + + // 2. + const backupCache = [...cache] + + // 3. + const addedItems = [] + + // 4.1 + const resultList = [] + + try { + // 4.2 + for (const operation of operations) { + // 4.2.1 + if (operation.type !== 'delete' && operation.type !== 'put') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'operation type does not match "delete" or "put"' + }) + } + + // 4.2.2 + if (operation.type === 'delete' && operation.response != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'delete operation should not have an associated response' + }) + } + + // 4.2.3 + if (this.#queryCache(operation.request, operation.options, addedItems).length) { + throw new DOMException('???', 'InvalidStateError') + } + + // 4.2.4 + let requestResponses + + // 4.2.5 + if (operation.type === 'delete') { + // 4.2.5.1 + requestResponses = this.#queryCache(operation.request, operation.options) + + // TODO: the spec is wrong, this is needed to pass WPTs + if (requestResponses.length === 0) { + return [] + } + + // 4.2.5.2 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.5.2.1 + cache.splice(idx, 1) + } + } else if (operation.type === 'put') { // 4.2.6 + // 4.2.6.1 + if (operation.response == null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'put operation should have an associated response' + }) + } + + // 4.2.6.2 + const r = operation.request + + // 4.2.6.3 + if (!urlIsHttpHttpsScheme(r.url)) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'expected http or https scheme' + }) + } + + // 4.2.6.4 + if (r.method !== 'GET') { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'not get method' + }) + } + + // 4.2.6.5 + if (operation.options != null) { + throw webidl.errors.exception({ + header: 'Cache.#batchCacheOperations', + message: 'options must not be defined' + }) + } + + // 4.2.6.6 + requestResponses = this.#queryCache(operation.request) + + // 4.2.6.7 + for (const requestResponse of requestResponses) { + const idx = cache.indexOf(requestResponse) + assert(idx !== -1) + + // 4.2.6.7.1 + cache.splice(idx, 1) + } + + // 4.2.6.8 + cache.push([operation.request, operation.response]) + + // 4.2.6.10 + addedItems.push([operation.request, operation.response]) + } + + // 4.2.7 + resultList.push([operation.request, operation.response]) + } + + // 4.3 + return resultList + } catch (e) { // 5. + // 5.1 + this.#relevantRequestResponseList.length = 0 + + // 5.2 + this.#relevantRequestResponseList = backupCache + + // 5.3 + throw e + } + } + + /** + * @see https://w3c.github.io/ServiceWorker/#query-cache + * @param {any} requestQuery + * @param {import('../../types/cache').CacheQueryOptions} options + * @param {requestResponseList} targetStorage + * @returns {requestResponseList} + */ + #queryCache (requestQuery, options, targetStorage) { + /** @type {requestResponseList} */ + const resultList = [] + + const storage = targetStorage ?? this.#relevantRequestResponseList + + for (const requestResponse of storage) { + const [cachedRequest, cachedResponse] = requestResponse + if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { + resultList.push(requestResponse) + } + } + + return resultList + } + + /** + * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm + * @param {any} requestQuery + * @param {any} request + * @param {any | null} response + * @param {import('../../types/cache').CacheQueryOptions | undefined} options + * @returns {boolean} + */ + #requestMatchesCachedItem (requestQuery, request, response = null, options) { + // if (options?.ignoreMethod === false && request.method === 'GET') { + // return false + // } + + const queryURL = new URL(requestQuery.url) + + const cachedURL = new URL(request.url) + + if (options?.ignoreSearch) { + cachedURL.search = '' + + queryURL.search = '' + } + + if (!urlEquals(queryURL, cachedURL, true)) { + return false + } + + if ( + response == null || + options?.ignoreVary || + !response.headersList.contains('vary') + ) { + return true + } + + const fieldValues = getFieldValues(response.headersList.get('vary')) + + for (const fieldValue of fieldValues) { + if (fieldValue === '*') { + return false + } + + const requestValue = request.headersList.get(fieldValue) + const queryValue = requestQuery.headersList.get(fieldValue) + + // If one has the header and the other doesn't, or one has + // a different value than the other, return false + if (requestValue !== queryValue) { + return false + } + } + + return true + } +} + +Object.defineProperties(Cache.prototype, { + [Symbol.toStringTag]: { + value: 'Cache', + configurable: true + }, + match: kEnumerableProperty, + matchAll: kEnumerableProperty, + add: kEnumerableProperty, + addAll: kEnumerableProperty, + put: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +const cacheQueryOptionConverters = [ + { + key: 'ignoreSearch', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreMethod', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'ignoreVary', + converter: webidl.converters.boolean, + defaultValue: false + } +] + +webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) + +webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ + ...cacheQueryOptionConverters, + { + key: 'cacheName', + converter: webidl.converters.DOMString + } +]) + +webidl.converters.Response = webidl.interfaceConverter(Response) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.RequestInfo +) + +module.exports = { + Cache +} + + +/***/ }), + +/***/ 4738: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { kConstruct } = __nccwpck_require__(296) +const { Cache } = __nccwpck_require__(479) +const { webidl } = __nccwpck_require__(4222) +const { kEnumerableProperty } = __nccwpck_require__(3440) + +class CacheStorage { + /** + * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map + * @type {Map} + */ + async has (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) + + cacheName = webidl.converters.DOMString(cacheName) + + // 2.1.1 + // 2.2 + return this.#caches.has(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open + * @param {string} cacheName + * @returns {Promise} + */ + async open (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' }) + + cacheName = webidl.converters.DOMString(cacheName) + + // 2.1 + if (this.#caches.has(cacheName)) { + // await caches.open('v1') !== await caches.open('v1') + + // 2.1.1 + const cache = this.#caches.get(cacheName) + + // 2.1.1.1 + return new Cache(kConstruct, cache) + } + + // 2.2 + const cache = [] + + // 2.3 + this.#caches.set(cacheName, cache) + + // 2.4 + return new Cache(kConstruct, cache) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete + * @param {string} cacheName + * @returns {Promise} + */ + async delete (cacheName) { + webidl.brandCheck(this, CacheStorage) + webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' }) + + cacheName = webidl.converters.DOMString(cacheName) + + return this.#caches.delete(cacheName) + } + + /** + * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys + * @returns {string[]} + */ + async keys () { + webidl.brandCheck(this, CacheStorage) + + // 2.1 + const keys = this.#caches.keys() + + // 2.2 + return [...keys] + } +} + +Object.defineProperties(CacheStorage.prototype, { + [Symbol.toStringTag]: { + value: 'CacheStorage', + configurable: true + }, + match: kEnumerableProperty, + has: kEnumerableProperty, + open: kEnumerableProperty, + delete: kEnumerableProperty, + keys: kEnumerableProperty +}) + +module.exports = { + CacheStorage +} + + +/***/ }), + +/***/ 296: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +module.exports = { + kConstruct: (__nccwpck_require__(6443).kConstruct) +} + + +/***/ }), + +/***/ 3993: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const assert = __nccwpck_require__(2613) +const { URLSerializer } = __nccwpck_require__(4322) +const { isValidHeaderName } = __nccwpck_require__(5523) + +/** + * @see https://url.spec.whatwg.org/#concept-url-equals + * @param {URL} A + * @param {URL} B + * @param {boolean | undefined} excludeFragment + * @returns {boolean} + */ +function urlEquals (A, B, excludeFragment = false) { + const serializedA = URLSerializer(A, excludeFragment) + + const serializedB = URLSerializer(B, excludeFragment) + + return serializedA === serializedB +} + +/** + * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 + * @param {string} header + */ +function fieldValues (header) { + assert(header !== null) + + const values = [] + + for (let value of header.split(',')) { + value = value.trim() + + if (!value.length) { + continue + } else if (!isValidHeaderName(value)) { + continue + } + + values.push(value) + } + + return values +} + +module.exports = { + urlEquals, + fieldValues +} + + +/***/ }), + +/***/ 6197: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// @ts-check + + + +/* global WebAssembly */ + +const assert = __nccwpck_require__(2613) +const net = __nccwpck_require__(9278) +const http = __nccwpck_require__(8611) +const { pipeline } = __nccwpck_require__(2203) +const util = __nccwpck_require__(3440) +const timers = __nccwpck_require__(8804) +const Request = __nccwpck_require__(4655) +const DispatcherBase = __nccwpck_require__(1) +const { + RequestContentLengthMismatchError, + ResponseContentLengthMismatchError, + InvalidArgumentError, + RequestAbortedError, + HeadersTimeoutError, + HeadersOverflowError, + SocketError, + InformationalError, + BodyTimeoutError, + HTTPParserError, + ResponseExceededMaxSizeError, + ClientDestroyedError +} = __nccwpck_require__(8707) +const buildConnector = __nccwpck_require__(9136) +const { + kUrl, + kReset, + kServerName, + kClient, + kBusy, + kParser, + kConnect, + kBlocking, + kResuming, + kRunning, + kPending, + kSize, + kWriting, + kQueue, + kConnected, + kConnecting, + kNeedDrain, + kNoRef, + kKeepAliveDefaultTimeout, + kHostHeader, + kPendingIdx, + kRunningIdx, + kError, + kPipelining, + kSocket, + kKeepAliveTimeoutValue, + kMaxHeadersSize, + kKeepAliveMaxTimeout, + kKeepAliveTimeoutThreshold, + kHeadersTimeout, + kBodyTimeout, + kStrictContentLength, + kConnector, + kMaxRedirections, + kMaxRequests, + kCounter, + kClose, + kDestroy, + kDispatch, + kInterceptors, + kLocalAddress, + kMaxResponseSize, + kHTTPConnVersion, + // HTTP2 + kHost, + kHTTP2Session, + kHTTP2SessionState, + kHTTP2BuildRequest, + kHTTP2CopyHeaders, + kHTTP1BuildRequest +} = __nccwpck_require__(6443) + +/** @type {import('http2')} */ +let http2 +try { + http2 = __nccwpck_require__(5675) +} catch { + // @ts-ignore + http2 = { constants: {} } +} + +const { + constants: { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_SCHEME, + HTTP2_HEADER_CONTENT_LENGTH, + HTTP2_HEADER_EXPECT, + HTTP2_HEADER_STATUS + } +} = http2 + +// Experimental +let h2ExperimentalWarned = false + +const FastBuffer = Buffer[Symbol.species] + +const kClosedResolve = Symbol('kClosedResolve') + +const channels = {} + +try { + const diagnosticsChannel = __nccwpck_require__(1637) + channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') + channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') + channels.connectError = diagnosticsChannel.channel('undici:client:connectError') + channels.connected = diagnosticsChannel.channel('undici:client:connected') +} catch { + channels.sendHeaders = { hasSubscribers: false } + channels.beforeConnect = { hasSubscribers: false } + channels.connectError = { hasSubscribers: false } + channels.connected = { hasSubscribers: false } +} + +/** + * @type {import('../types/client').default} + */ +class Client extends DispatcherBase { + /** + * + * @param {string|URL} url + * @param {import('../types/client').Client.Options} options + */ + constructor (url, { + interceptors, + maxHeaderSize, + headersTimeout, + socketTimeout, + requestTimeout, + connectTimeout, + bodyTimeout, + idleTimeout, + keepAlive, + keepAliveTimeout, + maxKeepAliveTimeout, + keepAliveMaxTimeout, + keepAliveTimeoutThreshold, + socketPath, + pipelining, + tls, + strictContentLength, + maxCachedSessions, + maxRedirections, + connect, + maxRequestsPerClient, + localAddress, + maxResponseSize, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + // h2 + allowH2, + maxConcurrentStreams + } = {}) { + super() + + if (keepAlive !== undefined) { + throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') + } + + if (socketTimeout !== undefined) { + throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') + } + + if (requestTimeout !== undefined) { + throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') + } + + if (idleTimeout !== undefined) { + throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') + } + + if (maxKeepAliveTimeout !== undefined) { + throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') + } + + if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { + throw new InvalidArgumentError('invalid maxHeaderSize') + } + + if (socketPath != null && typeof socketPath !== 'string') { + throw new InvalidArgumentError('invalid socketPath') + } + + if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { + throw new InvalidArgumentError('invalid connectTimeout') + } + + if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveTimeout') + } + + if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { + throw new InvalidArgumentError('invalid keepAliveMaxTimeout') + } + + if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { + throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') + } + + if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') + } + + if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { + throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') + } + + if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { + throw new InvalidArgumentError('localAddress must be valid string IP address') + } + + if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { + throw new InvalidArgumentError('maxResponseSize must be a positive number') + } + + if ( + autoSelectFamilyAttemptTimeout != null && + (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) + ) { + throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') + } + + // h2 + if (allowH2 != null && typeof allowH2 !== 'boolean') { + throw new InvalidArgumentError('allowH2 must be a valid boolean value') + } + + if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { + throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) + ? interceptors.Client + : [createRedirectInterceptor({ maxRedirections })] + this[kUrl] = util.parseOrigin(url) + this[kConnector] = connect + this[kSocket] = null + this[kPipelining] = pipelining != null ? pipelining : 1 + this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize + this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout + this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout + this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold + this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] + this[kServerName] = null + this[kLocalAddress] = localAddress != null ? localAddress : null + this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming + this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` + this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 + this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 + this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength + this[kMaxRedirections] = maxRedirections + this[kMaxRequests] = maxRequestsPerClient + this[kClosedResolve] = null + this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 + this[kHTTPConnVersion] = 'h1' + + // HTTP/2 + this[kHTTP2Session] = null + this[kHTTP2SessionState] = !allowH2 + ? null + : { + // streams: null, // Fixed queue of streams - For future support of `push` + openStreams: 0, // Keep track of them to decide wether or not unref the session + maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server + } + this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}` + + // kQueue is built up of 3 sections separated by + // the kRunningIdx and kPendingIdx indices. + // | complete | running | pending | + // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length + // kRunningIdx points to the first running element. + // kPendingIdx points to the first pending element. + // This implements a fast queue with an amortized + // time of O(1). + + this[kQueue] = [] + this[kRunningIdx] = 0 + this[kPendingIdx] = 0 + } + + get pipelining () { + return this[kPipelining] + } + + set pipelining (value) { + this[kPipelining] = value + resume(this, true) + } + + get [kPending] () { + return this[kQueue].length - this[kPendingIdx] + } + + get [kRunning] () { + return this[kPendingIdx] - this[kRunningIdx] + } + + get [kSize] () { + return this[kQueue].length - this[kRunningIdx] + } + + get [kConnected] () { + return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed + } + + get [kBusy] () { + const socket = this[kSocket] + return ( + (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || + (this[kSize] >= (this[kPipelining] || 1)) || + this[kPending] > 0 + ) + } + + /* istanbul ignore: only used for test */ + [kConnect] (cb) { + connect(this) + this.once('connect', cb) + } + + [kDispatch] (opts, handler) { + const origin = opts.origin || this[kUrl].origin + + const request = this[kHTTPConnVersion] === 'h2' + ? Request[kHTTP2BuildRequest](origin, opts, handler) + : Request[kHTTP1BuildRequest](origin, opts, handler) + + this[kQueue].push(request) + if (this[kResuming]) { + // Do nothing. + } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { + // Wait a tick in case stream/iterator is ended in the same tick. + this[kResuming] = 1 + process.nextTick(resume, this) + } else { + resume(this, true) + } + + if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { + this[kNeedDrain] = 2 + } + + return this[kNeedDrain] < 2 + } + + async [kClose] () { + // TODO: for H2 we need to gracefully flush the remaining enqueued + // request and close each stream. + return new Promise((resolve) => { + if (!this[kSize]) { + resolve(null) + } else { + this[kClosedResolve] = resolve + } + }) + } + + async [kDestroy] (err) { + return new Promise((resolve) => { + const requests = this[kQueue].splice(this[kPendingIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(this, request, err) + } + + const callback = () => { + if (this[kClosedResolve]) { + // TODO (fix): Should we error here with ClientDestroyedError? + this[kClosedResolve]() + this[kClosedResolve] = null + } + resolve() + } + + if (this[kHTTP2Session] != null) { + util.destroy(this[kHTTP2Session], err) + this[kHTTP2Session] = null + this[kHTTP2SessionState] = null + } + + if (!this[kSocket]) { + queueMicrotask(callback) + } else { + util.destroy(this[kSocket].on('close', callback), err) + } + + resume(this) + }) + } +} + +function onHttp2SessionError (err) { + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + this[kSocket][kError] = err + + onError(this[kClient], err) +} + +function onHttp2FrameError (type, code, id) { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + + if (id === 0) { + this[kSocket][kError] = err + onError(this[kClient], err) + } +} + +function onHttp2SessionEnd () { + util.destroy(this, new SocketError('other side closed')) + util.destroy(this[kSocket], new SocketError('other side closed')) +} + +function onHTTP2GoAway (code) { + const client = this[kClient] + const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`) + client[kSocket] = null + client[kHTTP2Session] = null + + if (client.destroyed) { + assert(this[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(this, request, err) + } + } else if (client[kRunning] > 0) { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + + errorRequest(client, request, err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', + client[kUrl], + [client], + err + ) + + resume(client) +} + +const constants = __nccwpck_require__(2824) +const createRedirectInterceptor = __nccwpck_require__(4415) +const EMPTY_BUF = Buffer.alloc(0) + +async function lazyllhttp () { + const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(3870) : undefined + + let mod + try { + mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(3434), 'base64')) + } catch (e) { + /* istanbul ignore next */ + + // We could check if the error was caused by the simd option not + // being enabled, but the occurring of this other error + // * https://github.com/emscripten-core/emscripten/issues/11495 + // got me to remove that check to avoid breaking Node 12. + mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(3870), 'base64')) + } + + return await WebAssembly.instantiate(mod, { + env: { + /* eslint-disable camelcase */ + + wasm_on_url: (p, at, len) => { + /* istanbul ignore next */ + return 0 + }, + wasm_on_status: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_begin: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageBegin() || 0 + }, + wasm_on_header_field: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_header_value: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 + }, + wasm_on_body: (p, at, len) => { + assert.strictEqual(currentParser.ptr, p) + const start = at - currentBufferPtr + currentBufferRef.byteOffset + return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 + }, + wasm_on_message_complete: (p) => { + assert.strictEqual(currentParser.ptr, p) + return currentParser.onMessageComplete() || 0 + } + + /* eslint-enable camelcase */ + } + }) +} + +let llhttpInstance = null +let llhttpPromise = lazyllhttp() +llhttpPromise.catch() + +let currentParser = null +let currentBufferRef = null +let currentBufferSize = 0 +let currentBufferPtr = null + +const TIMEOUT_HEADERS = 1 +const TIMEOUT_BODY = 2 +const TIMEOUT_IDLE = 3 + +class Parser { + constructor (client, socket, { exports }) { + assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) + + this.llhttp = exports + this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) + this.client = client + this.socket = socket + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + this.statusCode = null + this.statusText = '' + this.upgrade = false + this.headers = [] + this.headersSize = 0 + this.headersMaxSize = client[kMaxHeadersSize] + this.shouldKeepAlive = false + this.paused = false + this.resume = this.resume.bind(this) + + this.bytesRead = 0 + + this.keepAlive = '' + this.contentLength = '' + this.connection = '' + this.maxResponseSize = client[kMaxResponseSize] + } + + setTimeout (value, type) { + this.timeoutType = type + if (value !== this.timeoutValue) { + timers.clearTimeout(this.timeout) + if (value) { + this.timeout = timers.setTimeout(onParserTimeout, value, this) + // istanbul ignore else: only for jest + if (this.timeout.unref) { + this.timeout.unref() + } + } else { + this.timeout = null + } + this.timeoutValue = value + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + } + + resume () { + if (this.socket.destroyed || !this.paused) { + return + } + + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_resume(this.ptr) + + assert(this.timeoutType === TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + this.paused = false + this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. + this.readMore() + } + + readMore () { + while (!this.paused && this.ptr) { + const chunk = this.socket.read() + if (chunk === null) { + break + } + this.execute(chunk) + } + } + + execute (data) { + assert(this.ptr != null) + assert(currentParser == null) + assert(!this.paused) + + const { socket, llhttp } = this + + if (data.length > currentBufferSize) { + if (currentBufferPtr) { + llhttp.free(currentBufferPtr) + } + currentBufferSize = Math.ceil(data.length / 4096) * 4096 + currentBufferPtr = llhttp.malloc(currentBufferSize) + } + + new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) + + // Call `execute` on the wasm parser. + // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, + // and finally the length of bytes to parse. + // The return value is an error code or `constants.ERROR.OK`. + try { + let ret + + try { + currentBufferRef = data + currentParser = this + ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) + /* eslint-disable-next-line no-useless-catch */ + } catch (err) { + /* istanbul ignore next: difficult to make a test case for */ + throw err + } finally { + currentParser = null + currentBufferRef = null + } + + const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr + + if (ret === constants.ERROR.PAUSED_UPGRADE) { + this.onUpgrade(data.slice(offset)) + } else if (ret === constants.ERROR.PAUSED) { + this.paused = true + socket.unshift(data.slice(offset)) + } else if (ret !== constants.ERROR.OK) { + const ptr = llhttp.llhttp_get_error_reason(this.ptr) + let message = '' + /* istanbul ignore else: difficult to make a test case for */ + if (ptr) { + const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) + message = + 'Response does not match the HTTP/1.1 protocol (' + + Buffer.from(llhttp.memory.buffer, ptr, len).toString() + + ')' + } + throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) + } + } catch (err) { + util.destroy(socket, err) + } + } + + destroy () { + assert(this.ptr != null) + assert(currentParser == null) + + this.llhttp.llhttp_free(this.ptr) + this.ptr = null + + timers.clearTimeout(this.timeout) + this.timeout = null + this.timeoutValue = null + this.timeoutType = null + + this.paused = false + } + + onStatus (buf) { + this.statusText = buf.toString() + } + + onMessageBegin () { + const { socket, client } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + if (!request) { + return -1 + } + } + + onHeaderField (buf) { + const len = this.headers.length + + if ((len & 1) === 0) { + this.headers.push(buf) + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + this.trackHeader(buf.length) + } + + onHeaderValue (buf) { + let len = this.headers.length + + if ((len & 1) === 1) { + this.headers.push(buf) + len += 1 + } else { + this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) + } + + const key = this.headers[len - 2] + if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') { + this.keepAlive += buf.toString() + } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') { + this.connection += buf.toString() + } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') { + this.contentLength += buf.toString() + } + + this.trackHeader(buf.length) + } + + trackHeader (len) { + this.headersSize += len + if (this.headersSize >= this.headersMaxSize) { + util.destroy(this.socket, new HeadersOverflowError()) + } + } + + onUpgrade (head) { + const { upgrade, client, socket, headers, statusCode } = this + + assert(upgrade) + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(!socket.destroyed) + assert(socket === client[kSocket]) + assert(!this.paused) + assert(request.upgrade || request.method === 'CONNECT') + + this.statusCode = null + this.statusText = '' + this.shouldKeepAlive = null + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + socket.unshift(head) + + socket[kParser].destroy() + socket[kParser] = null + + socket[kClient] = null + socket[kError] = null + socket + .removeListener('error', onSocketError) + .removeListener('readable', onSocketReadable) + .removeListener('end', onSocketEnd) + .removeListener('close', onSocketClose) + + client[kSocket] = null + client[kQueue][client[kRunningIdx]++] = null + client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) + + try { + request.onUpgrade(statusCode, headers, socket) + } catch (err) { + util.destroy(socket, err) + } + + resume(client) + } + + onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { + const { client, socket, headers, statusText } = this + + /* istanbul ignore next: difficult to make a test case for */ + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + + /* istanbul ignore next: difficult to make a test case for */ + if (!request) { + return -1 + } + + assert(!this.upgrade) + assert(this.statusCode < 200) + + if (statusCode === 100) { + util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) + return -1 + } + + /* this can only happen if server is misbehaving */ + if (upgrade && !request.upgrade) { + util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) + return -1 + } + + assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) + + this.statusCode = statusCode + this.shouldKeepAlive = ( + shouldKeepAlive || + // Override llhttp value which does not allow keepAlive for HEAD. + (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') + ) + + if (this.statusCode >= 200) { + const bodyTimeout = request.bodyTimeout != null + ? request.bodyTimeout + : client[kBodyTimeout] + this.setTimeout(bodyTimeout, TIMEOUT_BODY) + } else if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + if (request.method === 'CONNECT') { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + if (upgrade) { + assert(client[kRunning] === 1) + this.upgrade = true + return 2 + } + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + if (this.shouldKeepAlive && client[kPipelining]) { + const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null + + if (keepAliveTimeout != null) { + const timeout = Math.min( + keepAliveTimeout - client[kKeepAliveTimeoutThreshold], + client[kKeepAliveMaxTimeout] + ) + if (timeout <= 0) { + socket[kReset] = true + } else { + client[kKeepAliveTimeoutValue] = timeout + } + } else { + client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] + } + } else { + // Stop more requests from being dispatched. + socket[kReset] = true + } + + const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false + + if (request.aborted) { + return -1 + } + + if (request.method === 'HEAD') { + return 1 + } + + if (statusCode < 200) { + return 1 + } + + if (socket[kBlocking]) { + socket[kBlocking] = false + resume(client) + } + + return pause ? constants.ERROR.PAUSED : 0 + } + + onBody (buf) { + const { client, socket, statusCode, maxResponseSize } = this + + if (socket.destroyed) { + return -1 + } + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert.strictEqual(this.timeoutType, TIMEOUT_BODY) + if (this.timeout) { + // istanbul ignore else: only for jest + if (this.timeout.refresh) { + this.timeout.refresh() + } + } + + assert(statusCode >= 200) + + if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { + util.destroy(socket, new ResponseExceededMaxSizeError()) + return -1 + } + + this.bytesRead += buf.length + + if (request.onData(buf) === false) { + return constants.ERROR.PAUSED + } + } + + onMessageComplete () { + const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this + + if (socket.destroyed && (!statusCode || shouldKeepAlive)) { + return -1 + } + + if (upgrade) { + return + } + + const request = client[kQueue][client[kRunningIdx]] + assert(request) + + assert(statusCode >= 100) + + this.statusCode = null + this.statusText = '' + this.bytesRead = 0 + this.contentLength = '' + this.keepAlive = '' + this.connection = '' + + assert(this.headers.length % 2 === 0) + this.headers = [] + this.headersSize = 0 + + if (statusCode < 200) { + return + } + + /* istanbul ignore next: should be handled by llhttp? */ + if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { + util.destroy(socket, new ResponseContentLengthMismatchError()) + return -1 + } + + request.onComplete(headers) + + client[kQueue][client[kRunningIdx]++] = null + + if (socket[kWriting]) { + assert.strictEqual(client[kRunning], 0) + // Response completed before request. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (!shouldKeepAlive) { + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (socket[kReset] && client[kRunning] === 0) { + // Destroy socket once all requests have completed. + // The request at the tail of the pipeline is the one + // that requested reset and no further requests should + // have been queued since then. + util.destroy(socket, new InformationalError('reset')) + return constants.ERROR.PAUSED + } else if (client[kPipelining] === 1) { + // We must wait a full event loop cycle to reuse this socket to make sure + // that non-spec compliant servers are not closing the connection even if they + // said they won't. + setImmediate(resume, client) + } else { + resume(client) + } + } +} + +function onParserTimeout (parser) { + const { socket, timeoutType, client } = parser + + /* istanbul ignore else */ + if (timeoutType === TIMEOUT_HEADERS) { + if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { + assert(!parser.paused, 'cannot be paused while waiting for headers') + util.destroy(socket, new HeadersTimeoutError()) + } + } else if (timeoutType === TIMEOUT_BODY) { + if (!parser.paused) { + util.destroy(socket, new BodyTimeoutError()) + } + } else if (timeoutType === TIMEOUT_IDLE) { + assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) + util.destroy(socket, new InformationalError('socket idle timeout')) + } +} + +function onSocketReadable () { + const { [kParser]: parser } = this + if (parser) { + parser.readMore() + } +} + +function onSocketError (err) { + const { [kClient]: client, [kParser]: parser } = this + + assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') + + if (client[kHTTPConnVersion] !== 'h2') { + // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded + // to the user. + if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so for as a valid response. + parser.onMessageComplete() + return + } + } + + this[kError] = err + + onError(this[kClient], err) +} + +function onError (client, err) { + if ( + client[kRunning] === 0 && + err.code !== 'UND_ERR_INFO' && + err.code !== 'UND_ERR_SOCKET' + ) { + // Error is not caused by running request and not a recoverable + // socket error. + + assert(client[kPendingIdx] === client[kRunningIdx]) + + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) + } + assert(client[kSize] === 0) + } +} + +function onSocketEnd () { + const { [kParser]: parser, [kClient]: client } = this + + if (client[kHTTPConnVersion] !== 'h2') { + if (parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + return + } + } + + util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) +} + +function onSocketClose () { + const { [kClient]: client, [kParser]: parser } = this + + if (client[kHTTPConnVersion] === 'h1' && parser) { + if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { + // We treat all incoming data so far as a valid response. + parser.onMessageComplete() + } + + this[kParser].destroy() + this[kParser] = null + } + + const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) + + client[kSocket] = null + + if (client.destroyed) { + assert(client[kPending] === 0) + + // Fail entire queue. + const requests = client[kQueue].splice(client[kRunningIdx]) + for (let i = 0; i < requests.length; i++) { + const request = requests[i] + errorRequest(client, request, err) + } + } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { + // Fail head of pipeline. + const request = client[kQueue][client[kRunningIdx]] + client[kQueue][client[kRunningIdx]++] = null + + errorRequest(client, request, err) + } + + client[kPendingIdx] = client[kRunningIdx] + + assert(client[kRunning] === 0) + + client.emit('disconnect', client[kUrl], [client], err) + + resume(client) +} + +async function connect (client) { + assert(!client[kConnecting]) + assert(!client[kSocket]) + + let { host, hostname, protocol, port } = client[kUrl] + + // Resolve ipv6 + if (hostname[0] === '[') { + const idx = hostname.indexOf(']') + + assert(idx !== -1) + const ip = hostname.substring(1, idx) + + assert(net.isIP(ip)) + hostname = ip + } + + client[kConnecting] = true + + if (channels.beforeConnect.hasSubscribers) { + channels.beforeConnect.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector] + }) + } + + try { + const socket = await new Promise((resolve, reject) => { + client[kConnector]({ + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, (err, socket) => { + if (err) { + reject(err) + } else { + resolve(socket) + } + }) + }) + + if (client.destroyed) { + util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) + return + } + + client[kConnecting] = false + + assert(socket) + + const isH2 = socket.alpnProtocol === 'h2' + if (isH2) { + if (!h2ExperimentalWarned) { + h2ExperimentalWarned = true + process.emitWarning('H2 support is experimental, expect them to change at any time.', { + code: 'UNDICI-H2' + }) + } + + const session = http2.connect(client[kUrl], { + createConnection: () => socket, + peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams + }) + + client[kHTTPConnVersion] = 'h2' + session[kClient] = client + session[kSocket] = socket + session.on('error', onHttp2SessionError) + session.on('frameError', onHttp2FrameError) + session.on('end', onHttp2SessionEnd) + session.on('goaway', onHTTP2GoAway) + session.on('close', onSocketClose) + session.unref() + + client[kHTTP2Session] = session + socket[kHTTP2Session] = session + } else { + if (!llhttpInstance) { + llhttpInstance = await llhttpPromise + llhttpPromise = null + } + + socket[kNoRef] = false + socket[kWriting] = false + socket[kReset] = false + socket[kBlocking] = false + socket[kParser] = new Parser(client, socket, llhttpInstance) + } + + socket[kCounter] = 0 + socket[kMaxRequests] = client[kMaxRequests] + socket[kClient] = client + socket[kError] = null + + socket + .on('error', onSocketError) + .on('readable', onSocketReadable) + .on('end', onSocketEnd) + .on('close', onSocketClose) + + client[kSocket] = socket + + if (channels.connected.hasSubscribers) { + channels.connected.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + socket + }) + } + client.emit('connect', client[kUrl], [client]) + } catch (err) { + if (client.destroyed) { + return + } + + client[kConnecting] = false + + if (channels.connectError.hasSubscribers) { + channels.connectError.publish({ + connectParams: { + host, + hostname, + protocol, + port, + servername: client[kServerName], + localAddress: client[kLocalAddress] + }, + connector: client[kConnector], + error: err + }) + } + + if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { + assert(client[kRunning] === 0) + while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { + const request = client[kQueue][client[kPendingIdx]++] + errorRequest(client, request, err) + } + } else { + onError(client, err) + } + + client.emit('connectionError', client[kUrl], [client], err) + } + + resume(client) +} + +function emitDrain (client) { + client[kNeedDrain] = 0 + client.emit('drain', client[kUrl], [client]) +} + +function resume (client, sync) { + if (client[kResuming] === 2) { + return + } + + client[kResuming] = 2 + + _resume(client, sync) + client[kResuming] = 0 + + if (client[kRunningIdx] > 256) { + client[kQueue].splice(0, client[kRunningIdx]) + client[kPendingIdx] -= client[kRunningIdx] + client[kRunningIdx] = 0 + } +} + +function _resume (client, sync) { + while (true) { + if (client.destroyed) { + assert(client[kPending] === 0) + return + } + + if (client[kClosedResolve] && !client[kSize]) { + client[kClosedResolve]() + client[kClosedResolve] = null + return + } + + const socket = client[kSocket] + + if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { + if (client[kSize] === 0) { + if (!socket[kNoRef] && socket.unref) { + socket.unref() + socket[kNoRef] = true + } + } else if (socket[kNoRef] && socket.ref) { + socket.ref() + socket[kNoRef] = false + } + + if (client[kSize] === 0) { + if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { + socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE) + } + } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { + if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { + const request = client[kQueue][client[kRunningIdx]] + const headersTimeout = request.headersTimeout != null + ? request.headersTimeout + : client[kHeadersTimeout] + socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) + } + } + } + + if (client[kBusy]) { + client[kNeedDrain] = 2 + } else if (client[kNeedDrain] === 2) { + if (sync) { + client[kNeedDrain] = 1 + process.nextTick(emitDrain, client) + } else { + emitDrain(client) + } + continue + } + + if (client[kPending] === 0) { + return + } + + if (client[kRunning] >= (client[kPipelining] || 1)) { + return + } + + const request = client[kQueue][client[kPendingIdx]] + + if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { + if (client[kRunning] > 0) { + return + } + + client[kServerName] = request.servername + + if (socket && socket.servername !== request.servername) { + util.destroy(socket, new InformationalError('servername changed')) + return + } + } + + if (client[kConnecting]) { + return + } + + if (!socket && !client[kHTTP2Session]) { + connect(client) + return + } + + if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { + return + } + + if (client[kRunning] > 0 && !request.idempotent) { + // Non-idempotent request cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } + + if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { + // Don't dispatch an upgrade until all preceding requests have completed. + // A misbehaving server might upgrade the connection before all pipelined + // request has completed. + return + } + + if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && + (util.isStream(request.body) || util.isAsyncIterable(request.body))) { + // Request with stream or iterator body can error while other requests + // are inflight and indirectly error those as well. + // Ensure this doesn't happen by waiting for inflight + // to complete before dispatching. + + // Request with stream or iterator body cannot be retried. + // Ensure that no other requests are inflight and + // could cause failure. + return + } + + if (!request.aborted && write(client, request)) { + client[kPendingIdx]++ + } else { + client[kQueue].splice(client[kPendingIdx], 1) + } + } +} + +// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 +function shouldSendContentLength (method) { + return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' +} + +function write (client, request) { + if (client[kHTTPConnVersion] === 'h2') { + writeH2(client, client[kHTTP2Session], request) + return + } + + const { body, method, path, host, upgrade, headers, blocking, reset } = request + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + const bodyLength = util.bodyLength(body) + + let contentLength = bodyLength + + if (contentLength === null) { + contentLength = request.contentLength + } + + if (contentLength === 0 && !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + const socket = client[kSocket] + + try { + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } + + errorRequest(client, request, err || new RequestAbortedError()) + + util.destroy(socket, new InformationalError('aborted')) + }) + } catch (err) { + errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + if (method === 'HEAD') { + // https://github.com/mcollina/undici/issues/258 + // Close after a HEAD request to interop with misbehaving servers + // that may send a body in the response. + + socket[kReset] = true + } + + if (upgrade || method === 'CONNECT') { + // On CONNECT or upgrade, block pipeline from dispatching further + // requests on this connection. + + socket[kReset] = true + } + + if (reset != null) { + socket[kReset] = reset + } + + if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { + socket[kReset] = true + } + + if (blocking) { + socket[kBlocking] = true + } + + let header = `${method} ${path} HTTP/1.1\r\n` + + if (typeof host === 'string') { + header += `host: ${host}\r\n` + } else { + header += client[kHostHeader] + } + + if (upgrade) { + header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` + } else if (client[kPipelining] && !socket[kReset]) { + header += 'connection: keep-alive\r\n' + } else { + header += 'connection: close\r\n' + } + + if (headers) { + header += headers + } + + if (channels.sendHeaders.hasSubscribers) { + channels.sendHeaders.publish({ request, headers: header, socket }) + } + + /* istanbul ignore else: assertion */ + if (!body || bodyLength === 0) { + if (contentLength === 0) { + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + assert(contentLength === null, 'no body must not have content length') + socket.write(`${header}\r\n`, 'latin1') + } + request.onRequestSent() + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(body) + socket.uncork() + request.onBodySent(body) + request.onRequestSent() + if (!expectsPayload) { + socket[kReset] = true + } + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload }) + } else { + writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }) + } + } else if (util.isStream(body)) { + writeStream({ body, client, request, socket, contentLength, header, expectsPayload }) + } else if (util.isIterable(body)) { + writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }) + } else { + assert(false) + } + + return true +} + +function writeH2 (client, session, request) { + const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request + + let headers + if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) + else headers = reqHeaders + + if (upgrade) { + errorRequest(client, request, new Error('Upgrade not supported for H2')) + return false + } + + try { + // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? + request.onConnect((err) => { + if (request.aborted || request.completed) { + return + } + + errorRequest(client, request, err || new RequestAbortedError()) + }) + } catch (err) { + errorRequest(client, request, err) + } + + if (request.aborted) { + return false + } + + /** @type {import('node:http2').ClientHttp2Stream} */ + let stream + const h2State = client[kHTTP2SessionState] + + headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] + headers[HTTP2_HEADER_METHOD] = method + + if (method === 'CONNECT') { + session.ref() + // we are already connected, streams are pending, first request + // will create a new stream. We trigger a request to create the stream and wait until + // `ready` event is triggered + // We disabled endStream to allow the user to write to the stream + stream = session.request(headers, { endStream: false, signal }) + + if (stream.id && !stream.pending) { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + } else { + stream.once('ready', () => { + request.onUpgrade(null, null, stream) + ++h2State.openStreams + }) + } + + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) session.unref() + }) + + return true + } + + // https://tools.ietf.org/html/rfc7540#section-8.3 + // :path and :scheme headers must be omited when sending CONNECT + + headers[HTTP2_HEADER_PATH] = path + headers[HTTP2_HEADER_SCHEME] = 'https' + + // https://tools.ietf.org/html/rfc7231#section-4.3.1 + // https://tools.ietf.org/html/rfc7231#section-4.3.2 + // https://tools.ietf.org/html/rfc7231#section-4.3.5 + + // Sending a payload body on a request that does not + // expect it can cause undefined behavior on some + // servers and corrupt connection state. Do not + // re-use the connection for further requests. + + const expectsPayload = ( + method === 'PUT' || + method === 'POST' || + method === 'PATCH' + ) + + if (body && typeof body.read === 'function') { + // Try to read EOF in order to get length. + body.read(0) + } + + let contentLength = util.bodyLength(body) + + if (contentLength == null) { + contentLength = request.contentLength + } + + if (contentLength === 0 || !expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD NOT send a Content-Length header field when + // the request message does not contain a payload body and the method + // semantics do not anticipate such a body. + + contentLength = null + } + + // https://github.com/nodejs/undici/issues/2046 + // A user agent may send a Content-Length header with 0 value, this should be allowed. + if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { + if (client[kStrictContentLength]) { + errorRequest(client, request, new RequestContentLengthMismatchError()) + return false + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + if (contentLength != null) { + assert(body, 'no body must not have content length') + headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` + } + + session.ref() + + const shouldEndStream = method === 'GET' || method === 'HEAD' + if (expectContinue) { + headers[HTTP2_HEADER_EXPECT] = '100-continue' + stream = session.request(headers, { endStream: shouldEndStream, signal }) + + stream.once('continue', writeBodyH2) + } else { + stream = session.request(headers, { + endStream: shouldEndStream, + signal + }) + writeBodyH2() + } + + // Increment counter as we have new several streams open + ++h2State.openStreams + + stream.once('response', headers => { + const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers + + if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { + stream.pause() + } + }) + + stream.once('end', () => { + request.onComplete([]) + }) + + stream.on('data', (chunk) => { + if (request.onData(chunk) === false) { + stream.pause() + } + }) + + stream.once('close', () => { + h2State.openStreams -= 1 + // TODO(HTTP/2): unref only if current streams count is 0 + if (h2State.openStreams === 0) { + session.unref() + } + }) + + stream.once('error', function (err) { + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) + + stream.once('frameError', (type, code) => { + const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) + errorRequest(client, request, err) + + if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { + h2State.streams -= 1 + util.destroy(stream, err) + } + }) + + // stream.on('aborted', () => { + // // TODO(HTTP/2): Support aborted + // }) + + // stream.on('timeout', () => { + // // TODO(HTTP/2): Support timeout + // }) + + // stream.on('push', headers => { + // // TODO(HTTP/2): Suppor push + // }) + + // stream.on('trailers', headers => { + // // TODO(HTTP/2): Support trailers + // }) + + return true + + function writeBodyH2 () { + /* istanbul ignore else: assertion */ + if (!body) { + request.onRequestSent() + } else if (util.isBuffer(body)) { + assert(contentLength === body.byteLength, 'buffer body must have content length') + stream.cork() + stream.write(body) + stream.uncork() + stream.end() + request.onBodySent(body) + request.onRequestSent() + } else if (util.isBlobLike(body)) { + if (typeof body.stream === 'function') { + writeIterable({ + client, + request, + contentLength, + h2stream: stream, + expectsPayload, + body: body.stream(), + socket: client[kSocket], + header: '' + }) + } else { + writeBlob({ + body, + client, + request, + contentLength, + expectsPayload, + h2stream: stream, + header: '', + socket: client[kSocket] + }) + } + } else if (util.isStream(body)) { + writeStream({ + body, + client, + request, + contentLength, + expectsPayload, + socket: client[kSocket], + h2stream: stream, + header: '' + }) + } else if (util.isIterable(body)) { + writeIterable({ + body, + client, + request, + contentLength, + expectsPayload, + header: '', + h2stream: stream, + socket: client[kSocket] + }) + } else { + assert(false) + } + } +} + +function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') + + if (client[kHTTPConnVersion] === 'h2') { + // For HTTP/2, is enough to pipe the stream + const pipe = pipeline( + body, + h2stream, + (err) => { + if (err) { + util.destroy(body, err) + util.destroy(h2stream, err) + } else { + request.onRequestSent() + } + } + ) + + pipe.on('data', onPipeData) + pipe.once('end', () => { + pipe.removeListener('data', onPipeData) + util.destroy(pipe) + }) + + function onPipeData (chunk) { + request.onBodySent(chunk) + } + + return + } + + let finished = false + + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + + const onData = function (chunk) { + if (finished) { + return + } + + try { + if (!writer.write(chunk) && this.pause) { + this.pause() + } + } catch (err) { + util.destroy(this, err) + } + } + const onDrain = function () { + if (finished) { + return + } + + if (body.resume) { + body.resume() + } + } + const onAbort = function () { + if (finished) { + return + } + const err = new RequestAbortedError() + queueMicrotask(() => onFinished(err)) + } + const onFinished = function (err) { + if (finished) { + return + } + + finished = true + + assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) + + socket + .off('drain', onDrain) + .off('error', onFinished) + + body + .removeListener('data', onData) + .removeListener('end', onFinished) + .removeListener('error', onFinished) + .removeListener('close', onAbort) + + if (!err) { + try { + writer.end() + } catch (er) { + err = er + } + } + + writer.destroy(err) + + if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { + util.destroy(body, err) + } else { + util.destroy(body) + } + } + + body + .on('data', onData) + .on('end', onFinished) + .on('error', onFinished) + .on('close', onAbort) + + if (body.resume) { + body.resume() + } + + socket + .on('drain', onDrain) + .on('error', onFinished) +} + +async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength === body.size, 'blob body must have content length') + + const isH2 = client[kHTTPConnVersion] === 'h2' + try { + if (contentLength != null && contentLength !== body.size) { + throw new RequestContentLengthMismatchError() + } + + const buffer = Buffer.from(await body.arrayBuffer()) + + if (isH2) { + h2stream.cork() + h2stream.write(buffer) + h2stream.uncork() + } else { + socket.cork() + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + socket.write(buffer) + socket.uncork() + } + + request.onBodySent(buffer) + request.onRequestSent() + + if (!expectsPayload) { + socket[kReset] = true + } + + resume(client) + } catch (err) { + util.destroy(isH2 ? h2stream : socket, err) + } +} + +async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { + assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') + + let callback = null + function onDrain () { + if (callback) { + const cb = callback + callback = null + cb() + } + } + + const waitForDrain = () => new Promise((resolve, reject) => { + assert(callback === null) + + if (socket[kError]) { + reject(socket[kError]) + } else { + callback = resolve + } + }) + + if (client[kHTTPConnVersion] === 'h2') { + h2stream + .on('close', onDrain) + .on('drain', onDrain) + + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + const res = h2stream.write(chunk) + request.onBodySent(chunk) + if (!res) { + await waitForDrain() + } + } + } catch (err) { + h2stream.destroy(err) + } finally { + request.onRequestSent() + h2stream.end() + h2stream + .off('close', onDrain) + .off('drain', onDrain) + } + + return + } + + socket + .on('close', onDrain) + .on('drain', onDrain) + + const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) + try { + // It's up to the user to somehow abort the async iterable. + for await (const chunk of body) { + if (socket[kError]) { + throw socket[kError] + } + + if (!writer.write(chunk)) { + await waitForDrain() + } + } + + writer.end() + } catch (err) { + writer.destroy(err) + } finally { + socket + .off('close', onDrain) + .off('drain', onDrain) + } +} + +class AsyncWriter { + constructor ({ socket, request, contentLength, client, expectsPayload, header }) { + this.socket = socket + this.request = request + this.contentLength = contentLength + this.client = client + this.bytesWritten = 0 + this.expectsPayload = expectsPayload + this.header = header + + socket[kWriting] = true + } + + write (chunk) { + const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return false + } + + const len = Buffer.byteLength(chunk) + if (!len) { + return true + } + + // We should defer writing chunks. + if (contentLength !== null && bytesWritten + len > contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } + + process.emitWarning(new RequestContentLengthMismatchError()) + } + + socket.cork() + + if (bytesWritten === 0) { + if (!expectsPayload) { + socket[kReset] = true + } + + if (contentLength === null) { + socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') + } else { + socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') + } + } + + if (contentLength === null) { + socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') + } + + this.bytesWritten += len + + const ret = socket.write(chunk) + + socket.uncork() + + request.onBodySent(chunk) + + if (!ret) { + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + } + + return ret + } + + end () { + const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this + request.onRequestSent() + + socket[kWriting] = false + + if (socket[kError]) { + throw socket[kError] + } + + if (socket.destroyed) { + return + } + + if (bytesWritten === 0) { + if (expectsPayload) { + // https://tools.ietf.org/html/rfc7230#section-3.3.2 + // A user agent SHOULD send a Content-Length in a request message when + // no Transfer-Encoding is sent and the request method defines a meaning + // for an enclosed payload body. + + socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') + } else { + socket.write(`${header}\r\n`, 'latin1') + } + } else if (contentLength === null) { + socket.write('\r\n0\r\n\r\n', 'latin1') + } + + if (contentLength !== null && bytesWritten !== contentLength) { + if (client[kStrictContentLength]) { + throw new RequestContentLengthMismatchError() + } else { + process.emitWarning(new RequestContentLengthMismatchError()) + } + } + + if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { + // istanbul ignore else: only for jest + if (socket[kParser].timeout.refresh) { + socket[kParser].timeout.refresh() + } + } + + resume(client) + } + + destroy (err) { + const { socket, client } = this + + socket[kWriting] = false + + if (err) { + assert(client[kRunning] <= 1, 'pipeline should only contain this request') + util.destroy(socket, err) + } + } +} + +function errorRequest (client, request, err) { + try { + request.onError(err) + assert(request.aborted) + } catch (err) { + client.emit('error', err) + } +} + +module.exports = Client + + +/***/ }), + +/***/ 3194: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +/* istanbul ignore file: only for Node 12 */ + +const { kConnected, kSize } = __nccwpck_require__(6443) + +class CompatWeakRef { + constructor (value) { + this.value = value + } + + deref () { + return this.value[kConnected] === 0 && this.value[kSize] === 0 + ? undefined + : this.value + } +} + +class CompatFinalizer { + constructor (finalizer) { + this.finalizer = finalizer + } + + register (dispatcher, key) { + if (dispatcher.on) { + dispatcher.on('disconnect', () => { + if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { + this.finalizer(key) + } + }) + } + } +} + +module.exports = function () { + // FIXME: remove workaround when the Node bug is fixed + // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 + if (process.env.NODE_V8_COVERAGE) { + return { + WeakRef: CompatWeakRef, + FinalizationRegistry: CompatFinalizer + } + } + return { + WeakRef: global.WeakRef || CompatWeakRef, + FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer + } +} + + +/***/ }), + +/***/ 9237: +/***/ ((module) => { + + + +// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size +const maxAttributeValueSize = 1024 + +// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size +const maxNameValuePairSize = 4096 + +module.exports = { + maxAttributeValueSize, + maxNameValuePairSize +} + + +/***/ }), + +/***/ 3168: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { parseSetCookie } = __nccwpck_require__(8915) +const { stringify } = __nccwpck_require__(3834) +const { webidl } = __nccwpck_require__(4222) +const { Headers } = __nccwpck_require__(6349) + +/** + * @typedef {Object} Cookie + * @property {string} name + * @property {string} value + * @property {Date|number|undefined} expires + * @property {number|undefined} maxAge + * @property {string|undefined} domain + * @property {string|undefined} path + * @property {boolean|undefined} secure + * @property {boolean|undefined} httpOnly + * @property {'Strict'|'Lax'|'None'} sameSite + * @property {string[]} unparsed + */ + +/** + * @param {Headers} headers + * @returns {Record} + */ +function getCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookie = headers.get('cookie') + const out = {} + + if (!cookie) { + return out + } + + for (const piece of cookie.split(';')) { + const [name, ...value] = piece.split('=') + + out[name.trim()] = value.join('=') + } + + return out +} + +/** + * @param {Headers} headers + * @param {string} name + * @param {{ path?: string, domain?: string }|undefined} attributes + * @returns {void} + */ +function deleteCookie (headers, name, attributes) { + webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + name = webidl.converters.DOMString(name) + attributes = webidl.converters.DeleteCookieAttributes(attributes) + + // Matches behavior of + // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 + setCookie(headers, { + name, + value: '', + expires: new Date(0), + ...attributes + }) +} + +/** + * @param {Headers} headers + * @returns {Cookie[]} + */ +function getSetCookies (headers) { + webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + const cookies = headers.getSetCookie() + + if (!cookies) { + return [] + } + + return cookies.map((pair) => parseSetCookie(pair)) +} + +/** + * @param {Headers} headers + * @param {Cookie} cookie + * @returns {void} + */ +function setCookie (headers, cookie) { + webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) + + webidl.brandCheck(headers, Headers, { strict: false }) + + cookie = webidl.converters.Cookie(cookie) + + const str = stringify(cookie) + + if (str) { + headers.append('Set-Cookie', stringify(cookie)) + } +} + +webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + } +]) + +webidl.converters.Cookie = webidl.dictionaryConverter([ + { + converter: webidl.converters.DOMString, + key: 'name' + }, + { + converter: webidl.converters.DOMString, + key: 'value' + }, + { + converter: webidl.nullableConverter((value) => { + if (typeof value === 'number') { + return webidl.converters['unsigned long long'](value) + } + + return new Date(value) + }), + key: 'expires', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters['long long']), + key: 'maxAge', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'domain', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.DOMString), + key: 'path', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'secure', + defaultValue: null + }, + { + converter: webidl.nullableConverter(webidl.converters.boolean), + key: 'httpOnly', + defaultValue: null + }, + { + converter: webidl.converters.USVString, + key: 'sameSite', + allowedValues: ['Strict', 'Lax', 'None'] + }, + { + converter: webidl.sequenceConverter(webidl.converters.DOMString), + key: 'unparsed', + defaultValue: [] + } +]) + +module.exports = { + getCookies, + deleteCookie, + getSetCookies, + setCookie +} + + +/***/ }), + +/***/ 8915: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(9237) +const { isCTLExcludingHtab } = __nccwpck_require__(3834) +const { collectASequenceOfCodePointsFast } = __nccwpck_require__(4322) +const assert = __nccwpck_require__(2613) + +/** + * @description Parses the field-value attributes of a set-cookie header string. + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} header + * @returns if the header is invalid, null will be returned + */ +function parseSetCookie (header) { + // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F + // character (CTL characters excluding HTAB): Abort these steps and + // ignore the set-cookie-string entirely. + if (isCTLExcludingHtab(header)) { + return null + } + + let nameValuePair = '' + let unparsedAttributes = '' + let name = '' + let value = '' + + // 2. If the set-cookie-string contains a %x3B (";") character: + if (header.includes(';')) { + // 1. The name-value-pair string consists of the characters up to, + // but not including, the first %x3B (";"), and the unparsed- + // attributes consist of the remainder of the set-cookie-string + // (including the %x3B (";") in question). + const position = { position: 0 } + + nameValuePair = collectASequenceOfCodePointsFast(';', header, position) + unparsedAttributes = header.slice(position.position) + } else { + // Otherwise: + + // 1. The name-value-pair string consists of all the characters + // contained in the set-cookie-string, and the unparsed- + // attributes is the empty string. + nameValuePair = header + } + + // 3. If the name-value-pair string lacks a %x3D ("=") character, then + // the name string is empty, and the value string is the value of + // name-value-pair. + if (!nameValuePair.includes('=')) { + value = nameValuePair + } else { + // Otherwise, the name string consists of the characters up to, but + // not including, the first %x3D ("=") character, and the (possibly + // empty) value string consists of the characters after the first + // %x3D ("=") character. + const position = { position: 0 } + name = collectASequenceOfCodePointsFast( + '=', + nameValuePair, + position + ) + value = nameValuePair.slice(position.position + 1) + } + + // 4. Remove any leading or trailing WSP characters from the name + // string and the value string. + name = name.trim() + value = value.trim() + + // 5. If the sum of the lengths of the name string and the value string + // is more than 4096 octets, abort these steps and ignore the set- + // cookie-string entirely. + if (name.length + value.length > maxNameValuePairSize) { + return null + } + + // 6. The cookie-name is the name string, and the cookie-value is the + // value string. + return { + name, value, ...parseUnparsedAttributes(unparsedAttributes) + } +} + +/** + * Parses the remaining attributes of a set-cookie header + * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 + * @param {string} unparsedAttributes + * @param {[Object.]={}} cookieAttributeList + */ +function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { + // 1. If the unparsed-attributes string is empty, skip the rest of + // these steps. + if (unparsedAttributes.length === 0) { + return cookieAttributeList + } + + // 2. Discard the first character of the unparsed-attributes (which + // will be a %x3B (";") character). + assert(unparsedAttributes[0] === ';') + unparsedAttributes = unparsedAttributes.slice(1) + + let cookieAv = '' + + // 3. If the remaining unparsed-attributes contains a %x3B (";") + // character: + if (unparsedAttributes.includes(';')) { + // 1. Consume the characters of the unparsed-attributes up to, but + // not including, the first %x3B (";") character. + cookieAv = collectASequenceOfCodePointsFast( + ';', + unparsedAttributes, + { position: 0 } + ) + unparsedAttributes = unparsedAttributes.slice(cookieAv.length) + } else { + // Otherwise: + + // 1. Consume the remainder of the unparsed-attributes. + cookieAv = unparsedAttributes + unparsedAttributes = '' + } + + // Let the cookie-av string be the characters consumed in this step. + + let attributeName = '' + let attributeValue = '' + + // 4. If the cookie-av string contains a %x3D ("=") character: + if (cookieAv.includes('=')) { + // 1. The (possibly empty) attribute-name string consists of the + // characters up to, but not including, the first %x3D ("=") + // character, and the (possibly empty) attribute-value string + // consists of the characters after the first %x3D ("=") + // character. + const position = { position: 0 } + + attributeName = collectASequenceOfCodePointsFast( + '=', + cookieAv, + position + ) + attributeValue = cookieAv.slice(position.position + 1) + } else { + // Otherwise: + + // 1. The attribute-name string consists of the entire cookie-av + // string, and the attribute-value string is empty. + attributeName = cookieAv + } + + // 5. Remove any leading or trailing WSP characters from the attribute- + // name string and the attribute-value string. + attributeName = attributeName.trim() + attributeValue = attributeValue.trim() + + // 6. If the attribute-value is longer than 1024 octets, ignore the + // cookie-av string and return to Step 1 of this algorithm. + if (attributeValue.length > maxAttributeValueSize) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 7. Process the attribute-name and attribute-value according to the + // requirements in the following subsections. (Notice that + // attributes with unrecognized attribute-names are ignored.) + const attributeNameLowercase = attributeName.toLowerCase() + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 + // If the attribute-name case-insensitively matches the string + // "Expires", the user agent MUST process the cookie-av as follows. + if (attributeNameLowercase === 'expires') { + // 1. Let the expiry-time be the result of parsing the attribute-value + // as cookie-date (see Section 5.1.1). + const expiryTime = new Date(attributeValue) + + // 2. If the attribute-value failed to parse as a cookie date, ignore + // the cookie-av. + + cookieAttributeList.expires = expiryTime + } else if (attributeNameLowercase === 'max-age') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 + // If the attribute-name case-insensitively matches the string "Max- + // Age", the user agent MUST process the cookie-av as follows. + + // 1. If the first character of the attribute-value is not a DIGIT or a + // "-" character, ignore the cookie-av. + const charCode = attributeValue.charCodeAt(0) + + if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 2. If the remainder of attribute-value contains a non-DIGIT + // character, ignore the cookie-av. + if (!/^\d+$/.test(attributeValue)) { + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) + } + + // 3. Let delta-seconds be the attribute-value converted to an integer. + const deltaSeconds = Number(attributeValue) + + // 4. Let cookie-age-limit be the maximum age of the cookie (which + // SHOULD be 400 days or less, see Section 4.1.2.2). + + // 5. Set delta-seconds to the smaller of its present value and cookie- + // age-limit. + // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) + + // 6. If delta-seconds is less than or equal to zero (0), let expiry- + // time be the earliest representable date and time. Otherwise, let + // the expiry-time be the current date and time plus delta-seconds + // seconds. + // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds + + // 7. Append an attribute to the cookie-attribute-list with an + // attribute-name of Max-Age and an attribute-value of expiry-time. + cookieAttributeList.maxAge = deltaSeconds + } else if (attributeNameLowercase === 'domain') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 + // If the attribute-name case-insensitively matches the string "Domain", + // the user agent MUST process the cookie-av as follows. + + // 1. Let cookie-domain be the attribute-value. + let cookieDomain = attributeValue + + // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be + // cookie-domain without its leading %x2E ("."). + if (cookieDomain[0] === '.') { + cookieDomain = cookieDomain.slice(1) + } + + // 3. Convert the cookie-domain to lower case. + cookieDomain = cookieDomain.toLowerCase() + + // 4. Append an attribute to the cookie-attribute-list with an + // attribute-name of Domain and an attribute-value of cookie-domain. + cookieAttributeList.domain = cookieDomain + } else if (attributeNameLowercase === 'path') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 + // If the attribute-name case-insensitively matches the string "Path", + // the user agent MUST process the cookie-av as follows. + + // 1. If the attribute-value is empty or if the first character of the + // attribute-value is not %x2F ("/"): + let cookiePath = '' + if (attributeValue.length === 0 || attributeValue[0] !== '/') { + // 1. Let cookie-path be the default-path. + cookiePath = '/' + } else { + // Otherwise: + + // 1. Let cookie-path be the attribute-value. + cookiePath = attributeValue + } + + // 2. Append an attribute to the cookie-attribute-list with an + // attribute-name of Path and an attribute-value of cookie-path. + cookieAttributeList.path = cookiePath + } else if (attributeNameLowercase === 'secure') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 + // If the attribute-name case-insensitively matches the string "Secure", + // the user agent MUST append an attribute to the cookie-attribute-list + // with an attribute-name of Secure and an empty attribute-value. + + cookieAttributeList.secure = true + } else if (attributeNameLowercase === 'httponly') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 + // If the attribute-name case-insensitively matches the string + // "HttpOnly", the user agent MUST append an attribute to the cookie- + // attribute-list with an attribute-name of HttpOnly and an empty + // attribute-value. + + cookieAttributeList.httpOnly = true + } else if (attributeNameLowercase === 'samesite') { + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 + // If the attribute-name case-insensitively matches the string + // "SameSite", the user agent MUST process the cookie-av as follows: + + // 1. Let enforcement be "Default". + let enforcement = 'Default' + + const attributeValueLowercase = attributeValue.toLowerCase() + // 2. If cookie-av's attribute-value is a case-insensitive match for + // "None", set enforcement to "None". + if (attributeValueLowercase.includes('none')) { + enforcement = 'None' + } + + // 3. If cookie-av's attribute-value is a case-insensitive match for + // "Strict", set enforcement to "Strict". + if (attributeValueLowercase.includes('strict')) { + enforcement = 'Strict' + } + + // 4. If cookie-av's attribute-value is a case-insensitive match for + // "Lax", set enforcement to "Lax". + if (attributeValueLowercase.includes('lax')) { + enforcement = 'Lax' + } + + // 5. Append an attribute to the cookie-attribute-list with an + // attribute-name of "SameSite" and an attribute-value of + // enforcement. + cookieAttributeList.sameSite = enforcement + } else { + cookieAttributeList.unparsed ??= [] + + cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) + } + + // 8. Return to Step 1 of this algorithm. + return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) +} + +module.exports = { + parseSetCookie, + parseUnparsedAttributes +} + + +/***/ }), + +/***/ 3834: +/***/ ((module) => { + + + +/** + * @param {string} value + * @returns {boolean} + */ +function isCTLExcludingHtab (value) { + if (value.length === 0) { + return false + } + + for (const char of value) { + const code = char.charCodeAt(0) + + if ( + (code >= 0x00 || code <= 0x08) || + (code >= 0x0A || code <= 0x1F) || + code === 0x7F + ) { + return false + } + } +} + +/** + CHAR = + token = 1* + separators = "(" | ")" | "<" | ">" | "@" + | "," | ";" | ":" | "\" | <"> + | "/" | "[" | "]" | "?" | "=" + | "{" | "}" | SP | HT + * @param {string} name + */ +function validateCookieName (name) { + for (const char of name) { + const code = char.charCodeAt(0) + + if ( + (code <= 0x20 || code > 0x7F) || + char === '(' || + char === ')' || + char === '>' || + char === '<' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' + ) { + throw new Error('Invalid cookie name') + } + } +} + +/** + cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) + cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E + ; US-ASCII characters excluding CTLs, + ; whitespace DQUOTE, comma, semicolon, + ; and backslash + * @param {string} value + */ +function validateCookieValue (value) { + for (const char of value) { + const code = char.charCodeAt(0) + + if ( + code < 0x21 || // exclude CTLs (0-31) + code === 0x22 || + code === 0x2C || + code === 0x3B || + code === 0x5C || + code > 0x7E // non-ascii + ) { + throw new Error('Invalid header value') + } + } +} + +/** + * path-value = + * @param {string} path + */ +function validateCookiePath (path) { + for (const char of path) { + const code = char.charCodeAt(0) + + if (code < 0x21 || char === ';') { + throw new Error('Invalid cookie path') + } + } +} + +/** + * I have no idea why these values aren't allowed to be honest, + * but Deno tests these. - Khafra + * @param {string} domain + */ +function validateCookieDomain (domain) { + if ( + domain.startsWith('-') || + domain.endsWith('.') || + domain.endsWith('-') + ) { + throw new Error('Invalid cookie domain') + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 + * @param {number|Date} date + IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT + ; fixed length/zone/capitalization subset of the format + ; see Section 3.3 of [RFC5322] + + day-name = %x4D.6F.6E ; "Mon", case-sensitive + / %x54.75.65 ; "Tue", case-sensitive + / %x57.65.64 ; "Wed", case-sensitive + / %x54.68.75 ; "Thu", case-sensitive + / %x46.72.69 ; "Fri", case-sensitive + / %x53.61.74 ; "Sat", case-sensitive + / %x53.75.6E ; "Sun", case-sensitive + date1 = day SP month SP year + ; e.g., 02 Jun 1982 + + day = 2DIGIT + month = %x4A.61.6E ; "Jan", case-sensitive + / %x46.65.62 ; "Feb", case-sensitive + / %x4D.61.72 ; "Mar", case-sensitive + / %x41.70.72 ; "Apr", case-sensitive + / %x4D.61.79 ; "May", case-sensitive + / %x4A.75.6E ; "Jun", case-sensitive + / %x4A.75.6C ; "Jul", case-sensitive + / %x41.75.67 ; "Aug", case-sensitive + / %x53.65.70 ; "Sep", case-sensitive + / %x4F.63.74 ; "Oct", case-sensitive + / %x4E.6F.76 ; "Nov", case-sensitive + / %x44.65.63 ; "Dec", case-sensitive + year = 4DIGIT + + GMT = %x47.4D.54 ; "GMT", case-sensitive + + time-of-day = hour ":" minute ":" second + ; 00:00:00 - 23:59:60 (leap second) + + hour = 2DIGIT + minute = 2DIGIT + second = 2DIGIT + */ +function toIMFDate (date) { + if (typeof date === 'number') { + date = new Date(date) + } + + const days = [ + 'Sun', 'Mon', 'Tue', 'Wed', + 'Thu', 'Fri', 'Sat' + ] + + const months = [ + 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' + ] + + const dayName = days[date.getUTCDay()] + const day = date.getUTCDate().toString().padStart(2, '0') + const month = months[date.getUTCMonth()] + const year = date.getUTCFullYear() + const hour = date.getUTCHours().toString().padStart(2, '0') + const minute = date.getUTCMinutes().toString().padStart(2, '0') + const second = date.getUTCSeconds().toString().padStart(2, '0') + + return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` +} + +/** + max-age-av = "Max-Age=" non-zero-digit *DIGIT + ; In practice, both expires-av and max-age-av + ; are limited to dates representable by the + ; user agent. + * @param {number} maxAge + */ +function validateCookieMaxAge (maxAge) { + if (maxAge < 0) { + throw new Error('Invalid cookie max-age') + } +} + +/** + * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 + * @param {import('./index').Cookie} cookie + */ +function stringify (cookie) { + if (cookie.name.length === 0) { + return null + } + + validateCookieName(cookie.name) + validateCookieValue(cookie.value) + + const out = [`${cookie.name}=${cookie.value}`] + + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 + // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 + if (cookie.name.startsWith('__Secure-')) { + cookie.secure = true + } + + if (cookie.name.startsWith('__Host-')) { + cookie.secure = true + cookie.domain = null + cookie.path = '/' + } + + if (cookie.secure) { + out.push('Secure') + } + + if (cookie.httpOnly) { + out.push('HttpOnly') + } + + if (typeof cookie.maxAge === 'number') { + validateCookieMaxAge(cookie.maxAge) + out.push(`Max-Age=${cookie.maxAge}`) + } + + if (cookie.domain) { + validateCookieDomain(cookie.domain) + out.push(`Domain=${cookie.domain}`) + } + + if (cookie.path) { + validateCookiePath(cookie.path) + out.push(`Path=${cookie.path}`) + } + + if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { + out.push(`Expires=${toIMFDate(cookie.expires)}`) + } + + if (cookie.sameSite) { + out.push(`SameSite=${cookie.sameSite}`) + } + + for (const part of cookie.unparsed) { + if (!part.includes('=')) { + throw new Error('Invalid unparsed') + } + + const [key, ...value] = part.split('=') + + out.push(`${key.trim()}=${value.join('=')}`) + } + + return out.join('; ') +} + +module.exports = { + isCTLExcludingHtab, + validateCookieName, + validateCookiePath, + validateCookieValue, + toIMFDate, + stringify +} + + +/***/ }), + +/***/ 9136: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const net = __nccwpck_require__(9278) +const assert = __nccwpck_require__(2613) +const util = __nccwpck_require__(3440) +const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8707) + +let tls // include tls conditionally since it is not always available + +// TODO: session re-use does not wait for the first +// connection to resolve the session and might therefore +// resolve the same servername multiple times even when +// re-use is enabled. + +let SessionCache +// FIXME: remove workaround when the Node bug is fixed +// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 +if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) { + SessionCache = class WeakSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + this._sessionRegistry = new global.FinalizationRegistry((key) => { + if (this._sessionCache.size < this._maxCachedSessions) { + return + } + + const ref = this._sessionCache.get(key) + if (ref !== undefined && ref.deref() === undefined) { + this._sessionCache.delete(key) + } + }) + } + + get (sessionKey) { + const ref = this._sessionCache.get(sessionKey) + return ref ? ref.deref() : null + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + this._sessionCache.set(sessionKey, new WeakRef(session)) + this._sessionRegistry.register(session, sessionKey) + } + } +} else { + SessionCache = class SimpleSessionCache { + constructor (maxCachedSessions) { + this._maxCachedSessions = maxCachedSessions + this._sessionCache = new Map() + } + + get (sessionKey) { + return this._sessionCache.get(sessionKey) + } + + set (sessionKey, session) { + if (this._maxCachedSessions === 0) { + return + } + + if (this._sessionCache.size >= this._maxCachedSessions) { + // remove the oldest session + const { value: oldestKey } = this._sessionCache.keys().next() + this._sessionCache.delete(oldestKey) + } + + this._sessionCache.set(sessionKey, session) + } + } +} + +function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) { + if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { + throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') + } + + const options = { path: socketPath, ...opts } + const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) + timeout = timeout == null ? 10e3 : timeout + allowH2 = allowH2 != null ? allowH2 : false + return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { + let socket + if (protocol === 'https:') { + if (!tls) { + tls = __nccwpck_require__(4756) + } + servername = servername || options.servername || util.getServerName(host) || null + + const sessionKey = servername || hostname + const session = sessionCache.get(sessionKey) || null + + assert(sessionKey) + + socket = tls.connect({ + highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... + ...options, + servername, + session, + localAddress, + // TODO(HTTP/2): Add support for h2c + ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], + socket: httpSocket, // upgrade socket connection + port: port || 443, + host: hostname + }) + + socket + .on('session', function (session) { + // TODO (fix): Can a session become invalid once established? Don't think so? + sessionCache.set(sessionKey, session) + }) + } else { + assert(!httpSocket, 'httpSocket can only be sent on TLS update') + socket = net.connect({ + highWaterMark: 64 * 1024, // Same as nodejs fs streams. + ...options, + localAddress, + port: port || 80, + host: hostname + }) + } + + // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket + if (options.keepAlive == null || options.keepAlive) { + const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay + socket.setKeepAlive(true, keepAliveInitialDelay) + } + + const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) + + socket + .setNoDelay(true) + .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { + cancelTimeout() + + if (callback) { + const cb = callback + callback = null + cb(null, this) + } + }) + .on('error', function (err) { + cancelTimeout() + + if (callback) { + const cb = callback + callback = null + cb(err) + } + }) + + return socket + } +} + +function setupTimeout (onConnectTimeout, timeout) { + if (!timeout) { + return () => {} + } + + let s1 = null + let s2 = null + const timeoutId = setTimeout(() => { + // setImmediate is added to make sure that we priotorise socket error events over timeouts + s1 = setImmediate(() => { + if (process.platform === 'win32') { + // Windows needs an extra setImmediate probably due to implementation differences in the socket logic + s2 = setImmediate(() => onConnectTimeout()) + } else { + onConnectTimeout() + } + }) + }, timeout) + return () => { + clearTimeout(timeoutId) + clearImmediate(s1) + clearImmediate(s2) + } +} + +function onConnectTimeout (socket) { + util.destroy(socket, new ConnectTimeoutError()) +} + +module.exports = buildConnector + + +/***/ }), + +/***/ 735: +/***/ ((module) => { + + + +/** @type {Record} */ +const headerNameLowerCasedRecord = {} + +// https://developer.mozilla.org/docs/Web/HTTP/Headers +const wellknownHeaderNames = [ + 'Accept', + 'Accept-Encoding', + 'Accept-Language', + 'Accept-Ranges', + 'Access-Control-Allow-Credentials', + 'Access-Control-Allow-Headers', + 'Access-Control-Allow-Methods', + 'Access-Control-Allow-Origin', + 'Access-Control-Expose-Headers', + 'Access-Control-Max-Age', + 'Access-Control-Request-Headers', + 'Access-Control-Request-Method', + 'Age', + 'Allow', + 'Alt-Svc', + 'Alt-Used', + 'Authorization', + 'Cache-Control', + 'Clear-Site-Data', + 'Connection', + 'Content-Disposition', + 'Content-Encoding', + 'Content-Language', + 'Content-Length', + 'Content-Location', + 'Content-Range', + 'Content-Security-Policy', + 'Content-Security-Policy-Report-Only', + 'Content-Type', + 'Cookie', + 'Cross-Origin-Embedder-Policy', + 'Cross-Origin-Opener-Policy', + 'Cross-Origin-Resource-Policy', + 'Date', + 'Device-Memory', + 'Downlink', + 'ECT', + 'ETag', + 'Expect', + 'Expect-CT', + 'Expires', + 'Forwarded', + 'From', + 'Host', + 'If-Match', + 'If-Modified-Since', + 'If-None-Match', + 'If-Range', + 'If-Unmodified-Since', + 'Keep-Alive', + 'Last-Modified', + 'Link', + 'Location', + 'Max-Forwards', + 'Origin', + 'Permissions-Policy', + 'Pragma', + 'Proxy-Authenticate', + 'Proxy-Authorization', + 'RTT', + 'Range', + 'Referer', + 'Referrer-Policy', + 'Refresh', + 'Retry-After', + 'Sec-WebSocket-Accept', + 'Sec-WebSocket-Extensions', + 'Sec-WebSocket-Key', + 'Sec-WebSocket-Protocol', + 'Sec-WebSocket-Version', + 'Server', + 'Server-Timing', + 'Service-Worker-Allowed', + 'Service-Worker-Navigation-Preload', + 'Set-Cookie', + 'SourceMap', + 'Strict-Transport-Security', + 'Supports-Loading-Mode', + 'TE', + 'Timing-Allow-Origin', + 'Trailer', + 'Transfer-Encoding', + 'Upgrade', + 'Upgrade-Insecure-Requests', + 'User-Agent', + 'Vary', + 'Via', + 'WWW-Authenticate', + 'X-Content-Type-Options', + 'X-DNS-Prefetch-Control', + 'X-Frame-Options', + 'X-Permitted-Cross-Domain-Policies', + 'X-Powered-By', + 'X-Requested-With', + 'X-XSS-Protection' +] + +for (let i = 0; i < wellknownHeaderNames.length; ++i) { + const key = wellknownHeaderNames[i] + const lowerCasedKey = key.toLowerCase() + headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = + lowerCasedKey +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(headerNameLowerCasedRecord, null) + +module.exports = { + wellknownHeaderNames, + headerNameLowerCasedRecord +} + + +/***/ }), + +/***/ 8707: +/***/ ((module) => { + + + +class UndiciError extends Error { + constructor (message) { + super(message) + this.name = 'UndiciError' + this.code = 'UND_ERR' + } +} + +class ConnectTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ConnectTimeoutError) + this.name = 'ConnectTimeoutError' + this.message = message || 'Connect Timeout Error' + this.code = 'UND_ERR_CONNECT_TIMEOUT' + } +} + +class HeadersTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersTimeoutError) + this.name = 'HeadersTimeoutError' + this.message = message || 'Headers Timeout Error' + this.code = 'UND_ERR_HEADERS_TIMEOUT' + } +} + +class HeadersOverflowError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, HeadersOverflowError) + this.name = 'HeadersOverflowError' + this.message = message || 'Headers Overflow Error' + this.code = 'UND_ERR_HEADERS_OVERFLOW' + } +} + +class BodyTimeoutError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, BodyTimeoutError) + this.name = 'BodyTimeoutError' + this.message = message || 'Body Timeout Error' + this.code = 'UND_ERR_BODY_TIMEOUT' + } +} + +class ResponseStatusCodeError extends UndiciError { + constructor (message, statusCode, headers, body) { + super(message) + Error.captureStackTrace(this, ResponseStatusCodeError) + this.name = 'ResponseStatusCodeError' + this.message = message || 'Response Status Code Error' + this.code = 'UND_ERR_RESPONSE_STATUS_CODE' + this.body = body + this.status = statusCode + this.statusCode = statusCode + this.headers = headers + } +} + +class InvalidArgumentError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidArgumentError) + this.name = 'InvalidArgumentError' + this.message = message || 'Invalid Argument Error' + this.code = 'UND_ERR_INVALID_ARG' + } +} + +class InvalidReturnValueError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InvalidReturnValueError) + this.name = 'InvalidReturnValueError' + this.message = message || 'Invalid Return Value Error' + this.code = 'UND_ERR_INVALID_RETURN_VALUE' + } +} + +class RequestAbortedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestAbortedError) + this.name = 'AbortError' + this.message = message || 'Request aborted' + this.code = 'UND_ERR_ABORTED' + } +} + +class InformationalError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, InformationalError) + this.name = 'InformationalError' + this.message = message || 'Request information' + this.code = 'UND_ERR_INFO' + } +} + +class RequestContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, RequestContentLengthMismatchError) + this.name = 'RequestContentLengthMismatchError' + this.message = message || 'Request body length does not match content-length header' + this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' + } +} + +class ResponseContentLengthMismatchError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseContentLengthMismatchError) + this.name = 'ResponseContentLengthMismatchError' + this.message = message || 'Response body length does not match content-length header' + this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' + } +} + +class ClientDestroyedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientDestroyedError) + this.name = 'ClientDestroyedError' + this.message = message || 'The client is destroyed' + this.code = 'UND_ERR_DESTROYED' + } +} + +class ClientClosedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ClientClosedError) + this.name = 'ClientClosedError' + this.message = message || 'The client is closed' + this.code = 'UND_ERR_CLOSED' + } +} + +class SocketError extends UndiciError { + constructor (message, socket) { + super(message) + Error.captureStackTrace(this, SocketError) + this.name = 'SocketError' + this.message = message || 'Socket error' + this.code = 'UND_ERR_SOCKET' + this.socket = socket + } +} + +class NotSupportedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'NotSupportedError' + this.message = message || 'Not supported error' + this.code = 'UND_ERR_NOT_SUPPORTED' + } +} + +class BalancedPoolMissingUpstreamError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, NotSupportedError) + this.name = 'MissingUpstreamError' + this.message = message || 'No upstream has been added to the BalancedPool' + this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' + } +} + +class HTTPParserError extends Error { + constructor (message, code, data) { + super(message) + Error.captureStackTrace(this, HTTPParserError) + this.name = 'HTTPParserError' + this.code = code ? `HPE_${code}` : undefined + this.data = data ? data.toString() : undefined + } +} + +class ResponseExceededMaxSizeError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, ResponseExceededMaxSizeError) + this.name = 'ResponseExceededMaxSizeError' + this.message = message || 'Response content exceeded max size' + this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' + } +} + +class RequestRetryError extends UndiciError { + constructor (message, code, { headers, data }) { + super(message) + Error.captureStackTrace(this, RequestRetryError) + this.name = 'RequestRetryError' + this.message = message || 'Request retry error' + this.code = 'UND_ERR_REQ_RETRY' + this.statusCode = code + this.data = data + this.headers = headers + } +} + +module.exports = { + HTTPParserError, + UndiciError, + HeadersTimeoutError, + HeadersOverflowError, + BodyTimeoutError, + RequestContentLengthMismatchError, + ConnectTimeoutError, + ResponseStatusCodeError, + InvalidArgumentError, + InvalidReturnValueError, + RequestAbortedError, + ClientDestroyedError, + ClientClosedError, + InformationalError, + SocketError, + NotSupportedError, + ResponseContentLengthMismatchError, + BalancedPoolMissingUpstreamError, + ResponseExceededMaxSizeError, + RequestRetryError +} + + +/***/ }), + +/***/ 4655: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { + InvalidArgumentError, + NotSupportedError +} = __nccwpck_require__(8707) +const assert = __nccwpck_require__(2613) +const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(6443) +const util = __nccwpck_require__(3440) + +// tokenRegExp and headerCharRegex have been lifted from +// https://github.com/nodejs/node/blob/main/lib/_http_common.js + +/** + * Verifies that the given val is a valid HTTP token + * per the rules defined in RFC 7230 + * See https://tools.ietf.org/html/rfc7230#section-3.2.6 + */ +const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ + +/** + * Matches if val contains an invalid field-vchar + * field-value = *( field-content / obs-fold ) + * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] + * field-vchar = VCHAR / obs-text + */ +const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ + +// Verifies that a given path is valid does not contain control chars \x00 to \x20 +const invalidPathRegex = /[^\u0021-\u00ff]/ + +const kHandler = Symbol('handler') + +const channels = {} + +let extractBody + +try { + const diagnosticsChannel = __nccwpck_require__(1637) + channels.create = diagnosticsChannel.channel('undici:request:create') + channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') + channels.headers = diagnosticsChannel.channel('undici:request:headers') + channels.trailers = diagnosticsChannel.channel('undici:request:trailers') + channels.error = diagnosticsChannel.channel('undici:request:error') +} catch { + channels.create = { hasSubscribers: false } + channels.bodySent = { hasSubscribers: false } + channels.headers = { hasSubscribers: false } + channels.trailers = { hasSubscribers: false } + channels.error = { hasSubscribers: false } +} + +class Request { + constructor (origin, { + path, + method, + body, + headers, + query, + idempotent, + blocking, + upgrade, + headersTimeout, + bodyTimeout, + reset, + throwOnError, + expectContinue + }, handler) { + if (typeof path !== 'string') { + throw new InvalidArgumentError('path must be a string') + } else if ( + path[0] !== '/' && + !(path.startsWith('http://') || path.startsWith('https://')) && + method !== 'CONNECT' + ) { + throw new InvalidArgumentError('path must be an absolute URL or start with a slash') + } else if (invalidPathRegex.exec(path) !== null) { + throw new InvalidArgumentError('invalid request path') + } + + if (typeof method !== 'string') { + throw new InvalidArgumentError('method must be a string') + } else if (tokenRegExp.exec(method) === null) { + throw new InvalidArgumentError('invalid request method') + } + + if (upgrade && typeof upgrade !== 'string') { + throw new InvalidArgumentError('upgrade must be a string') + } + + if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { + throw new InvalidArgumentError('invalid headersTimeout') + } + + if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { + throw new InvalidArgumentError('invalid bodyTimeout') + } + + if (reset != null && typeof reset !== 'boolean') { + throw new InvalidArgumentError('invalid reset') + } + + if (expectContinue != null && typeof expectContinue !== 'boolean') { + throw new InvalidArgumentError('invalid expectContinue') + } + + this.headersTimeout = headersTimeout + + this.bodyTimeout = bodyTimeout + + this.throwOnError = throwOnError === true + + this.method = method + + this.abort = null + + if (body == null) { + this.body = null + } else if (util.isStream(body)) { + this.body = body + + const rState = this.body._readableState + if (!rState || !rState.autoDestroy) { + this.endHandler = function autoDestroy () { + util.destroy(this) + } + this.body.on('end', this.endHandler) + } + + this.errorHandler = err => { + if (this.abort) { + this.abort(err) + } else { + this.error = err + } + } + this.body.on('error', this.errorHandler) + } else if (util.isBuffer(body)) { + this.body = body.byteLength ? body : null + } else if (ArrayBuffer.isView(body)) { + this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null + } else if (body instanceof ArrayBuffer) { + this.body = body.byteLength ? Buffer.from(body) : null + } else if (typeof body === 'string') { + this.body = body.length ? Buffer.from(body) : null + } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) { + this.body = body + } else { + throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') + } + + this.completed = false + + this.aborted = false + + this.upgrade = upgrade || null + + this.path = query ? util.buildURL(path, query) : path + + this.origin = origin + + this.idempotent = idempotent == null + ? method === 'HEAD' || method === 'GET' + : idempotent + + this.blocking = blocking == null ? false : blocking + + this.reset = reset == null ? null : reset + + this.host = null + + this.contentLength = null + + this.contentType = null + + this.headers = '' + + // Only for H2 + this.expectContinue = expectContinue != null ? expectContinue : false + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(this, headers[i], headers[i + 1]) + } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + processHeader(this, key, headers[key]) + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } + + if (util.isFormDataLike(this.body)) { + if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) { + throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.') + } + + if (!extractBody) { + extractBody = (__nccwpck_require__(8923).extractBody) + } + + const [bodyStream, contentType] = extractBody(body) + if (this.contentType == null) { + this.contentType = contentType + this.headers += `content-type: ${contentType}\r\n` + } + this.body = bodyStream.stream + this.contentLength = bodyStream.length + } else if (util.isBlobLike(body) && this.contentType == null && body.type) { + this.contentType = body.type + this.headers += `content-type: ${body.type}\r\n` + } + + util.validateHandler(handler, method, upgrade) + + this.servername = util.getServerName(this.host) + + this[kHandler] = handler + + if (channels.create.hasSubscribers) { + channels.create.publish({ request: this }) + } + } + + onBodySent (chunk) { + if (this[kHandler].onBodySent) { + try { + return this[kHandler].onBodySent(chunk) + } catch (err) { + this.abort(err) + } + } + } + + onRequestSent () { + if (channels.bodySent.hasSubscribers) { + channels.bodySent.publish({ request: this }) + } + + if (this[kHandler].onRequestSent) { + try { + return this[kHandler].onRequestSent() + } catch (err) { + this.abort(err) + } + } + } + + onConnect (abort) { + assert(!this.aborted) + assert(!this.completed) + + if (this.error) { + abort(this.error) + } else { + this.abort = abort + return this[kHandler].onConnect(abort) + } + } + + onHeaders (statusCode, headers, resume, statusText) { + assert(!this.aborted) + assert(!this.completed) + + if (channels.headers.hasSubscribers) { + channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) + } + + try { + return this[kHandler].onHeaders(statusCode, headers, resume, statusText) + } catch (err) { + this.abort(err) + } + } + + onData (chunk) { + assert(!this.aborted) + assert(!this.completed) + + try { + return this[kHandler].onData(chunk) + } catch (err) { + this.abort(err) + return false + } + } + + onUpgrade (statusCode, headers, socket) { + assert(!this.aborted) + assert(!this.completed) + + return this[kHandler].onUpgrade(statusCode, headers, socket) + } + + onComplete (trailers) { + this.onFinally() + + assert(!this.aborted) + + this.completed = true + if (channels.trailers.hasSubscribers) { + channels.trailers.publish({ request: this, trailers }) + } + + try { + return this[kHandler].onComplete(trailers) + } catch (err) { + // TODO (fix): This might be a bad idea? + this.onError(err) + } + } + + onError (error) { + this.onFinally() + + if (channels.error.hasSubscribers) { + channels.error.publish({ request: this, error }) + } + + if (this.aborted) { + return + } + this.aborted = true + + return this[kHandler].onError(error) + } + + onFinally () { + if (this.errorHandler) { + this.body.off('error', this.errorHandler) + this.errorHandler = null + } + + if (this.endHandler) { + this.body.off('end', this.endHandler) + this.endHandler = null + } + } + + // TODO: adjust to support H2 + addHeader (key, value) { + processHeader(this, key, value) + return this + } + + static [kHTTP1BuildRequest] (origin, opts, handler) { + // TODO: Migrate header parsing here, to make Requests + // HTTP agnostic + return new Request(origin, opts, handler) + } + + static [kHTTP2BuildRequest] (origin, opts, handler) { + const headers = opts.headers + opts = { ...opts, headers: null } + + const request = new Request(origin, opts, handler) + + request.headers = {} + + if (Array.isArray(headers)) { + if (headers.length % 2 !== 0) { + throw new InvalidArgumentError('headers array must be even') + } + for (let i = 0; i < headers.length; i += 2) { + processHeader(request, headers[i], headers[i + 1], true) + } + } else if (headers && typeof headers === 'object') { + const keys = Object.keys(headers) + for (let i = 0; i < keys.length; i++) { + const key = keys[i] + processHeader(request, key, headers[key], true) + } + } else if (headers != null) { + throw new InvalidArgumentError('headers must be an object or an array') + } + + return request + } + + static [kHTTP2CopyHeaders] (raw) { + const rawHeaders = raw.split('\r\n') + const headers = {} + + for (const header of rawHeaders) { + const [key, value] = header.split(': ') + + if (value == null || value.length === 0) continue + + if (headers[key]) headers[key] += `,${value}` + else headers[key] = value + } + + return headers + } +} + +function processHeaderValue (key, val, skipAppend) { + if (val && typeof val === 'object') { + throw new InvalidArgumentError(`invalid ${key} header`) + } + + val = val != null ? `${val}` : '' + + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + + return skipAppend ? val : `${key}: ${val}\r\n` +} + +function processHeader (request, key, val, skipAppend = false) { + if (val && (typeof val === 'object' && !Array.isArray(val))) { + throw new InvalidArgumentError(`invalid ${key} header`) + } else if (val === undefined) { + return + } + + if ( + request.host === null && + key.length === 4 && + key.toLowerCase() === 'host' + ) { + if (headerCharRegex.exec(val) !== null) { + throw new InvalidArgumentError(`invalid ${key} header`) + } + // Consumed by Client + request.host = val + } else if ( + request.contentLength === null && + key.length === 14 && + key.toLowerCase() === 'content-length' + ) { + request.contentLength = parseInt(val, 10) + if (!Number.isFinite(request.contentLength)) { + throw new InvalidArgumentError('invalid content-length header') + } + } else if ( + request.contentType === null && + key.length === 12 && + key.toLowerCase() === 'content-type' + ) { + request.contentType = val + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) + else request.headers += processHeaderValue(key, val) + } else if ( + key.length === 17 && + key.toLowerCase() === 'transfer-encoding' + ) { + throw new InvalidArgumentError('invalid transfer-encoding header') + } else if ( + key.length === 10 && + key.toLowerCase() === 'connection' + ) { + const value = typeof val === 'string' ? val.toLowerCase() : null + if (value !== 'close' && value !== 'keep-alive') { + throw new InvalidArgumentError('invalid connection header') + } else if (value === 'close') { + request.reset = true + } + } else if ( + key.length === 10 && + key.toLowerCase() === 'keep-alive' + ) { + throw new InvalidArgumentError('invalid keep-alive header') + } else if ( + key.length === 7 && + key.toLowerCase() === 'upgrade' + ) { + throw new InvalidArgumentError('invalid upgrade header') + } else if ( + key.length === 6 && + key.toLowerCase() === 'expect' + ) { + throw new NotSupportedError('expect header not supported') + } else if (tokenRegExp.exec(key) === null) { + throw new InvalidArgumentError('invalid header key') + } else { + if (Array.isArray(val)) { + for (let i = 0; i < val.length; i++) { + if (skipAppend) { + if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}` + else request.headers[key] = processHeaderValue(key, val[i], skipAppend) + } else { + request.headers += processHeaderValue(key, val[i]) + } + } + } else { + if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) + else request.headers += processHeaderValue(key, val) + } + } +} + +module.exports = Request + + +/***/ }), + +/***/ 6443: +/***/ ((module) => { + +module.exports = { + kClose: Symbol('close'), + kDestroy: Symbol('destroy'), + kDispatch: Symbol('dispatch'), + kUrl: Symbol('url'), + kWriting: Symbol('writing'), + kResuming: Symbol('resuming'), + kQueue: Symbol('queue'), + kConnect: Symbol('connect'), + kConnecting: Symbol('connecting'), + kHeadersList: Symbol('headers list'), + kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), + kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), + kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), + kKeepAliveTimeoutValue: Symbol('keep alive timeout'), + kKeepAlive: Symbol('keep alive'), + kHeadersTimeout: Symbol('headers timeout'), + kBodyTimeout: Symbol('body timeout'), + kServerName: Symbol('server name'), + kLocalAddress: Symbol('local address'), + kHost: Symbol('host'), + kNoRef: Symbol('no ref'), + kBodyUsed: Symbol('used'), + kRunning: Symbol('running'), + kBlocking: Symbol('blocking'), + kPending: Symbol('pending'), + kSize: Symbol('size'), + kBusy: Symbol('busy'), + kQueued: Symbol('queued'), + kFree: Symbol('free'), + kConnected: Symbol('connected'), + kClosed: Symbol('closed'), + kNeedDrain: Symbol('need drain'), + kReset: Symbol('reset'), + kDestroyed: Symbol.for('nodejs.stream.destroyed'), + kMaxHeadersSize: Symbol('max headers size'), + kRunningIdx: Symbol('running index'), + kPendingIdx: Symbol('pending index'), + kError: Symbol('error'), + kClients: Symbol('clients'), + kClient: Symbol('client'), + kParser: Symbol('parser'), + kOnDestroyed: Symbol('destroy callbacks'), + kPipelining: Symbol('pipelining'), + kSocket: Symbol('socket'), + kHostHeader: Symbol('host header'), + kConnector: Symbol('connector'), + kStrictContentLength: Symbol('strict content length'), + kMaxRedirections: Symbol('maxRedirections'), + kMaxRequests: Symbol('maxRequestsPerClient'), + kProxy: Symbol('proxy agent options'), + kCounter: Symbol('socket request counter'), + kInterceptors: Symbol('dispatch interceptors'), + kMaxResponseSize: Symbol('max response size'), + kHTTP2Session: Symbol('http2Session'), + kHTTP2SessionState: Symbol('http2Session state'), + kHTTP2BuildRequest: Symbol('http2 build request'), + kHTTP1BuildRequest: Symbol('http1 build request'), + kHTTP2CopyHeaders: Symbol('http2 copy headers'), + kHTTPConnVersion: Symbol('http connection version'), + kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), + kConstruct: Symbol('constructable') +} + + +/***/ }), + +/***/ 3440: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const assert = __nccwpck_require__(2613) +const { kDestroyed, kBodyUsed } = __nccwpck_require__(6443) +const { IncomingMessage } = __nccwpck_require__(8611) +const stream = __nccwpck_require__(2203) +const net = __nccwpck_require__(9278) +const { InvalidArgumentError } = __nccwpck_require__(8707) +const { Blob } = __nccwpck_require__(181) +const nodeUtil = __nccwpck_require__(9023) +const { stringify } = __nccwpck_require__(3480) +const { headerNameLowerCasedRecord } = __nccwpck_require__(735) + +const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) + +function nop () {} + +function isStream (obj) { + return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' +} + +// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) +function isBlobLike (object) { + return (Blob && object instanceof Blob) || ( + object && + typeof object === 'object' && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + /^(Blob|File)$/.test(object[Symbol.toStringTag]) + ) +} + +function buildURL (url, queryParams) { + if (url.includes('?') || url.includes('#')) { + throw new Error('Query params cannot be passed when url already contains "?" or "#".') + } + + const stringified = stringify(queryParams) + + if (stringified) { + url += '?' + stringified + } + + return url +} + +function parseURL (url) { + if (typeof url === 'string') { + url = new URL(url) + + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + return url + } + + if (!url || typeof url !== 'object') { + throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') + } + + if (!/^https?:/.test(url.origin || url.protocol)) { + throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') + } + + if (!(url instanceof URL)) { + if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) { + throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') + } + + if (url.path != null && typeof url.path !== 'string') { + throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') + } + + if (url.pathname != null && typeof url.pathname !== 'string') { + throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') + } + + if (url.hostname != null && typeof url.hostname !== 'string') { + throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') + } + + if (url.origin != null && typeof url.origin !== 'string') { + throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') + } + + const port = url.port != null + ? url.port + : (url.protocol === 'https:' ? 443 : 80) + let origin = url.origin != null + ? url.origin + : `${url.protocol}//${url.hostname}:${port}` + let path = url.path != null + ? url.path + : `${url.pathname || ''}${url.search || ''}` + + if (origin.endsWith('/')) { + origin = origin.substring(0, origin.length - 1) + } + + if (path && !path.startsWith('/')) { + path = `/${path}` + } + // new URL(path, origin) is unsafe when `path` contains an absolute URL + // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: + // If first parameter is a relative URL, second param is required, and will be used as the base URL. + // If first parameter is an absolute URL, a given second param will be ignored. + url = new URL(origin + path) + } + + return url +} + +function parseOrigin (url) { + url = parseURL(url) + + if (url.pathname !== '/' || url.search || url.hash) { + throw new InvalidArgumentError('invalid url') + } + + return url +} + +function getHostname (host) { + if (host[0] === '[') { + const idx = host.indexOf(']') + + assert(idx !== -1) + return host.substring(1, idx) + } + + const idx = host.indexOf(':') + if (idx === -1) return host + + return host.substring(0, idx) +} + +// IP addresses are not valid server names per RFC6066 +// > Currently, the only server names supported are DNS hostnames +function getServerName (host) { + if (!host) { + return null + } + + assert.strictEqual(typeof host, 'string') + + const servername = getHostname(host) + if (net.isIP(servername)) { + return '' + } + + return servername +} + +function deepClone (obj) { + return JSON.parse(JSON.stringify(obj)) +} + +function isAsyncIterable (obj) { + return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') +} + +function isIterable (obj) { + return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) +} + +function bodyLength (body) { + if (body == null) { + return 0 + } else if (isStream(body)) { + const state = body._readableState + return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) + ? state.length + : null + } else if (isBlobLike(body)) { + return body.size != null ? body.size : null + } else if (isBuffer(body)) { + return body.byteLength + } + + return null +} + +function isDestroyed (stream) { + return !stream || !!(stream.destroyed || stream[kDestroyed]) +} + +function isReadableAborted (stream) { + const state = stream && stream._readableState + return isDestroyed(stream) && state && !state.endEmitted +} + +function destroy (stream, err) { + if (stream == null || !isStream(stream) || isDestroyed(stream)) { + return + } + + if (typeof stream.destroy === 'function') { + if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { + // See: https://github.com/nodejs/node/pull/38505/files + stream.socket = null + } + + stream.destroy(err) + } else if (err) { + process.nextTick((stream, err) => { + stream.emit('error', err) + }, stream, err) + } + + if (stream.destroyed !== true) { + stream[kDestroyed] = true + } +} + +const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ +function parseKeepAliveTimeout (val) { + const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) + return m ? parseInt(m[1], 10) * 1000 : null +} + +/** + * Retrieves a header name and returns its lowercase value. + * @param {string | Buffer} value Header name + * @returns {string} + */ +function headerNameToString (value) { + return headerNameLowerCasedRecord[value] || value.toLowerCase() +} + +function parseHeaders (headers, obj = {}) { + // For H2 support + if (!Array.isArray(headers)) return headers + + for (let i = 0; i < headers.length; i += 2) { + const key = headers[i].toString().toLowerCase() + let val = obj[key] + + if (!val) { + if (Array.isArray(headers[i + 1])) { + obj[key] = headers[i + 1].map(x => x.toString('utf8')) + } else { + obj[key] = headers[i + 1].toString('utf8') + } + } else { + if (!Array.isArray(val)) { + val = [val] + obj[key] = val + } + val.push(headers[i + 1].toString('utf8')) + } + } + + // See https://github.com/nodejs/node/pull/46528 + if ('content-length' in obj && 'content-disposition' in obj) { + obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') + } + + return obj +} + +function parseRawHeaders (headers) { + const ret = [] + let hasContentLength = false + let contentDispositionIdx = -1 + + for (let n = 0; n < headers.length; n += 2) { + const key = headers[n + 0].toString() + const val = headers[n + 1].toString('utf8') + + if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) { + ret.push(key, val) + hasContentLength = true + } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { + contentDispositionIdx = ret.push(key, val) - 1 + } else { + ret.push(key, val) + } + } + + // See https://github.com/nodejs/node/pull/46528 + if (hasContentLength && contentDispositionIdx !== -1) { + ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') + } + + return ret +} + +function isBuffer (buffer) { + // See, https://github.com/mcollina/undici/pull/319 + return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) +} + +function validateHandler (handler, method, upgrade) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + if (typeof handler.onConnect !== 'function') { + throw new InvalidArgumentError('invalid onConnect method') + } + + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { + throw new InvalidArgumentError('invalid onBodySent method') + } + + if (upgrade || method === 'CONNECT') { + if (typeof handler.onUpgrade !== 'function') { + throw new InvalidArgumentError('invalid onUpgrade method') + } + } else { + if (typeof handler.onHeaders !== 'function') { + throw new InvalidArgumentError('invalid onHeaders method') + } + + if (typeof handler.onData !== 'function') { + throw new InvalidArgumentError('invalid onData method') + } + + if (typeof handler.onComplete !== 'function') { + throw new InvalidArgumentError('invalid onComplete method') + } + } +} + +// A body is disturbed if it has been read from and it cannot +// be re-used without losing state or data. +function isDisturbed (body) { + return !!(body && ( + stream.isDisturbed + ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed? + : body[kBodyUsed] || + body.readableDidRead || + (body._readableState && body._readableState.dataEmitted) || + isReadableAborted(body) + )) +} + +function isErrored (body) { + return !!(body && ( + stream.isErrored + ? stream.isErrored(body) + : /state: 'errored'/.test(nodeUtil.inspect(body) + ))) +} + +function isReadable (body) { + return !!(body && ( + stream.isReadable + ? stream.isReadable(body) + : /state: 'readable'/.test(nodeUtil.inspect(body) + ))) +} + +function getSocketInfo (socket) { + return { + localAddress: socket.localAddress, + localPort: socket.localPort, + remoteAddress: socket.remoteAddress, + remotePort: socket.remotePort, + remoteFamily: socket.remoteFamily, + timeout: socket.timeout, + bytesWritten: socket.bytesWritten, + bytesRead: socket.bytesRead + } +} + +async function * convertIterableToBuffer (iterable) { + for await (const chunk of iterable) { + yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) + } +} + +let ReadableStream +function ReadableStreamFrom (iterable) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(3774).ReadableStream) + } + + if (ReadableStream.from) { + return ReadableStream.from(convertIterableToBuffer(iterable)) + } + + let iterator + return new ReadableStream( + { + async start () { + iterator = iterable[Symbol.asyncIterator]() + }, + async pull (controller) { + const { done, value } = await iterator.next() + if (done) { + queueMicrotask(() => { + controller.close() + }) + } else { + const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) + controller.enqueue(new Uint8Array(buf)) + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + } + }, + 0 + ) +} + +// The chunk should be a FormData instance and contains +// all the required methods. +function isFormDataLike (object) { + return ( + object && + typeof object === 'object' && + typeof object.append === 'function' && + typeof object.delete === 'function' && + typeof object.get === 'function' && + typeof object.getAll === 'function' && + typeof object.has === 'function' && + typeof object.set === 'function' && + object[Symbol.toStringTag] === 'FormData' + ) +} + +function throwIfAborted (signal) { + if (!signal) { return } + if (typeof signal.throwIfAborted === 'function') { + signal.throwIfAborted() + } else { + if (signal.aborted) { + // DOMException not available < v17.0.0 + const err = new Error('The operation was aborted') + err.name = 'AbortError' + throw err + } + } +} + +function addAbortListener (signal, listener) { + if ('addEventListener' in signal) { + signal.addEventListener('abort', listener, { once: true }) + return () => signal.removeEventListener('abort', listener) + } + signal.addListener('abort', listener) + return () => signal.removeListener('abort', listener) +} + +const hasToWellFormed = !!String.prototype.toWellFormed + +/** + * @param {string} val + */ +function toUSVString (val) { + if (hasToWellFormed) { + return `${val}`.toWellFormed() + } else if (nodeUtil.toUSVString) { + return nodeUtil.toUSVString(val) + } + + return `${val}` +} + +// Parsed accordingly to RFC 9110 +// https://www.rfc-editor.org/rfc/rfc9110#field.content-range +function parseRangeHeader (range) { + if (range == null || range === '') return { start: 0, end: null, size: null } + + const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null + return m + ? { + start: parseInt(m[1]), + end: m[2] ? parseInt(m[2]) : null, + size: m[3] ? parseInt(m[3]) : null + } + : null +} + +const kEnumerableProperty = Object.create(null) +kEnumerableProperty.enumerable = true + +module.exports = { + kEnumerableProperty, + nop, + isDisturbed, + isErrored, + isReadable, + toUSVString, + isReadableAborted, + isBlobLike, + parseOrigin, + parseURL, + getServerName, + isStream, + isIterable, + isAsyncIterable, + isDestroyed, + headerNameToString, + parseRawHeaders, + parseHeaders, + parseKeepAliveTimeout, + destroy, + bodyLength, + deepClone, + ReadableStreamFrom, + isBuffer, + validateHandler, + getSocketInfo, + isFormDataLike, + buildURL, + throwIfAborted, + addAbortListener, + parseRangeHeader, + nodeMajor, + nodeMinor, + nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13), + safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +} + + +/***/ }), + +/***/ 1: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Dispatcher = __nccwpck_require__(992) +const { + ClientDestroyedError, + ClientClosedError, + InvalidArgumentError +} = __nccwpck_require__(8707) +const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(6443) + +const kDestroyed = Symbol('destroyed') +const kClosed = Symbol('closed') +const kOnDestroyed = Symbol('onDestroyed') +const kOnClosed = Symbol('onClosed') +const kInterceptedDispatch = Symbol('Intercepted Dispatch') + +class DispatcherBase extends Dispatcher { + constructor () { + super() + + this[kDestroyed] = false + this[kOnDestroyed] = null + this[kClosed] = false + this[kOnClosed] = [] + } + + get destroyed () { + return this[kDestroyed] + } + + get closed () { + return this[kClosed] + } + + get interceptors () { + return this[kInterceptors] + } + + set interceptors (newInterceptors) { + if (newInterceptors) { + for (let i = newInterceptors.length - 1; i >= 0; i--) { + const interceptor = this[kInterceptors][i] + if (typeof interceptor !== 'function') { + throw new InvalidArgumentError('interceptor must be an function') + } + } + } + + this[kInterceptors] = newInterceptors + } + + close (callback) { + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.close((err, data) => { + return err ? reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + queueMicrotask(() => callback(new ClientDestroyedError(), null)) + return + } + + if (this[kClosed]) { + if (this[kOnClosed]) { + this[kOnClosed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + this[kClosed] = true + this[kOnClosed].push(callback) + + const onClosed = () => { + const callbacks = this[kOnClosed] + this[kOnClosed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kClose]() + .then(() => this.destroy()) + .then(() => { + queueMicrotask(onClosed) + }) + } + + destroy (err, callback) { + if (typeof err === 'function') { + callback = err + err = null + } + + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.destroy(err, (err, data) => { + return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) + }) + }) + } + + if (typeof callback !== 'function') { + throw new InvalidArgumentError('invalid callback') + } + + if (this[kDestroyed]) { + if (this[kOnDestroyed]) { + this[kOnDestroyed].push(callback) + } else { + queueMicrotask(() => callback(null, null)) + } + return + } + + if (!err) { + err = new ClientDestroyedError() + } + + this[kDestroyed] = true + this[kOnDestroyed] = this[kOnDestroyed] || [] + this[kOnDestroyed].push(callback) + + const onDestroyed = () => { + const callbacks = this[kOnDestroyed] + this[kOnDestroyed] = null + for (let i = 0; i < callbacks.length; i++) { + callbacks[i](null, null) + } + } + + // Should not error. + this[kDestroy](err).then(() => { + queueMicrotask(onDestroyed) + }) + } + + [kInterceptedDispatch] (opts, handler) { + if (!this[kInterceptors] || this[kInterceptors].length === 0) { + this[kInterceptedDispatch] = this[kDispatch] + return this[kDispatch](opts, handler) + } + + let dispatch = this[kDispatch].bind(this) + for (let i = this[kInterceptors].length - 1; i >= 0; i--) { + dispatch = this[kInterceptors][i](dispatch) + } + this[kInterceptedDispatch] = dispatch + return dispatch(opts, handler) + } + + dispatch (opts, handler) { + if (!handler || typeof handler !== 'object') { + throw new InvalidArgumentError('handler must be an object') + } + + try { + if (!opts || typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object.') + } + + if (this[kDestroyed] || this[kOnDestroyed]) { + throw new ClientDestroyedError() + } + + if (this[kClosed]) { + throw new ClientClosedError() + } + + return this[kInterceptedDispatch](opts, handler) + } catch (err) { + if (typeof handler.onError !== 'function') { + throw new InvalidArgumentError('invalid onError method') + } + + handler.onError(err) + + return false + } + } +} + +module.exports = DispatcherBase + + +/***/ }), + +/***/ 992: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const EventEmitter = __nccwpck_require__(4434) + +class Dispatcher extends EventEmitter { + dispatch () { + throw new Error('not implemented') + } + + close () { + throw new Error('not implemented') + } + + destroy () { + throw new Error('not implemented') + } +} + +module.exports = Dispatcher + + +/***/ }), + +/***/ 8923: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Busboy = __nccwpck_require__(9581) +const util = __nccwpck_require__(3440) +const { + ReadableStreamFrom, + isBlobLike, + isReadableStreamLike, + readableStreamClose, + createDeferredPromise, + fullyReadBody +} = __nccwpck_require__(5523) +const { FormData } = __nccwpck_require__(3073) +const { kState } = __nccwpck_require__(9710) +const { webidl } = __nccwpck_require__(4222) +const { DOMException, structuredClone } = __nccwpck_require__(7326) +const { Blob, File: NativeFile } = __nccwpck_require__(181) +const { kBodyUsed } = __nccwpck_require__(6443) +const assert = __nccwpck_require__(2613) +const { isErrored } = __nccwpck_require__(3440) +const { isUint8Array, isArrayBuffer } = __nccwpck_require__(8253) +const { File: UndiciFile } = __nccwpck_require__(3041) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) + +let random +try { + const crypto = __nccwpck_require__(7598) + random = (max) => crypto.randomInt(0, max) +} catch { + random = (max) => Math.floor(Math.random(max)) +} + +let ReadableStream = globalThis.ReadableStream + +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile +const textEncoder = new TextEncoder() +const textDecoder = new TextDecoder() + +// https://fetch.spec.whatwg.org/#concept-bodyinit-extract +function extractBody (object, keepalive = false) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(3774).ReadableStream) + } + + // 1. Let stream be null. + let stream = null + + // 2. If object is a ReadableStream object, then set stream to object. + if (object instanceof ReadableStream) { + stream = object + } else if (isBlobLike(object)) { + // 3. Otherwise, if object is a Blob object, set stream to the + // result of running object’s get stream. + stream = object.stream() + } else { + // 4. Otherwise, set stream to a new ReadableStream object, and set + // up stream. + stream = new ReadableStream({ + async pull (controller) { + controller.enqueue( + typeof source === 'string' ? textEncoder.encode(source) : source + ) + queueMicrotask(() => readableStreamClose(controller)) + }, + start () {}, + type: undefined + }) + } + + // 5. Assert: stream is a ReadableStream object. + assert(isReadableStreamLike(stream)) + + // 6. Let action be null. + let action = null + + // 7. Let source be null. + let source = null + + // 8. Let length be null. + let length = null + + // 9. Let type be null. + let type = null + + // 10. Switch on object: + if (typeof object === 'string') { + // Set source to the UTF-8 encoding of object. + // Note: setting source to a Uint8Array here breaks some mocking assumptions. + source = object + + // Set type to `text/plain;charset=UTF-8`. + type = 'text/plain;charset=UTF-8' + } else if (object instanceof URLSearchParams) { + // URLSearchParams + + // spec says to run application/x-www-form-urlencoded on body.list + // this is implemented in Node.js as apart of an URLSearchParams instance toString method + // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 + // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 + + // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. + source = object.toString() + + // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. + type = 'application/x-www-form-urlencoded;charset=UTF-8' + } else if (isArrayBuffer(object)) { + // BufferSource/ArrayBuffer + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.slice()) + } else if (ArrayBuffer.isView(object)) { + // BufferSource/ArrayBufferView + + // Set source to a copy of the bytes held by object. + source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) + } else if (util.isFormDataLike(object)) { + const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` + const prefix = `--${boundary}\r\nContent-Disposition: form-data` + + /*! formdata-polyfill. MIT License. Jimmy Wärting */ + const escape = (str) => + str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') + const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') + + // Set action to this step: run the multipart/form-data + // encoding algorithm, with object’s entry list and UTF-8. + // - This ensures that the body is immutable and can't be changed afterwords + // - That the content-length is calculated in advance. + // - And that all parts are pre-encoded and ready to be sent. + + const blobParts = [] + const rn = new Uint8Array([13, 10]) // '\r\n' + length = 0 + let hasUnknownSizeValue = false + + for (const [name, value] of object) { + if (typeof value === 'string') { + const chunk = textEncoder.encode(prefix + + `; name="${escape(normalizeLinefeeds(name))}"` + + `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) + blobParts.push(chunk) + length += chunk.byteLength + } else { + const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + + (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + + `Content-Type: ${ + value.type || 'application/octet-stream' + }\r\n\r\n`) + blobParts.push(chunk, value, rn) + if (typeof value.size === 'number') { + length += chunk.byteLength + value.size + rn.byteLength + } else { + hasUnknownSizeValue = true + } + } + } + + const chunk = textEncoder.encode(`--${boundary}--`) + blobParts.push(chunk) + length += chunk.byteLength + if (hasUnknownSizeValue) { + length = null + } + + // Set source to object. + source = object + + action = async function * () { + for (const part of blobParts) { + if (part.stream) { + yield * part.stream() + } else { + yield part + } + } + } + + // Set type to `multipart/form-data; boundary=`, + // followed by the multipart/form-data boundary string generated + // by the multipart/form-data encoding algorithm. + type = 'multipart/form-data; boundary=' + boundary + } else if (isBlobLike(object)) { + // Blob + + // Set source to object. + source = object + + // Set length to object’s size. + length = object.size + + // If object’s type attribute is not the empty byte sequence, set + // type to its value. + if (object.type) { + type = object.type + } + } else if (typeof object[Symbol.asyncIterator] === 'function') { + // If keepalive is true, then throw a TypeError. + if (keepalive) { + throw new TypeError('keepalive') + } + + // If object is disturbed or locked, then throw a TypeError. + if (util.isDisturbed(object) || object.locked) { + throw new TypeError( + 'Response body object should not be disturbed or locked' + ) + } + + stream = + object instanceof ReadableStream ? object : ReadableStreamFrom(object) + } + + // 11. If source is a byte sequence, then set action to a + // step that returns source and length to source’s length. + if (typeof source === 'string' || util.isBuffer(source)) { + length = Buffer.byteLength(source) + } + + // 12. If action is non-null, then run these steps in in parallel: + if (action != null) { + // Run action. + let iterator + stream = new ReadableStream({ + async start () { + iterator = action(object)[Symbol.asyncIterator]() + }, + async pull (controller) { + const { value, done } = await iterator.next() + if (done) { + // When running action is done, close stream. + queueMicrotask(() => { + controller.close() + }) + } else { + // Whenever one or more bytes are available and stream is not errored, + // enqueue a Uint8Array wrapping an ArrayBuffer containing the available + // bytes into stream. + if (!isErrored(stream)) { + controller.enqueue(new Uint8Array(value)) + } + } + return controller.desiredSize > 0 + }, + async cancel (reason) { + await iterator.return() + }, + type: undefined + }) + } + + // 13. Let body be a body whose stream is stream, source is source, + // and length is length. + const body = { stream, source, length } + + // 14. Return (body, type). + return [body, type] +} + +// https://fetch.spec.whatwg.org/#bodyinit-safely-extract +function safelyExtractBody (object, keepalive = false) { + if (!ReadableStream) { + // istanbul ignore next + ReadableStream = (__nccwpck_require__(3774).ReadableStream) + } + + // To safely extract a body and a `Content-Type` value from + // a byte sequence or BodyInit object object, run these steps: + + // 1. If object is a ReadableStream object, then: + if (object instanceof ReadableStream) { + // Assert: object is neither disturbed nor locked. + // istanbul ignore next + assert(!util.isDisturbed(object), 'The body has already been consumed.') + // istanbul ignore next + assert(!object.locked, 'The stream is locked.') + } + + // 2. Return the results of extracting object. + return extractBody(object, keepalive) +} + +function cloneBody (body) { + // To clone a body body, run these steps: + + // https://fetch.spec.whatwg.org/#concept-body-clone + + // 1. Let « out1, out2 » be the result of teeing body’s stream. + const [out1, out2] = body.stream.tee() + const out2Clone = structuredClone(out2, { transfer: [out2] }) + // This, for whatever reasons, unrefs out2Clone which allows + // the process to exit by itself. + const [, finalClone] = out2Clone.tee() + + // 2. Set body’s stream to out1. + body.stream = out1 + + // 3. Return a body whose stream is out2 and other members are copied from body. + return { + stream: finalClone, + length: body.length, + source: body.source + } +} + +async function * consumeBody (body) { + if (body) { + if (isUint8Array(body)) { + yield body + } else { + const stream = body.stream + + if (util.isDisturbed(stream)) { + throw new TypeError('The body has already been consumed.') + } + + if (stream.locked) { + throw new TypeError('The stream is locked.') + } + + // Compat. + stream[kBodyUsed] = true + + yield * stream + } + } +} + +function throwIfAborted (state) { + if (state.aborted) { + throw new DOMException('The operation was aborted.', 'AbortError') + } +} + +function bodyMixinMethods (instance) { + const methods = { + blob () { + // The blob() method steps are to return the result of + // running consume body with this and the following step + // given a byte sequence bytes: return a Blob whose + // contents are bytes and whose type attribute is this’s + // MIME type. + return specConsumeBody(this, (bytes) => { + let mimeType = bodyMimeType(this) + + if (mimeType === 'failure') { + mimeType = '' + } else if (mimeType) { + mimeType = serializeAMimeType(mimeType) + } + + // Return a Blob whose contents are bytes and type attribute + // is mimeType. + return new Blob([bytes], { type: mimeType }) + }, instance) + }, + + arrayBuffer () { + // The arrayBuffer() method steps are to return the result + // of running consume body with this and the following step + // given a byte sequence bytes: return a new ArrayBuffer + // whose contents are bytes. + return specConsumeBody(this, (bytes) => { + return new Uint8Array(bytes).buffer + }, instance) + }, + + text () { + // The text() method steps are to return the result of running + // consume body with this and UTF-8 decode. + return specConsumeBody(this, utf8DecodeBytes, instance) + }, + + json () { + // The json() method steps are to return the result of running + // consume body with this and parse JSON from bytes. + return specConsumeBody(this, parseJSONFromBytes, instance) + }, + + async formData () { + webidl.brandCheck(this, instance) + + throwIfAborted(this[kState]) + + const contentType = this.headers.get('Content-Type') + + // If mimeType’s essence is "multipart/form-data", then: + if (/multipart\/form-data/.test(contentType)) { + const headers = {} + for (const [key, value] of this.headers) headers[key.toLowerCase()] = value + + const responseFormData = new FormData() + + let busboy + + try { + busboy = new Busboy({ + headers, + preservePath: true + }) + } catch (err) { + throw new DOMException(`${err}`, 'AbortError') + } + + busboy.on('field', (name, value) => { + responseFormData.append(name, value) + }) + busboy.on('file', (name, value, filename, encoding, mimeType) => { + const chunks = [] + + if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { + let base64chunk = '' + + value.on('data', (chunk) => { + base64chunk += chunk.toString().replace(/[\r\n]/gm, '') + + const end = base64chunk.length - base64chunk.length % 4 + chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) + + base64chunk = base64chunk.slice(end) + }) + value.on('end', () => { + chunks.push(Buffer.from(base64chunk, 'base64')) + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) + } else { + value.on('data', (chunk) => { + chunks.push(chunk) + }) + value.on('end', () => { + responseFormData.append(name, new File(chunks, filename, { type: mimeType })) + }) + } + }) + + const busboyResolve = new Promise((resolve, reject) => { + busboy.on('finish', resolve) + busboy.on('error', (err) => reject(new TypeError(err))) + }) + + if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) + busboy.end() + await busboyResolve + + return responseFormData + } else if (/application\/x-www-form-urlencoded/.test(contentType)) { + // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: + + // 1. Let entries be the result of parsing bytes. + let entries + try { + let text = '' + // application/x-www-form-urlencoded parser will keep the BOM. + // https://url.spec.whatwg.org/#concept-urlencoded-parser + // Note that streaming decoder is stateful and cannot be reused + const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true }) + + for await (const chunk of consumeBody(this[kState].body)) { + if (!isUint8Array(chunk)) { + throw new TypeError('Expected Uint8Array chunk') + } + text += streamingDecoder.decode(chunk, { stream: true }) + } + text += streamingDecoder.decode() + entries = new URLSearchParams(text) + } catch (err) { + // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. + // 2. If entries is failure, then throw a TypeError. + throw Object.assign(new TypeError(), { cause: err }) + } + + // 3. Return a new FormData object whose entries are entries. + const formData = new FormData() + for (const [name, value] of entries) { + formData.append(name, value) + } + return formData + } else { + // Wait a tick before checking if the request has been aborted. + // Otherwise, a TypeError can be thrown when an AbortError should. + await Promise.resolve() + + throwIfAborted(this[kState]) + + // Otherwise, throw a TypeError. + throw webidl.errors.exception({ + header: `${instance.name}.formData`, + message: 'Could not parse content as FormData.' + }) + } + } + } + + return methods +} + +function mixinBody (prototype) { + Object.assign(prototype.prototype, bodyMixinMethods(prototype)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-consume-body + * @param {Response|Request} object + * @param {(value: unknown) => unknown} convertBytesToJSValue + * @param {Response|Request} instance + */ +async function specConsumeBody (object, convertBytesToJSValue, instance) { + webidl.brandCheck(object, instance) + + throwIfAborted(object[kState]) + + // 1. If object is unusable, then return a promise rejected + // with a TypeError. + if (bodyUnusable(object[kState].body)) { + throw new TypeError('Body is unusable') + } + + // 2. Let promise be a new promise. + const promise = createDeferredPromise() + + // 3. Let errorSteps given error be to reject promise with error. + const errorSteps = (error) => promise.reject(error) + + // 4. Let successSteps given a byte sequence data be to resolve + // promise with the result of running convertBytesToJSValue + // with data. If that threw an exception, then run errorSteps + // with that exception. + const successSteps = (data) => { + try { + promise.resolve(convertBytesToJSValue(data)) + } catch (e) { + errorSteps(e) + } + } + + // 5. If object’s body is null, then run successSteps with an + // empty byte sequence. + if (object[kState].body == null) { + successSteps(new Uint8Array()) + return promise.promise + } + + // 6. Otherwise, fully read object’s body given successSteps, + // errorSteps, and object’s relevant global object. + await fullyReadBody(object[kState].body, successSteps, errorSteps) + + // 7. Return promise. + return promise.promise +} + +// https://fetch.spec.whatwg.org/#body-unusable +function bodyUnusable (body) { + // An object including the Body interface mixin is + // said to be unusable if its body is non-null and + // its body’s stream is disturbed or locked. + return body != null && (body.stream.locked || util.isDisturbed(body.stream)) +} + +/** + * @see https://encoding.spec.whatwg.org/#utf-8-decode + * @param {Buffer} buffer + */ +function utf8DecodeBytes (buffer) { + if (buffer.length === 0) { + return '' + } + + // 1. Let buffer be the result of peeking three bytes from + // ioQueue, converted to a byte sequence. + + // 2. If buffer is 0xEF 0xBB 0xBF, then read three + // bytes from ioQueue. (Do nothing with those bytes.) + if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { + buffer = buffer.subarray(3) + } + + // 3. Process a queue with an instance of UTF-8’s + // decoder, ioQueue, output, and "replacement". + const output = textDecoder.decode(buffer) + + // 4. Return output. + return output +} + +/** + * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value + * @param {Uint8Array} bytes + */ +function parseJSONFromBytes (bytes) { + return JSON.parse(utf8DecodeBytes(bytes)) +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-body-mime-type + * @param {import('./response').Response|import('./request').Request} object + */ +function bodyMimeType (object) { + const { headersList } = object[kState] + const contentType = headersList.get('content-type') + + if (contentType === null) { + return 'failure' + } + + return parseMIMEType(contentType) +} + +module.exports = { + extractBody, + safelyExtractBody, + cloneBody, + mixinBody +} + + +/***/ }), + +/***/ 7326: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(8167) + +const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] +const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) + +const nullBodyStatus = [101, 204, 205, 304] + +const redirectStatus = [301, 302, 303, 307, 308] +const redirectStatusSet = new Set(redirectStatus) + +// https://fetch.spec.whatwg.org/#block-bad-port +const badPorts = [ + '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', + '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', + '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', + '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', + '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697', + '10080' +] + +const badPortsSet = new Set(badPorts) + +// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies +const referrerPolicy = [ + '', + 'no-referrer', + 'no-referrer-when-downgrade', + 'same-origin', + 'origin', + 'strict-origin', + 'origin-when-cross-origin', + 'strict-origin-when-cross-origin', + 'unsafe-url' +] +const referrerPolicySet = new Set(referrerPolicy) + +const requestRedirect = ['follow', 'manual', 'error'] + +const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] +const safeMethodsSet = new Set(safeMethods) + +const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] + +const requestCredentials = ['omit', 'same-origin', 'include'] + +const requestCache = [ + 'default', + 'no-store', + 'reload', + 'no-cache', + 'force-cache', + 'only-if-cached' +] + +// https://fetch.spec.whatwg.org/#request-body-header-name +const requestBodyHeader = [ + 'content-encoding', + 'content-language', + 'content-location', + 'content-type', + // See https://github.com/nodejs/undici/issues/2021 + // 'Content-Length' is a forbidden header name, which is typically + // removed in the Headers implementation. However, undici doesn't + // filter out headers, so we add it here. + 'content-length' +] + +// https://fetch.spec.whatwg.org/#enumdef-requestduplex +const requestDuplex = [ + 'half' +] + +// http://fetch.spec.whatwg.org/#forbidden-method +const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] +const forbiddenMethodsSet = new Set(forbiddenMethods) + +const subresource = [ + 'audio', + 'audioworklet', + 'font', + 'image', + 'manifest', + 'paintworklet', + 'script', + 'style', + 'track', + 'video', + 'xslt', + '' +] +const subresourceSet = new Set(subresource) + +/** @type {globalThis['DOMException']} */ +const DOMException = globalThis.DOMException ?? (() => { + // DOMException was only made a global in Node v17.0.0, + // but fetch supports >= v16.8. + try { + atob('~') + } catch (err) { + return Object.getPrototypeOf(err).constructor + } +})() + +let channel + +/** @type {globalThis['structuredClone']} */ +const structuredClone = + globalThis.structuredClone ?? + // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js + // structuredClone was added in v17.0.0, but fetch supports v16.8 + function structuredClone (value, options = undefined) { + if (arguments.length === 0) { + throw new TypeError('missing argument') + } + + if (!channel) { + channel = new MessageChannel() + } + channel.port1.unref() + channel.port2.unref() + channel.port1.postMessage(value, options?.transfer) + return receiveMessageOnPort(channel.port2).message + } + +module.exports = { + DOMException, + structuredClone, + subresource, + forbiddenMethods, + requestBodyHeader, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + redirectStatus, + corsSafeListedMethods, + nullBodyStatus, + safeMethods, + badPorts, + requestDuplex, + subresourceSet, + badPortsSet, + redirectStatusSet, + corsSafeListedMethodsSet, + safeMethodsSet, + forbiddenMethodsSet, + referrerPolicySet +} + + +/***/ }), + +/***/ 4322: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const assert = __nccwpck_require__(2613) +const { atob } = __nccwpck_require__(181) +const { isomorphicDecode } = __nccwpck_require__(5523) + +const encoder = new TextEncoder() + +/** + * @see https://mimesniff.spec.whatwg.org/#http-token-code-point + */ +const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/ +const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line +/** + * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point + */ +const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line + +// https://fetch.spec.whatwg.org/#data-url-processor +/** @param {URL} dataURL */ +function dataURLProcessor (dataURL) { + // 1. Assert: dataURL’s scheme is "data". + assert(dataURL.protocol === 'data:') + + // 2. Let input be the result of running the URL + // serializer on dataURL with exclude fragment + // set to true. + let input = URLSerializer(dataURL, true) + + // 3. Remove the leading "data:" string from input. + input = input.slice(5) + + // 4. Let position point at the start of input. + const position = { position: 0 } + + // 5. Let mimeType be the result of collecting a + // sequence of code points that are not equal + // to U+002C (,), given position. + let mimeType = collectASequenceOfCodePointsFast( + ',', + input, + position + ) + + // 6. Strip leading and trailing ASCII whitespace + // from mimeType. + // Undici implementation note: we need to store the + // length because if the mimetype has spaces removed, + // the wrong amount will be sliced from the input in + // step #9 + const mimeTypeLength = mimeType.length + mimeType = removeASCIIWhitespace(mimeType, true, true) + + // 7. If position is past the end of input, then + // return failure + if (position.position >= input.length) { + return 'failure' + } + + // 8. Advance position by 1. + position.position++ + + // 9. Let encodedBody be the remainder of input. + const encodedBody = input.slice(mimeTypeLength + 1) + + // 10. Let body be the percent-decoding of encodedBody. + let body = stringPercentDecode(encodedBody) + + // 11. If mimeType ends with U+003B (;), followed by + // zero or more U+0020 SPACE, followed by an ASCII + // case-insensitive match for "base64", then: + if (/;(\u0020){0,}base64$/i.test(mimeType)) { + // 1. Let stringBody be the isomorphic decode of body. + const stringBody = isomorphicDecode(body) + + // 2. Set body to the forgiving-base64 decode of + // stringBody. + body = forgivingBase64(stringBody) + + // 3. If body is failure, then return failure. + if (body === 'failure') { + return 'failure' + } + + // 4. Remove the last 6 code points from mimeType. + mimeType = mimeType.slice(0, -6) + + // 5. Remove trailing U+0020 SPACE code points from mimeType, + // if any. + mimeType = mimeType.replace(/(\u0020)+$/, '') + + // 6. Remove the last U+003B (;) code point from mimeType. + mimeType = mimeType.slice(0, -1) + } + + // 12. If mimeType starts with U+003B (;), then prepend + // "text/plain" to mimeType. + if (mimeType.startsWith(';')) { + mimeType = 'text/plain' + mimeType + } + + // 13. Let mimeTypeRecord be the result of parsing + // mimeType. + let mimeTypeRecord = parseMIMEType(mimeType) + + // 14. If mimeTypeRecord is failure, then set + // mimeTypeRecord to text/plain;charset=US-ASCII. + if (mimeTypeRecord === 'failure') { + mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') + } + + // 15. Return a new data: URL struct whose MIME + // type is mimeTypeRecord and body is body. + // https://fetch.spec.whatwg.org/#data-url-struct + return { mimeType: mimeTypeRecord, body } +} + +// https://url.spec.whatwg.org/#concept-url-serializer +/** + * @param {URL} url + * @param {boolean} excludeFragment + */ +function URLSerializer (url, excludeFragment = false) { + if (!excludeFragment) { + return url.href + } + + const href = url.href + const hashLength = url.hash.length + + return hashLength === 0 ? href : href.substring(0, href.length - hashLength) +} + +// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points +/** + * @param {(char: string) => boolean} condition + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePoints (condition, input, position) { + // 1. Let result be the empty string. + let result = '' + + // 2. While position doesn’t point past the end of input and the + // code point at position within input meets the condition condition: + while (position.position < input.length && condition(input[position.position])) { + // 1. Append that code point to the end of result. + result += input[position.position] + + // 2. Advance position by 1. + position.position++ + } + + // 3. Return result. + return result +} + +/** + * A faster collectASequenceOfCodePoints that only works when comparing a single character. + * @param {string} char + * @param {string} input + * @param {{ position: number }} position + */ +function collectASequenceOfCodePointsFast (char, input, position) { + const idx = input.indexOf(char, position.position) + const start = position.position + + if (idx === -1) { + position.position = input.length + return input.slice(start) + } + + position.position = idx + return input.slice(start, position.position) +} + +// https://url.spec.whatwg.org/#string-percent-decode +/** @param {string} input */ +function stringPercentDecode (input) { + // 1. Let bytes be the UTF-8 encoding of input. + const bytes = encoder.encode(input) + + // 2. Return the percent-decoding of bytes. + return percentDecode(bytes) +} + +// https://url.spec.whatwg.org/#percent-decode +/** @param {Uint8Array} input */ +function percentDecode (input) { + // 1. Let output be an empty byte sequence. + /** @type {number[]} */ + const output = [] + + // 2. For each byte byte in input: + for (let i = 0; i < input.length; i++) { + const byte = input[i] + + // 1. If byte is not 0x25 (%), then append byte to output. + if (byte !== 0x25) { + output.push(byte) + + // 2. Otherwise, if byte is 0x25 (%) and the next two bytes + // after byte in input are not in the ranges + // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), + // and 0x61 (a) to 0x66 (f), all inclusive, append byte + // to output. + } else if ( + byte === 0x25 && + !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2])) + ) { + output.push(0x25) + + // 3. Otherwise: + } else { + // 1. Let bytePoint be the two bytes after byte in input, + // decoded, and then interpreted as hexadecimal number. + const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]) + const bytePoint = Number.parseInt(nextTwoBytes, 16) + + // 2. Append a byte whose value is bytePoint to output. + output.push(bytePoint) + + // 3. Skip the next two bytes in input. + i += 2 + } + } + + // 3. Return output. + return Uint8Array.from(output) +} + +// https://mimesniff.spec.whatwg.org/#parse-a-mime-type +/** @param {string} input */ +function parseMIMEType (input) { + // 1. Remove any leading and trailing HTTP whitespace + // from input. + input = removeHTTPWhitespace(input, true, true) + + // 2. Let position be a position variable for input, + // initially pointing at the start of input. + const position = { position: 0 } + + // 3. Let type be the result of collecting a sequence + // of code points that are not U+002F (/) from + // input, given position. + const type = collectASequenceOfCodePointsFast( + '/', + input, + position + ) + + // 4. If type is the empty string or does not solely + // contain HTTP token code points, then return failure. + // https://mimesniff.spec.whatwg.org/#http-token-code-point + if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { + return 'failure' + } + + // 5. If position is past the end of input, then return + // failure + if (position.position > input.length) { + return 'failure' + } + + // 6. Advance position by 1. (This skips past U+002F (/).) + position.position++ + + // 7. Let subtype be the result of collecting a sequence of + // code points that are not U+003B (;) from input, given + // position. + let subtype = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 8. Remove any trailing HTTP whitespace from subtype. + subtype = removeHTTPWhitespace(subtype, false, true) + + // 9. If subtype is the empty string or does not solely + // contain HTTP token code points, then return failure. + if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { + return 'failure' + } + + const typeLowercase = type.toLowerCase() + const subtypeLowercase = subtype.toLowerCase() + + // 10. Let mimeType be a new MIME type record whose type + // is type, in ASCII lowercase, and subtype is subtype, + // in ASCII lowercase. + // https://mimesniff.spec.whatwg.org/#mime-type + const mimeType = { + type: typeLowercase, + subtype: subtypeLowercase, + /** @type {Map} */ + parameters: new Map(), + // https://mimesniff.spec.whatwg.org/#mime-type-essence + essence: `${typeLowercase}/${subtypeLowercase}` + } + + // 11. While position is not past the end of input: + while (position.position < input.length) { + // 1. Advance position by 1. (This skips past U+003B (;).) + position.position++ + + // 2. Collect a sequence of code points that are HTTP + // whitespace from input given position. + collectASequenceOfCodePoints( + // https://fetch.spec.whatwg.org/#http-whitespace + char => HTTP_WHITESPACE_REGEX.test(char), + input, + position + ) + + // 3. Let parameterName be the result of collecting a + // sequence of code points that are not U+003B (;) + // or U+003D (=) from input, given position. + let parameterName = collectASequenceOfCodePoints( + (char) => char !== ';' && char !== '=', + input, + position + ) + + // 4. Set parameterName to parameterName, in ASCII + // lowercase. + parameterName = parameterName.toLowerCase() + + // 5. If position is not past the end of input, then: + if (position.position < input.length) { + // 1. If the code point at position within input is + // U+003B (;), then continue. + if (input[position.position] === ';') { + continue + } + + // 2. Advance position by 1. (This skips past U+003D (=).) + position.position++ + } + + // 6. If position is past the end of input, then break. + if (position.position > input.length) { + break + } + + // 7. Let parameterValue be null. + let parameterValue = null + + // 8. If the code point at position within input is + // U+0022 ("), then: + if (input[position.position] === '"') { + // 1. Set parameterValue to the result of collecting + // an HTTP quoted string from input, given position + // and the extract-value flag. + parameterValue = collectAnHTTPQuotedString(input, position, true) + + // 2. Collect a sequence of code points that are not + // U+003B (;) from input, given position. + collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 9. Otherwise: + } else { + // 1. Set parameterValue to the result of collecting + // a sequence of code points that are not U+003B (;) + // from input, given position. + parameterValue = collectASequenceOfCodePointsFast( + ';', + input, + position + ) + + // 2. Remove any trailing HTTP whitespace from parameterValue. + parameterValue = removeHTTPWhitespace(parameterValue, false, true) + + // 3. If parameterValue is the empty string, then continue. + if (parameterValue.length === 0) { + continue + } + } + + // 10. If all of the following are true + // - parameterName is not the empty string + // - parameterName solely contains HTTP token code points + // - parameterValue solely contains HTTP quoted-string token code points + // - mimeType’s parameters[parameterName] does not exist + // then set mimeType’s parameters[parameterName] to parameterValue. + if ( + parameterName.length !== 0 && + HTTP_TOKEN_CODEPOINTS.test(parameterName) && + (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && + !mimeType.parameters.has(parameterName) + ) { + mimeType.parameters.set(parameterName, parameterValue) + } + } + + // 12. Return mimeType. + return mimeType +} + +// https://infra.spec.whatwg.org/#forgiving-base64-decode +/** @param {string} data */ +function forgivingBase64 (data) { + // 1. Remove all ASCII whitespace from data. + data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line + + // 2. If data’s code point length divides by 4 leaving + // no remainder, then: + if (data.length % 4 === 0) { + // 1. If data ends with one or two U+003D (=) code points, + // then remove them from data. + data = data.replace(/=?=$/, '') + } + + // 3. If data’s code point length divides by 4 leaving + // a remainder of 1, then return failure. + if (data.length % 4 === 1) { + return 'failure' + } + + // 4. If data contains a code point that is not one of + // U+002B (+) + // U+002F (/) + // ASCII alphanumeric + // then return failure. + if (/[^+/0-9A-Za-z]/.test(data)) { + return 'failure' + } + + const binary = atob(data) + const bytes = new Uint8Array(binary.length) + + for (let byte = 0; byte < binary.length; byte++) { + bytes[byte] = binary.charCodeAt(byte) + } + + return bytes +} + +// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string +// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string +/** + * @param {string} input + * @param {{ position: number }} position + * @param {boolean?} extractValue + */ +function collectAnHTTPQuotedString (input, position, extractValue) { + // 1. Let positionStart be position. + const positionStart = position.position + + // 2. Let value be the empty string. + let value = '' + + // 3. Assert: the code point at position within input + // is U+0022 ("). + assert(input[position.position] === '"') + + // 4. Advance position by 1. + position.position++ + + // 5. While true: + while (true) { + // 1. Append the result of collecting a sequence of code points + // that are not U+0022 (") or U+005C (\) from input, given + // position, to value. + value += collectASequenceOfCodePoints( + (char) => char !== '"' && char !== '\\', + input, + position + ) + + // 2. If position is past the end of input, then break. + if (position.position >= input.length) { + break + } + + // 3. Let quoteOrBackslash be the code point at position within + // input. + const quoteOrBackslash = input[position.position] + + // 4. Advance position by 1. + position.position++ + + // 5. If quoteOrBackslash is U+005C (\), then: + if (quoteOrBackslash === '\\') { + // 1. If position is past the end of input, then append + // U+005C (\) to value and break. + if (position.position >= input.length) { + value += '\\' + break + } + + // 2. Append the code point at position within input to value. + value += input[position.position] + + // 3. Advance position by 1. + position.position++ + + // 6. Otherwise: + } else { + // 1. Assert: quoteOrBackslash is U+0022 ("). + assert(quoteOrBackslash === '"') + + // 2. Break. + break + } + } + + // 6. If the extract-value flag is set, then return value. + if (extractValue) { + return value + } + + // 7. Return the code points from positionStart to position, + // inclusive, within input. + return input.slice(positionStart, position.position) +} + +/** + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +function serializeAMimeType (mimeType) { + assert(mimeType !== 'failure') + const { parameters, essence } = mimeType + + // 1. Let serialization be the concatenation of mimeType’s + // type, U+002F (/), and mimeType’s subtype. + let serialization = essence + + // 2. For each name → value of mimeType’s parameters: + for (let [name, value] of parameters.entries()) { + // 1. Append U+003B (;) to serialization. + serialization += ';' + + // 2. Append name to serialization. + serialization += name + + // 3. Append U+003D (=) to serialization. + serialization += '=' + + // 4. If value does not solely contain HTTP token code + // points or value is the empty string, then: + if (!HTTP_TOKEN_CODEPOINTS.test(value)) { + // 1. Precede each occurence of U+0022 (") or + // U+005C (\) in value with U+005C (\). + value = value.replace(/(\\|")/g, '\\$1') + + // 2. Prepend U+0022 (") to value. + value = '"' + value + + // 3. Append U+0022 (") to value. + value += '"' + } + + // 5. Append value to serialization. + serialization += value + } + + // 3. Return serialization. + return serialization +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} char + */ +function isHTTPWhiteSpace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === ' ' +} + +/** + * @see https://fetch.spec.whatwg.org/#http-whitespace + * @param {string} str + */ +function removeHTTPWhitespace (str, leading = true, trailing = true) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); + } + + if (trailing) { + for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); + } + + return str.slice(lead, trail + 1) +} + +/** + * @see https://infra.spec.whatwg.org/#ascii-whitespace + * @param {string} char + */ +function isASCIIWhitespace (char) { + return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' +} + +/** + * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace + */ +function removeASCIIWhitespace (str, leading = true, trailing = true) { + let lead = 0 + let trail = str.length - 1 + + if (leading) { + for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); + } + + if (trailing) { + for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); + } + + return str.slice(lead, trail + 1) +} + +module.exports = { + dataURLProcessor, + URLSerializer, + collectASequenceOfCodePoints, + collectASequenceOfCodePointsFast, + stringPercentDecode, + parseMIMEType, + collectAnHTTPQuotedString, + serializeAMimeType +} + + +/***/ }), + +/***/ 3041: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { Blob, File: NativeFile } = __nccwpck_require__(181) +const { types } = __nccwpck_require__(9023) +const { kState } = __nccwpck_require__(9710) +const { isBlobLike } = __nccwpck_require__(5523) +const { webidl } = __nccwpck_require__(4222) +const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) +const { kEnumerableProperty } = __nccwpck_require__(3440) +const encoder = new TextEncoder() + +class File extends Blob { + constructor (fileBits, fileName, options = {}) { + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' }) + + fileBits = webidl.converters['sequence'](fileBits) + fileName = webidl.converters.USVString(fileName) + options = webidl.converters.FilePropertyBag(options) + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + // Note: Blob handles this for us + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // 2. Convert every character in t to ASCII lowercase. + let t = options.type + let d + + // eslint-disable-next-line no-labels + substep: { + if (t) { + t = parseMIMEType(t) + + if (t === 'failure') { + t = '' + // eslint-disable-next-line no-labels + break substep + } + + t = serializeAMimeType(t).toLowerCase() + } + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + d = options.lastModified + } + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + super(processBlobParts(fileBits, options), { type: t }) + this[kState] = { + name: n, + lastModified: d, + type: t + } + } + + get name () { + webidl.brandCheck(this, File) + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, File) + + return this[kState].lastModified + } + + get type () { + webidl.brandCheck(this, File) + + return this[kState].type + } +} + +class FileLike { + constructor (blobLike, fileName, options = {}) { + // TODO: argument idl type check + + // The File constructor is invoked with two or three parameters, depending + // on whether the optional dictionary parameter is used. When the File() + // constructor is invoked, user agents must run the following steps: + + // 1. Let bytes be the result of processing blob parts given fileBits and + // options. + + // 2. Let n be the fileName argument to the constructor. + const n = fileName + + // 3. Process FilePropertyBag dictionary argument by running the following + // substeps: + + // 1. If the type member is provided and is not the empty string, let t + // be set to the type dictionary member. If t contains any characters + // outside the range U+0020 to U+007E, then set t to the empty string + // and return from these substeps. + // TODO + const t = options.type + + // 2. Convert every character in t to ASCII lowercase. + // TODO + + // 3. If the lastModified member is provided, let d be set to the + // lastModified dictionary member. If it is not provided, set d to the + // current date and time represented as the number of milliseconds since + // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). + const d = options.lastModified ?? Date.now() + + // 4. Return a new File object F such that: + // F refers to the bytes byte sequence. + // F.size is set to the number of total bytes in bytes. + // F.name is set to n. + // F.type is set to t. + // F.lastModified is set to d. + + this[kState] = { + blobLike, + name: n, + type: t, + lastModified: d + } + } + + stream (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.stream(...args) + } + + arrayBuffer (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.arrayBuffer(...args) + } + + slice (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.slice(...args) + } + + text (...args) { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.text(...args) + } + + get size () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.size + } + + get type () { + webidl.brandCheck(this, FileLike) + + return this[kState].blobLike.type + } + + get name () { + webidl.brandCheck(this, FileLike) + + return this[kState].name + } + + get lastModified () { + webidl.brandCheck(this, FileLike) + + return this[kState].lastModified + } + + get [Symbol.toStringTag] () { + return 'File' + } +} + +Object.defineProperties(File.prototype, { + [Symbol.toStringTag]: { + value: 'File', + configurable: true + }, + name: kEnumerableProperty, + lastModified: kEnumerableProperty +}) + +webidl.converters.Blob = webidl.interfaceConverter(Blob) + +webidl.converters.BlobPart = function (V, opts) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if ( + ArrayBuffer.isView(V) || + types.isAnyArrayBuffer(V) + ) { + return webidl.converters.BufferSource(V, opts) + } + } + + return webidl.converters.USVString(V, opts) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.BlobPart +) + +// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag +webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ + { + key: 'lastModified', + converter: webidl.converters['long long'], + get defaultValue () { + return Date.now() + } + }, + { + key: 'type', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'endings', + converter: (value) => { + value = webidl.converters.DOMString(value) + value = value.toLowerCase() + + if (value !== 'native') { + value = 'transparent' + } + + return value + }, + defaultValue: 'transparent' + } +]) + +/** + * @see https://www.w3.org/TR/FileAPI/#process-blob-parts + * @param {(NodeJS.TypedArray|Blob|string)[]} parts + * @param {{ type: string, endings: string }} options + */ +function processBlobParts (parts, options) { + // 1. Let bytes be an empty sequence of bytes. + /** @type {NodeJS.TypedArray[]} */ + const bytes = [] + + // 2. For each element in parts: + for (const element of parts) { + // 1. If element is a USVString, run the following substeps: + if (typeof element === 'string') { + // 1. Let s be element. + let s = element + + // 2. If the endings member of options is "native", set s + // to the result of converting line endings to native + // of element. + if (options.endings === 'native') { + s = convertLineEndingsNative(s) + } + + // 3. Append the result of UTF-8 encoding s to bytes. + bytes.push(encoder.encode(s)) + } else if ( + types.isAnyArrayBuffer(element) || + types.isTypedArray(element) + ) { + // 2. If element is a BufferSource, get a copy of the + // bytes held by the buffer source, and append those + // bytes to bytes. + if (!element.buffer) { // ArrayBuffer + bytes.push(new Uint8Array(element)) + } else { + bytes.push( + new Uint8Array(element.buffer, element.byteOffset, element.byteLength) + ) + } + } else if (isBlobLike(element)) { + // 3. If element is a Blob, append the bytes it represents + // to bytes. + bytes.push(element) + } + } + + // 3. Return bytes. + return bytes +} + +/** + * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native + * @param {string} s + */ +function convertLineEndingsNative (s) { + // 1. Let native line ending be be the code point U+000A LF. + let nativeLineEnding = '\n' + + // 2. If the underlying platform’s conventions are to + // represent newlines as a carriage return and line feed + // sequence, set native line ending to the code point + // U+000D CR followed by the code point U+000A LF. + if (process.platform === 'win32') { + nativeLineEnding = '\r\n' + } + + return s.replace(/\r?\n/g, nativeLineEnding) +} + +// If this function is moved to ./util.js, some tools (such as +// rollup) will warn about circular dependencies. See: +// https://github.com/nodejs/undici/issues/1629 +function isFileLike (object) { + return ( + (NativeFile && object instanceof NativeFile) || + object instanceof File || ( + object && + (typeof object.stream === 'function' || + typeof object.arrayBuffer === 'function') && + object[Symbol.toStringTag] === 'File' + ) + ) +} + +module.exports = { File, FileLike, isFileLike } + + +/***/ }), + +/***/ 3073: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(5523) +const { kState } = __nccwpck_require__(9710) +const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(3041) +const { webidl } = __nccwpck_require__(4222) +const { Blob, File: NativeFile } = __nccwpck_require__(181) + +/** @type {globalThis['File']} */ +const File = NativeFile ?? UndiciFile + +// https://xhr.spec.whatwg.org/#formdata +class FormData { + constructor (form) { + if (form !== undefined) { + throw webidl.errors.conversionFailed({ + prefix: 'FormData constructor', + argument: 'Argument 1', + types: ['undefined'] + }) + } + + this[kState] = [] + } + + append (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? webidl.converters.USVString(filename) + : undefined + + // 2. Let entry be the result of creating an entry with + // name, value, and filename if given. + const entry = makeEntry(name, value, filename) + + // 3. Append entry to this’s entry list. + this[kState].push(entry) + } + + delete (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) + + name = webidl.converters.USVString(name) + + // The delete(name) method steps are to remove all entries whose name + // is name from this’s entry list. + this[kState] = this[kState].filter(entry => entry.name !== name) + } + + get (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return null. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx === -1) { + return null + } + + // 2. Return the value of the first entry whose name is name from + // this’s entry list. + return this[kState][idx].value + } + + getAll (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) + + name = webidl.converters.USVString(name) + + // 1. If there is no entry whose name is name in this’s entry list, + // then return the empty list. + // 2. Return the values of all entries whose name is name, in order, + // from this’s entry list. + return this[kState] + .filter((entry) => entry.name === name) + .map((entry) => entry.value) + } + + has (name) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) + + name = webidl.converters.USVString(name) + + // The has(name) method steps are to return true if there is an entry + // whose name is name in this’s entry list; otherwise false. + return this[kState].findIndex((entry) => entry.name === name) !== -1 + } + + set (name, value, filename = undefined) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) + + if (arguments.length === 3 && !isBlobLike(value)) { + throw new TypeError( + "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" + ) + } + + // The set(name, value) and set(name, blobValue, filename) method steps + // are: + + // 1. Let value be value if given; otherwise blobValue. + + name = webidl.converters.USVString(name) + value = isBlobLike(value) + ? webidl.converters.Blob(value, { strict: false }) + : webidl.converters.USVString(value) + filename = arguments.length === 3 + ? toUSVString(filename) + : undefined + + // 2. Let entry be the result of creating an entry with name, value, and + // filename if given. + const entry = makeEntry(name, value, filename) + + // 3. If there are entries in this’s entry list whose name is name, then + // replace the first such entry with entry and remove the others. + const idx = this[kState].findIndex((entry) => entry.name === name) + if (idx !== -1) { + this[kState] = [ + ...this[kState].slice(0, idx), + entry, + ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) + ] + } else { + // 4. Otherwise, append entry to this’s entry list. + this[kState].push(entry) + } + } + + entries () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key+value' + ) + } + + keys () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'key' + ) + } + + values () { + webidl.brandCheck(this, FormData) + + return makeIterator( + () => this[kState].map(pair => [pair.name, pair.value]), + 'FormData', + 'value' + ) + } + + /** + * @param {(value: string, key: string, self: FormData) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, FormData) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." + ) + } + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } +} + +FormData.prototype[Symbol.iterator] = FormData.prototype.entries + +Object.defineProperties(FormData.prototype, { + [Symbol.toStringTag]: { + value: 'FormData', + configurable: true + } +}) + +/** + * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry + * @param {string} name + * @param {string|Blob} value + * @param {?string} filename + * @returns + */ +function makeEntry (name, value, filename) { + // 1. Set name to the result of converting name into a scalar value string. + // "To convert a string into a scalar value string, replace any surrogates + // with U+FFFD." + // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end + name = Buffer.from(name).toString('utf8') + + // 2. If value is a string, then set value to the result of converting + // value into a scalar value string. + if (typeof value === 'string') { + value = Buffer.from(value).toString('utf8') + } else { + // 3. Otherwise: + + // 1. If value is not a File object, then set value to a new File object, + // representing the same bytes, whose name attribute value is "blob" + if (!isFileLike(value)) { + value = value instanceof Blob + ? new File([value], 'blob', { type: value.type }) + : new FileLike(value, 'blob', { type: value.type }) + } + + // 2. If filename is given, then set value to a new File object, + // representing the same bytes, whose name attribute is filename. + if (filename !== undefined) { + /** @type {FilePropertyBag} */ + const options = { + type: value.type, + lastModified: value.lastModified + } + + value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile + ? new File([value], filename, options) + : new FileLike(value, filename, options) + } + } + + // 4. Return an entry whose name is name and whose value is value. + return { name, value } +} + +module.exports = { FormData } + + +/***/ }), + +/***/ 5628: +/***/ ((module) => { + + + +// In case of breaking changes, increase the version +// number to avoid conflicts. +const globalOrigin = Symbol.for('undici.globalOrigin.1') + +function getGlobalOrigin () { + return globalThis[globalOrigin] +} + +function setGlobalOrigin (newOrigin) { + if (newOrigin === undefined) { + Object.defineProperty(globalThis, globalOrigin, { + value: undefined, + writable: true, + enumerable: false, + configurable: false + }) + + return + } + + const parsedURL = new URL(newOrigin) + + if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { + throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) + } + + Object.defineProperty(globalThis, globalOrigin, { + value: parsedURL, + writable: true, + enumerable: false, + configurable: false + }) +} + +module.exports = { + getGlobalOrigin, + setGlobalOrigin +} + + +/***/ }), + +/***/ 6349: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// https://github.com/Ethan-Arrowood/undici-fetch + + + +const { kHeadersList, kConstruct } = __nccwpck_require__(6443) +const { kGuard } = __nccwpck_require__(9710) +const { kEnumerableProperty } = __nccwpck_require__(3440) +const { + makeIterator, + isValidHeaderName, + isValidHeaderValue +} = __nccwpck_require__(5523) +const util = __nccwpck_require__(9023) +const { webidl } = __nccwpck_require__(4222) +const assert = __nccwpck_require__(2613) + +const kHeadersMap = Symbol('headers map') +const kHeadersSortedMap = Symbol('headers map sorted') + +/** + * @param {number} code + */ +function isHTTPWhiteSpaceCharCode (code) { + return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize + * @param {string} potentialValue + */ +function headerValueNormalize (potentialValue) { + // To normalize a byte sequence potentialValue, remove + // any leading and trailing HTTP whitespace bytes from + // potentialValue. + let i = 0; let j = potentialValue.length + + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j + while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i + + return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) +} + +function fill (headers, object) { + // To fill a Headers object headers with a given object object, run these steps: + + // 1. If object is a sequence, then for each header in object: + // Note: webidl conversion to array has already been done. + if (Array.isArray(object)) { + for (let i = 0; i < object.length; ++i) { + const header = object[i] + // 1. If header does not contain exactly two items, then throw a TypeError. + if (header.length !== 2) { + throw webidl.errors.exception({ + header: 'Headers constructor', + message: `expected name/value pair to be length 2, found ${header.length}.` + }) + } + + // 2. Append (header’s first item, header’s second item) to headers. + appendHeader(headers, header[0], header[1]) + } + } else if (typeof object === 'object' && object !== null) { + // Note: null should throw + + // 2. Otherwise, object is a record, then for each key → value in object, + // append (key, value) to headers + const keys = Object.keys(object) + for (let i = 0; i < keys.length; ++i) { + appendHeader(headers, keys[i], object[keys[i]]) + } + } else { + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) + } +} + +/** + * @see https://fetch.spec.whatwg.org/#concept-headers-append + */ +function appendHeader (headers, name, value) { + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.append', + value, + type: 'header value' + }) + } + + // 3. If headers’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if headers’s guard is "request" and name is a + // forbidden header name, return. + // Note: undici does not implement forbidden header names + if (headers[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (headers[kGuard] === 'request-no-cors') { + // 5. Otherwise, if headers’s guard is "request-no-cors": + // TODO + } + + // 6. Otherwise, if headers’s guard is "response" and name is a + // forbidden response-header name, return. + + // 7. Append (name, value) to headers’s header list. + return headers[kHeadersList].append(name, value) + + // 8. If headers’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from headers +} + +class HeadersList { + /** @type {[string, string][]|null} */ + cookies = null + + constructor (init) { + if (init instanceof HeadersList) { + this[kHeadersMap] = new Map(init[kHeadersMap]) + this[kHeadersSortedMap] = init[kHeadersSortedMap] + this.cookies = init.cookies === null ? null : [...init.cookies] + } else { + this[kHeadersMap] = new Map(init) + this[kHeadersSortedMap] = null + } + } + + // https://fetch.spec.whatwg.org/#header-list-contains + contains (name) { + // A header list list contains a header name name if list + // contains a header whose name is a byte-case-insensitive + // match for name. + name = name.toLowerCase() + + return this[kHeadersMap].has(name) + } + + clear () { + this[kHeadersMap].clear() + this[kHeadersSortedMap] = null + this.cookies = null + } + + // https://fetch.spec.whatwg.org/#concept-header-list-append + append (name, value) { + this[kHeadersSortedMap] = null + + // 1. If list contains name, then set name to the first such + // header’s name. + const lowercaseName = name.toLowerCase() + const exists = this[kHeadersMap].get(lowercaseName) + + // 2. Append (name, value) to list. + if (exists) { + const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' + this[kHeadersMap].set(lowercaseName, { + name: exists.name, + value: `${exists.value}${delimiter}${value}` + }) + } else { + this[kHeadersMap].set(lowercaseName, { name, value }) + } + + if (lowercaseName === 'set-cookie') { + this.cookies ??= [] + this.cookies.push(value) + } + } + + // https://fetch.spec.whatwg.org/#concept-header-list-set + set (name, value) { + this[kHeadersSortedMap] = null + const lowercaseName = name.toLowerCase() + + if (lowercaseName === 'set-cookie') { + this.cookies = [value] + } + + // 1. If list contains name, then set the value of + // the first such header to value and remove the + // others. + // 2. Otherwise, append header (name, value) to list. + this[kHeadersMap].set(lowercaseName, { name, value }) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-delete + delete (name) { + this[kHeadersSortedMap] = null + + name = name.toLowerCase() + + if (name === 'set-cookie') { + this.cookies = null + } + + this[kHeadersMap].delete(name) + } + + // https://fetch.spec.whatwg.org/#concept-header-list-get + get (name) { + const value = this[kHeadersMap].get(name.toLowerCase()) + + // 1. If list does not contain name, then return null. + // 2. Return the values of all headers in list whose name + // is a byte-case-insensitive match for name, + // separated from each other by 0x2C 0x20, in order. + return value === undefined ? null : value.value + } + + * [Symbol.iterator] () { + // use the lowercased name + for (const [name, { value }] of this[kHeadersMap]) { + yield [name, value] + } + } + + get entries () { + const headers = {} + + if (this[kHeadersMap].size) { + for (const { name, value } of this[kHeadersMap].values()) { + headers[name] = value + } + } + + return headers + } +} + +// https://fetch.spec.whatwg.org/#headers-class +class Headers { + constructor (init = undefined) { + if (init === kConstruct) { + return + } + this[kHeadersList] = new HeadersList() + + // The new Headers(init) constructor steps are: + + // 1. Set this’s guard to "none". + this[kGuard] = 'none' + + // 2. If init is given, then fill this with init. + if (init !== undefined) { + init = webidl.converters.HeadersInit(init) + fill(this, init) + } + } + + // https://fetch.spec.whatwg.org/#dom-headers-append + append (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) + + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) + + return appendHeader(this, name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-delete + delete (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.delete', + value: name, + type: 'header name' + }) + } + + // 2. If this’s guard is "immutable", then throw a TypeError. + // 3. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 4. Otherwise, if this’s guard is "request-no-cors", name + // is not a no-CORS-safelisted request-header name, and + // name is not a privileged no-CORS request-header name, + // return. + // 5. Otherwise, if this’s guard is "response" and name is + // a forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } + + // 6. If this’s header list does not contain name, then + // return. + if (!this[kHeadersList].contains(name)) { + return + } + + // 7. Delete name from this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this. + this[kHeadersList].delete(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-get + get (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.get', + value: name, + type: 'header name' + }) + } + + // 2. Return the result of getting name from this’s header + // list. + return this[kHeadersList].get(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-has + has (name) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) + + name = webidl.converters.ByteString(name) + + // 1. If name is not a header name, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.has', + value: name, + type: 'header name' + }) + } + + // 2. Return true if this’s header list contains name; + // otherwise false. + return this[kHeadersList].contains(name) + } + + // https://fetch.spec.whatwg.org/#dom-headers-set + set (name, value) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) + + name = webidl.converters.ByteString(name) + value = webidl.converters.ByteString(value) + + // 1. Normalize value. + value = headerValueNormalize(value) + + // 2. If name is not a header name or value is not a + // header value, then throw a TypeError. + if (!isValidHeaderName(name)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value: name, + type: 'header name' + }) + } else if (!isValidHeaderValue(value)) { + throw webidl.errors.invalidArgument({ + prefix: 'Headers.set', + value, + type: 'header value' + }) + } + + // 3. If this’s guard is "immutable", then throw a TypeError. + // 4. Otherwise, if this’s guard is "request" and name is a + // forbidden header name, return. + // 5. Otherwise, if this’s guard is "request-no-cors" and + // name/value is not a no-CORS-safelisted request-header, + // return. + // 6. Otherwise, if this’s guard is "response" and name is a + // forbidden response-header name, return. + // Note: undici does not implement forbidden header names + if (this[kGuard] === 'immutable') { + throw new TypeError('immutable') + } else if (this[kGuard] === 'request-no-cors') { + // TODO + } + + // 7. Set (name, value) in this’s header list. + // 8. If this’s guard is "request-no-cors", then remove + // privileged no-CORS request headers from this + this[kHeadersList].set(name, value) + } + + // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie + getSetCookie () { + webidl.brandCheck(this, Headers) + + // 1. If this’s header list does not contain `Set-Cookie`, then return « ». + // 2. Return the values of all headers in this’s header list whose name is + // a byte-case-insensitive match for `Set-Cookie`, in order. + + const list = this[kHeadersList].cookies + + if (list) { + return [...list] + } + + return [] + } + + // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine + get [kHeadersSortedMap] () { + if (this[kHeadersList][kHeadersSortedMap]) { + return this[kHeadersList][kHeadersSortedMap] + } + + // 1. Let headers be an empty list of headers with the key being the name + // and value the value. + const headers = [] + + // 2. Let names be the result of convert header names to a sorted-lowercase + // set with all the names of the headers in list. + const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1) + const cookies = this[kHeadersList].cookies + + // 3. For each name of names: + for (let i = 0; i < names.length; ++i) { + const [name, value] = names[i] + // 1. If name is `set-cookie`, then: + if (name === 'set-cookie') { + // 1. Let values be a list of all values of headers in list whose name + // is a byte-case-insensitive match for name, in order. + + // 2. For each value of values: + // 1. Append (name, value) to headers. + for (let j = 0; j < cookies.length; ++j) { + headers.push([name, cookies[j]]) + } + } else { + // 2. Otherwise: + + // 1. Let value be the result of getting name from list. + + // 2. Assert: value is non-null. + assert(value !== null) + + // 3. Append (name, value) to headers. + headers.push([name, value]) + } + } + + this[kHeadersList][kHeadersSortedMap] = headers + + // 4. Return headers. + return headers + } + + keys () { + webidl.brandCheck(this, Headers) + + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key') + } + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key' + ) + } + + values () { + webidl.brandCheck(this, Headers) + + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'value') + } + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'value' + ) + } + + entries () { + webidl.brandCheck(this, Headers) + + if (this[kGuard] === 'immutable') { + const value = this[kHeadersSortedMap] + return makeIterator(() => value, 'Headers', + 'key+value') + } + + return makeIterator( + () => [...this[kHeadersSortedMap].values()], + 'Headers', + 'key+value' + ) + } + + /** + * @param {(value: string, key: string, self: Headers) => void} callbackFn + * @param {unknown} thisArg + */ + forEach (callbackFn, thisArg = globalThis) { + webidl.brandCheck(this, Headers) + + webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) + + if (typeof callbackFn !== 'function') { + throw new TypeError( + "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." + ) + } + + for (const [key, value] of this) { + callbackFn.apply(thisArg, [value, key, this]) + } + } + + [Symbol.for('nodejs.util.inspect.custom')] () { + webidl.brandCheck(this, Headers) + + return this[kHeadersList] + } +} + +Headers.prototype[Symbol.iterator] = Headers.prototype.entries + +Object.defineProperties(Headers.prototype, { + append: kEnumerableProperty, + delete: kEnumerableProperty, + get: kEnumerableProperty, + has: kEnumerableProperty, + set: kEnumerableProperty, + getSetCookie: kEnumerableProperty, + keys: kEnumerableProperty, + values: kEnumerableProperty, + entries: kEnumerableProperty, + forEach: kEnumerableProperty, + [Symbol.iterator]: { enumerable: false }, + [Symbol.toStringTag]: { + value: 'Headers', + configurable: true + }, + [util.inspect.custom]: { + enumerable: false + } +}) + +webidl.converters.HeadersInit = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (V[Symbol.iterator]) { + return webidl.converters['sequence>'](V) + } + + return webidl.converters['record'](V) + } + + throw webidl.errors.conversionFailed({ + prefix: 'Headers constructor', + argument: 'Argument 1', + types: ['sequence>', 'record'] + }) +} + +module.exports = { + fill, + Headers, + HeadersList +} + + +/***/ }), + +/***/ 2315: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +// https://github.com/Ethan-Arrowood/undici-fetch + + + +const { + Response, + makeNetworkError, + makeAppropriateNetworkError, + filterResponse, + makeResponse +} = __nccwpck_require__(8676) +const { Headers } = __nccwpck_require__(6349) +const { Request, makeRequest } = __nccwpck_require__(5194) +const zlib = __nccwpck_require__(3106) +const { + bytesMatch, + makePolicyContainer, + clonePolicyContainer, + requestBadPort, + TAOCheck, + appendRequestOriginHeader, + responseLocationURL, + requestCurrentURL, + setRequestReferrerPolicyOnRedirect, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + createOpaqueTimingInfo, + appendFetchMetadata, + corsCheck, + crossOriginResourcePolicyCheck, + determineRequestsReferrer, + coarsenedSharedCurrentTime, + createDeferredPromise, + isBlobLike, + sameOrigin, + isCancelled, + isAborted, + isErrorLike, + fullyReadBody, + readableStreamClose, + isomorphicEncode, + urlIsLocal, + urlIsHttpHttpsScheme, + urlHasHttpsScheme +} = __nccwpck_require__(5523) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) +const assert = __nccwpck_require__(2613) +const { safelyExtractBody } = __nccwpck_require__(8923) +const { + redirectStatusSet, + nullBodyStatus, + safeMethodsSet, + requestBodyHeader, + subresourceSet, + DOMException +} = __nccwpck_require__(7326) +const { kHeadersList } = __nccwpck_require__(6443) +const EE = __nccwpck_require__(4434) +const { Readable, pipeline } = __nccwpck_require__(2203) +const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3440) +const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(4322) +const { TransformStream } = __nccwpck_require__(3774) +const { getGlobalDispatcher } = __nccwpck_require__(2581) +const { webidl } = __nccwpck_require__(4222) +const { STATUS_CODES } = __nccwpck_require__(8611) +const GET_OR_HEAD = ['GET', 'HEAD'] + +/** @type {import('buffer').resolveObjectURL} */ +let resolveObjectURL +let ReadableStream = globalThis.ReadableStream + +class Fetch extends EE { + constructor (dispatcher) { + super() + + this.dispatcher = dispatcher + this.connection = null + this.dump = false + this.state = 'ongoing' + // 2 terminated listeners get added per request, + // but only 1 gets removed. If there are 20 redirects, + // 21 listeners will be added. + // See https://github.com/nodejs/undici/issues/1711 + // TODO (fix): Find and fix root cause for leaked listener. + this.setMaxListeners(21) + } + + terminate (reason) { + if (this.state !== 'ongoing') { + return + } + + this.state = 'terminated' + this.connection?.destroy(reason) + this.emit('terminated', reason) + } + + // https://fetch.spec.whatwg.org/#fetch-controller-abort + abort (error) { + if (this.state !== 'ongoing') { + return + } + + // 1. Set controller’s state to "aborted". + this.state = 'aborted' + + // 2. Let fallbackError be an "AbortError" DOMException. + // 3. Set error to fallbackError if it is not given. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 4. Let serializedError be StructuredSerialize(error). + // If that threw an exception, catch it, and let + // serializedError be StructuredSerialize(fallbackError). + + // 5. Set controller’s serialized abort reason to serializedError. + this.serializedAbortReason = error + + this.connection?.destroy(error) + this.emit('terminated', error) + } +} + +// https://fetch.spec.whatwg.org/#fetch-method +function fetch (input, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) + + // 1. Let p be a new promise. + const p = createDeferredPromise() + + // 2. Let requestObject be the result of invoking the initial value of + // Request as constructor with input and init as arguments. If this throws + // an exception, reject p with it and return p. + let requestObject + + try { + requestObject = new Request(input, init) + } catch (e) { + p.reject(e) + return p.promise + } + + // 3. Let request be requestObject’s request. + const request = requestObject[kState] + + // 4. If requestObject’s signal’s aborted flag is set, then: + if (requestObject.signal.aborted) { + // 1. Abort the fetch() call with p, request, null, and + // requestObject’s signal’s abort reason. + abortFetch(p, request, null, requestObject.signal.reason) + + // 2. Return p. + return p.promise + } + + // 5. Let globalObject be request’s client’s global object. + const globalObject = request.client.globalObject + + // 6. If globalObject is a ServiceWorkerGlobalScope object, then set + // request’s service-workers mode to "none". + if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { + request.serviceWorkers = 'none' + } + + // 7. Let responseObject be null. + let responseObject = null + + // 8. Let relevantRealm be this’s relevant Realm. + const relevantRealm = null + + // 9. Let locallyAborted be false. + let locallyAborted = false + + // 10. Let controller be null. + let controller = null + + // 11. Add the following abort steps to requestObject’s signal: + addAbortListener( + requestObject.signal, + () => { + // 1. Set locallyAborted to true. + locallyAborted = true + + // 2. Assert: controller is non-null. + assert(controller != null) + + // 3. Abort controller with requestObject’s signal’s abort reason. + controller.abort(requestObject.signal.reason) + + // 4. Abort the fetch() call with p, request, responseObject, + // and requestObject’s signal’s abort reason. + abortFetch(p, request, responseObject, requestObject.signal.reason) + } + ) + + // 12. Let handleFetchDone given response response be to finalize and + // report timing with response, globalObject, and "fetch". + const handleFetchDone = (response) => + finalizeAndReportTiming(response, 'fetch') + + // 13. Set controller to the result of calling fetch given request, + // with processResponseEndOfBody set to handleFetchDone, and processResponse + // given response being these substeps: + + const processResponse = (response) => { + // 1. If locallyAborted is true, terminate these substeps. + if (locallyAborted) { + return Promise.resolve() + } + + // 2. If response’s aborted flag is set, then: + if (response.aborted) { + // 1. Let deserializedError be the result of deserialize a serialized + // abort reason given controller’s serialized abort reason and + // relevantRealm. + + // 2. Abort the fetch() call with p, request, responseObject, and + // deserializedError. + + abortFetch(p, request, responseObject, controller.serializedAbortReason) + return Promise.resolve() + } + + // 3. If response is a network error, then reject p with a TypeError + // and terminate these substeps. + if (response.type === 'error') { + p.reject( + Object.assign(new TypeError('fetch failed'), { cause: response.error }) + ) + return Promise.resolve() + } + + // 4. Set responseObject to the result of creating a Response object, + // given response, "immutable", and relevantRealm. + responseObject = new Response() + responseObject[kState] = response + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = response.headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + + // 5. Resolve p with responseObject. + p.resolve(responseObject) + } + + controller = fetching({ + request, + processResponseEndOfBody: handleFetchDone, + processResponse, + dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici + }) + + // 14. Return p. + return p.promise +} + +// https://fetch.spec.whatwg.org/#finalize-and-report-timing +function finalizeAndReportTiming (response, initiatorType = 'other') { + // 1. If response is an aborted network error, then return. + if (response.type === 'error' && response.aborted) { + return + } + + // 2. If response’s URL list is null or empty, then return. + if (!response.urlList?.length) { + return + } + + // 3. Let originalURL be response’s URL list[0]. + const originalURL = response.urlList[0] + + // 4. Let timingInfo be response’s timing info. + let timingInfo = response.timingInfo + + // 5. Let cacheState be response’s cache state. + let cacheState = response.cacheState + + // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. + if (!urlIsHttpHttpsScheme(originalURL)) { + return + } + + // 7. If timingInfo is null, then return. + if (timingInfo === null) { + return + } + + // 8. If response’s timing allow passed flag is not set, then: + if (!response.timingAllowPassed) { + // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. + timingInfo = createOpaqueTimingInfo({ + startTime: timingInfo.startTime + }) + + // 2. Set cacheState to the empty string. + cacheState = '' + } + + // 9. Set timingInfo’s end time to the coarsened shared current time + // given global’s relevant settings object’s cross-origin isolated + // capability. + // TODO: given global’s relevant settings object’s cross-origin isolated + // capability? + timingInfo.endTime = coarsenedSharedCurrentTime() + + // 10. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 11. Mark resource timing for timingInfo, originalURL, initiatorType, + // global, and cacheState. + markResourceTiming( + timingInfo, + originalURL, + initiatorType, + globalThis, + cacheState + ) +} + +// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing +function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) { + if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) { + performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState) + } +} + +// https://fetch.spec.whatwg.org/#abort-fetch +function abortFetch (p, request, responseObject, error) { + // Note: AbortSignal.reason was added in node v17.2.0 + // which would give us an undefined error to reject with. + // Remove this once node v16 is no longer supported. + if (!error) { + error = new DOMException('The operation was aborted.', 'AbortError') + } + + // 1. Reject promise with error. + p.reject(error) + + // 2. If request’s body is not null and is readable, then cancel request’s + // body with error. + if (request.body != null && isReadable(request.body?.stream)) { + request.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } + + // 3. If responseObject is null, then return. + if (responseObject == null) { + return + } + + // 4. Let response be responseObject’s response. + const response = responseObject[kState] + + // 5. If response’s body is not null and is readable, then error response’s + // body with error. + if (response.body != null && isReadable(response.body?.stream)) { + response.body.stream.cancel(error).catch((err) => { + if (err.code === 'ERR_INVALID_STATE') { + // Node bug? + return + } + throw err + }) + } +} + +// https://fetch.spec.whatwg.org/#fetching +function fetching ({ + request, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseEndOfBody, + processResponseConsumeBody, + useParallelQueue = false, + dispatcher // undici +}) { + // 1. Let taskDestination be null. + let taskDestination = null + + // 2. Let crossOriginIsolatedCapability be false. + let crossOriginIsolatedCapability = false + + // 3. If request’s client is non-null, then: + if (request.client != null) { + // 1. Set taskDestination to request’s client’s global object. + taskDestination = request.client.globalObject + + // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin + // isolated capability. + crossOriginIsolatedCapability = + request.client.crossOriginIsolatedCapability + } + + // 4. If useParallelQueue is true, then set taskDestination to the result of + // starting a new parallel queue. + // TODO + + // 5. Let timingInfo be a new fetch timing info whose start time and + // post-redirect start time are the coarsened shared current time given + // crossOriginIsolatedCapability. + const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) + const timingInfo = createOpaqueTimingInfo({ + startTime: currenTime + }) + + // 6. Let fetchParams be a new fetch params whose + // request is request, + // timing info is timingInfo, + // process request body chunk length is processRequestBodyChunkLength, + // process request end-of-body is processRequestEndOfBody, + // process response is processResponse, + // process response consume body is processResponseConsumeBody, + // process response end-of-body is processResponseEndOfBody, + // task destination is taskDestination, + // and cross-origin isolated capability is crossOriginIsolatedCapability. + const fetchParams = { + controller: new Fetch(dispatcher), + request, + timingInfo, + processRequestBodyChunkLength, + processRequestEndOfBody, + processResponse, + processResponseConsumeBody, + processResponseEndOfBody, + taskDestination, + crossOriginIsolatedCapability + } + + // 7. If request’s body is a byte sequence, then set request’s body to + // request’s body as a body. + // NOTE: Since fetching is only called from fetch, body should already be + // extracted. + assert(!request.body || request.body.stream) + + // 8. If request’s window is "client", then set request’s window to request’s + // client, if request’s client’s global object is a Window object; otherwise + // "no-window". + if (request.window === 'client') { + // TODO: What if request.client is null? + request.window = + request.client?.globalObject?.constructor?.name === 'Window' + ? request.client + : 'no-window' + } + + // 9. If request’s origin is "client", then set request’s origin to request’s + // client’s origin. + if (request.origin === 'client') { + // TODO: What if request.client is null? + request.origin = request.client?.origin + } + + // 10. If all of the following conditions are true: + // TODO + + // 11. If request’s policy container is "client", then: + if (request.policyContainer === 'client') { + // 1. If request’s client is non-null, then set request’s policy + // container to a clone of request’s client’s policy container. [HTML] + if (request.client != null) { + request.policyContainer = clonePolicyContainer( + request.client.policyContainer + ) + } else { + // 2. Otherwise, set request’s policy container to a new policy + // container. + request.policyContainer = makePolicyContainer() + } + } + + // 12. If request’s header list does not contain `Accept`, then: + if (!request.headersList.contains('accept')) { + // 1. Let value be `*/*`. + const value = '*/*' + + // 2. A user agent should set value to the first matching statement, if + // any, switching on request’s destination: + // "document" + // "frame" + // "iframe" + // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` + // "image" + // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` + // "style" + // `text/css,*/*;q=0.1` + // TODO + + // 3. Append `Accept`/value to request’s header list. + request.headersList.append('accept', value) + } + + // 13. If request’s header list does not contain `Accept-Language`, then + // user agents should append `Accept-Language`/an appropriate value to + // request’s header list. + if (!request.headersList.contains('accept-language')) { + request.headersList.append('accept-language', '*') + } + + // 14. If request’s priority is null, then use request’s initiator and + // destination appropriately in setting request’s priority to a + // user-agent-defined object. + if (request.priority === null) { + // TODO + } + + // 15. If request is a subresource request, then: + if (subresourceSet.has(request.destination)) { + // TODO + } + + // 16. Run main fetch given fetchParams. + mainFetch(fetchParams) + .catch(err => { + fetchParams.controller.terminate(err) + }) + + // 17. Return fetchParam's controller + return fetchParams.controller +} + +// https://fetch.spec.whatwg.org/#concept-main-fetch +async function mainFetch (fetchParams, recursive = false) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. If request’s local-URLs-only flag is set and request’s current URL is + // not local, then set response to a network error. + if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { + response = makeNetworkError('local URLs only') + } + + // 4. Run report Content Security Policy violations for request. + // TODO + + // 5. Upgrade request to a potentially trustworthy URL, if appropriate. + tryUpgradeRequestToAPotentiallyTrustworthyURL(request) + + // 6. If should request be blocked due to a bad port, should fetching request + // be blocked as mixed content, or should request be blocked by Content + // Security Policy returns blocked, then set response to a network error. + if (requestBadPort(request) === 'blocked') { + response = makeNetworkError('bad port') + } + // TODO: should fetching request be blocked as mixed content? + // TODO: should request be blocked by Content Security Policy? + + // 7. If request’s referrer policy is the empty string, then set request’s + // referrer policy to request’s policy container’s referrer policy. + if (request.referrerPolicy === '') { + request.referrerPolicy = request.policyContainer.referrerPolicy + } + + // 8. If request’s referrer is not "no-referrer", then set request’s + // referrer to the result of invoking determine request’s referrer. + if (request.referrer !== 'no-referrer') { + request.referrer = determineRequestsReferrer(request) + } + + // 9. Set request’s current URL’s scheme to "https" if all of the following + // conditions are true: + // - request’s current URL’s scheme is "http" + // - request’s current URL’s host is a domain + // - Matching request’s current URL’s host per Known HSTS Host Domain Name + // Matching results in either a superdomain match with an asserted + // includeSubDomains directive or a congruent match (with or without an + // asserted includeSubDomains directive). [HSTS] + // TODO + + // 10. If recursive is false, then run the remaining steps in parallel. + // TODO + + // 11. If response is null, then set response to the result of running + // the steps corresponding to the first matching statement: + if (response === null) { + response = await (async () => { + const currentURL = requestCurrentURL(request) + + if ( + // - request’s current URL’s origin is same origin with request’s origin, + // and request’s response tainting is "basic" + (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || + // request’s current URL’s scheme is "data" + (currentURL.protocol === 'data:') || + // - request’s mode is "navigate" or "websocket" + (request.mode === 'navigate' || request.mode === 'websocket') + ) { + // 1. Set request’s response tainting to "basic". + request.responseTainting = 'basic' + + // 2. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s mode is "same-origin" + if (request.mode === 'same-origin') { + // 1. Return a network error. + return makeNetworkError('request mode cannot be "same-origin"') + } + + // request’s mode is "no-cors" + if (request.mode === 'no-cors') { + // 1. If request’s redirect mode is not "follow", then return a network + // error. + if (request.redirect !== 'follow') { + return makeNetworkError( + 'redirect mode cannot be "follow" for "no-cors" request' + ) + } + + // 2. Set request’s response tainting to "opaque". + request.responseTainting = 'opaque' + + // 3. Return the result of running scheme fetch given fetchParams. + return await schemeFetch(fetchParams) + } + + // request’s current URL’s scheme is not an HTTP(S) scheme + if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { + // Return a network error. + return makeNetworkError('URL scheme must be a HTTP(S) scheme') + } + + // - request’s use-CORS-preflight flag is set + // - request’s unsafe-request flag is set and either request’s method is + // not a CORS-safelisted method or CORS-unsafe request-header names with + // request’s header list is not empty + // 1. Set request’s response tainting to "cors". + // 2. Let corsWithPreflightResponse be the result of running HTTP fetch + // given fetchParams and true. + // 3. If corsWithPreflightResponse is a network error, then clear cache + // entries using request. + // 4. Return corsWithPreflightResponse. + // TODO + + // Otherwise + // 1. Set request’s response tainting to "cors". + request.responseTainting = 'cors' + + // 2. Return the result of running HTTP fetch given fetchParams. + return await httpFetch(fetchParams) + })() + } + + // 12. If recursive is true, then return response. + if (recursive) { + return response + } + + // 13. If response is not a network error and response is not a filtered + // response, then: + if (response.status !== 0 && !response.internalResponse) { + // If request’s response tainting is "cors", then: + if (request.responseTainting === 'cors') { + // 1. Let headerNames be the result of extracting header list values + // given `Access-Control-Expose-Headers` and response’s header list. + // TODO + // 2. If request’s credentials mode is not "include" and headerNames + // contains `*`, then set response’s CORS-exposed header-name list to + // all unique header names in response’s header list. + // TODO + // 3. Otherwise, if headerNames is not null or failure, then set + // response’s CORS-exposed header-name list to headerNames. + // TODO + } + + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (request.responseTainting === 'basic') { + response = filterResponse(response, 'basic') + } else if (request.responseTainting === 'cors') { + response = filterResponse(response, 'cors') + } else if (request.responseTainting === 'opaque') { + response = filterResponse(response, 'opaque') + } else { + assert(false) + } + } + + // 14. Let internalResponse be response, if response is a network error, + // and response’s internal response otherwise. + let internalResponse = + response.status === 0 ? response : response.internalResponse + + // 15. If internalResponse’s URL list is empty, then set it to a clone of + // request’s URL list. + if (internalResponse.urlList.length === 0) { + internalResponse.urlList.push(...request.urlList) + } + + // 16. If request’s timing allow failed flag is unset, then set + // internalResponse’s timing allow passed flag. + if (!request.timingAllowFailed) { + response.timingAllowPassed = true + } + + // 17. If response is not a network error and any of the following returns + // blocked + // - should internalResponse to request be blocked as mixed content + // - should internalResponse to request be blocked by Content Security Policy + // - should internalResponse to request be blocked due to its MIME type + // - should internalResponse to request be blocked due to nosniff + // TODO + + // 18. If response’s type is "opaque", internalResponse’s status is 206, + // internalResponse’s range-requested flag is set, and request’s header + // list does not contain `Range`, then set response and internalResponse + // to a network error. + if ( + response.type === 'opaque' && + internalResponse.status === 206 && + internalResponse.rangeRequested && + !request.headers.contains('range') + ) { + response = internalResponse = makeNetworkError() + } + + // 19. If response is not a network error and either request’s method is + // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, + // set internalResponse’s body to null and disregard any enqueuing toward + // it (if any). + if ( + response.status !== 0 && + (request.method === 'HEAD' || + request.method === 'CONNECT' || + nullBodyStatus.includes(internalResponse.status)) + ) { + internalResponse.body = null + fetchParams.controller.dump = true + } + + // 20. If request’s integrity metadata is not the empty string, then: + if (request.integrity) { + // 1. Let processBodyError be this step: run fetch finale given fetchParams + // and a network error. + const processBodyError = (reason) => + fetchFinale(fetchParams, makeNetworkError(reason)) + + // 2. If request’s response tainting is "opaque", or response’s body is null, + // then run processBodyError and abort these steps. + if (request.responseTainting === 'opaque' || response.body == null) { + processBodyError(response.error) + return + } + + // 3. Let processBody given bytes be these steps: + const processBody = (bytes) => { + // 1. If bytes do not match request’s integrity metadata, + // then run processBodyError and abort these steps. [SRI] + if (!bytesMatch(bytes, request.integrity)) { + processBodyError('integrity mismatch') + return + } + + // 2. Set response’s body to bytes as a body. + response.body = safelyExtractBody(bytes)[0] + + // 3. Run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } + + // 4. Fully read response’s body given processBody and processBodyError. + await fullyReadBody(response.body, processBody, processBodyError) + } else { + // 21. Otherwise, run fetch finale given fetchParams and response. + fetchFinale(fetchParams, response) + } +} + +// https://fetch.spec.whatwg.org/#concept-scheme-fetch +// given a fetch params fetchParams +function schemeFetch (fetchParams) { + // Note: since the connection is destroyed on redirect, which sets fetchParams to a + // cancelled state, we do not want this condition to trigger *unless* there have been + // no redirects. See https://github.com/nodejs/undici/issues/1776 + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { + return Promise.resolve(makeAppropriateNetworkError(fetchParams)) + } + + // 2. Let request be fetchParams’s request. + const { request } = fetchParams + + const { protocol: scheme } = requestCurrentURL(request) + + // 3. Switch on request’s current URL’s scheme and run the associated steps: + switch (scheme) { + case 'about:': { + // If request’s current URL’s path is the string "blank", then return a new response + // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », + // and body is the empty byte sequence as a body. + + // Otherwise, return a network error. + return Promise.resolve(makeNetworkError('about scheme is not supported')) + } + case 'blob:': { + if (!resolveObjectURL) { + resolveObjectURL = (__nccwpck_require__(181).resolveObjectURL) + } + + // 1. Let blobURLEntry be request’s current URL’s blob URL entry. + const blobURLEntry = requestCurrentURL(request) + + // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 + // Buffer.resolveObjectURL does not ignore URL queries. + if (blobURLEntry.search.length !== 0) { + return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) + } + + const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) + + // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s + // object is not a Blob object, then return a network error. + if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) { + return Promise.resolve(makeNetworkError('invalid method')) + } + + // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. + const bodyWithType = safelyExtractBody(blobURLEntryObject) + + // 4. Let body be bodyWithType’s body. + const body = bodyWithType[0] + + // 5. Let length be body’s length, serialized and isomorphic encoded. + const length = isomorphicEncode(`${body.length}`) + + // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. + const type = bodyWithType[1] ?? '' + + // 7. Return a new response whose status message is `OK`, header list is + // « (`Content-Length`, length), (`Content-Type`, type) », and body is body. + const response = makeResponse({ + statusText: 'OK', + headersList: [ + ['content-length', { name: 'Content-Length', value: length }], + ['content-type', { name: 'Content-Type', value: type }] + ] + }) + + response.body = body + + return Promise.resolve(response) + } + case 'data:': { + // 1. Let dataURLStruct be the result of running the + // data: URL processor on request’s current URL. + const currentURL = requestCurrentURL(request) + const dataURLStruct = dataURLProcessor(currentURL) + + // 2. If dataURLStruct is failure, then return a + // network error. + if (dataURLStruct === 'failure') { + return Promise.resolve(makeNetworkError('failed to fetch the data URL')) + } + + // 3. Let mimeType be dataURLStruct’s MIME type, serialized. + const mimeType = serializeAMimeType(dataURLStruct.mimeType) + + // 4. Return a response whose status message is `OK`, + // header list is « (`Content-Type`, mimeType) », + // and body is dataURLStruct’s body as a body. + return Promise.resolve(makeResponse({ + statusText: 'OK', + headersList: [ + ['content-type', { name: 'Content-Type', value: mimeType }] + ], + body: safelyExtractBody(dataURLStruct.body)[0] + })) + } + case 'file:': { + // For now, unfortunate as it is, file URLs are left as an exercise for the reader. + // When in doubt, return a network error. + return Promise.resolve(makeNetworkError('not implemented... yet...')) + } + case 'http:': + case 'https:': { + // Return the result of running HTTP fetch given fetchParams. + + return httpFetch(fetchParams) + .catch((err) => makeNetworkError(err)) + } + default: { + return Promise.resolve(makeNetworkError('unknown scheme')) + } + } +} + +// https://fetch.spec.whatwg.org/#finalize-response +function finalizeResponse (fetchParams, response) { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // 2, If fetchParams’s process response done is not null, then queue a fetch + // task to run fetchParams’s process response done given response, with + // fetchParams’s task destination. + if (fetchParams.processResponseDone != null) { + queueMicrotask(() => fetchParams.processResponseDone(response)) + } +} + +// https://fetch.spec.whatwg.org/#fetch-finale +function fetchFinale (fetchParams, response) { + // 1. If response is a network error, then: + if (response.type === 'error') { + // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ». + response.urlList = [fetchParams.request.urlList[0]] + + // 2. Set response’s timing info to the result of creating an opaque timing + // info for fetchParams’s timing info. + response.timingInfo = createOpaqueTimingInfo({ + startTime: fetchParams.timingInfo.startTime + }) + } + + // 2. Let processResponseEndOfBody be the following steps: + const processResponseEndOfBody = () => { + // 1. Set fetchParams’s request’s done flag. + fetchParams.request.done = true + + // If fetchParams’s process response end-of-body is not null, + // then queue a fetch task to run fetchParams’s process response + // end-of-body given response with fetchParams’s task destination. + if (fetchParams.processResponseEndOfBody != null) { + queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) + } + } + + // 3. If fetchParams’s process response is non-null, then queue a fetch task + // to run fetchParams’s process response given response, with fetchParams’s + // task destination. + if (fetchParams.processResponse != null) { + queueMicrotask(() => fetchParams.processResponse(response)) + } + + // 4. If response’s body is null, then run processResponseEndOfBody. + if (response.body == null) { + processResponseEndOfBody() + } else { + // 5. Otherwise: + + // 1. Let transformStream be a new a TransformStream. + + // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, + // enqueues chunk in transformStream. + const identityTransformAlgorithm = (chunk, controller) => { + controller.enqueue(chunk) + } + + // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm + // and flushAlgorithm set to processResponseEndOfBody. + const transformStream = new TransformStream({ + start () {}, + transform: identityTransformAlgorithm, + flush: processResponseEndOfBody + }, { + size () { + return 1 + } + }, { + size () { + return 1 + } + }) + + // 4. Set response’s body to the result of piping response’s body through transformStream. + response.body = { stream: response.body.stream.pipeThrough(transformStream) } + } + + // 6. If fetchParams’s process response consume body is non-null, then: + if (fetchParams.processResponseConsumeBody != null) { + // 1. Let processBody given nullOrBytes be this step: run fetchParams’s + // process response consume body given response and nullOrBytes. + const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes) + + // 2. Let processBodyError be this step: run fetchParams’s process + // response consume body given response and failure. + const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) + + // 3. If response’s body is null, then queue a fetch task to run processBody + // given null, with fetchParams’s task destination. + if (response.body == null) { + queueMicrotask(() => processBody(null)) + } else { + // 4. Otherwise, fully read response’s body given processBody, processBodyError, + // and fetchParams’s task destination. + return fullyReadBody(response.body, processBody, processBodyError) + } + return Promise.resolve() + } +} + +// https://fetch.spec.whatwg.org/#http-fetch +async function httpFetch (fetchParams) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let actualResponse be null. + let actualResponse = null + + // 4. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 5. If request’s service-workers mode is "all", then: + if (request.serviceWorkers === 'all') { + // TODO + } + + // 6. If response is null, then: + if (response === null) { + // 1. If makeCORSPreflight is true and one of these conditions is true: + // TODO + + // 2. If request’s redirect mode is "follow", then set request’s + // service-workers mode to "none". + if (request.redirect === 'follow') { + request.serviceWorkers = 'none' + } + + // 3. Set response and actualResponse to the result of running + // HTTP-network-or-cache fetch given fetchParams. + actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) + + // 4. If request’s response tainting is "cors" and a CORS check + // for request and response returns failure, then return a network error. + if ( + request.responseTainting === 'cors' && + corsCheck(request, response) === 'failure' + ) { + return makeNetworkError('cors failure') + } + + // 5. If the TAO check for request and response returns failure, then set + // request’s timing allow failed flag. + if (TAOCheck(request, response) === 'failure') { + request.timingAllowFailed = true + } + } + + // 7. If either request’s response tainting or response’s type + // is "opaque", and the cross-origin resource policy check with + // request’s origin, request’s client, request’s destination, + // and actualResponse returns blocked, then return a network error. + if ( + (request.responseTainting === 'opaque' || response.type === 'opaque') && + crossOriginResourcePolicyCheck( + request.origin, + request.client, + request.destination, + actualResponse + ) === 'blocked' + ) { + return makeNetworkError('blocked') + } + + // 8. If actualResponse’s status is a redirect status, then: + if (redirectStatusSet.has(actualResponse.status)) { + // 1. If actualResponse’s status is not 303, request’s body is not null, + // and the connection uses HTTP/2, then user agents may, and are even + // encouraged to, transmit an RST_STREAM frame. + // See, https://github.com/whatwg/fetch/issues/1288 + if (request.redirect !== 'manual') { + fetchParams.controller.connection.destroy() + } + + // 2. Switch on request’s redirect mode: + if (request.redirect === 'error') { + // Set response to a network error. + response = makeNetworkError('unexpected redirect') + } else if (request.redirect === 'manual') { + // Set response to an opaque-redirect filtered response whose internal + // response is actualResponse. + // NOTE(spec): On the web this would return an `opaqueredirect` response, + // but that doesn't make sense server side. + // See https://github.com/nodejs/undici/issues/1193. + response = actualResponse + } else if (request.redirect === 'follow') { + // Set response to the result of running HTTP-redirect fetch given + // fetchParams and response. + response = await httpRedirectFetch(fetchParams, response) + } else { + assert(false) + } + } + + // 9. Set response’s timing info to timingInfo. + response.timingInfo = timingInfo + + // 10. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-redirect-fetch +function httpRedirectFetch (fetchParams, response) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let actualResponse be response, if response is not a filtered response, + // and response’s internal response otherwise. + const actualResponse = response.internalResponse + ? response.internalResponse + : response + + // 3. Let locationURL be actualResponse’s location URL given request’s current + // URL’s fragment. + let locationURL + + try { + locationURL = responseLocationURL( + actualResponse, + requestCurrentURL(request).hash + ) + + // 4. If locationURL is null, then return response. + if (locationURL == null) { + return response + } + } catch (err) { + // 5. If locationURL is failure, then return a network error. + return Promise.resolve(makeNetworkError(err)) + } + + // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network + // error. + if (!urlIsHttpHttpsScheme(locationURL)) { + return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) + } + + // 7. If request’s redirect count is 20, then return a network error. + if (request.redirectCount === 20) { + return Promise.resolve(makeNetworkError('redirect count exceeded')) + } + + // 8. Increase request’s redirect count by 1. + request.redirectCount += 1 + + // 9. If request’s mode is "cors", locationURL includes credentials, and + // request’s origin is not same origin with locationURL’s origin, then return + // a network error. + if ( + request.mode === 'cors' && + (locationURL.username || locationURL.password) && + !sameOrigin(request, locationURL) + ) { + return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) + } + + // 10. If request’s response tainting is "cors" and locationURL includes + // credentials, then return a network error. + if ( + request.responseTainting === 'cors' && + (locationURL.username || locationURL.password) + ) { + return Promise.resolve(makeNetworkError( + 'URL cannot contain credentials for request mode "cors"' + )) + } + + // 11. If actualResponse’s status is not 303, request’s body is non-null, + // and request’s body’s source is null, then return a network error. + if ( + actualResponse.status !== 303 && + request.body != null && + request.body.source == null + ) { + return Promise.resolve(makeNetworkError()) + } + + // 12. If one of the following is true + // - actualResponse’s status is 301 or 302 and request’s method is `POST` + // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` + if ( + ([301, 302].includes(actualResponse.status) && request.method === 'POST') || + (actualResponse.status === 303 && + !GET_OR_HEAD.includes(request.method)) + ) { + // then: + // 1. Set request’s method to `GET` and request’s body to null. + request.method = 'GET' + request.body = null + + // 2. For each headerName of request-body-header name, delete headerName from + // request’s header list. + for (const headerName of requestBodyHeader) { + request.headersList.delete(headerName) + } + } + + // 13. If request’s current URL’s origin is not same origin with locationURL’s + // origin, then for each headerName of CORS non-wildcard request-header name, + // delete headerName from request’s header list. + if (!sameOrigin(requestCurrentURL(request), locationURL)) { + // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name + request.headersList.delete('authorization') + + // https://fetch.spec.whatwg.org/#authentication-entries + request.headersList.delete('proxy-authorization', true) + + // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. + request.headersList.delete('cookie') + request.headersList.delete('host') + } + + // 14. If request’s body is non-null, then set request’s body to the first return + // value of safely extracting request’s body’s source. + if (request.body != null) { + assert(request.body.source != null) + request.body = safelyExtractBody(request.body.source)[0] + } + + // 15. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 16. Set timingInfo’s redirect end time and post-redirect start time to the + // coarsened shared current time given fetchParams’s cross-origin isolated + // capability. + timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = + coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) + + // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s + // redirect start time to timingInfo’s start time. + if (timingInfo.redirectStartTime === 0) { + timingInfo.redirectStartTime = timingInfo.startTime + } + + // 18. Append locationURL to request’s URL list. + request.urlList.push(locationURL) + + // 19. Invoke set request’s referrer policy on redirect on request and + // actualResponse. + setRequestReferrerPolicyOnRedirect(request, actualResponse) + + // 20. Return the result of running main fetch given fetchParams and true. + return mainFetch(fetchParams, true) +} + +// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch +async function httpNetworkOrCacheFetch ( + fetchParams, + isAuthenticationFetch = false, + isNewConnectionFetch = false +) { + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let httpFetchParams be null. + let httpFetchParams = null + + // 3. Let httpRequest be null. + let httpRequest = null + + // 4. Let response be null. + let response = null + + // 5. Let storedResponse be null. + // TODO: cache + + // 6. Let httpCache be null. + const httpCache = null + + // 7. Let the revalidatingFlag be unset. + const revalidatingFlag = false + + // 8. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If request’s window is "no-window" and request’s redirect mode is + // "error", then set httpFetchParams to fetchParams and httpRequest to + // request. + if (request.window === 'no-window' && request.redirect === 'error') { + httpFetchParams = fetchParams + httpRequest = request + } else { + // Otherwise: + + // 1. Set httpRequest to a clone of request. + httpRequest = makeRequest(request) + + // 2. Set httpFetchParams to a copy of fetchParams. + httpFetchParams = { ...fetchParams } + + // 3. Set httpFetchParams’s request to httpRequest. + httpFetchParams.request = httpRequest + } + + // 3. Let includeCredentials be true if one of + const includeCredentials = + request.credentials === 'include' || + (request.credentials === 'same-origin' && + request.responseTainting === 'basic') + + // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s + // body is non-null; otherwise null. + const contentLength = httpRequest.body ? httpRequest.body.length : null + + // 5. Let contentLengthHeaderValue be null. + let contentLengthHeaderValue = null + + // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or + // `PUT`, then set contentLengthHeaderValue to `0`. + if ( + httpRequest.body == null && + ['POST', 'PUT'].includes(httpRequest.method) + ) { + contentLengthHeaderValue = '0' + } + + // 7. If contentLength is non-null, then set contentLengthHeaderValue to + // contentLength, serialized and isomorphic encoded. + if (contentLength != null) { + contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) + } + + // 8. If contentLengthHeaderValue is non-null, then append + // `Content-Length`/contentLengthHeaderValue to httpRequest’s header + // list. + if (contentLengthHeaderValue != null) { + httpRequest.headersList.append('content-length', contentLengthHeaderValue) + } + + // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, + // contentLengthHeaderValue) to httpRequest’s header list. + + // 10. If contentLength is non-null and httpRequest’s keepalive is true, + // then: + if (contentLength != null && httpRequest.keepalive) { + // NOTE: keepalive is a noop outside of browser context. + } + + // 11. If httpRequest’s referrer is a URL, then append + // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, + // to httpRequest’s header list. + if (httpRequest.referrer instanceof URL) { + httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href)) + } + + // 12. Append a request `Origin` header for httpRequest. + appendRequestOriginHeader(httpRequest) + + // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] + appendFetchMetadata(httpRequest) + + // 14. If httpRequest’s header list does not contain `User-Agent`, then + // user agents should append `User-Agent`/default `User-Agent` value to + // httpRequest’s header list. + if (!httpRequest.headersList.contains('user-agent')) { + httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node') + } + + // 15. If httpRequest’s cache mode is "default" and httpRequest’s header + // list contains `If-Modified-Since`, `If-None-Match`, + // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set + // httpRequest’s cache mode to "no-store". + if ( + httpRequest.cache === 'default' && + (httpRequest.headersList.contains('if-modified-since') || + httpRequest.headersList.contains('if-none-match') || + httpRequest.headersList.contains('if-unmodified-since') || + httpRequest.headersList.contains('if-match') || + httpRequest.headersList.contains('if-range')) + ) { + httpRequest.cache = 'no-store' + } + + // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent + // no-cache cache-control header modification flag is unset, and + // httpRequest’s header list does not contain `Cache-Control`, then append + // `Cache-Control`/`max-age=0` to httpRequest’s header list. + if ( + httpRequest.cache === 'no-cache' && + !httpRequest.preventNoCacheCacheControlHeaderModification && + !httpRequest.headersList.contains('cache-control') + ) { + httpRequest.headersList.append('cache-control', 'max-age=0') + } + + // 17. If httpRequest’s cache mode is "no-store" or "reload", then: + if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { + // 1. If httpRequest’s header list does not contain `Pragma`, then append + // `Pragma`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('pragma')) { + httpRequest.headersList.append('pragma', 'no-cache') + } + + // 2. If httpRequest’s header list does not contain `Cache-Control`, + // then append `Cache-Control`/`no-cache` to httpRequest’s header list. + if (!httpRequest.headersList.contains('cache-control')) { + httpRequest.headersList.append('cache-control', 'no-cache') + } + } + + // 18. If httpRequest’s header list contains `Range`, then append + // `Accept-Encoding`/`identity` to httpRequest’s header list. + if (httpRequest.headersList.contains('range')) { + httpRequest.headersList.append('accept-encoding', 'identity') + } + + // 19. Modify httpRequest’s header list per HTTP. Do not append a given + // header if httpRequest’s header list contains that header’s name. + // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 + if (!httpRequest.headersList.contains('accept-encoding')) { + if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { + httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate') + } else { + httpRequest.headersList.append('accept-encoding', 'gzip, deflate') + } + } + + httpRequest.headersList.delete('host') + + // 20. If includeCredentials is true, then: + if (includeCredentials) { + // 1. If the user agent is not configured to block cookies for httpRequest + // (see section 7 of [COOKIES]), then: + // TODO: credentials + // 2. If httpRequest’s header list does not contain `Authorization`, then: + // TODO: credentials + } + + // 21. If there’s a proxy-authentication entry, use it as appropriate. + // TODO: proxy-authentication + + // 22. Set httpCache to the result of determining the HTTP cache + // partition, given httpRequest. + // TODO: cache + + // 23. If httpCache is null, then set httpRequest’s cache mode to + // "no-store". + if (httpCache == null) { + httpRequest.cache = 'no-store' + } + + // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", + // then: + if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { + // TODO: cache + } + + // 9. If aborted, then return the appropriate network error for fetchParams. + // TODO + + // 10. If response is null, then: + if (response == null) { + // 1. If httpRequest’s cache mode is "only-if-cached", then return a + // network error. + if (httpRequest.mode === 'only-if-cached') { + return makeNetworkError('only if cached') + } + + // 2. Let forwardResponse be the result of running HTTP-network fetch + // given httpFetchParams, includeCredentials, and isNewConnectionFetch. + const forwardResponse = await httpNetworkFetch( + httpFetchParams, + includeCredentials, + isNewConnectionFetch + ) + + // 3. If httpRequest’s method is unsafe and forwardResponse’s status is + // in the range 200 to 399, inclusive, invalidate appropriate stored + // responses in httpCache, as per the "Invalidation" chapter of HTTP + // Caching, and set storedResponse to null. [HTTP-CACHING] + if ( + !safeMethodsSet.has(httpRequest.method) && + forwardResponse.status >= 200 && + forwardResponse.status <= 399 + ) { + // TODO: cache + } + + // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, + // then: + if (revalidatingFlag && forwardResponse.status === 304) { + // TODO: cache + } + + // 5. If response is null, then: + if (response == null) { + // 1. Set response to forwardResponse. + response = forwardResponse + + // 2. Store httpRequest and forwardResponse in httpCache, as per the + // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] + // TODO: cache + } + } + + // 11. Set response’s URL list to a clone of httpRequest’s URL list. + response.urlList = [...httpRequest.urlList] + + // 12. If httpRequest’s header list contains `Range`, then set response’s + // range-requested flag. + if (httpRequest.headersList.contains('range')) { + response.rangeRequested = true + } + + // 13. Set response’s request-includes-credentials to includeCredentials. + response.requestIncludesCredentials = includeCredentials + + // 14. If response’s status is 401, httpRequest’s response tainting is not + // "cors", includeCredentials is true, and request’s window is an environment + // settings object, then: + // TODO + + // 15. If response’s status is 407, then: + if (response.status === 407) { + // 1. If request’s window is "no-window", then return a network error. + if (request.window === 'no-window') { + return makeNetworkError() + } + + // 2. ??? + + // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 4. Prompt the end user as appropriate in request’s window and store + // the result as a proxy-authentication entry. [HTTP-AUTH] + // TODO: Invoke some kind of callback? + + // 5. Set response to the result of running HTTP-network-or-cache fetch given + // fetchParams. + // TODO + return makeNetworkError('proxy authentication required') + } + + // 16. If all of the following are true + if ( + // response’s status is 421 + response.status === 421 && + // isNewConnectionFetch is false + !isNewConnectionFetch && + // request’s body is null, or request’s body is non-null and request’s body’s source is non-null + (request.body == null || request.body.source != null) + ) { + // then: + + // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. + if (isCancelled(fetchParams)) { + return makeAppropriateNetworkError(fetchParams) + } + + // 2. Set response to the result of running HTTP-network-or-cache + // fetch given fetchParams, isAuthenticationFetch, and true. + + // TODO (spec): The spec doesn't specify this but we need to cancel + // the active response before we can start a new one. + // https://github.com/whatwg/fetch/issues/1293 + fetchParams.controller.connection.destroy() + + response = await httpNetworkOrCacheFetch( + fetchParams, + isAuthenticationFetch, + true + ) + } + + // 17. If isAuthenticationFetch is true, then create an authentication entry + if (isAuthenticationFetch) { + // TODO + } + + // 18. Return response. + return response +} + +// https://fetch.spec.whatwg.org/#http-network-fetch +async function httpNetworkFetch ( + fetchParams, + includeCredentials = false, + forceNewConnection = false +) { + assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) + + fetchParams.controller.connection = { + abort: null, + destroyed: false, + destroy (err) { + if (!this.destroyed) { + this.destroyed = true + this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) + } + } + } + + // 1. Let request be fetchParams’s request. + const request = fetchParams.request + + // 2. Let response be null. + let response = null + + // 3. Let timingInfo be fetchParams’s timing info. + const timingInfo = fetchParams.timingInfo + + // 4. Let httpCache be the result of determining the HTTP cache partition, + // given request. + // TODO: cache + const httpCache = null + + // 5. If httpCache is null, then set request’s cache mode to "no-store". + if (httpCache == null) { + request.cache = 'no-store' + } + + // 6. Let networkPartitionKey be the result of determining the network + // partition key given request. + // TODO + + // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise + // "no". + const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars + + // 8. Switch on request’s mode: + if (request.mode === 'websocket') { + // Let connection be the result of obtaining a WebSocket connection, + // given request’s current URL. + // TODO + } else { + // Let connection be the result of obtaining a connection, given + // networkPartitionKey, request’s current URL’s origin, + // includeCredentials, and forceNewConnection. + // TODO + } + + // 9. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. If connection is failure, then return a network error. + + // 2. Set timingInfo’s final connection timing info to the result of + // calling clamp and coarsen connection timing info with connection’s + // timing info, timingInfo’s post-redirect start time, and fetchParams’s + // cross-origin isolated capability. + + // 3. If connection is not an HTTP/2 connection, request’s body is non-null, + // and request’s body’s source is null, then append (`Transfer-Encoding`, + // `chunked`) to request’s header list. + + // 4. Set timingInfo’s final network-request start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated + // capability. + + // 5. Set response to the result of making an HTTP request over connection + // using request with the following caveats: + + // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] + // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] + + // - If request’s body is non-null, and request’s body’s source is null, + // then the user agent may have a buffer of up to 64 kibibytes and store + // a part of request’s body in that buffer. If the user agent reads from + // request’s body beyond that buffer’s size and the user agent needs to + // resend request, then instead return a network error. + + // - Set timingInfo’s final network-response start time to the coarsened + // shared current time given fetchParams’s cross-origin isolated capability, + // immediately after the user agent’s HTTP parser receives the first byte + // of the response (e.g., frame header bytes for HTTP/2 or response status + // line for HTTP/1.x). + + // - Wait until all the headers are transmitted. + + // - Any responses whose status is in the range 100 to 199, inclusive, + // and is not 101, are to be ignored, except for the purposes of setting + // timingInfo’s final network-response start time above. + + // - If request’s header list contains `Transfer-Encoding`/`chunked` and + // response is transferred via HTTP/1.0 or older, then return a network + // error. + + // - If the HTTP request results in a TLS client certificate dialog, then: + + // 1. If request’s window is an environment settings object, make the + // dialog available in request’s window. + + // 2. Otherwise, return a network error. + + // To transmit request’s body body, run these steps: + let requestBody = null + // 1. If body is null and fetchParams’s process request end-of-body is + // non-null, then queue a fetch task given fetchParams’s process request + // end-of-body and fetchParams’s task destination. + if (request.body == null && fetchParams.processRequestEndOfBody) { + queueMicrotask(() => fetchParams.processRequestEndOfBody()) + } else if (request.body != null) { + // 2. Otherwise, if body is non-null: + + // 1. Let processBodyChunk given bytes be these steps: + const processBodyChunk = async function * (bytes) { + // 1. If the ongoing fetch is terminated, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. Run this step in parallel: transmit bytes. + yield bytes + + // 3. If fetchParams’s process request body is non-null, then run + // fetchParams’s process request body given bytes’s length. + fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) + } + + // 2. Let processEndOfBody be these steps: + const processEndOfBody = () => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If fetchParams’s process request end-of-body is non-null, + // then run fetchParams’s process request end-of-body. + if (fetchParams.processRequestEndOfBody) { + fetchParams.processRequestEndOfBody() + } + } + + // 3. Let processBodyError given e be these steps: + const processBodyError = (e) => { + // 1. If fetchParams is canceled, then abort these steps. + if (isCancelled(fetchParams)) { + return + } + + // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. + if (e.name === 'AbortError') { + fetchParams.controller.abort() + } else { + fetchParams.controller.terminate(e) + } + } + + // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, + // processBodyError, and fetchParams’s task destination. + requestBody = (async function * () { + try { + for await (const bytes of request.body.stream) { + yield * processBodyChunk(bytes) + } + processEndOfBody() + } catch (err) { + processBodyError(err) + } + })() + } + + try { + // socket is only provided for websockets + const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) + + if (socket) { + response = makeResponse({ status, statusText, headersList, socket }) + } else { + const iterator = body[Symbol.asyncIterator]() + fetchParams.controller.next = () => iterator.next() + + response = makeResponse({ status, statusText, headersList }) + } + } catch (err) { + // 10. If aborted, then: + if (err.name === 'AbortError') { + // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. + fetchParams.controller.connection.destroy() + + // 2. Return the appropriate network error for fetchParams. + return makeAppropriateNetworkError(fetchParams, err) + } + + return makeNetworkError(err) + } + + // 11. Let pullAlgorithm be an action that resumes the ongoing fetch + // if it is suspended. + const pullAlgorithm = () => { + fetchParams.controller.resume() + } + + // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s + // controller with reason, given reason. + const cancelAlgorithm = (reason) => { + fetchParams.controller.abort(reason) + } + + // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by + // the user agent. + // TODO + + // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object + // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. + // TODO + + // 15. Let stream be a new ReadableStream. + // 16. Set up stream with pullAlgorithm set to pullAlgorithm, + // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to + // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(3774).ReadableStream) + } + + const stream = new ReadableStream( + { + async start (controller) { + fetchParams.controller.controller = controller + }, + async pull (controller) { + await pullAlgorithm(controller) + }, + async cancel (reason) { + await cancelAlgorithm(reason) + } + }, + { + highWaterMark: 0, + size () { + return 1 + } + } + ) + + // 17. Run these steps, but abort when the ongoing fetch is terminated: + + // 1. Set response’s body to a new body whose stream is stream. + response.body = { stream } + + // 2. If response is not a network error and request’s cache mode is + // not "no-store", then update response in httpCache for request. + // TODO + + // 3. If includeCredentials is true and the user agent is not configured + // to block cookies for request (see section 7 of [COOKIES]), then run the + // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on + // the value of each header whose name is a byte-case-insensitive match for + // `Set-Cookie` in response’s header list, if any, and request’s current URL. + // TODO + + // 18. If aborted, then: + // TODO + + // 19. Run these steps in parallel: + + // 1. Run these steps, but abort when fetchParams is canceled: + fetchParams.controller.on('terminated', onAborted) + fetchParams.controller.resume = async () => { + // 1. While true + while (true) { + // 1-3. See onData... + + // 4. Set bytes to the result of handling content codings given + // codings and bytes. + let bytes + let isFailure + try { + const { done, value } = await fetchParams.controller.next() + + if (isAborted(fetchParams)) { + break + } + + bytes = done ? undefined : value + } catch (err) { + if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { + // zlib doesn't like empty streams. + bytes = undefined + } else { + bytes = err + + // err may be propagated from the result of calling readablestream.cancel, + // which might not be an error. https://github.com/nodejs/undici/issues/2009 + isFailure = true + } + } + + if (bytes === undefined) { + // 2. Otherwise, if the bytes transmission for response’s message + // body is done normally and stream is readable, then close + // stream, finalize response for fetchParams and response, and + // abort these in-parallel steps. + readableStreamClose(fetchParams.controller.controller) + + finalizeResponse(fetchParams, response) + + return + } + + // 5. Increase timingInfo’s decoded body size by bytes’s length. + timingInfo.decodedBodySize += bytes?.byteLength ?? 0 + + // 6. If bytes is failure, then terminate fetchParams’s controller. + if (isFailure) { + fetchParams.controller.terminate(bytes) + return + } + + // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes + // into stream. + fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) + + // 8. If stream is errored, then terminate the ongoing fetch. + if (isErrored(stream)) { + fetchParams.controller.terminate() + return + } + + // 9. If stream doesn’t need more data ask the user agent to suspend + // the ongoing fetch. + if (!fetchParams.controller.controller.desiredSize) { + return + } + } + } + + // 2. If aborted, then: + function onAborted (reason) { + // 2. If fetchParams is aborted, then: + if (isAborted(fetchParams)) { + // 1. Set response’s aborted flag. + response.aborted = true + + // 2. If stream is readable, then error stream with the result of + // deserialize a serialized abort reason given fetchParams’s + // controller’s serialized abort reason and an + // implementation-defined realm. + if (isReadable(stream)) { + fetchParams.controller.controller.error( + fetchParams.controller.serializedAbortReason + ) + } + } else { + // 3. Otherwise, if stream is readable, error stream with a TypeError. + if (isReadable(stream)) { + fetchParams.controller.controller.error(new TypeError('terminated', { + cause: isErrorLike(reason) ? reason : undefined + })) + } + } + + // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. + // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. + fetchParams.controller.connection.destroy() + } + + // 20. Return response. + return response + + async function dispatch ({ body }) { + const url = requestCurrentURL(request) + /** @type {import('../..').Agent} */ + const agent = fetchParams.controller.dispatcher + + return new Promise((resolve, reject) => agent.dispatch( + { + path: url.pathname + url.search, + origin: url.origin, + method: request.method, + body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, + headers: request.headersList.entries, + maxRedirections: 0, + upgrade: request.mode === 'websocket' ? 'websocket' : undefined + }, + { + body: null, + abort: null, + + onConnect (abort) { + // TODO (fix): Do we need connection here? + const { connection } = fetchParams.controller + + if (connection.destroyed) { + abort(new DOMException('The operation was aborted.', 'AbortError')) + } else { + fetchParams.controller.on('terminated', abort) + this.abort = connection.abort = abort + } + }, + + onHeaders (status, headersList, resume, statusText) { + if (status < 200) { + return + } + + let codings = [] + let location = '' + + const headers = new Headers() + + // For H2, the headers are a plain JS object + // We distinguish between them and iterate accordingly + if (Array.isArray(headersList)) { + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()) + } else if (key.toLowerCase() === 'location') { + location = val + } + + headers[kHeadersList].append(key, val) + } + } else { + const keys = Object.keys(headersList) + for (const key of keys) { + const val = headersList[key] + if (key.toLowerCase() === 'content-encoding') { + // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 + // "All content-coding values are case-insensitive..." + codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse() + } else if (key.toLowerCase() === 'location') { + location = val + } + + headers[kHeadersList].append(key, val) + } + } + + this.body = new Readable({ read: resume }) + + const decoders = [] + + const willFollow = request.redirect === 'follow' && + location && + redirectStatusSet.has(status) + + // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding + if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { + for (const coding of codings) { + // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 + if (coding === 'x-gzip' || coding === 'gzip') { + decoders.push(zlib.createGunzip({ + // Be less strict when decoding compressed responses, since sometimes + // servers send slightly invalid responses that are still accepted + // by common browsers. + // Always using Z_SYNC_FLUSH is what cURL does. + flush: zlib.constants.Z_SYNC_FLUSH, + finishFlush: zlib.constants.Z_SYNC_FLUSH + })) + } else if (coding === 'deflate') { + decoders.push(zlib.createInflate()) + } else if (coding === 'br') { + decoders.push(zlib.createBrotliDecompress()) + } else { + decoders.length = 0 + break + } + } + } + + resolve({ + status, + statusText, + headersList: headers[kHeadersList], + body: decoders.length + ? pipeline(this.body, ...decoders, () => { }) + : this.body.on('error', () => {}) + }) + + return true + }, + + onData (chunk) { + if (fetchParams.controller.dump) { + return + } + + // 1. If one or more bytes have been transmitted from response’s + // message body, then: + + // 1. Let bytes be the transmitted bytes. + const bytes = chunk + + // 2. Let codings be the result of extracting header list values + // given `Content-Encoding` and response’s header list. + // See pullAlgorithm. + + // 3. Increase timingInfo’s encoded body size by bytes’s length. + timingInfo.encodedBodySize += bytes.byteLength + + // 4. See pullAlgorithm... + + return this.body.push(bytes) + }, + + onComplete () { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + fetchParams.controller.ended = true + + this.body.push(null) + }, + + onError (error) { + if (this.abort) { + fetchParams.controller.off('terminated', this.abort) + } + + this.body?.destroy(error) + + fetchParams.controller.terminate(error) + + reject(error) + }, + + onUpgrade (status, headersList, socket) { + if (status !== 101) { + return + } + + const headers = new Headers() + + for (let n = 0; n < headersList.length; n += 2) { + const key = headersList[n + 0].toString('latin1') + const val = headersList[n + 1].toString('latin1') + + headers[kHeadersList].append(key, val) + } + + resolve({ + status, + statusText: STATUS_CODES[status], + headersList: headers[kHeadersList], + socket + }) + + return true + } + } + )) + } +} + +module.exports = { + fetch, + Fetch, + fetching, + finalizeAndReportTiming +} + + +/***/ }), + +/***/ 5194: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/* globals AbortController */ + + + +const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(8923) +const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(6349) +const { FinalizationRegistry } = __nccwpck_require__(3194)() +const util = __nccwpck_require__(3440) +const { + isValidHTTPToken, + sameOrigin, + normalizeMethod, + makePolicyContainer, + normalizeMethodRecord +} = __nccwpck_require__(5523) +const { + forbiddenMethodsSet, + corsSafeListedMethodsSet, + referrerPolicy, + requestRedirect, + requestMode, + requestCredentials, + requestCache, + requestDuplex +} = __nccwpck_require__(7326) +const { kEnumerableProperty } = util +const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(9710) +const { webidl } = __nccwpck_require__(4222) +const { getGlobalOrigin } = __nccwpck_require__(5628) +const { URLSerializer } = __nccwpck_require__(4322) +const { kHeadersList, kConstruct } = __nccwpck_require__(6443) +const assert = __nccwpck_require__(2613) +const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(4434) + +let TransformStream = globalThis.TransformStream + +const kAbortController = Symbol('abortController') + +const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { + signal.removeEventListener('abort', abort) +}) + +// https://fetch.spec.whatwg.org/#request-class +class Request { + // https://fetch.spec.whatwg.org/#dom-request + constructor (input, init = {}) { + if (input === kConstruct) { + return + } + + webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) + + input = webidl.converters.RequestInfo(input) + init = webidl.converters.RequestInit(init) + + // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object + this[kRealm] = { + settingsObject: { + baseUrl: getGlobalOrigin(), + get origin () { + return this.baseUrl?.origin + }, + policyContainer: makePolicyContainer() + } + } + + // 1. Let request be null. + let request = null + + // 2. Let fallbackMode be null. + let fallbackMode = null + + // 3. Let baseURL be this’s relevant settings object’s API base URL. + const baseUrl = this[kRealm].settingsObject.baseUrl + + // 4. Let signal be null. + let signal = null + + // 5. If input is a string, then: + if (typeof input === 'string') { + // 1. Let parsedURL be the result of parsing input with baseURL. + // 2. If parsedURL is failure, then throw a TypeError. + let parsedURL + try { + parsedURL = new URL(input, baseUrl) + } catch (err) { + throw new TypeError('Failed to parse URL from ' + input, { cause: err }) + } + + // 3. If parsedURL includes credentials, then throw a TypeError. + if (parsedURL.username || parsedURL.password) { + throw new TypeError( + 'Request cannot be constructed from a URL that includes credentials: ' + + input + ) + } + + // 4. Set request to a new request whose URL is parsedURL. + request = makeRequest({ urlList: [parsedURL] }) + + // 5. Set fallbackMode to "cors". + fallbackMode = 'cors' + } else { + // 6. Otherwise: + + // 7. Assert: input is a Request object. + assert(input instanceof Request) + + // 8. Set request to input’s request. + request = input[kState] + + // 9. Set signal to input’s signal. + signal = input[kSignal] + } + + // 7. Let origin be this’s relevant settings object’s origin. + const origin = this[kRealm].settingsObject.origin + + // 8. Let window be "client". + let window = 'client' + + // 9. If request’s window is an environment settings object and its origin + // is same origin with origin, then set window to request’s window. + if ( + request.window?.constructor?.name === 'EnvironmentSettingsObject' && + sameOrigin(request.window, origin) + ) { + window = request.window + } + + // 10. If init["window"] exists and is non-null, then throw a TypeError. + if (init.window != null) { + throw new TypeError(`'window' option '${window}' must be null`) + } + + // 11. If init["window"] exists, then set window to "no-window". + if ('window' in init) { + window = 'no-window' + } + + // 12. Set request to a new request with the following properties: + request = makeRequest({ + // URL request’s URL. + // undici implementation note: this is set as the first item in request's urlList in makeRequest + // method request’s method. + method: request.method, + // header list A copy of request’s header list. + // undici implementation note: headersList is cloned in makeRequest + headersList: request.headersList, + // unsafe-request flag Set. + unsafeRequest: request.unsafeRequest, + // client This’s relevant settings object. + client: this[kRealm].settingsObject, + // window window. + window, + // priority request’s priority. + priority: request.priority, + // origin request’s origin. The propagation of the origin is only significant for navigation requests + // being handled by a service worker. In this scenario a request can have an origin that is different + // from the current client. + origin: request.origin, + // referrer request’s referrer. + referrer: request.referrer, + // referrer policy request’s referrer policy. + referrerPolicy: request.referrerPolicy, + // mode request’s mode. + mode: request.mode, + // credentials mode request’s credentials mode. + credentials: request.credentials, + // cache mode request’s cache mode. + cache: request.cache, + // redirect mode request’s redirect mode. + redirect: request.redirect, + // integrity metadata request’s integrity metadata. + integrity: request.integrity, + // keepalive request’s keepalive. + keepalive: request.keepalive, + // reload-navigation flag request’s reload-navigation flag. + reloadNavigation: request.reloadNavigation, + // history-navigation flag request’s history-navigation flag. + historyNavigation: request.historyNavigation, + // URL list A clone of request’s URL list. + urlList: [...request.urlList] + }) + + const initHasKey = Object.keys(init).length !== 0 + + // 13. If init is not empty, then: + if (initHasKey) { + // 1. If request’s mode is "navigate", then set it to "same-origin". + if (request.mode === 'navigate') { + request.mode = 'same-origin' + } + + // 2. Unset request’s reload-navigation flag. + request.reloadNavigation = false + + // 3. Unset request’s history-navigation flag. + request.historyNavigation = false + + // 4. Set request’s origin to "client". + request.origin = 'client' + + // 5. Set request’s referrer to "client" + request.referrer = 'client' + + // 6. Set request’s referrer policy to the empty string. + request.referrerPolicy = '' + + // 7. Set request’s URL to request’s current URL. + request.url = request.urlList[request.urlList.length - 1] + + // 8. Set request’s URL list to « request’s URL ». + request.urlList = [request.url] + } + + // 14. If init["referrer"] exists, then: + if (init.referrer !== undefined) { + // 1. Let referrer be init["referrer"]. + const referrer = init.referrer + + // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". + if (referrer === '') { + request.referrer = 'no-referrer' + } else { + // 1. Let parsedReferrer be the result of parsing referrer with + // baseURL. + // 2. If parsedReferrer is failure, then throw a TypeError. + let parsedReferrer + try { + parsedReferrer = new URL(referrer, baseUrl) + } catch (err) { + throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) + } + + // 3. If one of the following is true + // - parsedReferrer’s scheme is "about" and path is the string "client" + // - parsedReferrer’s origin is not same origin with origin + // then set request’s referrer to "client". + if ( + (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || + (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl)) + ) { + request.referrer = 'client' + } else { + // 4. Otherwise, set request’s referrer to parsedReferrer. + request.referrer = parsedReferrer + } + } + } + + // 15. If init["referrerPolicy"] exists, then set request’s referrer policy + // to it. + if (init.referrerPolicy !== undefined) { + request.referrerPolicy = init.referrerPolicy + } + + // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. + let mode + if (init.mode !== undefined) { + mode = init.mode + } else { + mode = fallbackMode + } + + // 17. If mode is "navigate", then throw a TypeError. + if (mode === 'navigate') { + throw webidl.errors.exception({ + header: 'Request constructor', + message: 'invalid request mode navigate.' + }) + } + + // 18. If mode is non-null, set request’s mode to mode. + if (mode != null) { + request.mode = mode + } + + // 19. If init["credentials"] exists, then set request’s credentials mode + // to it. + if (init.credentials !== undefined) { + request.credentials = init.credentials + } + + // 18. If init["cache"] exists, then set request’s cache mode to it. + if (init.cache !== undefined) { + request.cache = init.cache + } + + // 21. If request’s cache mode is "only-if-cached" and request’s mode is + // not "same-origin", then throw a TypeError. + if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { + throw new TypeError( + "'only-if-cached' can be set only with 'same-origin' mode" + ) + } + + // 22. If init["redirect"] exists, then set request’s redirect mode to it. + if (init.redirect !== undefined) { + request.redirect = init.redirect + } + + // 23. If init["integrity"] exists, then set request’s integrity metadata to it. + if (init.integrity != null) { + request.integrity = String(init.integrity) + } + + // 24. If init["keepalive"] exists, then set request’s keepalive to it. + if (init.keepalive !== undefined) { + request.keepalive = Boolean(init.keepalive) + } + + // 25. If init["method"] exists, then: + if (init.method !== undefined) { + // 1. Let method be init["method"]. + let method = init.method + + // 2. If method is not a method or method is a forbidden method, then + // throw a TypeError. + if (!isValidHTTPToken(method)) { + throw new TypeError(`'${method}' is not a valid HTTP method.`) + } + + if (forbiddenMethodsSet.has(method.toUpperCase())) { + throw new TypeError(`'${method}' HTTP method is unsupported.`) + } + + // 3. Normalize method. + method = normalizeMethodRecord[method] ?? normalizeMethod(method) + + // 4. Set request’s method to method. + request.method = method + } + + // 26. If init["signal"] exists, then set signal to it. + if (init.signal !== undefined) { + signal = init.signal + } + + // 27. Set this’s request to request. + this[kState] = request + + // 28. Set this’s signal to a new AbortSignal object with this’s relevant + // Realm. + // TODO: could this be simplified with AbortSignal.any + // (https://dom.spec.whatwg.org/#dom-abortsignal-any) + const ac = new AbortController() + this[kSignal] = ac.signal + this[kSignal][kRealm] = this[kRealm] + + // 29. If signal is not null, then make this’s signal follow signal. + if (signal != null) { + if ( + !signal || + typeof signal.aborted !== 'boolean' || + typeof signal.addEventListener !== 'function' + ) { + throw new TypeError( + "Failed to construct 'Request': member signal is not of type AbortSignal." + ) + } + + if (signal.aborted) { + ac.abort(signal.reason) + } else { + // Keep a strong ref to ac while request object + // is alive. This is needed to prevent AbortController + // from being prematurely garbage collected. + // See, https://github.com/nodejs/undici/issues/1926. + this[kAbortController] = ac + + const acRef = new WeakRef(ac) + const abort = function () { + const ac = acRef.deref() + if (ac !== undefined) { + ac.abort(this.reason) + } + } + + // Third-party AbortControllers may not work with these. + // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. + try { + // If the max amount of listeners is equal to the default, increase it + // This is only available in node >= v19.9.0 + if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { + setMaxListeners(100, signal) + } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { + setMaxListeners(100, signal) + } + } catch {} + + util.addAbortListener(signal, abort) + requestFinalizer.register(ac, { signal, abort }) + } + } + + // 30. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is request’s header list and guard is + // "request". + this[kHeaders] = new Headers(kConstruct) + this[kHeaders][kHeadersList] = request.headersList + this[kHeaders][kGuard] = 'request' + this[kHeaders][kRealm] = this[kRealm] + + // 31. If this’s request’s mode is "no-cors", then: + if (mode === 'no-cors') { + // 1. If this’s request’s method is not a CORS-safelisted method, + // then throw a TypeError. + if (!corsSafeListedMethodsSet.has(request.method)) { + throw new TypeError( + `'${request.method} is unsupported in no-cors mode.` + ) + } + + // 2. Set this’s headers’s guard to "request-no-cors". + this[kHeaders][kGuard] = 'request-no-cors' + } + + // 32. If init is not empty, then: + if (initHasKey) { + /** @type {HeadersList} */ + const headersList = this[kHeaders][kHeadersList] + // 1. Let headers be a copy of this’s headers and its associated header + // list. + // 2. If init["headers"] exists, then set headers to init["headers"]. + const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) + + // 3. Empty this’s headers’s header list. + headersList.clear() + + // 4. If headers is a Headers object, then for each header in its header + // list, append header’s name/header’s value to this’s headers. + if (headers instanceof HeadersList) { + for (const [key, val] of headers) { + headersList.append(key, val) + } + // Note: Copy the `set-cookie` meta-data. + headersList.cookies = headers.cookies + } else { + // 5. Otherwise, fill this’s headers with headers. + fillHeaders(this[kHeaders], headers) + } + } + + // 33. Let inputBody be input’s request’s body if input is a Request + // object; otherwise null. + const inputBody = input instanceof Request ? input[kState].body : null + + // 34. If either init["body"] exists and is non-null or inputBody is + // non-null, and request’s method is `GET` or `HEAD`, then throw a + // TypeError. + if ( + (init.body != null || inputBody != null) && + (request.method === 'GET' || request.method === 'HEAD') + ) { + throw new TypeError('Request with GET/HEAD method cannot have body.') + } + + // 35. Let initBody be null. + let initBody = null + + // 36. If init["body"] exists and is non-null, then: + if (init.body != null) { + // 1. Let Content-Type be null. + // 2. Set initBody and Content-Type to the result of extracting + // init["body"], with keepalive set to request’s keepalive. + const [extractedBody, contentType] = extractBody( + init.body, + request.keepalive + ) + initBody = extractedBody + + // 3, If Content-Type is non-null and this’s headers’s header list does + // not contain `Content-Type`, then append `Content-Type`/Content-Type to + // this’s headers. + if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) { + this[kHeaders].append('content-type', contentType) + } + } + + // 37. Let inputOrInitBody be initBody if it is non-null; otherwise + // inputBody. + const inputOrInitBody = initBody ?? inputBody + + // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is + // null, then: + if (inputOrInitBody != null && inputOrInitBody.source == null) { + // 1. If initBody is non-null and init["duplex"] does not exist, + // then throw a TypeError. + if (initBody != null && init.duplex == null) { + throw new TypeError('RequestInit: duplex option is required when sending a body.') + } + + // 2. If this’s request’s mode is neither "same-origin" nor "cors", + // then throw a TypeError. + if (request.mode !== 'same-origin' && request.mode !== 'cors') { + throw new TypeError( + 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' + ) + } + + // 3. Set this’s request’s use-CORS-preflight flag. + request.useCORSPreflightFlag = true + } + + // 39. Let finalBody be inputOrInitBody. + let finalBody = inputOrInitBody + + // 40. If initBody is null and inputBody is non-null, then: + if (initBody == null && inputBody != null) { + // 1. If input is unusable, then throw a TypeError. + if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { + throw new TypeError( + 'Cannot construct a Request with a Request object that has already been used.' + ) + } + + // 2. Set finalBody to the result of creating a proxy for inputBody. + if (!TransformStream) { + TransformStream = (__nccwpck_require__(3774).TransformStream) + } + + // https://streams.spec.whatwg.org/#readablestream-create-a-proxy + const identityTransform = new TransformStream() + inputBody.stream.pipeThrough(identityTransform) + finalBody = { + source: inputBody.source, + length: inputBody.length, + stream: identityTransform.readable + } + } + + // 41. Set this’s request’s body to finalBody. + this[kState].body = finalBody + } + + // Returns request’s HTTP method, which is "GET" by default. + get method () { + webidl.brandCheck(this, Request) + + // The method getter steps are to return this’s request’s method. + return this[kState].method + } + + // Returns the URL of request as a string. + get url () { + webidl.brandCheck(this, Request) + + // The url getter steps are to return this’s request’s URL, serialized. + return URLSerializer(this[kState].url) + } + + // Returns a Headers object consisting of the headers associated with request. + // Note that headers added in the network layer by the user agent will not + // be accounted for in this object, e.g., the "Host" header. + get headers () { + webidl.brandCheck(this, Request) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + // Returns the kind of resource requested by request, e.g., "document" + // or "script". + get destination () { + webidl.brandCheck(this, Request) + + // The destination getter are to return this’s request’s destination. + return this[kState].destination + } + + // Returns the referrer of request. Its value can be a same-origin URL if + // explicitly set in init, the empty string to indicate no referrer, and + // "about:client" when defaulting to the global’s default. This is used + // during fetching to determine the value of the `Referer` header of the + // request being made. + get referrer () { + webidl.brandCheck(this, Request) + + // 1. If this’s request’s referrer is "no-referrer", then return the + // empty string. + if (this[kState].referrer === 'no-referrer') { + return '' + } + + // 2. If this’s request’s referrer is "client", then return + // "about:client". + if (this[kState].referrer === 'client') { + return 'about:client' + } + + // Return this’s request’s referrer, serialized. + return this[kState].referrer.toString() + } + + // Returns the referrer policy associated with request. + // This is used during fetching to compute the value of the request’s + // referrer. + get referrerPolicy () { + webidl.brandCheck(this, Request) + + // The referrerPolicy getter steps are to return this’s request’s referrer policy. + return this[kState].referrerPolicy + } + + // Returns the mode associated with request, which is a string indicating + // whether the request will use CORS, or will be restricted to same-origin + // URLs. + get mode () { + webidl.brandCheck(this, Request) + + // The mode getter steps are to return this’s request’s mode. + return this[kState].mode + } + + // Returns the credentials mode associated with request, + // which is a string indicating whether credentials will be sent with the + // request always, never, or only when sent to a same-origin URL. + get credentials () { + // The credentials getter steps are to return this’s request’s credentials mode. + return this[kState].credentials + } + + // Returns the cache mode associated with request, + // which is a string indicating how the request will + // interact with the browser’s cache when fetching. + get cache () { + webidl.brandCheck(this, Request) + + // The cache getter steps are to return this’s request’s cache mode. + return this[kState].cache + } + + // Returns the redirect mode associated with request, + // which is a string indicating how redirects for the + // request will be handled during fetching. A request + // will follow redirects by default. + get redirect () { + webidl.brandCheck(this, Request) + + // The redirect getter steps are to return this’s request’s redirect mode. + return this[kState].redirect + } + + // Returns request’s subresource integrity metadata, which is a + // cryptographic hash of the resource being fetched. Its value + // consists of multiple hashes separated by whitespace. [SRI] + get integrity () { + webidl.brandCheck(this, Request) + + // The integrity getter steps are to return this’s request’s integrity + // metadata. + return this[kState].integrity + } + + // Returns a boolean indicating whether or not request can outlive the + // global in which it was created. + get keepalive () { + webidl.brandCheck(this, Request) + + // The keepalive getter steps are to return this’s request’s keepalive. + return this[kState].keepalive + } + + // Returns a boolean indicating whether or not request is for a reload + // navigation. + get isReloadNavigation () { + webidl.brandCheck(this, Request) + + // The isReloadNavigation getter steps are to return true if this’s + // request’s reload-navigation flag is set; otherwise false. + return this[kState].reloadNavigation + } + + // Returns a boolean indicating whether or not request is for a history + // navigation (a.k.a. back-foward navigation). + get isHistoryNavigation () { + webidl.brandCheck(this, Request) + + // The isHistoryNavigation getter steps are to return true if this’s request’s + // history-navigation flag is set; otherwise false. + return this[kState].historyNavigation + } + + // Returns the signal associated with request, which is an AbortSignal + // object indicating whether or not request has been aborted, and its + // abort event handler. + get signal () { + webidl.brandCheck(this, Request) + + // The signal getter steps are to return this’s signal. + return this[kSignal] + } + + get body () { + webidl.brandCheck(this, Request) + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Request) + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + get duplex () { + webidl.brandCheck(this, Request) + + return 'half' + } + + // Returns a clone of request. + clone () { + webidl.brandCheck(this, Request) + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || this.body?.locked) { + throw new TypeError('unusable') + } + + // 2. Let clonedRequest be the result of cloning this’s request. + const clonedRequest = cloneRequest(this[kState]) + + // 3. Let clonedRequestObject be the result of creating a Request object, + // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. + const clonedRequestObject = new Request(kConstruct) + clonedRequestObject[kState] = clonedRequest + clonedRequestObject[kRealm] = this[kRealm] + clonedRequestObject[kHeaders] = new Headers(kConstruct) + clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList + clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] + + // 4. Make clonedRequestObject’s signal follow this’s signal. + const ac = new AbortController() + if (this.signal.aborted) { + ac.abort(this.signal.reason) + } else { + util.addAbortListener( + this.signal, + () => { + ac.abort(this.signal.reason) + } + ) + } + clonedRequestObject[kSignal] = ac.signal + + // 4. Return clonedRequestObject. + return clonedRequestObject + } +} + +mixinBody(Request) + +function makeRequest (init) { + // https://fetch.spec.whatwg.org/#requests + const request = { + method: 'GET', + localURLsOnly: false, + unsafeRequest: false, + body: null, + client: null, + reservedClient: null, + replacesClientId: '', + window: 'client', + keepalive: false, + serviceWorkers: 'all', + initiator: '', + destination: '', + priority: null, + origin: 'client', + policyContainer: 'client', + referrer: 'client', + referrerPolicy: '', + mode: 'no-cors', + useCORSPreflightFlag: false, + credentials: 'same-origin', + useCredentials: false, + cache: 'default', + redirect: 'follow', + integrity: '', + cryptoGraphicsNonceMetadata: '', + parserMetadata: '', + reloadNavigation: false, + historyNavigation: false, + userActivation: false, + taintedOrigin: false, + redirectCount: 0, + responseTainting: 'basic', + preventNoCacheCacheControlHeaderModification: false, + done: false, + timingAllowFailed: false, + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList() + } + request.url = request.urlList[0] + return request +} + +// https://fetch.spec.whatwg.org/#concept-request-clone +function cloneRequest (request) { + // To clone a request request, run these steps: + + // 1. Let newRequest be a copy of request, except for its body. + const newRequest = makeRequest({ ...request, body: null }) + + // 2. If request’s body is non-null, set newRequest’s body to the + // result of cloning request’s body. + if (request.body != null) { + newRequest.body = cloneBody(request.body) + } + + // 3. Return newRequest. + return newRequest +} + +Object.defineProperties(Request.prototype, { + method: kEnumerableProperty, + url: kEnumerableProperty, + headers: kEnumerableProperty, + redirect: kEnumerableProperty, + clone: kEnumerableProperty, + signal: kEnumerableProperty, + duplex: kEnumerableProperty, + destination: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + isHistoryNavigation: kEnumerableProperty, + isReloadNavigation: kEnumerableProperty, + keepalive: kEnumerableProperty, + integrity: kEnumerableProperty, + cache: kEnumerableProperty, + credentials: kEnumerableProperty, + attribute: kEnumerableProperty, + referrerPolicy: kEnumerableProperty, + referrer: kEnumerableProperty, + mode: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Request', + configurable: true + } +}) + +webidl.converters.Request = webidl.interfaceConverter( + Request +) + +// https://fetch.spec.whatwg.org/#requestinfo +webidl.converters.RequestInfo = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (V instanceof Request) { + return webidl.converters.Request(V) + } + + return webidl.converters.USVString(V) +} + +webidl.converters.AbortSignal = webidl.interfaceConverter( + AbortSignal +) + +// https://fetch.spec.whatwg.org/#requestinit +webidl.converters.RequestInit = webidl.dictionaryConverter([ + { + key: 'method', + converter: webidl.converters.ByteString + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + }, + { + key: 'body', + converter: webidl.nullableConverter( + webidl.converters.BodyInit + ) + }, + { + key: 'referrer', + converter: webidl.converters.USVString + }, + { + key: 'referrerPolicy', + converter: webidl.converters.DOMString, + // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy + allowedValues: referrerPolicy + }, + { + key: 'mode', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#concept-request-mode + allowedValues: requestMode + }, + { + key: 'credentials', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcredentials + allowedValues: requestCredentials + }, + { + key: 'cache', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestcache + allowedValues: requestCache + }, + { + key: 'redirect', + converter: webidl.converters.DOMString, + // https://fetch.spec.whatwg.org/#requestredirect + allowedValues: requestRedirect + }, + { + key: 'integrity', + converter: webidl.converters.DOMString + }, + { + key: 'keepalive', + converter: webidl.converters.boolean + }, + { + key: 'signal', + converter: webidl.nullableConverter( + (signal) => webidl.converters.AbortSignal( + signal, + { strict: false } + ) + ) + }, + { + key: 'window', + converter: webidl.converters.any + }, + { + key: 'duplex', + converter: webidl.converters.DOMString, + allowedValues: requestDuplex + } +]) + +module.exports = { Request, makeRequest } + + +/***/ }), + +/***/ 8676: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { Headers, HeadersList, fill } = __nccwpck_require__(6349) +const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(8923) +const util = __nccwpck_require__(3440) +const { kEnumerableProperty } = util +const { + isValidReasonPhrase, + isCancelled, + isAborted, + isBlobLike, + serializeJavascriptValueToJSONString, + isErrorLike, + isomorphicEncode +} = __nccwpck_require__(5523) +const { + redirectStatusSet, + nullBodyStatus, + DOMException +} = __nccwpck_require__(7326) +const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) +const { webidl } = __nccwpck_require__(4222) +const { FormData } = __nccwpck_require__(3073) +const { getGlobalOrigin } = __nccwpck_require__(5628) +const { URLSerializer } = __nccwpck_require__(4322) +const { kHeadersList, kConstruct } = __nccwpck_require__(6443) +const assert = __nccwpck_require__(2613) +const { types } = __nccwpck_require__(9023) + +const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(3774).ReadableStream) +const textEncoder = new TextEncoder('utf-8') + +// https://fetch.spec.whatwg.org/#response-class +class Response { + // Creates network error Response. + static error () { + // TODO + const relevantRealm = { settingsObject: {} } + + // The static error() method steps are to return the result of creating a + // Response object, given a new network error, "immutable", and this’s + // relevant Realm. + const responseObject = new Response() + responseObject[kState] = makeNetworkError() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response-json + static json (data, init = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) + + if (init !== null) { + init = webidl.converters.ResponseInit(init) + } + + // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. + const bytes = textEncoder.encode( + serializeJavascriptValueToJSONString(data) + ) + + // 2. Let body be the result of extracting bytes. + const body = extractBody(bytes) + + // 3. Let responseObject be the result of creating a Response object, given a new response, + // "response", and this’s relevant Realm. + const relevantRealm = { settingsObject: {} } + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'response' + responseObject[kHeaders][kRealm] = relevantRealm + + // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). + initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) + + // 5. Return responseObject. + return responseObject + } + + // Creates a redirect Response that redirects to url with status status. + static redirect (url, status = 302) { + const relevantRealm = { settingsObject: {} } + + webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) + + url = webidl.converters.USVString(url) + status = webidl.converters['unsigned short'](status) + + // 1. Let parsedURL be the result of parsing url with current settings + // object’s API base URL. + // 2. If parsedURL is failure, then throw a TypeError. + // TODO: base-URL? + let parsedURL + try { + parsedURL = new URL(url, getGlobalOrigin()) + } catch (err) { + throw Object.assign(new TypeError('Failed to parse URL from ' + url), { + cause: err + }) + } + + // 3. If status is not a redirect status, then throw a RangeError. + if (!redirectStatusSet.has(status)) { + throw new RangeError('Invalid status code ' + status) + } + + // 4. Let responseObject be the result of creating a Response object, + // given a new response, "immutable", and this’s relevant Realm. + const responseObject = new Response() + responseObject[kRealm] = relevantRealm + responseObject[kHeaders][kGuard] = 'immutable' + responseObject[kHeaders][kRealm] = relevantRealm + + // 5. Set responseObject’s response’s status to status. + responseObject[kState].status = status + + // 6. Let value be parsedURL, serialized and isomorphic encoded. + const value = isomorphicEncode(URLSerializer(parsedURL)) + + // 7. Append `Location`/value to responseObject’s response’s header list. + responseObject[kState].headersList.append('location', value) + + // 8. Return responseObject. + return responseObject + } + + // https://fetch.spec.whatwg.org/#dom-response + constructor (body = null, init = {}) { + if (body !== null) { + body = webidl.converters.BodyInit(body) + } + + init = webidl.converters.ResponseInit(init) + + // TODO + this[kRealm] = { settingsObject: {} } + + // 1. Set this’s response to a new response. + this[kState] = makeResponse({}) + + // 2. Set this’s headers to a new Headers object with this’s relevant + // Realm, whose header list is this’s response’s header list and guard + // is "response". + this[kHeaders] = new Headers(kConstruct) + this[kHeaders][kGuard] = 'response' + this[kHeaders][kHeadersList] = this[kState].headersList + this[kHeaders][kRealm] = this[kRealm] + + // 3. Let bodyWithType be null. + let bodyWithType = null + + // 4. If body is non-null, then set bodyWithType to the result of extracting body. + if (body != null) { + const [extractedBody, type] = extractBody(body) + bodyWithType = { body: extractedBody, type } + } + + // 5. Perform initialize a response given this, init, and bodyWithType. + initializeResponse(this, init, bodyWithType) + } + + // Returns response’s type, e.g., "cors". + get type () { + webidl.brandCheck(this, Response) + + // The type getter steps are to return this’s response’s type. + return this[kState].type + } + + // Returns response’s URL, if it has one; otherwise the empty string. + get url () { + webidl.brandCheck(this, Response) + + const urlList = this[kState].urlList + + // The url getter steps are to return the empty string if this’s + // response’s URL is null; otherwise this’s response’s URL, + // serialized with exclude fragment set to true. + const url = urlList[urlList.length - 1] ?? null + + if (url === null) { + return '' + } + + return URLSerializer(url, true) + } + + // Returns whether response was obtained through a redirect. + get redirected () { + webidl.brandCheck(this, Response) + + // The redirected getter steps are to return true if this’s response’s URL + // list has more than one item; otherwise false. + return this[kState].urlList.length > 1 + } + + // Returns response’s status. + get status () { + webidl.brandCheck(this, Response) + + // The status getter steps are to return this’s response’s status. + return this[kState].status + } + + // Returns whether response’s status is an ok status. + get ok () { + webidl.brandCheck(this, Response) + + // The ok getter steps are to return true if this’s response’s status is an + // ok status; otherwise false. + return this[kState].status >= 200 && this[kState].status <= 299 + } + + // Returns response’s status message. + get statusText () { + webidl.brandCheck(this, Response) + + // The statusText getter steps are to return this’s response’s status + // message. + return this[kState].statusText + } + + // Returns response’s headers as Headers. + get headers () { + webidl.brandCheck(this, Response) + + // The headers getter steps are to return this’s headers. + return this[kHeaders] + } + + get body () { + webidl.brandCheck(this, Response) + + return this[kState].body ? this[kState].body.stream : null + } + + get bodyUsed () { + webidl.brandCheck(this, Response) + + return !!this[kState].body && util.isDisturbed(this[kState].body.stream) + } + + // Returns a clone of response. + clone () { + webidl.brandCheck(this, Response) + + // 1. If this is unusable, then throw a TypeError. + if (this.bodyUsed || (this.body && this.body.locked)) { + throw webidl.errors.exception({ + header: 'Response.clone', + message: 'Body has already been consumed.' + }) + } + + // 2. Let clonedResponse be the result of cloning this’s response. + const clonedResponse = cloneResponse(this[kState]) + + // 3. Return the result of creating a Response object, given + // clonedResponse, this’s headers’s guard, and this’s relevant Realm. + const clonedResponseObject = new Response() + clonedResponseObject[kState] = clonedResponse + clonedResponseObject[kRealm] = this[kRealm] + clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList + clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard] + clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm] + + return clonedResponseObject + } +} + +mixinBody(Response) + +Object.defineProperties(Response.prototype, { + type: kEnumerableProperty, + url: kEnumerableProperty, + status: kEnumerableProperty, + ok: kEnumerableProperty, + redirected: kEnumerableProperty, + statusText: kEnumerableProperty, + headers: kEnumerableProperty, + clone: kEnumerableProperty, + body: kEnumerableProperty, + bodyUsed: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'Response', + configurable: true + } +}) + +Object.defineProperties(Response, { + json: kEnumerableProperty, + redirect: kEnumerableProperty, + error: kEnumerableProperty +}) + +// https://fetch.spec.whatwg.org/#concept-response-clone +function cloneResponse (response) { + // To clone a response response, run these steps: + + // 1. If response is a filtered response, then return a new identical + // filtered response whose internal response is a clone of response’s + // internal response. + if (response.internalResponse) { + return filterResponse( + cloneResponse(response.internalResponse), + response.type + ) + } + + // 2. Let newResponse be a copy of response, except for its body. + const newResponse = makeResponse({ ...response, body: null }) + + // 3. If response’s body is non-null, then set newResponse’s body to the + // result of cloning response’s body. + if (response.body != null) { + newResponse.body = cloneBody(response.body) + } + + // 4. Return newResponse. + return newResponse +} + +function makeResponse (init) { + return { + aborted: false, + rangeRequested: false, + timingAllowPassed: false, + requestIncludesCredentials: false, + type: 'default', + status: 200, + timingInfo: null, + cacheState: '', + statusText: '', + ...init, + headersList: init.headersList + ? new HeadersList(init.headersList) + : new HeadersList(), + urlList: init.urlList ? [...init.urlList] : [] + } +} + +function makeNetworkError (reason) { + const isError = isErrorLike(reason) + return makeResponse({ + type: 'error', + status: 0, + error: isError + ? reason + : new Error(reason ? String(reason) : reason), + aborted: reason && reason.name === 'AbortError' + }) +} + +function makeFilteredResponse (response, state) { + state = { + internalResponse: response, + ...state + } + + return new Proxy(response, { + get (target, p) { + return p in state ? state[p] : target[p] + }, + set (target, p, value) { + assert(!(p in state)) + target[p] = value + return true + } + }) +} + +// https://fetch.spec.whatwg.org/#concept-filtered-response +function filterResponse (response, type) { + // Set response to the following filtered response with response as its + // internal response, depending on request’s response tainting: + if (type === 'basic') { + // A basic filtered response is a filtered response whose type is "basic" + // and header list excludes any headers in internal response’s header list + // whose name is a forbidden response-header name. + + // Note: undici does not implement forbidden response-header names + return makeFilteredResponse(response, { + type: 'basic', + headersList: response.headersList + }) + } else if (type === 'cors') { + // A CORS filtered response is a filtered response whose type is "cors" + // and header list excludes any headers in internal response’s header + // list whose name is not a CORS-safelisted response-header name, given + // internal response’s CORS-exposed header-name list. + + // Note: undici does not implement CORS-safelisted response-header names + return makeFilteredResponse(response, { + type: 'cors', + headersList: response.headersList + }) + } else if (type === 'opaque') { + // An opaque filtered response is a filtered response whose type is + // "opaque", URL list is the empty list, status is 0, status message + // is the empty byte sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaque', + urlList: Object.freeze([]), + status: 0, + statusText: '', + body: null + }) + } else if (type === 'opaqueredirect') { + // An opaque-redirect filtered response is a filtered response whose type + // is "opaqueredirect", status is 0, status message is the empty byte + // sequence, header list is empty, and body is null. + + return makeFilteredResponse(response, { + type: 'opaqueredirect', + status: 0, + statusText: '', + headersList: [], + body: null + }) + } else { + assert(false) + } +} + +// https://fetch.spec.whatwg.org/#appropriate-network-error +function makeAppropriateNetworkError (fetchParams, err = null) { + // 1. Assert: fetchParams is canceled. + assert(isCancelled(fetchParams)) + + // 2. Return an aborted network error if fetchParams is aborted; + // otherwise return a network error. + return isAborted(fetchParams) + ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) + : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) +} + +// https://whatpr.org/fetch/1392.html#initialize-a-response +function initializeResponse (response, init, body) { + // 1. If init["status"] is not in the range 200 to 599, inclusive, then + // throw a RangeError. + if (init.status !== null && (init.status < 200 || init.status > 599)) { + throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') + } + + // 2. If init["statusText"] does not match the reason-phrase token production, + // then throw a TypeError. + if ('statusText' in init && init.statusText != null) { + // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: + // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) + if (!isValidReasonPhrase(String(init.statusText))) { + throw new TypeError('Invalid statusText') + } + } + + // 3. Set response’s response’s status to init["status"]. + if ('status' in init && init.status != null) { + response[kState].status = init.status + } + + // 4. Set response’s response’s status message to init["statusText"]. + if ('statusText' in init && init.statusText != null) { + response[kState].statusText = init.statusText + } + + // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. + if ('headers' in init && init.headers != null) { + fill(response[kHeaders], init.headers) + } + + // 6. If body was given, then: + if (body) { + // 1. If response's status is a null body status, then throw a TypeError. + if (nullBodyStatus.includes(response.status)) { + throw webidl.errors.exception({ + header: 'Response constructor', + message: 'Invalid response status code ' + response.status + }) + } + + // 2. Set response's body to body's body. + response[kState].body = body.body + + // 3. If body's type is non-null and response's header list does not contain + // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. + if (body.type != null && !response[kState].headersList.contains('Content-Type')) { + response[kState].headersList.append('content-type', body.type) + } + } +} + +webidl.converters.ReadableStream = webidl.interfaceConverter( + ReadableStream +) + +webidl.converters.FormData = webidl.interfaceConverter( + FormData +) + +webidl.converters.URLSearchParams = webidl.interfaceConverter( + URLSearchParams +) + +// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit +webidl.converters.XMLHttpRequestBodyInit = function (V) { + if (typeof V === 'string') { + return webidl.converters.USVString(V) + } + + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { + return webidl.converters.BufferSource(V) + } + + if (util.isFormDataLike(V)) { + return webidl.converters.FormData(V, { strict: false }) + } + + if (V instanceof URLSearchParams) { + return webidl.converters.URLSearchParams(V) + } + + return webidl.converters.DOMString(V) +} + +// https://fetch.spec.whatwg.org/#bodyinit +webidl.converters.BodyInit = function (V) { + if (V instanceof ReadableStream) { + return webidl.converters.ReadableStream(V) + } + + // Note: the spec doesn't include async iterables, + // this is an undici extension. + if (V?.[Symbol.asyncIterator]) { + return V + } + + return webidl.converters.XMLHttpRequestBodyInit(V) +} + +webidl.converters.ResponseInit = webidl.dictionaryConverter([ + { + key: 'status', + converter: webidl.converters['unsigned short'], + defaultValue: 200 + }, + { + key: 'statusText', + converter: webidl.converters.ByteString, + defaultValue: '' + }, + { + key: 'headers', + converter: webidl.converters.HeadersInit + } +]) + +module.exports = { + makeNetworkError, + makeResponse, + makeAppropriateNetworkError, + filterResponse, + Response, + cloneResponse +} + + +/***/ }), + +/***/ 9710: +/***/ ((module) => { + + + +module.exports = { + kUrl: Symbol('url'), + kHeaders: Symbol('headers'), + kSignal: Symbol('signal'), + kState: Symbol('state'), + kGuard: Symbol('guard'), + kRealm: Symbol('realm') +} + + +/***/ }), + +/***/ 5523: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(7326) +const { getGlobalOrigin } = __nccwpck_require__(5628) +const { performance } = __nccwpck_require__(2987) +const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3440) +const assert = __nccwpck_require__(2613) +const { isUint8Array } = __nccwpck_require__(8253) + +let supportedHashes = [] + +// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable +/** @type {import('crypto')|undefined} */ +let crypto + +try { + crypto = __nccwpck_require__(6982) + const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] + supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) +/* c8 ignore next 3 */ +} catch { +} + +function responseURL (response) { + // https://fetch.spec.whatwg.org/#responses + // A response has an associated URL. It is a pointer to the last URL + // in response’s URL list and null if response’s URL list is empty. + const urlList = response.urlList + const length = urlList.length + return length === 0 ? null : urlList[length - 1].toString() +} + +// https://fetch.spec.whatwg.org/#concept-response-location-url +function responseLocationURL (response, requestFragment) { + // 1. If response’s status is not a redirect status, then return null. + if (!redirectStatusSet.has(response.status)) { + return null + } + + // 2. Let location be the result of extracting header list values given + // `Location` and response’s header list. + let location = response.headersList.get('location') + + // 3. If location is a header value, then set location to the result of + // parsing location with response’s URL. + if (location !== null && isValidHeaderValue(location)) { + location = new URL(location, responseURL(response)) + } + + // 4. If location is a URL whose fragment is null, then set location’s + // fragment to requestFragment. + if (location && !location.hash) { + location.hash = requestFragment + } + + // 5. Return location. + return location +} + +/** @returns {URL} */ +function requestCurrentURL (request) { + return request.urlList[request.urlList.length - 1] +} + +function requestBadPort (request) { + // 1. Let url be request’s current URL. + const url = requestCurrentURL(request) + + // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, + // then return blocked. + if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { + return 'blocked' + } + + // 3. Return allowed. + return 'allowed' +} + +function isErrorLike (object) { + return object instanceof Error || ( + object?.constructor?.name === 'Error' || + object?.constructor?.name === 'DOMException' + ) +} + +// Check whether |statusText| is a ByteString and +// matches the Reason-Phrase token production. +// RFC 2616: https://tools.ietf.org/html/rfc2616 +// RFC 7230: https://tools.ietf.org/html/rfc7230 +// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" +// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 +function isValidReasonPhrase (statusText) { + for (let i = 0; i < statusText.length; ++i) { + const c = statusText.charCodeAt(i) + if ( + !( + ( + c === 0x09 || // HTAB + (c >= 0x20 && c <= 0x7e) || // SP / VCHAR + (c >= 0x80 && c <= 0xff) + ) // obs-text + ) + ) { + return false + } + } + return true +} + +/** + * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 + * @param {number} c + */ +function isTokenCharCode (c) { + switch (c) { + case 0x22: + case 0x28: + case 0x29: + case 0x2c: + case 0x2f: + case 0x3a: + case 0x3b: + case 0x3c: + case 0x3d: + case 0x3e: + case 0x3f: + case 0x40: + case 0x5b: + case 0x5c: + case 0x5d: + case 0x7b: + case 0x7d: + // DQUOTE and "(),/:;<=>?@[\]{}" + return false + default: + // VCHAR %x21-7E + return c >= 0x21 && c <= 0x7e + } +} + +/** + * @param {string} characters + */ +function isValidHTTPToken (characters) { + if (characters.length === 0) { + return false + } + for (let i = 0; i < characters.length; ++i) { + if (!isTokenCharCode(characters.charCodeAt(i))) { + return false + } + } + return true +} + +/** + * @see https://fetch.spec.whatwg.org/#header-name + * @param {string} potentialValue + */ +function isValidHeaderName (potentialValue) { + return isValidHTTPToken(potentialValue) +} + +/** + * @see https://fetch.spec.whatwg.org/#header-value + * @param {string} potentialValue + */ +function isValidHeaderValue (potentialValue) { + // - Has no leading or trailing HTTP tab or space bytes. + // - Contains no 0x00 (NUL) or HTTP newline bytes. + if ( + potentialValue.startsWith('\t') || + potentialValue.startsWith(' ') || + potentialValue.endsWith('\t') || + potentialValue.endsWith(' ') + ) { + return false + } + + if ( + potentialValue.includes('\0') || + potentialValue.includes('\r') || + potentialValue.includes('\n') + ) { + return false + } + + return true +} + +// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect +function setRequestReferrerPolicyOnRedirect (request, actualResponse) { + // Given a request request and a response actualResponse, this algorithm + // updates request’s referrer policy according to the Referrer-Policy + // header (if any) in actualResponse. + + // 1. Let policy be the result of executing § 8.1 Parse a referrer policy + // from a Referrer-Policy header on actualResponse. + + // 8.1 Parse a referrer policy from a Referrer-Policy header + // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. + const { headersList } = actualResponse + // 2. Let policy be the empty string. + // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. + // 4. Return policy. + const policyHeader = (headersList.get('referrer-policy') ?? '').split(',') + + // Note: As the referrer-policy can contain multiple policies + // separated by comma, we need to loop through all of them + // and pick the first valid one. + // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy + let policy = '' + if (policyHeader.length > 0) { + // The right-most policy takes precedence. + // The left-most policy is the fallback. + for (let i = policyHeader.length; i !== 0; i--) { + const token = policyHeader[i - 1].trim() + if (referrerPolicyTokens.has(token)) { + policy = token + break + } + } + } + + // 2. If policy is not the empty string, then set request’s referrer policy to policy. + if (policy !== '') { + request.referrerPolicy = policy + } +} + +// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check +function crossOriginResourcePolicyCheck () { + // TODO + return 'allowed' +} + +// https://fetch.spec.whatwg.org/#concept-cors-check +function corsCheck () { + // TODO + return 'success' +} + +// https://fetch.spec.whatwg.org/#concept-tao-check +function TAOCheck () { + // TODO + return 'success' +} + +function appendFetchMetadata (httpRequest) { + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header + + // 1. Assert: r’s url is a potentially trustworthy URL. + // TODO + + // 2. Let header be a Structured Header whose value is a token. + let header = null + + // 3. Set header’s value to r’s mode. + header = httpRequest.mode + + // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. + httpRequest.headersList.set('sec-fetch-mode', header) + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header + // TODO + + // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header + // TODO +} + +// https://fetch.spec.whatwg.org/#append-a-request-origin-header +function appendRequestOriginHeader (request) { + // 1. Let serializedOrigin be the result of byte-serializing a request origin with request. + let serializedOrigin = request.origin + + // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list. + if (request.responseTainting === 'cors' || request.mode === 'websocket') { + if (serializedOrigin) { + request.headersList.append('origin', serializedOrigin) + } + + // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: + } else if (request.method !== 'GET' && request.method !== 'HEAD') { + // 1. Switch on request’s referrer policy: + switch (request.referrerPolicy) { + case 'no-referrer': + // Set serializedOrigin to `null`. + serializedOrigin = null + break + case 'no-referrer-when-downgrade': + case 'strict-origin': + case 'strict-origin-when-cross-origin': + // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`. + if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { + serializedOrigin = null + } + break + case 'same-origin': + // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`. + if (!sameOrigin(request, requestCurrentURL(request))) { + serializedOrigin = null + } + break + default: + // Do nothing. + } + + if (serializedOrigin) { + // 2. Append (`Origin`, serializedOrigin) to request’s header list. + request.headersList.append('origin', serializedOrigin) + } + } +} + +function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { + // TODO + return performance.now() +} + +// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info +function createOpaqueTimingInfo (timingInfo) { + return { + startTime: timingInfo.startTime ?? 0, + redirectStartTime: 0, + redirectEndTime: 0, + postRedirectStartTime: timingInfo.startTime ?? 0, + finalServiceWorkerStartTime: 0, + finalNetworkResponseStartTime: 0, + finalNetworkRequestStartTime: 0, + endTime: 0, + encodedBodySize: 0, + decodedBodySize: 0, + finalConnectionTimingInfo: null + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#policy-container +function makePolicyContainer () { + // Note: the fetch spec doesn't make use of embedder policy or CSP list + return { + referrerPolicy: 'strict-origin-when-cross-origin' + } +} + +// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container +function clonePolicyContainer (policyContainer) { + return { + referrerPolicy: policyContainer.referrerPolicy + } +} + +// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer +function determineRequestsReferrer (request) { + // 1. Let policy be request's referrer policy. + const policy = request.referrerPolicy + + // Note: policy cannot (shouldn't) be null or an empty string. + assert(policy) + + // 2. Let environment be request’s client. + + let referrerSource = null + + // 3. Switch on request’s referrer: + if (request.referrer === 'client') { + // Note: node isn't a browser and doesn't implement document/iframes, + // so we bypass this step and replace it with our own. + + const globalOrigin = getGlobalOrigin() + + if (!globalOrigin || globalOrigin.origin === 'null') { + return 'no-referrer' + } + + // note: we need to clone it as it's mutated + referrerSource = new URL(globalOrigin) + } else if (request.referrer instanceof URL) { + // Let referrerSource be request’s referrer. + referrerSource = request.referrer + } + + // 4. Let request’s referrerURL be the result of stripping referrerSource for + // use as a referrer. + let referrerURL = stripURLForReferrer(referrerSource) + + // 5. Let referrerOrigin be the result of stripping referrerSource for use as + // a referrer, with the origin-only flag set to true. + const referrerOrigin = stripURLForReferrer(referrerSource, true) + + // 6. If the result of serializing referrerURL is a string whose length is + // greater than 4096, set referrerURL to referrerOrigin. + if (referrerURL.toString().length > 4096) { + referrerURL = referrerOrigin + } + + const areSameOrigin = sameOrigin(request, referrerURL) + const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && + !isURLPotentiallyTrustworthy(request.url) + + // 8. Execute the switch statements corresponding to the value of policy: + switch (policy) { + case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) + case 'unsafe-url': return referrerURL + case 'same-origin': + return areSameOrigin ? referrerOrigin : 'no-referrer' + case 'origin-when-cross-origin': + return areSameOrigin ? referrerURL : referrerOrigin + case 'strict-origin-when-cross-origin': { + const currentURL = requestCurrentURL(request) + + // 1. If the origin of referrerURL and the origin of request’s current + // URL are the same, then return referrerURL. + if (sameOrigin(referrerURL, currentURL)) { + return referrerURL + } + + // 2. If referrerURL is a potentially trustworthy URL and request’s + // current URL is not a potentially trustworthy URL, then return no + // referrer. + if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { + return 'no-referrer' + } + + // 3. Return referrerOrigin. + return referrerOrigin + } + case 'strict-origin': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + case 'no-referrer-when-downgrade': // eslint-disable-line + /** + * 1. If referrerURL is a potentially trustworthy URL and + * request’s current URL is not a potentially trustworthy URL, + * then return no referrer. + * 2. Return referrerOrigin + */ + + default: // eslint-disable-line + return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin + } +} + +/** + * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url + * @param {URL} url + * @param {boolean|undefined} originOnly + */ +function stripURLForReferrer (url, originOnly) { + // 1. Assert: url is a URL. + assert(url instanceof URL) + + // 2. If url’s scheme is a local scheme, then return no referrer. + if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { + return 'no-referrer' + } + + // 3. Set url’s username to the empty string. + url.username = '' + + // 4. Set url’s password to the empty string. + url.password = '' + + // 5. Set url’s fragment to null. + url.hash = '' + + // 6. If the origin-only flag is true, then: + if (originOnly) { + // 1. Set url’s path to « the empty string ». + url.pathname = '' + + // 2. Set url’s query to null. + url.search = '' + } + + // 7. Return url. + return url +} + +function isURLPotentiallyTrustworthy (url) { + if (!(url instanceof URL)) { + return false + } + + // If child of about, return true + if (url.href === 'about:blank' || url.href === 'about:srcdoc') { + return true + } + + // If scheme is data, return true + if (url.protocol === 'data:') return true + + // If file, return true + if (url.protocol === 'file:') return true + + return isOriginPotentiallyTrustworthy(url.origin) + + function isOriginPotentiallyTrustworthy (origin) { + // If origin is explicitly null, return false + if (origin == null || origin === 'null') return false + + const originAsURL = new URL(origin) + + // If secure, return true + if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { + return true + } + + // If localhost or variants, return true + if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || + (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || + (originAsURL.hostname.endsWith('.localhost'))) { + return true + } + + // If any other, return false + return false + } +} + +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist + * @param {Uint8Array} bytes + * @param {string} metadataList + */ +function bytesMatch (bytes, metadataList) { + // If node is not built with OpenSSL support, we cannot check + // a request's integrity, so allow it by default (the spec will + // allow requests if an invalid hash is given, as precedence). + /* istanbul ignore if: only if node is built with --without-ssl */ + if (crypto === undefined) { + return true + } + + // 1. Let parsedMetadata be the result of parsing metadataList. + const parsedMetadata = parseMetadata(metadataList) + + // 2. If parsedMetadata is no metadata, return true. + if (parsedMetadata === 'no metadata') { + return true + } + + // 3. If response is not eligible for integrity validation, return false. + // TODO + + // 4. If parsedMetadata is the empty set, return true. + if (parsedMetadata.length === 0) { + return true + } + + // 5. Let metadata be the result of getting the strongest + // metadata from parsedMetadata. + const strongest = getStrongestMetadata(parsedMetadata) + const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) + + // 6. For each item in metadata: + for (const item of metadata) { + // 1. Let algorithm be the alg component of item. + const algorithm = item.algo + + // 2. Let expectedValue be the val component of item. + const expectedValue = item.hash + + // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e + // "be liberal with padding". This is annoying, and it's not even in the spec. + + // 3. Let actualValue be the result of applying algorithm to bytes. + let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') + + if (actualValue[actualValue.length - 1] === '=') { + if (actualValue[actualValue.length - 2] === '=') { + actualValue = actualValue.slice(0, -2) + } else { + actualValue = actualValue.slice(0, -1) + } + } + + // 4. If actualValue is a case-sensitive match for expectedValue, + // return true. + if (compareBase64Mixed(actualValue, expectedValue)) { + return true + } + } + + // 7. Return false. + return false +} + +// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options +// https://www.w3.org/TR/CSP2/#source-list-syntax +// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 +const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i + +/** + * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata + * @param {string} metadata + */ +function parseMetadata (metadata) { + // 1. Let result be the empty set. + /** @type {{ algo: string, hash: string }[]} */ + const result = [] + + // 2. Let empty be equal to true. + let empty = true + + // 3. For each token returned by splitting metadata on spaces: + for (const token of metadata.split(' ')) { + // 1. Set empty to false. + empty = false + + // 2. Parse token as a hash-with-options. + const parsedToken = parseHashWithOptions.exec(token) + + // 3. If token does not parse, continue to the next token. + if ( + parsedToken === null || + parsedToken.groups === undefined || + parsedToken.groups.algo === undefined + ) { + // Note: Chromium blocks the request at this point, but Firefox + // gives a warning that an invalid integrity was given. The + // correct behavior is to ignore these, and subsequently not + // check the integrity of the resource. + continue + } + + // 4. Let algorithm be the hash-algo component of token. + const algorithm = parsedToken.groups.algo.toLowerCase() + + // 5. If algorithm is a hash function recognized by the user + // agent, add the parsed token to result. + if (supportedHashes.includes(algorithm)) { + result.push(parsedToken.groups) + } + } + + // 4. Return no metadata if empty is true, otherwise return result. + if (empty === true) { + return 'no metadata' + } + + return result +} + +/** + * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList + */ +function getStrongestMetadata (metadataList) { + // Let algorithm be the algo component of the first item in metadataList. + // Can be sha256 + let algorithm = metadataList[0].algo + // If the algorithm is sha512, then it is the strongest + // and we can return immediately + if (algorithm[3] === '5') { + return algorithm + } + + for (let i = 1; i < metadataList.length; ++i) { + const metadata = metadataList[i] + // If the algorithm is sha512, then it is the strongest + // and we can break the loop immediately + if (metadata.algo[3] === '5') { + algorithm = 'sha512' + break + // If the algorithm is sha384, then a potential sha256 or sha384 is ignored + } else if (algorithm[3] === '3') { + continue + // algorithm is sha256, check if algorithm is sha384 and if so, set it as + // the strongest + } else if (metadata.algo[3] === '3') { + algorithm = 'sha384' + } + } + return algorithm +} + +function filterMetadataListByAlgorithm (metadataList, algorithm) { + if (metadataList.length === 1) { + return metadataList + } + + let pos = 0 + for (let i = 0; i < metadataList.length; ++i) { + if (metadataList[i].algo === algorithm) { + metadataList[pos++] = metadataList[i] + } + } + + metadataList.length = pos + + return metadataList +} + +/** + * Compares two base64 strings, allowing for base64url + * in the second string. + * +* @param {string} actualValue always base64 + * @param {string} expectedValue base64 or base64url + * @returns {boolean} + */ +function compareBase64Mixed (actualValue, expectedValue) { + if (actualValue.length !== expectedValue.length) { + return false + } + for (let i = 0; i < actualValue.length; ++i) { + if (actualValue[i] !== expectedValue[i]) { + if ( + (actualValue[i] === '+' && expectedValue[i] === '-') || + (actualValue[i] === '/' && expectedValue[i] === '_') + ) { + continue + } + return false + } + } + + return true +} + +// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request +function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { + // TODO +} + +/** + * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} + * @param {URL} A + * @param {URL} B + */ +function sameOrigin (A, B) { + // 1. If A and B are the same opaque origin, then return true. + if (A.origin === B.origin && A.origin === 'null') { + return true + } + + // 2. If A and B are both tuple origins and their schemes, + // hosts, and port are identical, then return true. + if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { + return true + } + + // 3. Return false. + return false +} + +function createDeferredPromise () { + let res + let rej + const promise = new Promise((resolve, reject) => { + res = resolve + rej = reject + }) + + return { promise, resolve: res, reject: rej } +} + +function isAborted (fetchParams) { + return fetchParams.controller.state === 'aborted' +} + +function isCancelled (fetchParams) { + return fetchParams.controller.state === 'aborted' || + fetchParams.controller.state === 'terminated' +} + +const normalizeMethodRecord = { + delete: 'DELETE', + DELETE: 'DELETE', + get: 'GET', + GET: 'GET', + head: 'HEAD', + HEAD: 'HEAD', + options: 'OPTIONS', + OPTIONS: 'OPTIONS', + post: 'POST', + POST: 'POST', + put: 'PUT', + PUT: 'PUT' +} + +// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. +Object.setPrototypeOf(normalizeMethodRecord, null) + +/** + * @see https://fetch.spec.whatwg.org/#concept-method-normalize + * @param {string} method + */ +function normalizeMethod (method) { + return normalizeMethodRecord[method.toLowerCase()] ?? method +} + +// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string +function serializeJavascriptValueToJSONString (value) { + // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). + const result = JSON.stringify(value) + + // 2. If result is undefined, then throw a TypeError. + if (result === undefined) { + throw new TypeError('Value is not JSON serializable') + } + + // 3. Assert: result is a string. + assert(typeof result === 'string') + + // 4. Return result. + return result +} + +// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object +const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) + +/** + * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object + * @param {() => unknown[]} iterator + * @param {string} name name of the instance + * @param {'key'|'value'|'key+value'} kind + */ +function makeIterator (iterator, name, kind) { + const object = { + index: 0, + kind, + target: iterator + } + + const i = { + next () { + // 1. Let interface be the interface for which the iterator prototype object exists. + + // 2. Let thisValue be the this value. + + // 3. Let object be ? ToObject(thisValue). + + // 4. If object is a platform object, then perform a security + // check, passing: + + // 5. If object is not a default iterator object for interface, + // then throw a TypeError. + if (Object.getPrototypeOf(this) !== i) { + throw new TypeError( + `'next' called on an object that does not implement interface ${name} Iterator.` + ) + } + + // 6. Let index be object’s index. + // 7. Let kind be object’s kind. + // 8. Let values be object’s target's value pairs to iterate over. + const { index, kind, target } = object + const values = target() + + // 9. Let len be the length of values. + const len = values.length + + // 10. If index is greater than or equal to len, then return + // CreateIterResultObject(undefined, true). + if (index >= len) { + return { value: undefined, done: true } + } + + // 11. Let pair be the entry in values at index index. + const pair = values[index] + + // 12. Set object’s index to index + 1. + object.index = index + 1 + + // 13. Return the iterator result for pair and kind. + return iteratorResult(pair, kind) + }, + // The class string of an iterator prototype object for a given interface is the + // result of concatenating the identifier of the interface and the string " Iterator". + [Symbol.toStringTag]: `${name} Iterator` + } + + // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. + Object.setPrototypeOf(i, esIteratorPrototype) + // esIteratorPrototype needs to be the prototype of i + // which is the prototype of an empty object. Yes, it's confusing. + return Object.setPrototypeOf({}, i) +} + +// https://webidl.spec.whatwg.org/#iterator-result +function iteratorResult (pair, kind) { + let result + + // 1. Let result be a value determined by the value of kind: + switch (kind) { + case 'key': { + // 1. Let idlKey be pair’s key. + // 2. Let key be the result of converting idlKey to an + // ECMAScript value. + // 3. result is key. + result = pair[0] + break + } + case 'value': { + // 1. Let idlValue be pair’s value. + // 2. Let value be the result of converting idlValue to + // an ECMAScript value. + // 3. result is value. + result = pair[1] + break + } + case 'key+value': { + // 1. Let idlKey be pair’s key. + // 2. Let idlValue be pair’s value. + // 3. Let key be the result of converting idlKey to an + // ECMAScript value. + // 4. Let value be the result of converting idlValue to + // an ECMAScript value. + // 5. Let array be ! ArrayCreate(2). + // 6. Call ! CreateDataProperty(array, "0", key). + // 7. Call ! CreateDataProperty(array, "1", value). + // 8. result is array. + result = pair + break + } + } + + // 2. Return CreateIterResultObject(result, false). + return { value: result, done: false } +} + +/** + * @see https://fetch.spec.whatwg.org/#body-fully-read + */ +async function fullyReadBody (body, processBody, processBodyError) { + // 1. If taskDestination is null, then set taskDestination to + // the result of starting a new parallel queue. + + // 2. Let successSteps given a byte sequence bytes be to queue a + // fetch task to run processBody given bytes, with taskDestination. + const successSteps = processBody + + // 3. Let errorSteps be to queue a fetch task to run processBodyError, + // with taskDestination. + const errorSteps = processBodyError + + // 4. Let reader be the result of getting a reader for body’s stream. + // If that threw an exception, then run errorSteps with that + // exception and return. + let reader + + try { + reader = body.stream.getReader() + } catch (e) { + errorSteps(e) + return + } + + // 5. Read all bytes from reader, given successSteps and errorSteps. + try { + const result = await readAllBytes(reader) + successSteps(result) + } catch (e) { + errorSteps(e) + } +} + +/** @type {ReadableStream} */ +let ReadableStream = globalThis.ReadableStream + +function isReadableStreamLike (stream) { + if (!ReadableStream) { + ReadableStream = (__nccwpck_require__(3774).ReadableStream) + } + + return stream instanceof ReadableStream || ( + stream[Symbol.toStringTag] === 'ReadableStream' && + typeof stream.tee === 'function' + ) +} + +const MAXIMUM_ARGUMENT_LENGTH = 65535 + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-decode + * @param {number[]|Uint8Array} input + */ +function isomorphicDecode (input) { + // 1. To isomorphic decode a byte sequence input, return a string whose code point + // length is equal to input’s length and whose code points have the same values + // as the values of input’s bytes, in the same order. + + if (input.length < MAXIMUM_ARGUMENT_LENGTH) { + return String.fromCharCode(...input) + } + + return input.reduce((previous, current) => previous + String.fromCharCode(current), '') +} + +/** + * @param {ReadableStreamController} controller + */ +function readableStreamClose (controller) { + try { + controller.close() + } catch (err) { + // TODO: add comment explaining why this error occurs. + if (!err.message.includes('Controller is already closed')) { + throw err + } + } +} + +/** + * @see https://infra.spec.whatwg.org/#isomorphic-encode + * @param {string} input + */ +function isomorphicEncode (input) { + // 1. Assert: input contains no code points greater than U+00FF. + for (let i = 0; i < input.length; i++) { + assert(input.charCodeAt(i) <= 0xFF) + } + + // 2. Return a byte sequence whose length is equal to input’s code + // point length and whose bytes have the same values as the + // values of input’s code points, in the same order + return input +} + +/** + * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes + * @see https://streams.spec.whatwg.org/#read-loop + * @param {ReadableStreamDefaultReader} reader + */ +async function readAllBytes (reader) { + const bytes = [] + let byteLength = 0 + + while (true) { + const { done, value: chunk } = await reader.read() + + if (done) { + // 1. Call successSteps with bytes. + return Buffer.concat(bytes, byteLength) + } + + // 1. If chunk is not a Uint8Array object, call failureSteps + // with a TypeError and abort these steps. + if (!isUint8Array(chunk)) { + throw new TypeError('Received non-Uint8Array chunk') + } + + // 2. Append the bytes represented by chunk to bytes. + bytes.push(chunk) + byteLength += chunk.length + + // 3. Read-loop given reader, bytes, successSteps, and failureSteps. + } +} + +/** + * @see https://fetch.spec.whatwg.org/#is-local + * @param {URL} url + */ +function urlIsLocal (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' +} + +/** + * @param {string|URL} url + */ +function urlHasHttpsScheme (url) { + if (typeof url === 'string') { + return url.startsWith('https:') + } + + return url.protocol === 'https:' +} + +/** + * @see https://fetch.spec.whatwg.org/#http-scheme + * @param {URL} url + */ +function urlIsHttpHttpsScheme (url) { + assert('protocol' in url) // ensure it's a url object + + const protocol = url.protocol + + return protocol === 'http:' || protocol === 'https:' +} + +/** + * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0. + */ +const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key)) + +module.exports = { + isAborted, + isCancelled, + createDeferredPromise, + ReadableStreamFrom, + toUSVString, + tryUpgradeRequestToAPotentiallyTrustworthyURL, + coarsenedSharedCurrentTime, + determineRequestsReferrer, + makePolicyContainer, + clonePolicyContainer, + appendFetchMetadata, + appendRequestOriginHeader, + TAOCheck, + corsCheck, + crossOriginResourcePolicyCheck, + createOpaqueTimingInfo, + setRequestReferrerPolicyOnRedirect, + isValidHTTPToken, + requestBadPort, + requestCurrentURL, + responseURL, + responseLocationURL, + isBlobLike, + isURLPotentiallyTrustworthy, + isValidReasonPhrase, + sameOrigin, + normalizeMethod, + serializeJavascriptValueToJSONString, + makeIterator, + isValidHeaderName, + isValidHeaderValue, + hasOwn, + isErrorLike, + fullyReadBody, + bytesMatch, + isReadableStreamLike, + readableStreamClose, + isomorphicEncode, + isomorphicDecode, + urlIsLocal, + urlHasHttpsScheme, + urlIsHttpHttpsScheme, + readAllBytes, + normalizeMethodRecord, + parseMetadata +} + + +/***/ }), + +/***/ 4222: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { types } = __nccwpck_require__(9023) +const { hasOwn, toUSVString } = __nccwpck_require__(5523) + +/** @type {import('../../types/webidl').Webidl} */ +const webidl = {} +webidl.converters = {} +webidl.util = {} +webidl.errors = {} + +webidl.errors.exception = function (message) { + return new TypeError(`${message.header}: ${message.message}`) +} + +webidl.errors.conversionFailed = function (context) { + const plural = context.types.length === 1 ? '' : ' one of' + const message = + `${context.argument} could not be converted to` + + `${plural}: ${context.types.join(', ')}.` + + return webidl.errors.exception({ + header: context.prefix, + message + }) +} + +webidl.errors.invalidArgument = function (context) { + return webidl.errors.exception({ + header: context.prefix, + message: `"${context.value}" is an invalid ${context.type}.` + }) +} + +// https://webidl.spec.whatwg.org/#implements +webidl.brandCheck = function (V, I, opts = undefined) { + if (opts?.strict !== false && !(V instanceof I)) { + throw new TypeError('Illegal invocation') + } else { + return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] + } +} + +webidl.argumentLengthCheck = function ({ length }, min, ctx) { + if (length < min) { + throw webidl.errors.exception({ + message: `${min} argument${min !== 1 ? 's' : ''} required, ` + + `but${length ? ' only' : ''} ${length} found.`, + ...ctx + }) + } +} + +webidl.illegalConstructor = function () { + throw webidl.errors.exception({ + header: 'TypeError', + message: 'Illegal constructor' + }) +} + +// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values +webidl.util.Type = function (V) { + switch (typeof V) { + case 'undefined': return 'Undefined' + case 'boolean': return 'Boolean' + case 'string': return 'String' + case 'symbol': return 'Symbol' + case 'number': return 'Number' + case 'bigint': return 'BigInt' + case 'function': + case 'object': { + if (V === null) { + return 'Null' + } + + return 'Object' + } + } +} + +// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint +webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { + let upperBound + let lowerBound + + // 1. If bitLength is 64, then: + if (bitLength === 64) { + // 1. Let upperBound be 2^53 − 1. + upperBound = Math.pow(2, 53) - 1 + + // 2. If signedness is "unsigned", then let lowerBound be 0. + if (signedness === 'unsigned') { + lowerBound = 0 + } else { + // 3. Otherwise let lowerBound be −2^53 + 1. + lowerBound = Math.pow(-2, 53) + 1 + } + } else if (signedness === 'unsigned') { + // 2. Otherwise, if signedness is "unsigned", then: + + // 1. Let lowerBound be 0. + lowerBound = 0 + + // 2. Let upperBound be 2^bitLength − 1. + upperBound = Math.pow(2, bitLength) - 1 + } else { + // 3. Otherwise: + + // 1. Let lowerBound be -2^bitLength − 1. + lowerBound = Math.pow(-2, bitLength) - 1 + + // 2. Let upperBound be 2^bitLength − 1 − 1. + upperBound = Math.pow(2, bitLength - 1) - 1 + } + + // 4. Let x be ? ToNumber(V). + let x = Number(V) + + // 5. If x is −0, then set x to +0. + if (x === 0) { + x = 0 + } + + // 6. If the conversion is to an IDL type associated + // with the [EnforceRange] extended attribute, then: + if (opts.enforceRange === true) { + // 1. If x is NaN, +∞, or −∞, then throw a TypeError. + if ( + Number.isNaN(x) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Could not convert ${V} to an integer.` + }) + } + + // 2. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 3. If x < lowerBound or x > upperBound, then + // throw a TypeError. + if (x < lowerBound || x > upperBound) { + throw webidl.errors.exception({ + header: 'Integer conversion', + message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` + }) + } + + // 4. Return x. + return x + } + + // 7. If x is not NaN and the conversion is to an IDL + // type associated with the [Clamp] extended + // attribute, then: + if (!Number.isNaN(x) && opts.clamp === true) { + // 1. Set x to min(max(x, lowerBound), upperBound). + x = Math.min(Math.max(x, lowerBound), upperBound) + + // 2. Round x to the nearest integer, choosing the + // even integer if it lies halfway between two, + // and choosing +0 rather than −0. + if (Math.floor(x) % 2 === 0) { + x = Math.floor(x) + } else { + x = Math.ceil(x) + } + + // 3. Return x. + return x + } + + // 8. If x is NaN, +0, +∞, or −∞, then return +0. + if ( + Number.isNaN(x) || + (x === 0 && Object.is(0, x)) || + x === Number.POSITIVE_INFINITY || + x === Number.NEGATIVE_INFINITY + ) { + return 0 + } + + // 9. Set x to IntegerPart(x). + x = webidl.util.IntegerPart(x) + + // 10. Set x to x modulo 2^bitLength. + x = x % Math.pow(2, bitLength) + + // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, + // then return x − 2^bitLength. + if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { + return x - Math.pow(2, bitLength) + } + + // 12. Otherwise, return x. + return x +} + +// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart +webidl.util.IntegerPart = function (n) { + // 1. Let r be floor(abs(n)). + const r = Math.floor(Math.abs(n)) + + // 2. If n < 0, then return -1 × r. + if (n < 0) { + return -1 * r + } + + // 3. Otherwise, return r. + return r +} + +// https://webidl.spec.whatwg.org/#es-sequence +webidl.sequenceConverter = function (converter) { + return (V) => { + // 1. If Type(V) is not Object, throw a TypeError. + if (webidl.util.Type(V) !== 'Object') { + throw webidl.errors.exception({ + header: 'Sequence', + message: `Value of type ${webidl.util.Type(V)} is not an Object.` + }) + } + + // 2. Let method be ? GetMethod(V, @@iterator). + /** @type {Generator} */ + const method = V?.[Symbol.iterator]?.() + const seq = [] + + // 3. If method is undefined, throw a TypeError. + if ( + method === undefined || + typeof method.next !== 'function' + ) { + throw webidl.errors.exception({ + header: 'Sequence', + message: 'Object is not an iterator.' + }) + } + + // https://webidl.spec.whatwg.org/#create-sequence-from-iterable + while (true) { + const { done, value } = method.next() + + if (done) { + break + } + + seq.push(converter(value)) + } + + return seq + } +} + +// https://webidl.spec.whatwg.org/#es-to-record +webidl.recordConverter = function (keyConverter, valueConverter) { + return (O) => { + // 1. If Type(O) is not Object, throw a TypeError. + if (webidl.util.Type(O) !== 'Object') { + throw webidl.errors.exception({ + header: 'Record', + message: `Value of type ${webidl.util.Type(O)} is not an Object.` + }) + } + + // 2. Let result be a new empty instance of record. + const result = {} + + if (!types.isProxy(O)) { + // Object.keys only returns enumerable properties + const keys = Object.keys(O) + + for (const key of keys) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + + // 5. Return result. + return result + } + + // 3. Let keys be ? O.[[OwnPropertyKeys]](). + const keys = Reflect.ownKeys(O) + + // 4. For each key of keys. + for (const key of keys) { + // 1. Let desc be ? O.[[GetOwnProperty]](key). + const desc = Reflect.getOwnPropertyDescriptor(O, key) + + // 2. If desc is not undefined and desc.[[Enumerable]] is true: + if (desc?.enumerable) { + // 1. Let typedKey be key converted to an IDL value of type K. + const typedKey = keyConverter(key) + + // 2. Let value be ? Get(O, key). + // 3. Let typedValue be value converted to an IDL value of type V. + const typedValue = valueConverter(O[key]) + + // 4. Set result[typedKey] to typedValue. + result[typedKey] = typedValue + } + } + + // 5. Return result. + return result + } +} + +webidl.interfaceConverter = function (i) { + return (V, opts = {}) => { + if (opts.strict !== false && !(V instanceof i)) { + throw webidl.errors.exception({ + header: i.name, + message: `Expected ${V} to be an instance of ${i.name}.` + }) + } + + return V + } +} + +webidl.dictionaryConverter = function (converters) { + return (dictionary) => { + const type = webidl.util.Type(dictionary) + const dict = {} + + if (type === 'Null' || type === 'Undefined') { + return dict + } else if (type !== 'Object') { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` + }) + } + + for (const options of converters) { + const { key, defaultValue, required, converter } = options + + if (required === true) { + if (!hasOwn(dictionary, key)) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `Missing required key "${key}".` + }) + } + } + + let value = dictionary[key] + const hasDefault = hasOwn(options, 'defaultValue') + + // Only use defaultValue if value is undefined and + // a defaultValue options was provided. + if (hasDefault && value !== null) { + value = value ?? defaultValue + } + + // A key can be optional and have no default value. + // When this happens, do not perform a conversion, + // and do not assign the key a value. + if (required || hasDefault || value !== undefined) { + value = converter(value) + + if ( + options.allowedValues && + !options.allowedValues.includes(value) + ) { + throw webidl.errors.exception({ + header: 'Dictionary', + message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` + }) + } + + dict[key] = value + } + } + + return dict + } +} + +webidl.nullableConverter = function (converter) { + return (V) => { + if (V === null) { + return V + } + + return converter(V) + } +} + +// https://webidl.spec.whatwg.org/#es-DOMString +webidl.converters.DOMString = function (V, opts = {}) { + // 1. If V is null and the conversion is to an IDL type + // associated with the [LegacyNullToEmptyString] + // extended attribute, then return the DOMString value + // that represents the empty string. + if (V === null && opts.legacyNullToEmptyString) { + return '' + } + + // 2. Let x be ? ToString(V). + if (typeof V === 'symbol') { + throw new TypeError('Could not convert argument of type symbol to string.') + } + + // 3. Return the IDL DOMString value that represents the + // same sequence of code units as the one the + // ECMAScript String value x represents. + return String(V) +} + +// https://webidl.spec.whatwg.org/#es-ByteString +webidl.converters.ByteString = function (V) { + // 1. Let x be ? ToString(V). + // Note: DOMString converter perform ? ToString(V) + const x = webidl.converters.DOMString(V) + + // 2. If the value of any element of x is greater than + // 255, then throw a TypeError. + for (let index = 0; index < x.length; index++) { + if (x.charCodeAt(index) > 255) { + throw new TypeError( + 'Cannot convert argument to a ByteString because the character at ' + + `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` + ) + } + } + + // 3. Return an IDL ByteString value whose length is the + // length of x, and where the value of each element is + // the value of the corresponding element of x. + return x +} + +// https://webidl.spec.whatwg.org/#es-USVString +webidl.converters.USVString = toUSVString + +// https://webidl.spec.whatwg.org/#es-boolean +webidl.converters.boolean = function (V) { + // 1. Let x be the result of computing ToBoolean(V). + const x = Boolean(V) + + // 2. Return the IDL boolean value that is the one that represents + // the same truth value as the ECMAScript Boolean value x. + return x +} + +// https://webidl.spec.whatwg.org/#es-any +webidl.converters.any = function (V) { + return V +} + +// https://webidl.spec.whatwg.org/#es-long-long +webidl.converters['long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "signed"). + const x = webidl.util.ConvertToInt(V, 64, 'signed') + + // 2. Return the IDL long long value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long-long +webidl.converters['unsigned long long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). + const x = webidl.util.ConvertToInt(V, 64, 'unsigned') + + // 2. Return the IDL unsigned long long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-long +webidl.converters['unsigned long'] = function (V) { + // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). + const x = webidl.util.ConvertToInt(V, 32, 'unsigned') + + // 2. Return the IDL unsigned long value that + // represents the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#es-unsigned-short +webidl.converters['unsigned short'] = function (V, opts) { + // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). + const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts) + + // 2. Return the IDL unsigned short value that represents + // the same numeric value as x. + return x +} + +// https://webidl.spec.whatwg.org/#idl-ArrayBuffer +webidl.converters.ArrayBuffer = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have an + // [[ArrayBufferData]] internal slot, then throw a + // TypeError. + // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances + // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances + if ( + webidl.util.Type(V) !== 'Object' || + !types.isAnyArrayBuffer(V) + ) { + throw webidl.errors.conversionFailed({ + prefix: `${V}`, + argument: `${V}`, + types: ['ArrayBuffer'] + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V) is true, then throw a + // TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V) is true, then throw a + // TypeError. + // Note: resizable ArrayBuffers are currently a proposal. + + // 4. Return the IDL ArrayBuffer value that is a + // reference to the same object as V. + return V +} + +webidl.converters.TypedArray = function (V, T, opts = {}) { + // 1. Let T be the IDL type V is being converted to. + + // 2. If Type(V) is not Object, or V does not have a + // [[TypedArrayName]] internal slot with a value + // equal to T’s name, then throw a TypeError. + if ( + webidl.util.Type(V) !== 'Object' || + !types.isTypedArray(V) || + V.constructor.name !== T.name + ) { + throw webidl.errors.conversionFailed({ + prefix: `${T.name}`, + argument: `${V}`, + types: [T.name] + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 4. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable array buffers are currently a proposal + + // 5. Return the IDL value of type T that is a reference + // to the same object as V. + return V +} + +webidl.converters.DataView = function (V, opts = {}) { + // 1. If Type(V) is not Object, or V does not have a + // [[DataView]] internal slot, then throw a TypeError. + if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { + throw webidl.errors.exception({ + header: 'DataView', + message: 'Object is not a DataView.' + }) + } + + // 2. If the conversion is not to an IDL type associated + // with the [AllowShared] extended attribute, and + // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, + // then throw a TypeError. + if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { + throw webidl.errors.exception({ + header: 'ArrayBuffer', + message: 'SharedArrayBuffer is not allowed.' + }) + } + + // 3. If the conversion is not to an IDL type associated + // with the [AllowResizable] extended attribute, and + // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is + // true, then throw a TypeError. + // Note: resizable ArrayBuffers are currently a proposal + + // 4. Return the IDL DataView value that is a reference + // to the same object as V. + return V +} + +// https://webidl.spec.whatwg.org/#BufferSource +webidl.converters.BufferSource = function (V, opts = {}) { + if (types.isAnyArrayBuffer(V)) { + return webidl.converters.ArrayBuffer(V, opts) + } + + if (types.isTypedArray(V)) { + return webidl.converters.TypedArray(V, V.constructor) + } + + if (types.isDataView(V)) { + return webidl.converters.DataView(V, opts) + } + + throw new TypeError(`Could not convert ${V} to a BufferSource.`) +} + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.ByteString +) + +webidl.converters['sequence>'] = webidl.sequenceConverter( + webidl.converters['sequence'] +) + +webidl.converters['record'] = webidl.recordConverter( + webidl.converters.ByteString, + webidl.converters.ByteString +) + +module.exports = { + webidl +} + + +/***/ }), + +/***/ 396: +/***/ ((module) => { + + + +/** + * @see https://encoding.spec.whatwg.org/#concept-encoding-get + * @param {string|undefined} label + */ +function getEncoding (label) { + if (!label) { + return 'failure' + } + + // 1. Remove any leading and trailing ASCII whitespace from label. + // 2. If label is an ASCII case-insensitive match for any of the + // labels listed in the table below, then return the + // corresponding encoding; otherwise return failure. + switch (label.trim().toLowerCase()) { + case 'unicode-1-1-utf-8': + case 'unicode11utf8': + case 'unicode20utf8': + case 'utf-8': + case 'utf8': + case 'x-unicode20utf8': + return 'UTF-8' + case '866': + case 'cp866': + case 'csibm866': + case 'ibm866': + return 'IBM866' + case 'csisolatin2': + case 'iso-8859-2': + case 'iso-ir-101': + case 'iso8859-2': + case 'iso88592': + case 'iso_8859-2': + case 'iso_8859-2:1987': + case 'l2': + case 'latin2': + return 'ISO-8859-2' + case 'csisolatin3': + case 'iso-8859-3': + case 'iso-ir-109': + case 'iso8859-3': + case 'iso88593': + case 'iso_8859-3': + case 'iso_8859-3:1988': + case 'l3': + case 'latin3': + return 'ISO-8859-3' + case 'csisolatin4': + case 'iso-8859-4': + case 'iso-ir-110': + case 'iso8859-4': + case 'iso88594': + case 'iso_8859-4': + case 'iso_8859-4:1988': + case 'l4': + case 'latin4': + return 'ISO-8859-4' + case 'csisolatincyrillic': + case 'cyrillic': + case 'iso-8859-5': + case 'iso-ir-144': + case 'iso8859-5': + case 'iso88595': + case 'iso_8859-5': + case 'iso_8859-5:1988': + return 'ISO-8859-5' + case 'arabic': + case 'asmo-708': + case 'csiso88596e': + case 'csiso88596i': + case 'csisolatinarabic': + case 'ecma-114': + case 'iso-8859-6': + case 'iso-8859-6-e': + case 'iso-8859-6-i': + case 'iso-ir-127': + case 'iso8859-6': + case 'iso88596': + case 'iso_8859-6': + case 'iso_8859-6:1987': + return 'ISO-8859-6' + case 'csisolatingreek': + case 'ecma-118': + case 'elot_928': + case 'greek': + case 'greek8': + case 'iso-8859-7': + case 'iso-ir-126': + case 'iso8859-7': + case 'iso88597': + case 'iso_8859-7': + case 'iso_8859-7:1987': + case 'sun_eu_greek': + return 'ISO-8859-7' + case 'csiso88598e': + case 'csisolatinhebrew': + case 'hebrew': + case 'iso-8859-8': + case 'iso-8859-8-e': + case 'iso-ir-138': + case 'iso8859-8': + case 'iso88598': + case 'iso_8859-8': + case 'iso_8859-8:1988': + case 'visual': + return 'ISO-8859-8' + case 'csiso88598i': + case 'iso-8859-8-i': + case 'logical': + return 'ISO-8859-8-I' + case 'csisolatin6': + case 'iso-8859-10': + case 'iso-ir-157': + case 'iso8859-10': + case 'iso885910': + case 'l6': + case 'latin6': + return 'ISO-8859-10' + case 'iso-8859-13': + case 'iso8859-13': + case 'iso885913': + return 'ISO-8859-13' + case 'iso-8859-14': + case 'iso8859-14': + case 'iso885914': + return 'ISO-8859-14' + case 'csisolatin9': + case 'iso-8859-15': + case 'iso8859-15': + case 'iso885915': + case 'iso_8859-15': + case 'l9': + return 'ISO-8859-15' + case 'iso-8859-16': + return 'ISO-8859-16' + case 'cskoi8r': + case 'koi': + case 'koi8': + case 'koi8-r': + case 'koi8_r': + return 'KOI8-R' + case 'koi8-ru': + case 'koi8-u': + return 'KOI8-U' + case 'csmacintosh': + case 'mac': + case 'macintosh': + case 'x-mac-roman': + return 'macintosh' + case 'iso-8859-11': + case 'iso8859-11': + case 'iso885911': + case 'tis-620': + case 'windows-874': + return 'windows-874' + case 'cp1250': + case 'windows-1250': + case 'x-cp1250': + return 'windows-1250' + case 'cp1251': + case 'windows-1251': + case 'x-cp1251': + return 'windows-1251' + case 'ansi_x3.4-1968': + case 'ascii': + case 'cp1252': + case 'cp819': + case 'csisolatin1': + case 'ibm819': + case 'iso-8859-1': + case 'iso-ir-100': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'iso_8859-1:1987': + case 'l1': + case 'latin1': + case 'us-ascii': + case 'windows-1252': + case 'x-cp1252': + return 'windows-1252' + case 'cp1253': + case 'windows-1253': + case 'x-cp1253': + return 'windows-1253' + case 'cp1254': + case 'csisolatin5': + case 'iso-8859-9': + case 'iso-ir-148': + case 'iso8859-9': + case 'iso88599': + case 'iso_8859-9': + case 'iso_8859-9:1989': + case 'l5': + case 'latin5': + case 'windows-1254': + case 'x-cp1254': + return 'windows-1254' + case 'cp1255': + case 'windows-1255': + case 'x-cp1255': + return 'windows-1255' + case 'cp1256': + case 'windows-1256': + case 'x-cp1256': + return 'windows-1256' + case 'cp1257': + case 'windows-1257': + case 'x-cp1257': + return 'windows-1257' + case 'cp1258': + case 'windows-1258': + case 'x-cp1258': + return 'windows-1258' + case 'x-mac-cyrillic': + case 'x-mac-ukrainian': + return 'x-mac-cyrillic' + case 'chinese': + case 'csgb2312': + case 'csiso58gb231280': + case 'gb2312': + case 'gb_2312': + case 'gb_2312-80': + case 'gbk': + case 'iso-ir-58': + case 'x-gbk': + return 'GBK' + case 'gb18030': + return 'gb18030' + case 'big5': + case 'big5-hkscs': + case 'cn-big5': + case 'csbig5': + case 'x-x-big5': + return 'Big5' + case 'cseucpkdfmtjapanese': + case 'euc-jp': + case 'x-euc-jp': + return 'EUC-JP' + case 'csiso2022jp': + case 'iso-2022-jp': + return 'ISO-2022-JP' + case 'csshiftjis': + case 'ms932': + case 'ms_kanji': + case 'shift-jis': + case 'shift_jis': + case 'sjis': + case 'windows-31j': + case 'x-sjis': + return 'Shift_JIS' + case 'cseuckr': + case 'csksc56011987': + case 'euc-kr': + case 'iso-ir-149': + case 'korean': + case 'ks_c_5601-1987': + case 'ks_c_5601-1989': + case 'ksc5601': + case 'ksc_5601': + case 'windows-949': + return 'EUC-KR' + case 'csiso2022kr': + case 'hz-gb-2312': + case 'iso-2022-cn': + case 'iso-2022-cn-ext': + case 'iso-2022-kr': + case 'replacement': + return 'replacement' + case 'unicodefffe': + case 'utf-16be': + return 'UTF-16BE' + case 'csunicode': + case 'iso-10646-ucs-2': + case 'ucs-2': + case 'unicode': + case 'unicodefeff': + case 'utf-16': + case 'utf-16le': + return 'UTF-16LE' + case 'x-user-defined': + return 'x-user-defined' + default: return 'failure' + } +} + +module.exports = { + getEncoding +} + + +/***/ }), + +/***/ 2160: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} = __nccwpck_require__(165) +const { + kState, + kError, + kResult, + kEvents, + kAborted +} = __nccwpck_require__(6812) +const { webidl } = __nccwpck_require__(4222) +const { kEnumerableProperty } = __nccwpck_require__(3440) + +class FileReader extends EventTarget { + constructor () { + super() + + this[kState] = 'empty' + this[kResult] = null + this[kError] = null + this[kEvents] = { + loadend: null, + error: null, + abort: null, + load: null, + progress: null, + loadstart: null + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer + * @param {import('buffer').Blob} blob + */ + readAsArrayBuffer (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsArrayBuffer(blob) method, when invoked, + // must initiate a read operation for blob with ArrayBuffer. + readOperation(this, blob, 'ArrayBuffer') + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsBinaryString + * @param {import('buffer').Blob} blob + */ + readAsBinaryString (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsBinaryString(blob) method, when invoked, + // must initiate a read operation for blob with BinaryString. + readOperation(this, blob, 'BinaryString') + } + + /** + * @see https://w3c.github.io/FileAPI/#readAsDataText + * @param {import('buffer').Blob} blob + * @param {string?} encoding + */ + readAsText (blob, encoding = undefined) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + if (encoding !== undefined) { + encoding = webidl.converters.DOMString(encoding) + } + + // The readAsText(blob, encoding) method, when invoked, + // must initiate a read operation for blob with Text and encoding. + readOperation(this, blob, 'Text', encoding) + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL + * @param {import('buffer').Blob} blob + */ + readAsDataURL (blob) { + webidl.brandCheck(this, FileReader) + + webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) + + blob = webidl.converters.Blob(blob, { strict: false }) + + // The readAsDataURL(blob) method, when invoked, must + // initiate a read operation for blob with DataURL. + readOperation(this, blob, 'DataURL') + } + + /** + * @see https://w3c.github.io/FileAPI/#dfn-abort + */ + abort () { + // 1. If this's state is "empty" or if this's state is + // "done" set this's result to null and terminate + // this algorithm. + if (this[kState] === 'empty' || this[kState] === 'done') { + this[kResult] = null + return + } + + // 2. If this's state is "loading" set this's state to + // "done" and set this's result to null. + if (this[kState] === 'loading') { + this[kState] = 'done' + this[kResult] = null + } + + // 3. If there are any tasks from this on the file reading + // task source in an affiliated task queue, then remove + // those tasks from that task queue. + this[kAborted] = true + + // 4. Terminate the algorithm for the read method being processed. + // TODO + + // 5. Fire a progress event called abort at this. + fireAProgressEvent('abort', this) + + // 6. If this's state is not "loading", fire a progress + // event called loadend at this. + if (this[kState] !== 'loading') { + fireAProgressEvent('loadend', this) + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate + */ + get readyState () { + webidl.brandCheck(this, FileReader) + + switch (this[kState]) { + case 'empty': return this.EMPTY + case 'loading': return this.LOADING + case 'done': return this.DONE + } + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-result + */ + get result () { + webidl.brandCheck(this, FileReader) + + // The result attribute’s getter, when invoked, must return + // this's result. + return this[kResult] + } + + /** + * @see https://w3c.github.io/FileAPI/#dom-filereader-error + */ + get error () { + webidl.brandCheck(this, FileReader) + + // The error attribute’s getter, when invoked, must return + // this's error. + return this[kError] + } + + get onloadend () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadend + } + + set onloadend (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadend) { + this.removeEventListener('loadend', this[kEvents].loadend) + } + + if (typeof fn === 'function') { + this[kEvents].loadend = fn + this.addEventListener('loadend', fn) + } else { + this[kEvents].loadend = null + } + } + + get onerror () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].error + } + + set onerror (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].error) { + this.removeEventListener('error', this[kEvents].error) + } + + if (typeof fn === 'function') { + this[kEvents].error = fn + this.addEventListener('error', fn) + } else { + this[kEvents].error = null + } + } + + get onloadstart () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].loadstart + } + + set onloadstart (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].loadstart) { + this.removeEventListener('loadstart', this[kEvents].loadstart) + } + + if (typeof fn === 'function') { + this[kEvents].loadstart = fn + this.addEventListener('loadstart', fn) + } else { + this[kEvents].loadstart = null + } + } + + get onprogress () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].progress + } + + set onprogress (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].progress) { + this.removeEventListener('progress', this[kEvents].progress) + } + + if (typeof fn === 'function') { + this[kEvents].progress = fn + this.addEventListener('progress', fn) + } else { + this[kEvents].progress = null + } + } + + get onload () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].load + } + + set onload (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].load) { + this.removeEventListener('load', this[kEvents].load) + } + + if (typeof fn === 'function') { + this[kEvents].load = fn + this.addEventListener('load', fn) + } else { + this[kEvents].load = null + } + } + + get onabort () { + webidl.brandCheck(this, FileReader) + + return this[kEvents].abort + } + + set onabort (fn) { + webidl.brandCheck(this, FileReader) + + if (this[kEvents].abort) { + this.removeEventListener('abort', this[kEvents].abort) + } + + if (typeof fn === 'function') { + this[kEvents].abort = fn + this.addEventListener('abort', fn) + } else { + this[kEvents].abort = null + } + } +} + +// https://w3c.github.io/FileAPI/#dom-filereader-empty +FileReader.EMPTY = FileReader.prototype.EMPTY = 0 +// https://w3c.github.io/FileAPI/#dom-filereader-loading +FileReader.LOADING = FileReader.prototype.LOADING = 1 +// https://w3c.github.io/FileAPI/#dom-filereader-done +FileReader.DONE = FileReader.prototype.DONE = 2 + +Object.defineProperties(FileReader.prototype, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors, + readAsArrayBuffer: kEnumerableProperty, + readAsBinaryString: kEnumerableProperty, + readAsText: kEnumerableProperty, + readAsDataURL: kEnumerableProperty, + abort: kEnumerableProperty, + readyState: kEnumerableProperty, + result: kEnumerableProperty, + error: kEnumerableProperty, + onloadstart: kEnumerableProperty, + onprogress: kEnumerableProperty, + onload: kEnumerableProperty, + onabort: kEnumerableProperty, + onerror: kEnumerableProperty, + onloadend: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'FileReader', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(FileReader, { + EMPTY: staticPropertyDescriptors, + LOADING: staticPropertyDescriptors, + DONE: staticPropertyDescriptors +}) + +module.exports = { + FileReader +} + + +/***/ }), + +/***/ 5976: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { webidl } = __nccwpck_require__(4222) + +const kState = Symbol('ProgressEvent state') + +/** + * @see https://xhr.spec.whatwg.org/#progressevent + */ +class ProgressEvent extends Event { + constructor (type, eventInitDict = {}) { + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) + + super(type, eventInitDict) + + this[kState] = { + lengthComputable: eventInitDict.lengthComputable, + loaded: eventInitDict.loaded, + total: eventInitDict.total + } + } + + get lengthComputable () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].lengthComputable + } + + get loaded () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].loaded + } + + get total () { + webidl.brandCheck(this, ProgressEvent) + + return this[kState].total + } +} + +webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ + { + key: 'lengthComputable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'loaded', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'total', + converter: webidl.converters['unsigned long long'], + defaultValue: 0 + }, + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } +]) + +module.exports = { + ProgressEvent +} + + +/***/ }), + +/***/ 6812: +/***/ ((module) => { + + + +module.exports = { + kState: Symbol('FileReader state'), + kResult: Symbol('FileReader result'), + kError: Symbol('FileReader error'), + kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), + kEvents: Symbol('FileReader events'), + kAborted: Symbol('FileReader aborted') +} + + +/***/ }), + +/***/ 165: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { + kState, + kError, + kResult, + kAborted, + kLastProgressEventFired +} = __nccwpck_require__(6812) +const { ProgressEvent } = __nccwpck_require__(5976) +const { getEncoding } = __nccwpck_require__(396) +const { DOMException } = __nccwpck_require__(7326) +const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(4322) +const { types } = __nccwpck_require__(9023) +const { StringDecoder } = __nccwpck_require__(3193) +const { btoa } = __nccwpck_require__(181) + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +/** + * @see https://w3c.github.io/FileAPI/#readOperation + * @param {import('./filereader').FileReader} fr + * @param {import('buffer').Blob} blob + * @param {string} type + * @param {string?} encodingName + */ +function readOperation (fr, blob, type, encodingName) { + // 1. If fr’s state is "loading", throw an InvalidStateError + // DOMException. + if (fr[kState] === 'loading') { + throw new DOMException('Invalid state', 'InvalidStateError') + } + + // 2. Set fr’s state to "loading". + fr[kState] = 'loading' + + // 3. Set fr’s result to null. + fr[kResult] = null + + // 4. Set fr’s error to null. + fr[kError] = null + + // 5. Let stream be the result of calling get stream on blob. + /** @type {import('stream/web').ReadableStream} */ + const stream = blob.stream() + + // 6. Let reader be the result of getting a reader from stream. + const reader = stream.getReader() + + // 7. Let bytes be an empty byte sequence. + /** @type {Uint8Array[]} */ + const bytes = [] + + // 8. Let chunkPromise be the result of reading a chunk from + // stream with reader. + let chunkPromise = reader.read() + + // 9. Let isFirstChunk be true. + let isFirstChunk = true + + // 10. In parallel, while true: + // Note: "In parallel" just means non-blocking + // Note 2: readOperation itself cannot be async as double + // reading the body would then reject the promise, instead + // of throwing an error. + ;(async () => { + while (!fr[kAborted]) { + // 1. Wait for chunkPromise to be fulfilled or rejected. + try { + const { done, value } = await chunkPromise + + // 2. If chunkPromise is fulfilled, and isFirstChunk is + // true, queue a task to fire a progress event called + // loadstart at fr. + if (isFirstChunk && !fr[kAborted]) { + queueMicrotask(() => { + fireAProgressEvent('loadstart', fr) + }) + } + + // 3. Set isFirstChunk to false. + isFirstChunk = false + + // 4. If chunkPromise is fulfilled with an object whose + // done property is false and whose value property is + // a Uint8Array object, run these steps: + if (!done && types.isUint8Array(value)) { + // 1. Let bs be the byte sequence represented by the + // Uint8Array object. + + // 2. Append bs to bytes. + bytes.push(value) + + // 3. If roughly 50ms have passed since these steps + // were last invoked, queue a task to fire a + // progress event called progress at fr. + if ( + ( + fr[kLastProgressEventFired] === undefined || + Date.now() - fr[kLastProgressEventFired] >= 50 + ) && + !fr[kAborted] + ) { + fr[kLastProgressEventFired] = Date.now() + queueMicrotask(() => { + fireAProgressEvent('progress', fr) + }) + } + + // 4. Set chunkPromise to the result of reading a + // chunk from stream with reader. + chunkPromise = reader.read() + } else if (done) { + // 5. Otherwise, if chunkPromise is fulfilled with an + // object whose done property is true, queue a task + // to run the following steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Let result be the result of package data given + // bytes, type, blob’s type, and encodingName. + try { + const result = packageData(bytes, type, blob.type, encodingName) + + // 4. Else: + + if (fr[kAborted]) { + return + } + + // 1. Set fr’s result to result. + fr[kResult] = result + + // 2. Fire a progress event called load at the fr. + fireAProgressEvent('load', fr) + } catch (error) { + // 3. If package data threw an exception error: + + // 1. Set fr’s error to error. + fr[kError] = error + + // 2. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + } + + // 5. If fr’s state is not "loading", fire a progress + // event called loadend at the fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } catch (error) { + if (fr[kAborted]) { + return + } + + // 6. Otherwise, if chunkPromise is rejected with an + // error error, queue a task to run the following + // steps and abort this algorithm: + queueMicrotask(() => { + // 1. Set fr’s state to "done". + fr[kState] = 'done' + + // 2. Set fr’s error to error. + fr[kError] = error + + // 3. Fire a progress event called error at fr. + fireAProgressEvent('error', fr) + + // 4. If fr’s state is not "loading", fire a progress + // event called loadend at fr. + if (fr[kState] !== 'loading') { + fireAProgressEvent('loadend', fr) + } + }) + + break + } + } + })() +} + +/** + * @see https://w3c.github.io/FileAPI/#fire-a-progress-event + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e The name of the event + * @param {import('./filereader').FileReader} reader + */ +function fireAProgressEvent (e, reader) { + // The progress event e does not bubble. e.bubbles must be false + // The progress event e is NOT cancelable. e.cancelable must be false + const event = new ProgressEvent(e, { + bubbles: false, + cancelable: false + }) + + reader.dispatchEvent(event) +} + +/** + * @see https://w3c.github.io/FileAPI/#blob-package-data + * @param {Uint8Array[]} bytes + * @param {string} type + * @param {string?} mimeType + * @param {string?} encodingName + */ +function packageData (bytes, type, mimeType, encodingName) { + // 1. A Blob has an associated package data algorithm, given + // bytes, a type, a optional mimeType, and a optional + // encodingName, which switches on type and runs the + // associated steps: + + switch (type) { + case 'DataURL': { + // 1. Return bytes as a DataURL [RFC2397] subject to + // the considerations below: + // * Use mimeType as part of the Data URL if it is + // available in keeping with the Data URL + // specification [RFC2397]. + // * If mimeType is not available return a Data URL + // without a media-type. [RFC2397]. + + // https://datatracker.ietf.org/doc/html/rfc2397#section-3 + // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data + // mediatype := [ type "/" subtype ] *( ";" parameter ) + // data := *urlchar + // parameter := attribute "=" value + let dataURL = 'data:' + + const parsed = parseMIMEType(mimeType || 'application/octet-stream') + + if (parsed !== 'failure') { + dataURL += serializeAMimeType(parsed) + } + + dataURL += ';base64,' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + dataURL += btoa(decoder.write(chunk)) + } + + dataURL += btoa(decoder.end()) + + return dataURL + } + case 'Text': { + // 1. Let encoding be failure + let encoding = 'failure' + + // 2. If the encodingName is present, set encoding to the + // result of getting an encoding from encodingName. + if (encodingName) { + encoding = getEncoding(encodingName) + } + + // 3. If encoding is failure, and mimeType is present: + if (encoding === 'failure' && mimeType) { + // 1. Let type be the result of parse a MIME type + // given mimeType. + const type = parseMIMEType(mimeType) + + // 2. If type is not failure, set encoding to the result + // of getting an encoding from type’s parameters["charset"]. + if (type !== 'failure') { + encoding = getEncoding(type.parameters.get('charset')) + } + } + + // 4. If encoding is failure, then set encoding to UTF-8. + if (encoding === 'failure') { + encoding = 'UTF-8' + } + + // 5. Decode bytes using fallback encoding encoding, and + // return the result. + return decode(bytes, encoding) + } + case 'ArrayBuffer': { + // Return a new ArrayBuffer whose contents are bytes. + const sequence = combineByteSequences(bytes) + + return sequence.buffer + } + case 'BinaryString': { + // Return bytes as a binary string, in which every byte + // is represented by a code unit of equal value [0..255]. + let binaryString = '' + + const decoder = new StringDecoder('latin1') + + for (const chunk of bytes) { + binaryString += decoder.write(chunk) + } + + binaryString += decoder.end() + + return binaryString + } + } +} + +/** + * @see https://encoding.spec.whatwg.org/#decode + * @param {Uint8Array[]} ioQueue + * @param {string} encoding + */ +function decode (ioQueue, encoding) { + const bytes = combineByteSequences(ioQueue) + + // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. + const BOMEncoding = BOMSniffing(bytes) + + let slice = 0 + + // 2. If BOMEncoding is non-null: + if (BOMEncoding !== null) { + // 1. Set encoding to BOMEncoding. + encoding = BOMEncoding + + // 2. Read three bytes from ioQueue, if BOMEncoding is + // UTF-8; otherwise read two bytes. + // (Do nothing with those bytes.) + slice = BOMEncoding === 'UTF-8' ? 3 : 2 + } + + // 3. Process a queue with an instance of encoding’s + // decoder, ioQueue, output, and "replacement". + + // 4. Return output. + + const sliced = bytes.slice(slice) + return new TextDecoder(encoding).decode(sliced) +} + +/** + * @see https://encoding.spec.whatwg.org/#bom-sniff + * @param {Uint8Array} ioQueue + */ +function BOMSniffing (ioQueue) { + // 1. Let BOM be the result of peeking 3 bytes from ioQueue, + // converted to a byte sequence. + const [a, b, c] = ioQueue + + // 2. For each of the rows in the table below, starting with + // the first one and going down, if BOM starts with the + // bytes given in the first column, then return the + // encoding given in the cell in the second column of that + // row. Otherwise, return null. + if (a === 0xEF && b === 0xBB && c === 0xBF) { + return 'UTF-8' + } else if (a === 0xFE && b === 0xFF) { + return 'UTF-16BE' + } else if (a === 0xFF && b === 0xFE) { + return 'UTF-16LE' + } + + return null +} + +/** + * @param {Uint8Array[]} sequences + */ +function combineByteSequences (sequences) { + const size = sequences.reduce((a, b) => { + return a + b.byteLength + }, 0) + + let offset = 0 + + return sequences.reduce((a, b) => { + a.set(b, offset) + offset += b.byteLength + return a + }, new Uint8Array(size)) +} + +module.exports = { + staticPropertyDescriptors, + readOperation, + fireAProgressEvent +} + + +/***/ }), + +/***/ 2581: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +// We include a version number for the Dispatcher API. In case of breaking changes, +// this version number must be increased to avoid conflicts. +const globalDispatcher = Symbol.for('undici.globalDispatcher.1') +const { InvalidArgumentError } = __nccwpck_require__(8707) +const Agent = __nccwpck_require__(9965) + +if (getGlobalDispatcher() === undefined) { + setGlobalDispatcher(new Agent()) +} + +function setGlobalDispatcher (agent) { + if (!agent || typeof agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument agent must implement Agent') + } + Object.defineProperty(globalThis, globalDispatcher, { + value: agent, + writable: true, + enumerable: false, + configurable: false + }) +} + +function getGlobalDispatcher () { + return globalThis[globalDispatcher] +} + +module.exports = { + setGlobalDispatcher, + getGlobalDispatcher +} + + +/***/ }), + +/***/ 8840: +/***/ ((module) => { + + + +module.exports = class DecoratorHandler { + constructor (handler) { + this.handler = handler + } + + onConnect (...args) { + return this.handler.onConnect(...args) + } + + onError (...args) { + return this.handler.onError(...args) + } + + onUpgrade (...args) { + return this.handler.onUpgrade(...args) + } + + onHeaders (...args) { + return this.handler.onHeaders(...args) + } + + onData (...args) { + return this.handler.onData(...args) + } + + onComplete (...args) { + return this.handler.onComplete(...args) + } + + onBodySent (...args) { + return this.handler.onBodySent(...args) + } +} + + +/***/ }), + +/***/ 8299: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const util = __nccwpck_require__(3440) +const { kBodyUsed } = __nccwpck_require__(6443) +const assert = __nccwpck_require__(2613) +const { InvalidArgumentError } = __nccwpck_require__(8707) +const EE = __nccwpck_require__(4434) + +const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] + +const kBody = Symbol('body') + +class BodyAsyncIterable { + constructor (body) { + this[kBody] = body + this[kBodyUsed] = false + } + + async * [Symbol.asyncIterator] () { + assert(!this[kBodyUsed], 'disturbed') + this[kBodyUsed] = true + yield * this[kBody] + } +} + +class RedirectHandler { + constructor (dispatch, maxRedirections, opts, handler) { + if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { + throw new InvalidArgumentError('maxRedirections must be a positive number') + } + + util.validateHandler(handler, opts.method, opts.upgrade) + + this.dispatch = dispatch + this.location = null + this.abort = null + this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy + this.maxRedirections = maxRedirections + this.handler = handler + this.history = [] + + if (util.isStream(this.opts.body)) { + // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp + // so that it can be dispatched again? + // TODO (fix): Do we need 100-expect support to provide a way to do this properly? + if (util.bodyLength(this.opts.body) === 0) { + this.opts.body + .on('data', function () { + assert(false) + }) + } + + if (typeof this.opts.body.readableDidRead !== 'boolean') { + this.opts.body[kBodyUsed] = false + EE.prototype.on.call(this.opts.body, 'data', function () { + this[kBodyUsed] = true + }) + } + } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { + // TODO (fix): We can't access ReadableStream internal state + // to determine whether or not it has been disturbed. This is just + // a workaround. + this.opts.body = new BodyAsyncIterable(this.opts.body) + } else if ( + this.opts.body && + typeof this.opts.body !== 'string' && + !ArrayBuffer.isView(this.opts.body) && + util.isIterable(this.opts.body) + ) { + // TODO: Should we allow re-using iterable if !this.opts.idempotent + // or through some other flag? + this.opts.body = new BodyAsyncIterable(this.opts.body) + } + } + + onConnect (abort) { + this.abort = abort + this.handler.onConnect(abort, { history: this.history }) + } + + onUpgrade (statusCode, headers, socket) { + this.handler.onUpgrade(statusCode, headers, socket) + } + + onError (error) { + this.handler.onError(error) + } + + onHeaders (statusCode, headers, resume, statusText) { + this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) + ? null + : parseLocation(statusCode, headers) + + if (this.opts.origin) { + this.history.push(new URL(this.opts.path, this.opts.origin)) + } + + if (!this.location) { + return this.handler.onHeaders(statusCode, headers, resume, statusText) + } + + const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) + const path = search ? `${pathname}${search}` : pathname + + // Remove headers referring to the original URL. + // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. + // https://tools.ietf.org/html/rfc7231#section-6.4 + this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) + this.opts.path = path + this.opts.origin = origin + this.opts.maxRedirections = 0 + this.opts.query = null + + // https://tools.ietf.org/html/rfc7231#section-6.4.4 + // In case of HTTP 303, always replace method to be either HEAD or GET + if (statusCode === 303 && this.opts.method !== 'HEAD') { + this.opts.method = 'GET' + this.opts.body = null + } + } + + onData (chunk) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response bodies. + + Redirection is used to serve the requested resource from another URL, so it is assumes that + no body is generated (and thus can be ignored). Even though generating a body is not prohibited. + + For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually + (which means it's optional and not mandated) contain just an hyperlink to the value of + the Location response header, so the body can be ignored safely. + + For status 300, which is "Multiple Choices", the spec mentions both generating a Location + response header AND a response body with the other possible location to follow. + Since the spec explicitily chooses not to specify a format for such body and leave it to + servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. + */ + } else { + return this.handler.onData(chunk) + } + } + + onComplete (trailers) { + if (this.location) { + /* + https://tools.ietf.org/html/rfc7231#section-6.4 + + TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections + and neither are useful if present. + + See comment on onData method above for more detailed informations. + */ + + this.location = null + this.abort = null + + this.dispatch(this.opts, this) + } else { + this.handler.onComplete(trailers) + } + } + + onBodySent (chunk) { + if (this.handler.onBodySent) { + this.handler.onBodySent(chunk) + } + } +} + +function parseLocation (statusCode, headers) { + if (redirectableStatusCodes.indexOf(statusCode) === -1) { + return null + } + + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toString().toLowerCase() === 'location') { + return headers[i + 1] + } + } +} + +// https://tools.ietf.org/html/rfc7231#section-6.4.4 +function shouldRemoveHeader (header, removeContent, unknownOrigin) { + if (header.length === 4) { + return util.headerNameToString(header) === 'host' + } + if (removeContent && util.headerNameToString(header).startsWith('content-')) { + return true + } + if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { + const name = util.headerNameToString(header) + return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' + } + return false +} + +// https://tools.ietf.org/html/rfc7231#section-6.4 +function cleanRequestHeaders (headers, removeContent, unknownOrigin) { + const ret = [] + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { + ret.push(headers[i], headers[i + 1]) + } + } + } else if (headers && typeof headers === 'object') { + for (const key of Object.keys(headers)) { + if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { + ret.push(key, headers[key]) + } + } + } else { + assert(headers == null, 'headers must be an object or an array') + } + return ret +} + +module.exports = RedirectHandler + + +/***/ }), + +/***/ 3573: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const assert = __nccwpck_require__(2613) + +const { kRetryHandlerDefaultRetry } = __nccwpck_require__(6443) +const { RequestRetryError } = __nccwpck_require__(8707) +const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(3440) + +function calculateRetryAfterHeader (retryAfter) { + const current = Date.now() + const diff = new Date(retryAfter).getTime() - current + + return diff +} + +class RetryHandler { + constructor (opts, handlers) { + const { retryOptions, ...dispatchOpts } = opts + const { + // Retry scoped + retry: retryFn, + maxRetries, + maxTimeout, + minTimeout, + timeoutFactor, + // Response scoped + methods, + errorCodes, + retryAfter, + statusCodes + } = retryOptions ?? {} + + this.dispatch = handlers.dispatch + this.handler = handlers.handler + this.opts = dispatchOpts + this.abort = null + this.aborted = false + this.retryOpts = { + retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], + retryAfter: retryAfter ?? true, + maxTimeout: maxTimeout ?? 30 * 1000, // 30s, + timeout: minTimeout ?? 500, // .5s + timeoutFactor: timeoutFactor ?? 2, + maxRetries: maxRetries ?? 5, + // What errors we should retry + methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], + // Indicates which errors to retry + statusCodes: statusCodes ?? [500, 502, 503, 504, 429], + // List of errors to retry + errorCodes: errorCodes ?? [ + 'ECONNRESET', + 'ECONNREFUSED', + 'ENOTFOUND', + 'ENETDOWN', + 'ENETUNREACH', + 'EHOSTDOWN', + 'EHOSTUNREACH', + 'EPIPE' + ] + } + + this.retryCount = 0 + this.start = 0 + this.end = null + this.etag = null + this.resume = null + + // Handle possible onConnect duplication + this.handler.onConnect(reason => { + this.aborted = true + if (this.abort) { + this.abort(reason) + } else { + this.reason = reason + } + }) + } + + onRequestSent () { + if (this.handler.onRequestSent) { + this.handler.onRequestSent() + } + } + + onUpgrade (statusCode, headers, socket) { + if (this.handler.onUpgrade) { + this.handler.onUpgrade(statusCode, headers, socket) + } + } + + onConnect (abort) { + if (this.aborted) { + abort(this.reason) + } else { + this.abort = abort + } + } + + onBodySent (chunk) { + if (this.handler.onBodySent) return this.handler.onBodySent(chunk) + } + + static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { + const { statusCode, code, headers } = err + const { method, retryOptions } = opts + const { + maxRetries, + timeout, + maxTimeout, + timeoutFactor, + statusCodes, + errorCodes, + methods + } = retryOptions + let { counter, currentTimeout } = state + + currentTimeout = + currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout + + // Any code that is not a Undici's originated and allowed to retry + if ( + code && + code !== 'UND_ERR_REQ_RETRY' && + code !== 'UND_ERR_SOCKET' && + !errorCodes.includes(code) + ) { + cb(err) + return + } + + // If a set of method are provided and the current method is not in the list + if (Array.isArray(methods) && !methods.includes(method)) { + cb(err) + return + } + + // If a set of status code are provided and the current status code is not in the list + if ( + statusCode != null && + Array.isArray(statusCodes) && + !statusCodes.includes(statusCode) + ) { + cb(err) + return + } + + // If we reached the max number of retries + if (counter > maxRetries) { + cb(err) + return + } + + let retryAfterHeader = headers != null && headers['retry-after'] + if (retryAfterHeader) { + retryAfterHeader = Number(retryAfterHeader) + retryAfterHeader = isNaN(retryAfterHeader) + ? calculateRetryAfterHeader(retryAfterHeader) + : retryAfterHeader * 1e3 // Retry-After is in seconds + } + + const retryTimeout = + retryAfterHeader > 0 + ? Math.min(retryAfterHeader, maxTimeout) + : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) + + state.currentTimeout = retryTimeout + + setTimeout(() => cb(null), retryTimeout) + } + + onHeaders (statusCode, rawHeaders, resume, statusMessage) { + const headers = parseHeaders(rawHeaders) + + this.retryCount += 1 + + if (statusCode >= 300) { + this.abort( + new RequestRetryError('Request failed', statusCode, { + headers, + count: this.retryCount + }) + ) + return false + } + + // Checkpoint for resume from where we left it + if (this.resume != null) { + this.resume = null + + if (statusCode !== 206) { + return true + } + + const contentRange = parseRangeHeader(headers['content-range']) + // If no content range + if (!contentRange) { + this.abort( + new RequestRetryError('Content-Range mismatch', statusCode, { + headers, + count: this.retryCount + }) + ) + return false + } + + // Let's start with a weak etag check + if (this.etag != null && this.etag !== headers.etag) { + this.abort( + new RequestRetryError('ETag mismatch', statusCode, { + headers, + count: this.retryCount + }) + ) + return false + } + + const { start, size, end = size } = contentRange + + assert(this.start === start, 'content-range mismatch') + assert(this.end == null || this.end === end, 'content-range mismatch') + + this.resume = resume + return true + } + + if (this.end == null) { + if (statusCode === 206) { + // First time we receive 206 + const range = parseRangeHeader(headers['content-range']) + + if (range == null) { + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } + + const { start, size, end = size } = range + + assert( + start != null && Number.isFinite(start) && this.start !== start, + 'content-range mismatch' + ) + assert(Number.isFinite(start)) + assert( + end != null && Number.isFinite(end) && this.end !== end, + 'invalid content-length' + ) + + this.start = start + this.end = end + } + + // We make our best to checkpoint the body for further range headers + if (this.end == null) { + const contentLength = headers['content-length'] + this.end = contentLength != null ? Number(contentLength) : null + } + + assert(Number.isFinite(this.start)) + assert( + this.end == null || Number.isFinite(this.end), + 'invalid content-length' + ) + + this.resume = resume + this.etag = headers.etag != null ? headers.etag : null + + return this.handler.onHeaders( + statusCode, + rawHeaders, + resume, + statusMessage + ) + } + + const err = new RequestRetryError('Request failed', statusCode, { + headers, + count: this.retryCount + }) + + this.abort(err) + + return false + } + + onData (chunk) { + this.start += chunk.length + + return this.handler.onData(chunk) + } + + onComplete (rawTrailers) { + this.retryCount = 0 + return this.handler.onComplete(rawTrailers) + } + + onError (err) { + if (this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } + + this.retryOpts.retry( + err, + { + state: { counter: this.retryCount++, currentTimeout: this.retryAfter }, + opts: { retryOptions: this.retryOpts, ...this.opts } + }, + onRetry.bind(this) + ) + + function onRetry (err) { + if (err != null || this.aborted || isDisturbed(this.opts.body)) { + return this.handler.onError(err) + } + + if (this.start !== 0) { + this.opts = { + ...this.opts, + headers: { + ...this.opts.headers, + range: `bytes=${this.start}-${this.end ?? ''}` + } + } + } + + try { + this.dispatch(this.opts, this) + } catch (err) { + this.handler.onError(err) + } + } + } +} + +module.exports = RetryHandler + + +/***/ }), + +/***/ 4415: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const RedirectHandler = __nccwpck_require__(8299) + +function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { + return (dispatch) => { + return function Intercept (opts, handler) { + const { maxRedirections = defaultMaxRedirections } = opts + + if (!maxRedirections) { + return dispatch(opts, handler) + } + + const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) + opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. + return dispatch(opts, redirectHandler) + } + } +} + +module.exports = createRedirectInterceptor + + +/***/ }), + +/***/ 2824: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; +const utils_1 = __nccwpck_require__(172); +// C headers +var ERROR; +(function (ERROR) { + ERROR[ERROR["OK"] = 0] = "OK"; + ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; + ERROR[ERROR["STRICT"] = 2] = "STRICT"; + ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; + ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; + ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; + ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; + ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; + ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; + ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; + ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; + ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; + ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; + ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; + ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; + ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; + ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; + ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; + ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; + ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; + ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; + ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; + ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; + ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; + ERROR[ERROR["USER"] = 24] = "USER"; +})(ERROR = exports.ERROR || (exports.ERROR = {})); +var TYPE; +(function (TYPE) { + TYPE[TYPE["BOTH"] = 0] = "BOTH"; + TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; + TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; +})(TYPE = exports.TYPE || (exports.TYPE = {})); +var FLAGS; +(function (FLAGS) { + FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; + FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; + FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; + FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; + FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; + FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; + FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; + FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; + // 1 << 8 is unused + FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; +})(FLAGS = exports.FLAGS || (exports.FLAGS = {})); +var LENIENT_FLAGS; +(function (LENIENT_FLAGS) { + LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; + LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; + LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; +})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); +var METHODS; +(function (METHODS) { + METHODS[METHODS["DELETE"] = 0] = "DELETE"; + METHODS[METHODS["GET"] = 1] = "GET"; + METHODS[METHODS["HEAD"] = 2] = "HEAD"; + METHODS[METHODS["POST"] = 3] = "POST"; + METHODS[METHODS["PUT"] = 4] = "PUT"; + /* pathological */ + METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; + METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; + METHODS[METHODS["TRACE"] = 7] = "TRACE"; + /* WebDAV */ + METHODS[METHODS["COPY"] = 8] = "COPY"; + METHODS[METHODS["LOCK"] = 9] = "LOCK"; + METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; + METHODS[METHODS["MOVE"] = 11] = "MOVE"; + METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; + METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; + METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; + METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; + METHODS[METHODS["BIND"] = 16] = "BIND"; + METHODS[METHODS["REBIND"] = 17] = "REBIND"; + METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; + METHODS[METHODS["ACL"] = 19] = "ACL"; + /* subversion */ + METHODS[METHODS["REPORT"] = 20] = "REPORT"; + METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; + METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; + METHODS[METHODS["MERGE"] = 23] = "MERGE"; + /* upnp */ + METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; + METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; + METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; + METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; + /* RFC-5789 */ + METHODS[METHODS["PATCH"] = 28] = "PATCH"; + METHODS[METHODS["PURGE"] = 29] = "PURGE"; + /* CalDAV */ + METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; + /* RFC-2068, section 19.6.1.2 */ + METHODS[METHODS["LINK"] = 31] = "LINK"; + METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; + /* icecast */ + METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; + /* RFC-7540, section 11.6 */ + METHODS[METHODS["PRI"] = 34] = "PRI"; + /* RFC-2326 RTSP */ + METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; + METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; + METHODS[METHODS["SETUP"] = 37] = "SETUP"; + METHODS[METHODS["PLAY"] = 38] = "PLAY"; + METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; + METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; + METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; + METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; + METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; + METHODS[METHODS["RECORD"] = 44] = "RECORD"; + /* RAOP */ + METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; +})(METHODS = exports.METHODS || (exports.METHODS = {})); +exports.METHODS_HTTP = [ + METHODS.DELETE, + METHODS.GET, + METHODS.HEAD, + METHODS.POST, + METHODS.PUT, + METHODS.CONNECT, + METHODS.OPTIONS, + METHODS.TRACE, + METHODS.COPY, + METHODS.LOCK, + METHODS.MKCOL, + METHODS.MOVE, + METHODS.PROPFIND, + METHODS.PROPPATCH, + METHODS.SEARCH, + METHODS.UNLOCK, + METHODS.BIND, + METHODS.REBIND, + METHODS.UNBIND, + METHODS.ACL, + METHODS.REPORT, + METHODS.MKACTIVITY, + METHODS.CHECKOUT, + METHODS.MERGE, + METHODS['M-SEARCH'], + METHODS.NOTIFY, + METHODS.SUBSCRIBE, + METHODS.UNSUBSCRIBE, + METHODS.PATCH, + METHODS.PURGE, + METHODS.MKCALENDAR, + METHODS.LINK, + METHODS.UNLINK, + METHODS.PRI, + // TODO(indutny): should we allow it with HTTP? + METHODS.SOURCE, +]; +exports.METHODS_ICE = [ + METHODS.SOURCE, +]; +exports.METHODS_RTSP = [ + METHODS.OPTIONS, + METHODS.DESCRIBE, + METHODS.ANNOUNCE, + METHODS.SETUP, + METHODS.PLAY, + METHODS.PAUSE, + METHODS.TEARDOWN, + METHODS.GET_PARAMETER, + METHODS.SET_PARAMETER, + METHODS.REDIRECT, + METHODS.RECORD, + METHODS.FLUSH, + // For AirPlay + METHODS.GET, + METHODS.POST, +]; +exports.METHOD_MAP = utils_1.enumToMap(METHODS); +exports.H_METHOD_MAP = {}; +Object.keys(exports.METHOD_MAP).forEach((key) => { + if (/^H/.test(key)) { + exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; + } +}); +var FINISH; +(function (FINISH) { + FINISH[FINISH["SAFE"] = 0] = "SAFE"; + FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; + FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; +})(FINISH = exports.FINISH || (exports.FINISH = {})); +exports.ALPHA = []; +for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { + // Upper case + exports.ALPHA.push(String.fromCharCode(i)); + // Lower case + exports.ALPHA.push(String.fromCharCode(i + 0x20)); +} +exports.NUM_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, +}; +exports.HEX_MAP = { + 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, + 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, + A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, + a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, +}; +exports.NUM = [ + '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', +]; +exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); +exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; +exports.USERINFO_CHARS = exports.ALPHANUM + .concat(exports.MARK) + .concat(['%', ';', ':', '&', '=', '+', '$', ',']); +// TODO(indutny): use RFC +exports.STRICT_URL_CHAR = [ + '!', '"', '$', '%', '&', '\'', + '(', ')', '*', '+', ',', '-', '.', '/', + ':', ';', '<', '=', '>', + '@', '[', '\\', ']', '^', '_', + '`', + '{', '|', '}', '~', +].concat(exports.ALPHANUM); +exports.URL_CHAR = exports.STRICT_URL_CHAR + .concat(['\t', '\f']); +// All characters with 0x80 bit set to 1 +for (let i = 0x80; i <= 0xff; i++) { + exports.URL_CHAR.push(i); +} +exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); +/* Tokens as defined by rfc 2616. Also lowercases them. + * token = 1* + * separators = "(" | ")" | "<" | ">" | "@" + * | "," | ";" | ":" | "\" | <"> + * | "/" | "[" | "]" | "?" | "=" + * | "{" | "}" | SP | HT + */ +exports.STRICT_TOKEN = [ + '!', '#', '$', '%', '&', '\'', + '*', '+', '-', '.', + '^', '_', '`', + '|', '~', +].concat(exports.ALPHANUM); +exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); +/* + * Verify that a char is a valid visible (printable) US-ASCII + * character or %x80-FF + */ +exports.HEADER_CHARS = ['\t']; +for (let i = 32; i <= 255; i++) { + if (i !== 127) { + exports.HEADER_CHARS.push(i); + } +} +// ',' = \x44 +exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); +exports.MAJOR = exports.NUM_MAP; +exports.MINOR = exports.MAJOR; +var HEADER_STATE; +(function (HEADER_STATE) { + HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; + HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; + HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; + HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; + HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; + HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; + HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; + HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; +})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); +exports.SPECIAL_HEADERS = { + 'connection': HEADER_STATE.CONNECTION, + 'content-length': HEADER_STATE.CONTENT_LENGTH, + 'proxy-connection': HEADER_STATE.CONNECTION, + 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, + 'upgrade': HEADER_STATE.UPGRADE, +}; +//# sourceMappingURL=constants.js.map + +/***/ }), + +/***/ 3870: +/***/ ((module) => { + +module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2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ACQkbGxodHRwX3NldF9sZW5pZW50X3RyYW5zZmVyX2VuY29kaW5nACUYbGxodHRwX21lc3NhZ2VfbmVlZHNfZW9mAD8JFwEAQQELEQECAwQFCwYHNTk3MS8tJyspCsLgAkUCAAsIABCIgICAAAsZACAAEMKAgIAAGiAAIAI2AjggACABOgAoCxwAIAAgAC8BMiAALQAuIAAQwYCAgAAQgICAgAALKgEBf0HAABDGgICAACIBEMKAgIAAGiABQYCIgIAANgI4IAEgADoAKCABCwoAIAAQyICAgAALBwAgAC0AKAsHACAALQAqCwcAIAAtACsLBwAgAC0AKQsHACAALwEyCwcAIAAtAC4LRQEEfyAAKAIYIQEgAC0ALSECIAAtACghAyAAKAI4IQQgABDCgICAABogACAENgI4IAAgAzoAKCAAIAI6AC0gACABNgIYCxEAIAAgASABIAJqEMOAgIAACxAAIABBAEHcABDMgICAABoLZwEBf0EAIQECQCAAKAIMDQACQAJAAkACQCAALQAvDgMBAAMCCyAAKAI4IgFFDQAgASgCLCIBRQ0AIAAgARGAgICAAAAiAQ0DC0EADwsQyoCAgAAACyAAQcOWgIAANgIQQQ4hAQsgAQseAAJAIAAoAgwNACAAQdGbgIAANgIQIABBFTYCDAsLFgACQCAAKAIMQRVHDQAgAEEANgIMCwsWAAJAIAAoAgxBFkcNACAAQQA2AgwLCwcAIAAoAgwLBwAgACgCEAsJACAAIAE2AhALBwAgACgCFAsiAAJAIABBJEkNABDKgICAAAALIABBAnRBoLOAgABqKAIACyIAAkAgAEEuSQ0AEMqAgIAAAAsgAEECdEGwtICAAGooAgAL7gsBAX9B66iAgAAhAQJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQ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QELQQEhAyAALQAoQQFGDQAgAC8BMkH//wNxIgVBnH9qQeQASQ0AIAVBzAFGDQAgBUGwAkYNACAEQcAAcQ0AQQAhAyAEQYgEcUGABEYNACAEQShxQQBHIQMLIABBADsBMCAAQQA6AC8gAwuZAQECfwJAAkACQCAALQAqRQ0AIAAtACtFDQBBACEBIAAvATAiAkECcUUNAQwCC0EAIQEgAC8BMCICQQFxRQ0BC0EBIQEgAC0AKEEBRg0AIAAvATJB//8DcSIAQZx/akHkAEkNACAAQcwBRg0AIABBsAJGDQAgAkHAAHENAEEAIQEgAkGIBHFBgARGDQAgAkEocUEARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQA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AAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAQDscBAAECAwQFBgcICQoLDA0ODxAREhMUFRYXGBkaGxweHyAhIyUoP0BBREVGR0hJSktMTU9QUVJT3gNXWVtcXWBiZWZnaGlqa2xtb3BxcnN0dXZ3eHl6e3x9foABggGFAYYBhwGJAYsBjAGNAY4BjwGQAZEBlAGVAZYBlwGYAZkBmgGbAZwBnQGeAZ8BoAGhAaIBowGkAaUBpgGnAagBqQGqAasBrAGtAa4BrwGwAbEBsgGzAbQBtQG2AbcBuAG5AboBuwG8Ab0BvgG/AcABwQHCAcMBxAHFAcYBxwHIAckBygHLAcwBzQHOAc8B0AHRAdIB0wHUAd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xBACEQDLEBCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxRCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDLABCyAAQQA2AhwgACABNgIUIABBxoqAgAA2AhAgAEEHNgIMQQAhEAyvAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAyuAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMSQsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAytAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2Ah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GogAf0LAwAgAEEgaiAB/QsDACAAQd0BNgIcQQALewEBfwJAIAAoAgwiAw0AAkAgACgCBEUNACAAIAE2AgQLAkAgACABIAIQxICAgAAiAw0AIAAoAgwPCyAAIAM2AhxBACEDIAAoAgQiAUUNACAAIAEgAiAAKAIIEYGAgIAAACIBRQ0AIAAgAjYCFCAAIAE2AgwgASEDCyADC+TzAQMOfwN+BH8jgICAgABBEGsiAySAgICAACABIQQgASEFIAEhBiABIQcgASEIIAEhCSABIQogASELIAEhDCABIQ0gASEOIAEhDwJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQCAAKAIcIhBBf2oO3QHaAQHZAQIDBAUGBwgJCgsMDQ7YAQ8Q1wEREtYBExQVFhcYGRob4AHfARwdHtUBHyAhIiMkJdQBJicoKSorLNMB0gEtLtEB0AEvMDEyMzQ1Njc4OTo7PD0+P0BBQkNERUbbAUdISUrPAc4BS80BTMwBTU5PUFFSU1RVVldYWVpbXF1eX2BhYmNkZWZnaGlqa2xtbm9wcXJzdHV2d3h5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wSC0GzASEQDBELQbIBIRAMEAtBtAEhEAwPC0G1ASEQDA4LQbYBIRAMDQtBtwEhEAwMC0G4ASEQDAsLQbkBIRAMCgtBugEhEAwJC0G7ASEQDAgLQcYBIRAMBwtBvAEhEAwGC0G9ASEQDAULQb4BIRAMBAtBvwEhEAwDC0HAASEQDAILQcIBIRAMAQtBwQEhEAsDQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJ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AEiASACEMCAgIAAQQFHDeYBIABCADcDIAznAQsgACABIgEgAhC0gICAACIQDecBIAEhAQz1AgsCQCABIgEgAkcNAEEGIRAM8AMLIAAgAUEBaiIBIAIQu4CAgAAiEA3oASABIQEMMQsgAEIANwMgQRIhEAzVAwsgASIQIAJHDStBHSEQDO0DCwJAIAEiASACRg0AIAFBAWohAUEQIRAM1AMLQQchEAzsAwsgAEIAIAApAyAiESACIAEiEGutIhJ9IhMgEyARVhs3AyAgESASViIURQ3lAUEIIRAM6wMLAkAgASIBIAJGDQAgAEGJgICAADYCCCAAIAE2AgQgASEBQRQhEAzSAwtBCSEQDOoDCyABIQEgACkDIFAN5AEgASEBDPICCwJAIAEiASACRw0AQQshEAzpAwsgACABQQFqIgEgAhC2gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeUBIAEhAQzyAgsgACABIgEgAhC4gICAACIQDeYBIAEhAQwNCyAAIAEiASACELqAgIAAIhAN5wEgASEBDPACCwJAIAEiASACRw0AQQ8hEAzlAwsgAS0AACIQQTtGDQggEEENRw3oASABQQFqIQEM7wILIAAgASIBIAIQuoCAgAAiEA3oASABIQEM8gILA0ACQCABLQAAQfC1gIAAai0AACIQQQFGDQAgEEECRw3rASAAKAIEIRAgAEEANgIEIAAgECABQQFqIgEQuYCAgAAiEA3qASABIQEM9AILIAFBAWoiASACRw0AC0ESIRAM4gMLIAAgASIBIAIQuoCAgAAiEA3pASABIQEMCgsgASIBIAJHDQZBGyEQDOADCwJAIAEiASACRw0AQRYhEAzgAwsgAEGKgICAADYCCCAAIAE2AgQgACABIAIQuICAgAAiEA3qASABIQFBICEQDMYDCwJAIAEiASACRg0AA0ACQCABLQAAQfC3gIAAai0AACIQQQJGDQACQCAQQX9qDgTlAewBAOsB7AELIAFBAWohAUEIIRAMyAMLIAFBAWoiASACRw0AC0EVIRAM3wMLQRUhEAzeAwsDQAJAIAEtAABB8LmAgABqLQAAIhBBAkYNACAQQX9qDgTeAewB4AHrAewBCyAB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RAgAEEANgIcIAAgATYCFCAAQZCzgIAANgIQIABBCDYCDAy3AQsgAEEANgIAIBdBAWohAQJAIAAtAClBIUcNACABIQEMVgsgAEEANgIcIAAgATYCFCAAQZuKgIAANgIQIABBCDYCDEEAIRAMtgELIABBADYCACAXQQFqIQECQCAALQApIhBBXWpBC08NACABIQEMVQsCQCAQQQZLDQBBASAQdEHKAHFFDQAgASEBDFULQQAhECAAQQA2AhwgACABNgIUIABB94mAgAA2AhAgAEEINgIMDLUBCyAQQRVGDXEgAEEANgIcIAAgATYCFCAAQbmNgIAANgIQIABBGjYCDEEAIRAMtAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAylAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHSADYCHCAAIBQ2AhQgACABNgIMQQAhEAykAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMPwsgAEHTADYCHCAAIBQ2AhQgACABNgIMQQAhEAyjAQsgACgCBCEBIABBADYCBAJAIAAgASAUEKeAgIAAIgENACAUIQEMQwsgAEHlADYCHCAAIBQ2AhQgACABNgIMQQAhEAyiAQsgAEEANgIcIAAgFDYCFCAAQcOPgIAANgIQIABBBzYCDEEAIRAMoQELIABBADYCHCAAIAE2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKABC0EAIRAgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDAyfAQsgAEEANgIcIAAgFDYCFCAAQYycgIAANgIQIABBBzYCDEEAIRAMngELIABBADYCHCAAIBQ2AhQgAEH+kYCAADYCECAAQQc2AgxBACEQDJ0BCyAAQQA2AhwgACABNgIUIABBjpuAgAA2AhAgAEEGNgIMQQAhEAycAQsgEEEVRg1XIABBADYCHCAAIAE2AhQgAEHMjoCAADYCECAAQSA2AgxBACEQDJsBCyAAQQA2AgAgEEEBaiEBQSQhEAsgACAQOgApIAAoAgQhECAAQQA2AgQgACAQIAEQq4CAgAAiEA1UIAEhAQw+CyAAQQA2AgALQQAhECAAQQA2AhwgACAENgIUIABB8ZuAgAA2AhA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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAQAAAQAAAAAAAAAAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==' + + +/***/ }), + +/***/ 172: +/***/ ((__unused_webpack_module, exports) => { + + +Object.defineProperty(exports, "__esModule", ({ value: true })); +exports.enumToMap = void 0; +function enumToMap(obj) { + const res = {}; + Object.keys(obj).forEach((key) => { + const value = obj[key]; + if (typeof value === 'number') { + res[key] = value; + } + }); + return res; +} +exports.enumToMap = enumToMap; +//# sourceMappingURL=utils.js.map + +/***/ }), + +/***/ 7501: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { kClients } = __nccwpck_require__(6443) +const Agent = __nccwpck_require__(9965) +const { + kAgent, + kMockAgentSet, + kMockAgentGet, + kDispatches, + kIsMockActive, + kNetConnect, + kGetNetConnect, + kOptions, + kFactory +} = __nccwpck_require__(1117) +const MockClient = __nccwpck_require__(7365) +const MockPool = __nccwpck_require__(4004) +const { matchValue, buildMockOptions } = __nccwpck_require__(3397) +const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8707) +const Dispatcher = __nccwpck_require__(992) +const Pluralizer = __nccwpck_require__(1529) +const PendingInterceptorsFormatter = __nccwpck_require__(6142) + +class FakeWeakRef { + constructor (value) { + this.value = value + } + + deref () { + return this.value + } +} + +class MockAgent extends Dispatcher { + constructor (opts) { + super(opts) + + this[kNetConnect] = true + this[kIsMockActive] = true + + // Instantiate Agent and encapsulate + if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + const agent = opts && opts.agent ? opts.agent : new Agent(opts) + this[kAgent] = agent + + this[kClients] = agent[kClients] + this[kOptions] = buildMockOptions(opts) + } + + get (origin) { + let dispatcher = this[kMockAgentGet](origin) + + if (!dispatcher) { + dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + } + return dispatcher + } + + dispatch (opts, handler) { + // Call MockAgent.get to perform additional setup before dispatching as normal + this.get(opts.origin) + return this[kAgent].dispatch(opts, handler) + } + + async close () { + await this[kAgent].close() + this[kClients].clear() + } + + deactivate () { + this[kIsMockActive] = false + } + + activate () { + this[kIsMockActive] = true + } + + enableNetConnect (matcher) { + if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { + if (Array.isArray(this[kNetConnect])) { + this[kNetConnect].push(matcher) + } else { + this[kNetConnect] = [matcher] + } + } else if (typeof matcher === 'undefined') { + this[kNetConnect] = true + } else { + throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') + } + } + + disableNetConnect () { + this[kNetConnect] = false + } + + // This is required to bypass issues caused by using global symbols - see: + // https://github.com/nodejs/undici/issues/1447 + get isMockActive () { + return this[kIsMockActive] + } + + [kMockAgentSet] (origin, dispatcher) { + this[kClients].set(origin, new FakeWeakRef(dispatcher)) + } + + [kFactory] (origin) { + const mockOptions = Object.assign({ agent: this }, this[kOptions]) + return this[kOptions] && this[kOptions].connections === 1 + ? new MockClient(origin, mockOptions) + : new MockPool(origin, mockOptions) + } + + [kMockAgentGet] (origin) { + // First check if we can immediately find it + const ref = this[kClients].get(origin) + if (ref) { + return ref.deref() + } + + // If the origin is not a string create a dummy parent pool and return to user + if (typeof origin !== 'string') { + const dispatcher = this[kFactory]('http://localhost:9999') + this[kMockAgentSet](origin, dispatcher) + return dispatcher + } + + // If we match, create a pool and assign the same dispatches + for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) { + const nonExplicitDispatcher = nonExplicitRef.deref() + if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { + const dispatcher = this[kFactory](origin) + this[kMockAgentSet](origin, dispatcher) + dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] + return dispatcher + } + } + } + + [kGetNetConnect] () { + return this[kNetConnect] + } + + pendingInterceptors () { + const mockAgentClients = this[kClients] + + return Array.from(mockAgentClients.entries()) + .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) + .filter(({ pending }) => pending) + } + + assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { + const pending = this.pendingInterceptors() + + if (pending.length === 0) { + return + } + + const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) + + throw new UndiciError(` +${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: + +${pendingInterceptorsFormatter.format(pending)} +`.trim()) + } +} + +module.exports = MockAgent + + +/***/ }), + +/***/ 7365: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { promisify } = __nccwpck_require__(9023) +const Client = __nccwpck_require__(6197) +const { buildMockDispatch } = __nccwpck_require__(3397) +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = __nccwpck_require__(1117) +const { MockInterceptor } = __nccwpck_require__(1511) +const Symbols = __nccwpck_require__(6443) +const { InvalidArgumentError } = __nccwpck_require__(8707) + +/** + * MockClient provides an API that extends the Client to influence the mockDispatches. + */ +class MockClient extends Client { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockClient + + +/***/ }), + +/***/ 2429: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { UndiciError } = __nccwpck_require__(8707) + +class MockNotMatchedError extends UndiciError { + constructor (message) { + super(message) + Error.captureStackTrace(this, MockNotMatchedError) + this.name = 'MockNotMatchedError' + this.message = message || 'The request does not match any registered mock dispatches' + this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' + } +} + +module.exports = { + MockNotMatchedError +} + + +/***/ }), + +/***/ 1511: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(3397) +const { + kDispatches, + kDispatchKey, + kDefaultHeaders, + kDefaultTrailers, + kContentLength, + kMockDispatch +} = __nccwpck_require__(1117) +const { InvalidArgumentError } = __nccwpck_require__(8707) +const { buildURL } = __nccwpck_require__(3440) + +/** + * Defines the scope API for an interceptor reply + */ +class MockScope { + constructor (mockDispatch) { + this[kMockDispatch] = mockDispatch + } + + /** + * Delay a reply by a set amount in ms. + */ + delay (waitInMs) { + if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { + throw new InvalidArgumentError('waitInMs must be a valid integer > 0') + } + + this[kMockDispatch].delay = waitInMs + return this + } + + /** + * For a defined reply, never mark as consumed. + */ + persist () { + this[kMockDispatch].persist = true + return this + } + + /** + * Allow one to define a reply for a set amount of matching requests. + */ + times (repeatTimes) { + if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { + throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') + } + + this[kMockDispatch].times = repeatTimes + return this + } +} + +/** + * Defines an interceptor for a Mock + */ +class MockInterceptor { + constructor (opts, mockDispatches) { + if (typeof opts !== 'object') { + throw new InvalidArgumentError('opts must be an object') + } + if (typeof opts.path === 'undefined') { + throw new InvalidArgumentError('opts.path must be defined') + } + if (typeof opts.method === 'undefined') { + opts.method = 'GET' + } + // See https://github.com/nodejs/undici/issues/1245 + // As per RFC 3986, clients are not supposed to send URI + // fragments to servers when they retrieve a document, + if (typeof opts.path === 'string') { + if (opts.query) { + opts.path = buildURL(opts.path, opts.query) + } else { + // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811 + const parsedURL = new URL(opts.path, 'data://') + opts.path = parsedURL.pathname + parsedURL.search + } + } + if (typeof opts.method === 'string') { + opts.method = opts.method.toUpperCase() + } + + this[kDispatchKey] = buildKey(opts) + this[kDispatches] = mockDispatches + this[kDefaultHeaders] = {} + this[kDefaultTrailers] = {} + this[kContentLength] = false + } + + createMockScopeDispatchData (statusCode, data, responseOptions = {}) { + const responseData = getResponseData(data) + const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} + const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } + const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } + + return { statusCode, data, headers, trailers } + } + + validateReplyParameters (statusCode, data, responseOptions) { + if (typeof statusCode === 'undefined') { + throw new InvalidArgumentError('statusCode must be defined') + } + if (typeof data === 'undefined') { + throw new InvalidArgumentError('data must be defined') + } + if (typeof responseOptions !== 'object') { + throw new InvalidArgumentError('responseOptions must be an object') + } + } + + /** + * Mock an undici request with a defined reply. + */ + reply (replyData) { + // Values of reply aren't available right now as they + // can only be available when the reply callback is invoked. + if (typeof replyData === 'function') { + // We'll first wrap the provided callback in another function, + // this function will properly resolve the data from the callback + // when invoked. + const wrappedDefaultsCallback = (opts) => { + // Our reply options callback contains the parameter for statusCode, data and options. + const resolvedData = replyData(opts) + + // Check if it is in the right format + if (typeof resolvedData !== 'object') { + throw new InvalidArgumentError('reply options callback must return an object') + } + + const { statusCode, data = '', responseOptions = {} } = resolvedData + this.validateReplyParameters(statusCode, data, responseOptions) + // Since the values can be obtained immediately we return them + // from this higher order function that will be resolved later. + return { + ...this.createMockScopeDispatchData(statusCode, data, responseOptions) + } + } + + // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) + return new MockScope(newMockDispatch) + } + + // We can have either one or three parameters, if we get here, + // we should have 1-3 parameters. So we spread the arguments of + // this function to obtain the parameters, since replyData will always + // just be the statusCode. + const [statusCode, data = '', responseOptions = {}] = [...arguments] + this.validateReplyParameters(statusCode, data, responseOptions) + + // Send in-already provided data like usual + const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions) + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) + return new MockScope(newMockDispatch) + } + + /** + * Mock an undici request with a defined error. + */ + replyWithError (error) { + if (typeof error === 'undefined') { + throw new InvalidArgumentError('error must be defined') + } + + const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) + return new MockScope(newMockDispatch) + } + + /** + * Set default reply headers on the interceptor for subsequent replies + */ + defaultReplyHeaders (headers) { + if (typeof headers === 'undefined') { + throw new InvalidArgumentError('headers must be defined') + } + + this[kDefaultHeaders] = headers + return this + } + + /** + * Set default reply trailers on the interceptor for subsequent replies + */ + defaultReplyTrailers (trailers) { + if (typeof trailers === 'undefined') { + throw new InvalidArgumentError('trailers must be defined') + } + + this[kDefaultTrailers] = trailers + return this + } + + /** + * Set reply content length header for replies on the interceptor + */ + replyContentLength () { + this[kContentLength] = true + return this + } +} + +module.exports.MockInterceptor = MockInterceptor +module.exports.MockScope = MockScope + + +/***/ }), + +/***/ 4004: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { promisify } = __nccwpck_require__(9023) +const Pool = __nccwpck_require__(5076) +const { buildMockDispatch } = __nccwpck_require__(3397) +const { + kDispatches, + kMockAgent, + kClose, + kOriginalClose, + kOrigin, + kOriginalDispatch, + kConnected +} = __nccwpck_require__(1117) +const { MockInterceptor } = __nccwpck_require__(1511) +const Symbols = __nccwpck_require__(6443) +const { InvalidArgumentError } = __nccwpck_require__(8707) + +/** + * MockPool provides an API that extends the Pool to influence the mockDispatches. + */ +class MockPool extends Pool { + constructor (origin, opts) { + super(origin, opts) + + if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { + throw new InvalidArgumentError('Argument opts.agent must implement Agent') + } + + this[kMockAgent] = opts.agent + this[kOrigin] = origin + this[kDispatches] = [] + this[kConnected] = 1 + this[kOriginalDispatch] = this.dispatch + this[kOriginalClose] = this.close.bind(this) + + this.dispatch = buildMockDispatch.call(this) + this.close = this[kClose] + } + + get [Symbols.kConnected] () { + return this[kConnected] + } + + /** + * Sets up the base interceptor for mocking replies from undici. + */ + intercept (opts) { + return new MockInterceptor(opts, this[kDispatches]) + } + + async [kClose] () { + await promisify(this[kOriginalClose])() + this[kConnected] = 0 + this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) + } +} + +module.exports = MockPool + + +/***/ }), + +/***/ 1117: +/***/ ((module) => { + + + +module.exports = { + kAgent: Symbol('agent'), + kOptions: Symbol('options'), + kFactory: Symbol('factory'), + kDispatches: Symbol('dispatches'), + kDispatchKey: Symbol('dispatch key'), + kDefaultHeaders: Symbol('default headers'), + kDefaultTrailers: Symbol('default trailers'), + kContentLength: Symbol('content length'), + kMockAgent: Symbol('mock agent'), + kMockAgentSet: Symbol('mock agent set'), + kMockAgentGet: Symbol('mock agent get'), + kMockDispatch: Symbol('mock dispatch'), + kClose: Symbol('close'), + kOriginalClose: Symbol('original agent close'), + kOrigin: Symbol('origin'), + kIsMockActive: Symbol('is mock active'), + kNetConnect: Symbol('net connect'), + kGetNetConnect: Symbol('get net connect'), + kConnected: Symbol('connected') +} + + +/***/ }), + +/***/ 3397: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { MockNotMatchedError } = __nccwpck_require__(2429) +const { + kDispatches, + kMockAgent, + kOriginalDispatch, + kOrigin, + kGetNetConnect +} = __nccwpck_require__(1117) +const { buildURL, nop } = __nccwpck_require__(3440) +const { STATUS_CODES } = __nccwpck_require__(8611) +const { + types: { + isPromise + } +} = __nccwpck_require__(9023) + +function matchValue (match, value) { + if (typeof match === 'string') { + return match === value + } + if (match instanceof RegExp) { + return match.test(value) + } + if (typeof match === 'function') { + return match(value) === true + } + return false +} + +function lowerCaseEntries (headers) { + return Object.fromEntries( + Object.entries(headers).map(([headerName, headerValue]) => { + return [headerName.toLocaleLowerCase(), headerValue] + }) + ) +} + +/** + * @param {import('../../index').Headers|string[]|Record} headers + * @param {string} key + */ +function getHeaderByName (headers, key) { + if (Array.isArray(headers)) { + for (let i = 0; i < headers.length; i += 2) { + if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { + return headers[i + 1] + } + } + + return undefined + } else if (typeof headers.get === 'function') { + return headers.get(key) + } else { + return lowerCaseEntries(headers)[key.toLocaleLowerCase()] + } +} + +/** @param {string[]} headers */ +function buildHeadersFromArray (headers) { // fetch HeadersList + const clone = headers.slice() + const entries = [] + for (let index = 0; index < clone.length; index += 2) { + entries.push([clone[index], clone[index + 1]]) + } + return Object.fromEntries(entries) +} + +function matchHeaders (mockDispatch, headers) { + if (typeof mockDispatch.headers === 'function') { + if (Array.isArray(headers)) { // fetch HeadersList + headers = buildHeadersFromArray(headers) + } + return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) + } + if (typeof mockDispatch.headers === 'undefined') { + return true + } + if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { + return false + } + + for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { + const headerValue = getHeaderByName(headers, matchHeaderName) + + if (!matchValue(matchHeaderValue, headerValue)) { + return false + } + } + return true +} + +function safeUrl (path) { + if (typeof path !== 'string') { + return path + } + + const pathSegments = path.split('?') + + if (pathSegments.length !== 2) { + return path + } + + const qp = new URLSearchParams(pathSegments.pop()) + qp.sort() + return [...pathSegments, qp.toString()].join('?') +} + +function matchKey (mockDispatch, { path, method, body, headers }) { + const pathMatch = matchValue(mockDispatch.path, path) + const methodMatch = matchValue(mockDispatch.method, method) + const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true + const headersMatch = matchHeaders(mockDispatch, headers) + return pathMatch && methodMatch && bodyMatch && headersMatch +} + +function getResponseData (data) { + if (Buffer.isBuffer(data)) { + return data + } else if (typeof data === 'object') { + return JSON.stringify(data) + } else { + return data.toString() + } +} + +function getMockDispatch (mockDispatches, key) { + const basePath = key.query ? buildURL(key.path, key.query) : key.path + const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath + + // Match path + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) + } + + // Match method + matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`) + } + + // Match body + matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`) + } + + // Match headers + matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) + if (matchedMockDispatches.length === 0) { + throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`) + } + + return matchedMockDispatches[0] +} + +function addMockDispatch (mockDispatches, key, data) { + const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } + const replyData = typeof data === 'function' ? { callback: data } : { ...data } + const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } + mockDispatches.push(newMockDispatch) + return newMockDispatch +} + +function deleteMockDispatch (mockDispatches, key) { + const index = mockDispatches.findIndex(dispatch => { + if (!dispatch.consumed) { + return false + } + return matchKey(dispatch, key) + }) + if (index !== -1) { + mockDispatches.splice(index, 1) + } +} + +function buildKey (opts) { + const { path, method, body, headers, query } = opts + return { + path, + method, + body, + headers, + query + } +} + +function generateKeyValues (data) { + return Object.entries(data).reduce((keyValuePairs, [key, value]) => [ + ...keyValuePairs, + Buffer.from(`${key}`), + Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`) + ], []) +} + +/** + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status + * @param {number} statusCode + */ +function getStatusText (statusCode) { + return STATUS_CODES[statusCode] || 'unknown' +} + +async function getResponse (body) { + const buffers = [] + for await (const data of body) { + buffers.push(data) + } + return Buffer.concat(buffers).toString('utf8') +} + +/** + * Mock dispatch function used to simulate undici dispatches + */ +function mockDispatch (opts, handler) { + // Get mock dispatch from built key + const key = buildKey(opts) + const mockDispatch = getMockDispatch(this[kDispatches], key) + + mockDispatch.timesInvoked++ + + // Here's where we resolve a callback if a callback is present for the dispatch data. + if (mockDispatch.data.callback) { + mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } + } + + // Parse mockDispatch data + const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch + const { timesInvoked, times } = mockDispatch + + // If it's used up and not persistent, mark as consumed + mockDispatch.consumed = !persist && timesInvoked >= times + mockDispatch.pending = timesInvoked < times + + // If specified, trigger dispatch error + if (error !== null) { + deleteMockDispatch(this[kDispatches], key) + handler.onError(error) + return true + } + + // Handle the request with a delay if necessary + if (typeof delay === 'number' && delay > 0) { + setTimeout(() => { + handleReply(this[kDispatches]) + }, delay) + } else { + handleReply(this[kDispatches]) + } + + function handleReply (mockDispatches, _data = data) { + // fetch's HeadersList is a 1D string array + const optsHeaders = Array.isArray(opts.headers) + ? buildHeadersFromArray(opts.headers) + : opts.headers + const body = typeof _data === 'function' + ? _data({ ...opts, headers: optsHeaders }) + : _data + + // util.types.isPromise is likely needed for jest. + if (isPromise(body)) { + // If handleReply is asynchronous, throwing an error + // in the callback will reject the promise, rather than + // synchronously throw the error, which breaks some tests. + // Rather, we wait for the callback to resolve if it is a + // promise, and then re-run handleReply with the new body. + body.then((newData) => handleReply(mockDispatches, newData)) + return + } + + const responseData = getResponseData(body) + const responseHeaders = generateKeyValues(headers) + const responseTrailers = generateKeyValues(trailers) + + handler.abort = nop + handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) + handler.onData(Buffer.from(responseData)) + handler.onComplete(responseTrailers) + deleteMockDispatch(mockDispatches, key) + } + + function resume () {} + + return true +} + +function buildMockDispatch () { + const agent = this[kMockAgent] + const origin = this[kOrigin] + const originalDispatch = this[kOriginalDispatch] + + return function dispatch (opts, handler) { + if (agent.isMockActive) { + try { + mockDispatch.call(this, opts, handler) + } catch (error) { + if (error instanceof MockNotMatchedError) { + const netConnect = agent[kGetNetConnect]() + if (netConnect === false) { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) + } + if (checkNetConnect(netConnect, origin)) { + originalDispatch.call(this, opts, handler) + } else { + throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) + } + } else { + throw error + } + } + } else { + originalDispatch.call(this, opts, handler) + } + } +} + +function checkNetConnect (netConnect, origin) { + const url = new URL(origin) + if (netConnect === true) { + return true + } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { + return true + } + return false +} + +function buildMockOptions (opts) { + if (opts) { + const { agent, ...mockOptions } = opts + return mockOptions + } +} + +module.exports = { + getResponseData, + getMockDispatch, + addMockDispatch, + deleteMockDispatch, + buildKey, + generateKeyValues, + matchValue, + getResponse, + getStatusText, + mockDispatch, + buildMockDispatch, + checkNetConnect, + buildMockOptions, + getHeaderByName +} + + +/***/ }), + +/***/ 6142: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { Transform } = __nccwpck_require__(2203) +const { Console } = __nccwpck_require__(4236) + +/** + * Gets the output of `console.table(…)` as a string. + */ +module.exports = class PendingInterceptorsFormatter { + constructor ({ disableColors } = {}) { + this.transform = new Transform({ + transform (chunk, _enc, cb) { + cb(null, chunk) + } + }) + + this.logger = new Console({ + stdout: this.transform, + inspectOptions: { + colors: !disableColors && !process.env.CI + } + }) + } + + format (pendingInterceptors) { + const withPrettyHeaders = pendingInterceptors.map( + ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + Method: method, + Origin: origin, + Path: path, + 'Status code': statusCode, + Persistent: persist ? '✅' : '❌', + Invocations: timesInvoked, + Remaining: persist ? Infinity : times - timesInvoked + })) + + this.logger.table(withPrettyHeaders) + return this.transform.read().toString() + } +} + + +/***/ }), + +/***/ 1529: +/***/ ((module) => { + + + +const singulars = { + pronoun: 'it', + is: 'is', + was: 'was', + this: 'this' +} + +const plurals = { + pronoun: 'they', + is: 'are', + was: 'were', + this: 'these' +} + +module.exports = class Pluralizer { + constructor (singular, plural) { + this.singular = singular + this.plural = plural + } + + pluralize (count) { + const one = count === 1 + const keys = one ? singulars : plurals + const noun = one ? this.singular : this.plural + return { ...keys, count, noun } + } +} + + +/***/ }), + +/***/ 4869: +/***/ ((module) => { + +/* eslint-disable */ + + + +// Extracted from node/lib/internal/fixed_queue.js + +// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. +const kSize = 2048; +const kMask = kSize - 1; + +// The FixedQueue is implemented as a singly-linked list of fixed-size +// circular buffers. It looks something like this: +// +// head tail +// | | +// v v +// +-----------+ <-----\ +-----------+ <------\ +-----------+ +// | [null] | \----- | next | \------- | next | +// +-----------+ +-----------+ +-----------+ +// | item | <-- bottom | item | <-- bottom | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | | [empty] | +// | item | | item | bottom --> | item | +// | item | | item | | item | +// | ... | | ... | | ... | +// | item | | item | | item | +// | item | | item | | item | +// | [empty] | <-- top | item | | item | +// | [empty] | | item | | item | +// | [empty] | | [empty] | <-- top top --> | [empty] | +// +-----------+ +-----------+ +-----------+ +// +// Or, if there is only one circular buffer, it looks something +// like either of these: +// +// head tail head tail +// | | | | +// v v v v +// +-----------+ +-----------+ +// | [null] | | [null] | +// +-----------+ +-----------+ +// | [empty] | | item | +// | [empty] | | item | +// | item | <-- bottom top --> | [empty] | +// | item | | [empty] | +// | [empty] | <-- top bottom --> | item | +// | [empty] | | item | +// +-----------+ +-----------+ +// +// Adding a value means moving `top` forward by one, removing means +// moving `bottom` forward by one. After reaching the end, the queue +// wraps around. +// +// When `top === bottom` the current queue is empty and when +// `top + 1 === bottom` it's full. This wastes a single space of storage +// but allows much quicker checks. + +class FixedCircularBuffer { + constructor() { + this.bottom = 0; + this.top = 0; + this.list = new Array(kSize); + this.next = null; + } + + isEmpty() { + return this.top === this.bottom; + } + + isFull() { + return ((this.top + 1) & kMask) === this.bottom; + } + + push(data) { + this.list[this.top] = data; + this.top = (this.top + 1) & kMask; + } + + shift() { + const nextItem = this.list[this.bottom]; + if (nextItem === undefined) + return null; + this.list[this.bottom] = undefined; + this.bottom = (this.bottom + 1) & kMask; + return nextItem; + } +} + +module.exports = class FixedQueue { + constructor() { + this.head = this.tail = new FixedCircularBuffer(); + } + + isEmpty() { + return this.head.isEmpty(); + } + + push(data) { + if (this.head.isFull()) { + // Head is full: Creates a new queue, sets the old queue's `.next` to it, + // and sets it as the new main queue. + this.head = this.head.next = new FixedCircularBuffer(); + } + this.head.push(data); + } + + shift() { + const tail = this.tail; + const next = tail.shift(); + if (tail.isEmpty() && tail.next !== null) { + // If there is another queue, it forms the new tail. + this.tail = tail.next; + } + return next; + } +}; + + +/***/ }), + +/***/ 8640: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const DispatcherBase = __nccwpck_require__(1) +const FixedQueue = __nccwpck_require__(4869) +const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(6443) +const PoolStats = __nccwpck_require__(4622) + +const kClients = Symbol('clients') +const kNeedDrain = Symbol('needDrain') +const kQueue = Symbol('queue') +const kClosedResolve = Symbol('closed resolve') +const kOnDrain = Symbol('onDrain') +const kOnConnect = Symbol('onConnect') +const kOnDisconnect = Symbol('onDisconnect') +const kOnConnectionError = Symbol('onConnectionError') +const kGetDispatcher = Symbol('get dispatcher') +const kAddClient = Symbol('add client') +const kRemoveClient = Symbol('remove client') +const kStats = Symbol('stats') + +class PoolBase extends DispatcherBase { + constructor () { + super() + + this[kQueue] = new FixedQueue() + this[kClients] = [] + this[kQueued] = 0 + + const pool = this + + this[kOnDrain] = function onDrain (origin, targets) { + const queue = pool[kQueue] + + let needDrain = false + + while (!needDrain) { + const item = queue.shift() + if (!item) { + break + } + pool[kQueued]-- + needDrain = !this.dispatch(item.opts, item.handler) + } + + this[kNeedDrain] = needDrain + + if (!this[kNeedDrain] && pool[kNeedDrain]) { + pool[kNeedDrain] = false + pool.emit('drain', origin, [pool, ...targets]) + } + + if (pool[kClosedResolve] && queue.isEmpty()) { + Promise + .all(pool[kClients].map(c => c.close())) + .then(pool[kClosedResolve]) + } + } + + this[kOnConnect] = (origin, targets) => { + pool.emit('connect', origin, [pool, ...targets]) + } + + this[kOnDisconnect] = (origin, targets, err) => { + pool.emit('disconnect', origin, [pool, ...targets], err) + } + + this[kOnConnectionError] = (origin, targets, err) => { + pool.emit('connectionError', origin, [pool, ...targets], err) + } + + this[kStats] = new PoolStats(this) + } + + get [kBusy] () { + return this[kNeedDrain] + } + + get [kConnected] () { + return this[kClients].filter(client => client[kConnected]).length + } + + get [kFree] () { + return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length + } + + get [kPending] () { + let ret = this[kQueued] + for (const { [kPending]: pending } of this[kClients]) { + ret += pending + } + return ret + } + + get [kRunning] () { + let ret = 0 + for (const { [kRunning]: running } of this[kClients]) { + ret += running + } + return ret + } + + get [kSize] () { + let ret = this[kQueued] + for (const { [kSize]: size } of this[kClients]) { + ret += size + } + return ret + } + + get stats () { + return this[kStats] + } + + async [kClose] () { + if (this[kQueue].isEmpty()) { + return Promise.all(this[kClients].map(c => c.close())) + } else { + return new Promise((resolve) => { + this[kClosedResolve] = resolve + }) + } + } + + async [kDestroy] (err) { + while (true) { + const item = this[kQueue].shift() + if (!item) { + break + } + item.handler.onError(err) + } + + return Promise.all(this[kClients].map(c => c.destroy(err))) + } + + [kDispatch] (opts, handler) { + const dispatcher = this[kGetDispatcher]() + + if (!dispatcher) { + this[kNeedDrain] = true + this[kQueue].push({ opts, handler }) + this[kQueued]++ + } else if (!dispatcher.dispatch(opts, handler)) { + dispatcher[kNeedDrain] = true + this[kNeedDrain] = !this[kGetDispatcher]() + } + + return !this[kNeedDrain] + } + + [kAddClient] (client) { + client + .on('drain', this[kOnDrain]) + .on('connect', this[kOnConnect]) + .on('disconnect', this[kOnDisconnect]) + .on('connectionError', this[kOnConnectionError]) + + this[kClients].push(client) + + if (this[kNeedDrain]) { + process.nextTick(() => { + if (this[kNeedDrain]) { + this[kOnDrain](client[kUrl], [this, client]) + } + }) + } + + return this + } + + [kRemoveClient] (client) { + client.close(() => { + const idx = this[kClients].indexOf(client) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + }) + + this[kNeedDrain] = this[kClients].some(dispatcher => ( + !dispatcher[kNeedDrain] && + dispatcher.closed !== true && + dispatcher.destroyed !== true + )) + } +} + +module.exports = { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kRemoveClient, + kGetDispatcher +} + + +/***/ }), + +/***/ 4622: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(6443) +const kPool = Symbol('pool') + +class PoolStats { + constructor (pool) { + this[kPool] = pool + } + + get connected () { + return this[kPool][kConnected] + } + + get free () { + return this[kPool][kFree] + } + + get pending () { + return this[kPool][kPending] + } + + get queued () { + return this[kPool][kQueued] + } + + get running () { + return this[kPool][kRunning] + } + + get size () { + return this[kPool][kSize] + } +} + +module.exports = PoolStats + + +/***/ }), + +/***/ 5076: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { + PoolBase, + kClients, + kNeedDrain, + kAddClient, + kGetDispatcher +} = __nccwpck_require__(8640) +const Client = __nccwpck_require__(6197) +const { + InvalidArgumentError +} = __nccwpck_require__(8707) +const util = __nccwpck_require__(3440) +const { kUrl, kInterceptors } = __nccwpck_require__(6443) +const buildConnector = __nccwpck_require__(9136) + +const kOptions = Symbol('options') +const kConnections = Symbol('connections') +const kFactory = Symbol('factory') + +function defaultFactory (origin, opts) { + return new Client(origin, opts) +} + +class Pool extends PoolBase { + constructor (origin, { + connections, + factory = defaultFactory, + connect, + connectTimeout, + tls, + maxCachedSessions, + socketPath, + autoSelectFamily, + autoSelectFamilyAttemptTimeout, + allowH2, + ...options + } = {}) { + super() + + if (connections != null && (!Number.isFinite(connections) || connections < 0)) { + throw new InvalidArgumentError('invalid connections') + } + + if (typeof factory !== 'function') { + throw new InvalidArgumentError('factory must be a function.') + } + + if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { + throw new InvalidArgumentError('connect must be a function or an object') + } + + if (typeof connect !== 'function') { + connect = buildConnector({ + ...tls, + maxCachedSessions, + allowH2, + socketPath, + timeout: connectTimeout, + ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), + ...connect + }) + } + + this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) + ? options.interceptors.Pool + : [] + this[kConnections] = connections || null + this[kUrl] = util.parseOrigin(origin) + this[kOptions] = { ...util.deepClone(options), connect, allowH2 } + this[kOptions].interceptors = options.interceptors + ? { ...options.interceptors } + : undefined + this[kFactory] = factory + + this.on('connectionError', (origin, targets, error) => { + // If a connection error occurs, we remove the client from the pool, + // and emit a connectionError event. They will not be re-used. + // Fixes https://github.com/nodejs/undici/issues/3895 + for (const target of targets) { + // Do not use kRemoveClient here, as it will close the client, + // but the client cannot be closed in this state. + const idx = this[kClients].indexOf(target) + if (idx !== -1) { + this[kClients].splice(idx, 1) + } + } + }) + } + + [kGetDispatcher] () { + let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) + + if (dispatcher) { + return dispatcher + } + + if (!this[kConnections] || this[kClients].length < this[kConnections]) { + dispatcher = this[kFactory](this[kUrl], this[kOptions]) + this[kAddClient](dispatcher) + } + + return dispatcher + } +} + +module.exports = Pool + + +/***/ }), + +/***/ 2720: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(6443) +const { URL } = __nccwpck_require__(7016) +const Agent = __nccwpck_require__(9965) +const Pool = __nccwpck_require__(5076) +const DispatcherBase = __nccwpck_require__(1) +const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8707) +const buildConnector = __nccwpck_require__(9136) + +const kAgent = Symbol('proxy agent') +const kClient = Symbol('proxy client') +const kProxyHeaders = Symbol('proxy headers') +const kRequestTls = Symbol('request tls settings') +const kProxyTls = Symbol('proxy tls settings') +const kConnectEndpoint = Symbol('connect endpoint function') + +function defaultProtocolPort (protocol) { + return protocol === 'https:' ? 443 : 80 +} + +function buildProxyOptions (opts) { + if (typeof opts === 'string') { + opts = { uri: opts } + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + return { + uri: opts.uri, + protocol: opts.protocol || 'https' + } +} + +function defaultFactory (origin, opts) { + return new Pool(origin, opts) +} + +class ProxyAgent extends DispatcherBase { + constructor (opts) { + super(opts) + this[kProxy] = buildProxyOptions(opts) + this[kAgent] = new Agent(opts) + this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) + ? opts.interceptors.ProxyAgent + : [] + + if (typeof opts === 'string') { + opts = { uri: opts } + } + + if (!opts || !opts.uri) { + throw new InvalidArgumentError('Proxy opts.uri is mandatory') + } + + const { clientFactory = defaultFactory } = opts + + if (typeof clientFactory !== 'function') { + throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') + } + + this[kRequestTls] = opts.requestTls + this[kProxyTls] = opts.proxyTls + this[kProxyHeaders] = opts.headers || {} + + const resolvedUrl = new URL(opts.uri) + const { origin, port, host, username, password } = resolvedUrl + + if (opts.auth && opts.token) { + throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') + } else if (opts.auth) { + /* @deprecated in favour of opts.token */ + this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` + } else if (opts.token) { + this[kProxyHeaders]['proxy-authorization'] = opts.token + } else if (username && password) { + this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` + } + + const connect = buildConnector({ ...opts.proxyTls }) + this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) + this[kClient] = clientFactory(resolvedUrl, { connect }) + this[kAgent] = new Agent({ + ...opts, + connect: async (opts, callback) => { + let requestedHost = opts.host + if (!opts.port) { + requestedHost += `:${defaultProtocolPort(opts.protocol)}` + } + try { + const { socket, statusCode } = await this[kClient].connect({ + origin, + port, + path: requestedHost, + signal: opts.signal, + headers: { + ...this[kProxyHeaders], + host + } + }) + if (statusCode !== 200) { + socket.on('error', () => {}).destroy() + callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) + } + if (opts.protocol !== 'https:') { + callback(null, socket) + return + } + let servername + if (this[kRequestTls]) { + servername = this[kRequestTls].servername + } else { + servername = opts.servername + } + this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) + } catch (err) { + callback(err) + } + } + }) + } + + dispatch (opts, handler) { + const { host } = new URL(opts.origin) + const headers = buildHeaders(opts.headers) + throwIfProxyAuthIsSent(headers) + return this[kAgent].dispatch( + { + ...opts, + headers: { + ...headers, + host + } + }, + handler + ) + } + + async [kClose] () { + await this[kAgent].close() + await this[kClient].close() + } + + async [kDestroy] () { + await this[kAgent].destroy() + await this[kClient].destroy() + } +} + +/** + * @param {string[] | Record} headers + * @returns {Record} + */ +function buildHeaders (headers) { + // When using undici.fetch, the headers list is stored + // as an array. + if (Array.isArray(headers)) { + /** @type {Record} */ + const headersPair = {} + + for (let i = 0; i < headers.length; i += 2) { + headersPair[headers[i]] = headers[i + 1] + } + + return headersPair + } + + return headers +} + +/** + * @param {Record} headers + * + * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers + * Nevertheless, it was changed and to avoid a security vulnerability by end users + * this check was created. + * It should be removed in the next major version for performance reasons + */ +function throwIfProxyAuthIsSent (headers) { + const existProxyAuth = headers && Object.keys(headers) + .find((key) => key.toLowerCase() === 'proxy-authorization') + if (existProxyAuth) { + throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') + } +} + +module.exports = ProxyAgent + + +/***/ }), + +/***/ 8804: +/***/ ((module) => { + + + +let fastNow = Date.now() +let fastNowTimeout + +const fastTimers = [] + +function onTimeout () { + fastNow = Date.now() + + let len = fastTimers.length + let idx = 0 + while (idx < len) { + const timer = fastTimers[idx] + + if (timer.state === 0) { + timer.state = fastNow + timer.delay + } else if (timer.state > 0 && fastNow >= timer.state) { + timer.state = -1 + timer.callback(timer.opaque) + } + + if (timer.state === -1) { + timer.state = -2 + if (idx !== len - 1) { + fastTimers[idx] = fastTimers.pop() + } else { + fastTimers.pop() + } + len -= 1 + } else { + idx += 1 + } + } + + if (fastTimers.length > 0) { + refreshTimeout() + } +} + +function refreshTimeout () { + if (fastNowTimeout && fastNowTimeout.refresh) { + fastNowTimeout.refresh() + } else { + clearTimeout(fastNowTimeout) + fastNowTimeout = setTimeout(onTimeout, 1e3) + if (fastNowTimeout.unref) { + fastNowTimeout.unref() + } + } +} + +class Timeout { + constructor (callback, delay, opaque) { + this.callback = callback + this.delay = delay + this.opaque = opaque + + // -2 not in timer list + // -1 in timer list but inactive + // 0 in timer list waiting for time + // > 0 in timer list waiting for time to expire + this.state = -2 + + this.refresh() + } + + refresh () { + if (this.state === -2) { + fastTimers.push(this) + if (!fastNowTimeout || fastTimers.length === 1) { + refreshTimeout() + } + } + + this.state = 0 + } + + clear () { + this.state = -1 + } +} + +module.exports = { + setTimeout (callback, delay, opaque) { + return delay < 1e3 + ? setTimeout(callback, delay, opaque) + : new Timeout(callback, delay, opaque) + }, + clearTimeout (timeout) { + if (timeout instanceof Timeout) { + timeout.clear() + } else { + clearTimeout(timeout) + } + } +} + + +/***/ }), + +/***/ 8550: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const diagnosticsChannel = __nccwpck_require__(1637) +const { uid, states } = __nccwpck_require__(5913) +const { + kReadyState, + kSentClose, + kByteParser, + kReceivedClose +} = __nccwpck_require__(2933) +const { fireEvent, failWebsocketConnection } = __nccwpck_require__(3574) +const { CloseEvent } = __nccwpck_require__(6255) +const { makeRequest } = __nccwpck_require__(5194) +const { fetching } = __nccwpck_require__(2315) +const { Headers } = __nccwpck_require__(6349) +const { getGlobalDispatcher } = __nccwpck_require__(2581) +const { kHeadersList } = __nccwpck_require__(6443) + +const channels = {} +channels.open = diagnosticsChannel.channel('undici:websocket:open') +channels.close = diagnosticsChannel.channel('undici:websocket:close') +channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') + +/** @type {import('crypto')} */ +let crypto +try { + crypto = __nccwpck_require__(6982) +} catch { + +} + +/** + * @see https://websockets.spec.whatwg.org/#concept-websocket-establish + * @param {URL} url + * @param {string|string[]} protocols + * @param {import('./websocket').WebSocket} ws + * @param {(response: any) => void} onEstablish + * @param {Partial} options + */ +function establishWebSocketConnection (url, protocols, ws, onEstablish, options) { + // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s + // scheme is "ws", and to "https" otherwise. + const requestURL = url + + requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' + + // 2. Let request be a new request, whose URL is requestURL, client is client, + // service-workers mode is "none", referrer is "no-referrer", mode is + // "websocket", credentials mode is "include", cache mode is "no-store" , + // and redirect mode is "error". + const request = makeRequest({ + urlList: [requestURL], + serviceWorkers: 'none', + referrer: 'no-referrer', + mode: 'websocket', + credentials: 'include', + cache: 'no-store', + redirect: 'error' + }) + + // Note: undici extension, allow setting custom headers. + if (options.headers) { + const headersList = new Headers(options.headers)[kHeadersList] + + request.headersList = headersList + } + + // 3. Append (`Upgrade`, `websocket`) to request’s header list. + // 4. Append (`Connection`, `Upgrade`) to request’s header list. + // Note: both of these are handled by undici currently. + // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 + + // 5. Let keyValue be a nonce consisting of a randomly selected + // 16-byte value that has been forgiving-base64-encoded and + // isomorphic encoded. + const keyValue = crypto.randomBytes(16).toString('base64') + + // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s + // header list. + request.headersList.append('sec-websocket-key', keyValue) + + // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s + // header list. + request.headersList.append('sec-websocket-version', '13') + + // 8. For each protocol in protocols, combine + // (`Sec-WebSocket-Protocol`, protocol) in request’s header + // list. + for (const protocol of protocols) { + request.headersList.append('sec-websocket-protocol', protocol) + } + + // 9. Let permessageDeflate be a user-agent defined + // "permessage-deflate" extension header value. + // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 + // TODO: enable once permessage-deflate is supported + const permessageDeflate = '' // 'permessage-deflate; 15' + + // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to + // request’s header list. + // request.headersList.append('sec-websocket-extensions', permessageDeflate) + + // 11. Fetch request with useParallelQueue set to true, and + // processResponse given response being these steps: + const controller = fetching({ + request, + useParallelQueue: true, + dispatcher: options.dispatcher ?? getGlobalDispatcher(), + processResponse (response) { + // 1. If response is a network error or its status is not 101, + // fail the WebSocket connection. + if (response.type === 'error' || response.status !== 101) { + failWebsocketConnection(ws, 'Received network error or non-101 status code.') + return + } + + // 2. If protocols is not the empty list and extracting header + // list values given `Sec-WebSocket-Protocol` and response’s + // header list results in null, failure, or the empty byte + // sequence, then fail the WebSocket connection. + if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Server did not respond with sent protocols.') + return + } + + // 3. Follow the requirements stated step 2 to step 6, inclusive, + // of the last set of steps in section 4.1 of The WebSocket + // Protocol to validate response. This either results in fail + // the WebSocket connection or the WebSocket connection is + // established. + + // 2. If the response lacks an |Upgrade| header field or the |Upgrade| + // header field contains a value that is not an ASCII case- + // insensitive match for the value "websocket", the client MUST + // _Fail the WebSocket Connection_. + if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { + failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') + return + } + + // 3. If the response lacks a |Connection| header field or the + // |Connection| header field doesn't contain a token that is an + // ASCII case-insensitive match for the value "Upgrade", the client + // MUST _Fail the WebSocket Connection_. + if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { + failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') + return + } + + // 4. If the response lacks a |Sec-WebSocket-Accept| header field or + // the |Sec-WebSocket-Accept| contains a value other than the + // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- + // Key| (as a string, not base64-decoded) with the string "258EAFA5- + // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and + // trailing whitespace, the client MUST _Fail the WebSocket + // Connection_. + const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') + const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') + if (secWSAccept !== digest) { + failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') + return + } + + // 5. If the response includes a |Sec-WebSocket-Extensions| header + // field and this header field indicates the use of an extension + // that was not present in the client's handshake (the server has + // indicated an extension not requested by the client), the client + // MUST _Fail the WebSocket Connection_. (The parsing of this + // header field to determine which extensions are requested is + // discussed in Section 9.1.) + const secExtension = response.headersList.get('Sec-WebSocket-Extensions') + + if (secExtension !== null && secExtension !== permessageDeflate) { + failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') + return + } + + // 6. If the response includes a |Sec-WebSocket-Protocol| header field + // and this header field indicates the use of a subprotocol that was + // not present in the client's handshake (the server has indicated a + // subprotocol not requested by the client), the client MUST _Fail + // the WebSocket Connection_. + const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') + + if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { + failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') + return + } + + response.socket.on('data', onSocketData) + response.socket.on('close', onSocketClose) + response.socket.on('error', onSocketError) + + if (channels.open.hasSubscribers) { + channels.open.publish({ + address: response.socket.address(), + protocol: secProtocol, + extensions: secExtension + }) + } + + onEstablish(response) + } + }) + + return controller +} + +/** + * @param {Buffer} chunk + */ +function onSocketData (chunk) { + if (!this.ws[kByteParser].write(chunk)) { + this.pause() + } +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 + */ +function onSocketClose () { + const { ws } = this + + // If the TCP connection was closed after the + // WebSocket closing handshake was completed, the WebSocket connection + // is said to have been closed _cleanly_. + const wasClean = ws[kSentClose] && ws[kReceivedClose] + + let code = 1005 + let reason = '' + + const result = ws[kByteParser].closingInfo + + if (result) { + code = result.code ?? 1005 + reason = result.reason + } else if (!ws[kSentClose]) { + // If _The WebSocket + // Connection is Closed_ and no Close control frame was received by the + // endpoint (such as could occur if the underlying transport connection + // is lost), _The WebSocket Connection Close Code_ is considered to be + // 1006. + code = 1006 + } + + // 1. Change the ready state to CLOSED (3). + ws[kReadyState] = states.CLOSED + + // 2. If the user agent was required to fail the WebSocket + // connection, or if the WebSocket connection was closed + // after being flagged as full, fire an event named error + // at the WebSocket object. + // TODO + + // 3. Fire an event named close at the WebSocket object, + // using CloseEvent, with the wasClean attribute + // initialized to true if the connection closed cleanly + // and false otherwise, the code attribute initialized to + // the WebSocket connection close code, and the reason + // attribute initialized to the result of applying UTF-8 + // decode without BOM to the WebSocket connection close + // reason. + fireEvent('close', ws, CloseEvent, { + wasClean, code, reason + }) + + if (channels.close.hasSubscribers) { + channels.close.publish({ + websocket: ws, + code, + reason + }) + } +} + +function onSocketError (error) { + const { ws } = this + + ws[kReadyState] = states.CLOSING + + if (channels.socketError.hasSubscribers) { + channels.socketError.publish(error) + } + + this.destroy() +} + +module.exports = { + establishWebSocketConnection +} + + +/***/ }), + +/***/ 5913: +/***/ ((module) => { + + + +// This is a Globally Unique Identifier unique used +// to validate that the endpoint accepts websocket +// connections. +// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 +const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' + +/** @type {PropertyDescriptor} */ +const staticPropertyDescriptors = { + enumerable: true, + writable: false, + configurable: false +} + +const states = { + CONNECTING: 0, + OPEN: 1, + CLOSING: 2, + CLOSED: 3 +} + +const opcodes = { + CONTINUATION: 0x0, + TEXT: 0x1, + BINARY: 0x2, + CLOSE: 0x8, + PING: 0x9, + PONG: 0xA +} + +const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 + +const parserStates = { + INFO: 0, + PAYLOADLENGTH_16: 2, + PAYLOADLENGTH_64: 3, + READ_DATA: 4 +} + +const emptyBuffer = Buffer.allocUnsafe(0) + +module.exports = { + uid, + staticPropertyDescriptors, + states, + opcodes, + maxUnsigned16Bit, + parserStates, + emptyBuffer +} + + +/***/ }), + +/***/ 6255: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { webidl } = __nccwpck_require__(4222) +const { kEnumerableProperty } = __nccwpck_require__(3440) +const { MessagePort } = __nccwpck_require__(8167) + +/** + * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent + */ +class MessageEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.MessageEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + } + + get data () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.data + } + + get origin () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.origin + } + + get lastEventId () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.lastEventId + } + + get source () { + webidl.brandCheck(this, MessageEvent) + + return this.#eventInit.source + } + + get ports () { + webidl.brandCheck(this, MessageEvent) + + if (!Object.isFrozen(this.#eventInit.ports)) { + Object.freeze(this.#eventInit.ports) + } + + return this.#eventInit.ports + } + + initMessageEvent ( + type, + bubbles = false, + cancelable = false, + data = null, + origin = '', + lastEventId = '', + source = null, + ports = [] + ) { + webidl.brandCheck(this, MessageEvent) + + webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) + + return new MessageEvent(type, { + bubbles, cancelable, data, origin, lastEventId, source, ports + }) + } +} + +/** + * @see https://websockets.spec.whatwg.org/#the-closeevent-interface + */ +class CloseEvent extends Event { + #eventInit + + constructor (type, eventInitDict = {}) { + webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.CloseEventInit(eventInitDict) + + super(type, eventInitDict) + + this.#eventInit = eventInitDict + } + + get wasClean () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.wasClean + } + + get code () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.code + } + + get reason () { + webidl.brandCheck(this, CloseEvent) + + return this.#eventInit.reason + } +} + +// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface +class ErrorEvent extends Event { + #eventInit + + constructor (type, eventInitDict) { + webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) + + super(type, eventInitDict) + + type = webidl.converters.DOMString(type) + eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) + + this.#eventInit = eventInitDict + } + + get message () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.message + } + + get filename () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.filename + } + + get lineno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.lineno + } + + get colno () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.colno + } + + get error () { + webidl.brandCheck(this, ErrorEvent) + + return this.#eventInit.error + } +} + +Object.defineProperties(MessageEvent.prototype, { + [Symbol.toStringTag]: { + value: 'MessageEvent', + configurable: true + }, + data: kEnumerableProperty, + origin: kEnumerableProperty, + lastEventId: kEnumerableProperty, + source: kEnumerableProperty, + ports: kEnumerableProperty, + initMessageEvent: kEnumerableProperty +}) + +Object.defineProperties(CloseEvent.prototype, { + [Symbol.toStringTag]: { + value: 'CloseEvent', + configurable: true + }, + reason: kEnumerableProperty, + code: kEnumerableProperty, + wasClean: kEnumerableProperty +}) + +Object.defineProperties(ErrorEvent.prototype, { + [Symbol.toStringTag]: { + value: 'ErrorEvent', + configurable: true + }, + message: kEnumerableProperty, + filename: kEnumerableProperty, + lineno: kEnumerableProperty, + colno: kEnumerableProperty, + error: kEnumerableProperty +}) + +webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.MessagePort +) + +const eventInit = [ + { + key: 'bubbles', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'cancelable', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'composed', + converter: webidl.converters.boolean, + defaultValue: false + } +] + +webidl.converters.MessageEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'data', + converter: webidl.converters.any, + defaultValue: null + }, + { + key: 'origin', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lastEventId', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'source', + // Node doesn't implement WindowProxy or ServiceWorker, so the only + // valid value for source is a MessagePort. + converter: webidl.nullableConverter(webidl.converters.MessagePort), + defaultValue: null + }, + { + key: 'ports', + converter: webidl.converters['sequence'], + get defaultValue () { + return [] + } + } +]) + +webidl.converters.CloseEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'wasClean', + converter: webidl.converters.boolean, + defaultValue: false + }, + { + key: 'code', + converter: webidl.converters['unsigned short'], + defaultValue: 0 + }, + { + key: 'reason', + converter: webidl.converters.USVString, + defaultValue: '' + } +]) + +webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ + ...eventInit, + { + key: 'message', + converter: webidl.converters.DOMString, + defaultValue: '' + }, + { + key: 'filename', + converter: webidl.converters.USVString, + defaultValue: '' + }, + { + key: 'lineno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'colno', + converter: webidl.converters['unsigned long'], + defaultValue: 0 + }, + { + key: 'error', + converter: webidl.converters.any + } +]) + +module.exports = { + MessageEvent, + CloseEvent, + ErrorEvent +} + + +/***/ }), + +/***/ 1237: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { maxUnsigned16Bit } = __nccwpck_require__(5913) + +/** @type {import('crypto')} */ +let crypto +try { + crypto = __nccwpck_require__(6982) +} catch { + +} + +class WebsocketFrameSend { + /** + * @param {Buffer|undefined} data + */ + constructor (data) { + this.frameData = data + this.maskKey = crypto.randomBytes(4) + } + + createFrame (opcode) { + const bodyLength = this.frameData?.byteLength ?? 0 + + /** @type {number} */ + let payloadLength = bodyLength // 0-125 + let offset = 6 + + if (bodyLength > maxUnsigned16Bit) { + offset += 8 // payload length is next 8 bytes + payloadLength = 127 + } else if (bodyLength > 125) { + offset += 2 // payload length is next 2 bytes + payloadLength = 126 + } + + const buffer = Buffer.allocUnsafe(bodyLength + offset) + + // Clear first 2 bytes, everything else is overwritten + buffer[0] = buffer[1] = 0 + buffer[0] |= 0x80 // FIN + buffer[0] = (buffer[0] & 0xF0) + opcode // opcode + + /*! ws. MIT License. Einar Otto Stangvik */ + buffer[offset - 4] = this.maskKey[0] + buffer[offset - 3] = this.maskKey[1] + buffer[offset - 2] = this.maskKey[2] + buffer[offset - 1] = this.maskKey[3] + + buffer[1] = payloadLength + + if (payloadLength === 126) { + buffer.writeUInt16BE(bodyLength, 2) + } else if (payloadLength === 127) { + // Clear extended payload length + buffer[2] = buffer[3] = 0 + buffer.writeUIntBE(bodyLength, 4, 6) + } + + buffer[1] |= 0x80 // MASK + + // mask body + for (let i = 0; i < bodyLength; i++) { + buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] + } + + return buffer + } +} + +module.exports = { + WebsocketFrameSend +} + + +/***/ }), + +/***/ 3171: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { Writable } = __nccwpck_require__(2203) +const diagnosticsChannel = __nccwpck_require__(1637) +const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(5913) +const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(2933) +const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(3574) +const { WebsocketFrameSend } = __nccwpck_require__(1237) + +// This code was influenced by ws released under the MIT license. +// Copyright (c) 2011 Einar Otto Stangvik +// Copyright (c) 2013 Arnout Kazemier and contributors +// Copyright (c) 2016 Luigi Pinca and contributors + +const channels = {} +channels.ping = diagnosticsChannel.channel('undici:websocket:ping') +channels.pong = diagnosticsChannel.channel('undici:websocket:pong') + +class ByteParser extends Writable { + #buffers = [] + #byteOffset = 0 + + #state = parserStates.INFO + + #info = {} + #fragments = [] + + constructor (ws) { + super() + + this.ws = ws + } + + /** + * @param {Buffer} chunk + * @param {() => void} callback + */ + _write (chunk, _, callback) { + this.#buffers.push(chunk) + this.#byteOffset += chunk.length + + this.run(callback) + } + + /** + * Runs whenever a new chunk is received. + * Callback is called whenever there are no more chunks buffering, + * or not enough bytes are buffered to parse. + */ + run (callback) { + while (true) { + if (this.#state === parserStates.INFO) { + // If there aren't enough bytes to parse the payload length, etc. + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.fin = (buffer[0] & 0x80) !== 0 + this.#info.opcode = buffer[0] & 0x0F + + // If we receive a fragmented message, we use the type of the first + // frame to parse the full message as binary/text, when it's terminated + this.#info.originalOpcode ??= this.#info.opcode + + this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION + + if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) { + // Only text and binary frames can be fragmented + failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') + return + } + + const payloadLength = buffer[1] & 0x7F + + if (payloadLength <= 125) { + this.#info.payloadLength = payloadLength + this.#state = parserStates.READ_DATA + } else if (payloadLength === 126) { + this.#state = parserStates.PAYLOADLENGTH_16 + } else if (payloadLength === 127) { + this.#state = parserStates.PAYLOADLENGTH_64 + } + + if (this.#info.fragmented && payloadLength > 125) { + // A fragmented frame can't be fragmented itself + failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') + return + } else if ( + (this.#info.opcode === opcodes.PING || + this.#info.opcode === opcodes.PONG || + this.#info.opcode === opcodes.CLOSE) && + payloadLength > 125 + ) { + // Control frames can have a payload length of 125 bytes MAX + failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.') + return + } else if (this.#info.opcode === opcodes.CLOSE) { + if (payloadLength === 1) { + failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') + return + } + + const body = this.consume(payloadLength) + + this.#info.closeInfo = this.parseCloseBody(false, body) + + if (!this.ws[kSentClose]) { + // If an endpoint receives a Close frame and did not previously send a + // Close frame, the endpoint MUST send a Close frame in response. (When + // sending a Close frame in response, the endpoint typically echos the + // status code it received.) + const body = Buffer.allocUnsafe(2) + body.writeUInt16BE(this.#info.closeInfo.code, 0) + const closeFrame = new WebsocketFrameSend(body) + + this.ws[kResponse].socket.write( + closeFrame.createFrame(opcodes.CLOSE), + (err) => { + if (!err) { + this.ws[kSentClose] = true + } + } + ) + } + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this.ws[kReadyState] = states.CLOSING + this.ws[kReceivedClose] = true + + this.end() + + return + } else if (this.#info.opcode === opcodes.PING) { + // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in + // response, unless it already received a Close frame. + // A Pong frame sent in response to a Ping frame must have identical + // "Application data" + + const body = this.consume(payloadLength) + + if (!this.ws[kReceivedClose]) { + const frame = new WebsocketFrameSend(body) + + this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) + + if (channels.ping.hasSubscribers) { + channels.ping.publish({ + payload: body + }) + } + } + + this.#state = parserStates.INFO + + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } else if (this.#info.opcode === opcodes.PONG) { + // A Pong frame MAY be sent unsolicited. This serves as a + // unidirectional heartbeat. A response to an unsolicited Pong frame is + // not expected. + + const body = this.consume(payloadLength) + + if (channels.pong.hasSubscribers) { + channels.pong.publish({ + payload: body + }) + } + + if (this.#byteOffset > 0) { + continue + } else { + callback() + return + } + } + } else if (this.#state === parserStates.PAYLOADLENGTH_16) { + if (this.#byteOffset < 2) { + return callback() + } + + const buffer = this.consume(2) + + this.#info.payloadLength = buffer.readUInt16BE(0) + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.PAYLOADLENGTH_64) { + if (this.#byteOffset < 8) { + return callback() + } + + const buffer = this.consume(8) + const upper = buffer.readUInt32BE(0) + + // 2^31 is the maxinimum bytes an arraybuffer can contain + // on 32-bit systems. Although, on 64-bit systems, this is + // 2^53-1 bytes. + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 + // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e + if (upper > 2 ** 31 - 1) { + failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') + return + } + + const lower = buffer.readUInt32BE(4) + + this.#info.payloadLength = (upper << 8) + lower + this.#state = parserStates.READ_DATA + } else if (this.#state === parserStates.READ_DATA) { + if (this.#byteOffset < this.#info.payloadLength) { + // If there is still more data in this chunk that needs to be read + return callback() + } else if (this.#byteOffset >= this.#info.payloadLength) { + // If the server sent multiple frames in a single chunk + + const body = this.consume(this.#info.payloadLength) + + this.#fragments.push(body) + + // If the frame is unfragmented, or a fragmented frame was terminated, + // a message was received + if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) { + const fullMessage = Buffer.concat(this.#fragments) + + websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) + + this.#info = {} + this.#fragments.length = 0 + } + + this.#state = parserStates.INFO + } + } + + if (this.#byteOffset > 0) { + continue + } else { + callback() + break + } + } + } + + /** + * Take n bytes from the buffered Buffers + * @param {number} n + * @returns {Buffer|null} + */ + consume (n) { + if (n > this.#byteOffset) { + return null + } else if (n === 0) { + return emptyBuffer + } + + if (this.#buffers[0].length === n) { + this.#byteOffset -= this.#buffers[0].length + return this.#buffers.shift() + } + + const buffer = Buffer.allocUnsafe(n) + let offset = 0 + + while (offset !== n) { + const next = this.#buffers[0] + const { length } = next + + if (length + offset === n) { + buffer.set(this.#buffers.shift(), offset) + break + } else if (length + offset > n) { + buffer.set(next.subarray(0, n - offset), offset) + this.#buffers[0] = next.subarray(n - offset) + break + } else { + buffer.set(this.#buffers.shift(), offset) + offset += next.length + } + } + + this.#byteOffset -= n + + return buffer + } + + parseCloseBody (onlyCode, data) { + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 + /** @type {number|undefined} */ + let code + + if (data.length >= 2) { + // _The WebSocket Connection Close Code_ is + // defined as the status code (Section 7.4) contained in the first Close + // control frame received by the application + code = data.readUInt16BE(0) + } + + if (onlyCode) { + if (!isValidStatusCode(code)) { + return null + } + + return { code } + } + + // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 + /** @type {Buffer} */ + let reason = data.subarray(2) + + // Remove BOM + if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { + reason = reason.subarray(3) + } + + if (code !== undefined && !isValidStatusCode(code)) { + return null + } + + try { + // TODO: optimize this + reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) + } catch { + return null + } + + return { code, reason } + } + + get closingInfo () { + return this.#info.closeInfo + } +} + +module.exports = { + ByteParser +} + + +/***/ }), + +/***/ 2933: +/***/ ((module) => { + + + +module.exports = { + kWebSocketURL: Symbol('url'), + kReadyState: Symbol('ready state'), + kController: Symbol('controller'), + kResponse: Symbol('response'), + kBinaryType: Symbol('binary type'), + kSentClose: Symbol('sent close'), + kReceivedClose: Symbol('received close'), + kByteParser: Symbol('byte parser') +} + + +/***/ }), + +/***/ 3574: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(2933) +const { states, opcodes } = __nccwpck_require__(5913) +const { MessageEvent, ErrorEvent } = __nccwpck_require__(6255) + +/* globals Blob */ + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isEstablished (ws) { + // If the server's response is validated as provided for above, it is + // said that _The WebSocket Connection is Established_ and that the + // WebSocket Connection is in the OPEN state. + return ws[kReadyState] === states.OPEN +} + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosing (ws) { + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + return ws[kReadyState] === states.CLOSING +} + +/** + * @param {import('./websocket').WebSocket} ws + */ +function isClosed (ws) { + return ws[kReadyState] === states.CLOSED +} + +/** + * @see https://dom.spec.whatwg.org/#concept-event-fire + * @param {string} e + * @param {EventTarget} target + * @param {EventInit | undefined} eventInitDict + */ +function fireEvent (e, target, eventConstructor = Event, eventInitDict) { + // 1. If eventConstructor is not given, then let eventConstructor be Event. + + // 2. Let event be the result of creating an event given eventConstructor, + // in the relevant realm of target. + // 3. Initialize event’s type attribute to e. + const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap + + // 4. Initialize any other IDL attributes of event as described in the + // invocation of this algorithm. + + // 5. Return the result of dispatching event at target, with legacy target + // override flag set if set. + target.dispatchEvent(event) +} + +/** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + * @param {import('./websocket').WebSocket} ws + * @param {number} type Opcode + * @param {Buffer} data application data + */ +function websocketMessageReceived (ws, type, data) { + // 1. If ready state is not OPEN (1), then return. + if (ws[kReadyState] !== states.OPEN) { + return + } + + // 2. Let dataForEvent be determined by switching on type and binary type: + let dataForEvent + + if (type === opcodes.TEXT) { + // -> type indicates that the data is Text + // a new DOMString containing data + try { + dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data) + } catch { + failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') + return + } + } else if (type === opcodes.BINARY) { + if (ws[kBinaryType] === 'blob') { + // -> type indicates that the data is Binary and binary type is "blob" + // a new Blob object, created in the relevant Realm of the WebSocket + // object, that represents data as its raw data + dataForEvent = new Blob([data]) + } else { + // -> type indicates that the data is Binary and binary type is "arraybuffer" + // a new ArrayBuffer object, created in the relevant Realm of the + // WebSocket object, whose contents are data + dataForEvent = new Uint8Array(data).buffer + } + } + + // 3. Fire an event named message at the WebSocket object, using MessageEvent, + // with the origin attribute initialized to the serialization of the WebSocket + // object’s url's origin, and the data attribute initialized to dataForEvent. + fireEvent('message', ws, MessageEvent, { + origin: ws[kWebSocketURL].origin, + data: dataForEvent + }) +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455 + * @see https://datatracker.ietf.org/doc/html/rfc2616 + * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 + * @param {string} protocol + */ +function isValidSubprotocol (protocol) { + // If present, this value indicates one + // or more comma-separated subprotocol the client wishes to speak, + // ordered by preference. The elements that comprise this value + // MUST be non-empty strings with characters in the range U+0021 to + // U+007E not including separator characters as defined in + // [RFC2616] and MUST all be unique strings. + if (protocol.length === 0) { + return false + } + + for (const char of protocol) { + const code = char.charCodeAt(0) + + if ( + code < 0x21 || + code > 0x7E || + char === '(' || + char === ')' || + char === '<' || + char === '>' || + char === '@' || + char === ',' || + char === ';' || + char === ':' || + char === '\\' || + char === '"' || + char === '/' || + char === '[' || + char === ']' || + char === '?' || + char === '=' || + char === '{' || + char === '}' || + code === 32 || // SP + code === 9 // HT + ) { + return false + } + } + + return true +} + +/** + * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 + * @param {number} code + */ +function isValidStatusCode (code) { + if (code >= 1000 && code < 1015) { + return ( + code !== 1004 && // reserved + code !== 1005 && // "MUST NOT be set as a status code" + code !== 1006 // "MUST NOT be set as a status code" + ) + } + + return code >= 3000 && code <= 4999 +} + +/** + * @param {import('./websocket').WebSocket} ws + * @param {string|undefined} reason + */ +function failWebsocketConnection (ws, reason) { + const { [kController]: controller, [kResponse]: response } = ws + + controller.abort() + + if (response?.socket && !response.socket.destroyed) { + response.socket.destroy() + } + + if (reason) { + fireEvent('error', ws, ErrorEvent, { + error: new Error(reason) + }) + } +} + +module.exports = { + isEstablished, + isClosing, + isClosed, + fireEvent, + isValidSubprotocol, + isValidStatusCode, + failWebsocketConnection, + websocketMessageReceived +} + + +/***/ }), + +/***/ 5171: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const { webidl } = __nccwpck_require__(4222) +const { DOMException } = __nccwpck_require__(7326) +const { URLSerializer } = __nccwpck_require__(4322) +const { getGlobalOrigin } = __nccwpck_require__(5628) +const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(5913) +const { + kWebSocketURL, + kReadyState, + kController, + kBinaryType, + kResponse, + kSentClose, + kByteParser +} = __nccwpck_require__(2933) +const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(3574) +const { establishWebSocketConnection } = __nccwpck_require__(8550) +const { WebsocketFrameSend } = __nccwpck_require__(1237) +const { ByteParser } = __nccwpck_require__(3171) +const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3440) +const { getGlobalDispatcher } = __nccwpck_require__(2581) +const { types } = __nccwpck_require__(9023) + +let experimentalWarned = false + +// https://websockets.spec.whatwg.org/#interface-definition +class WebSocket extends EventTarget { + #events = { + open: null, + error: null, + close: null, + message: null + } + + #bufferedAmount = 0 + #protocol = '' + #extensions = '' + + /** + * @param {string} url + * @param {string|string[]} protocols + */ + constructor (url, protocols = []) { + super() + + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) + + if (!experimentalWarned) { + experimentalWarned = true + process.emitWarning('WebSockets are experimental, expect them to change at any time.', { + code: 'UNDICI-WS' + }) + } + + const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) + + url = webidl.converters.USVString(url) + protocols = options.protocols + + // 1. Let baseURL be this's relevant settings object's API base URL. + const baseURL = getGlobalOrigin() + + // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. + let urlRecord + + try { + urlRecord = new URL(url, baseURL) + } catch (e) { + // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. + throw new DOMException(e, 'SyntaxError') + } + + // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". + if (urlRecord.protocol === 'http:') { + urlRecord.protocol = 'ws:' + } else if (urlRecord.protocol === 'https:') { + // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". + urlRecord.protocol = 'wss:' + } + + // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. + if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { + throw new DOMException( + `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, + 'SyntaxError' + ) + } + + // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" + // DOMException. + if (urlRecord.hash || urlRecord.href.endsWith('#')) { + throw new DOMException('Got fragment', 'SyntaxError') + } + + // 8. If protocols is a string, set protocols to a sequence consisting + // of just that string. + if (typeof protocols === 'string') { + protocols = [protocols] + } + + // 9. If any of the values in protocols occur more than once or otherwise + // fail to match the requirements for elements that comprise the value + // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket + // protocol, then throw a "SyntaxError" DOMException. + if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { + throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') + } + + // 10. Set this's url to urlRecord. + this[kWebSocketURL] = new URL(urlRecord.href) + + // 11. Let client be this's relevant settings object. + + // 12. Run this step in parallel: + + // 1. Establish a WebSocket connection given urlRecord, protocols, + // and client. + this[kController] = establishWebSocketConnection( + urlRecord, + protocols, + this, + (response) => this.#onConnectionEstablished(response), + options + ) + + // Each WebSocket object has an associated ready state, which is a + // number representing the state of the connection. Initially it must + // be CONNECTING (0). + this[kReadyState] = WebSocket.CONNECTING + + // The extensions attribute must initially return the empty string. + + // The protocol attribute must initially return the empty string. + + // Each WebSocket object has an associated binary type, which is a + // BinaryType. Initially it must be "blob". + this[kBinaryType] = 'blob' + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-close + * @param {number|undefined} code + * @param {string|undefined} reason + */ + close (code = undefined, reason = undefined) { + webidl.brandCheck(this, WebSocket) + + if (code !== undefined) { + code = webidl.converters['unsigned short'](code, { clamp: true }) + } + + if (reason !== undefined) { + reason = webidl.converters.USVString(reason) + } + + // 1. If code is present, but is neither an integer equal to 1000 nor an + // integer in the range 3000 to 4999, inclusive, throw an + // "InvalidAccessError" DOMException. + if (code !== undefined) { + if (code !== 1000 && (code < 3000 || code > 4999)) { + throw new DOMException('invalid code', 'InvalidAccessError') + } + } + + let reasonByteLength = 0 + + // 2. If reason is present, then run these substeps: + if (reason !== undefined) { + // 1. Let reasonBytes be the result of encoding reason. + // 2. If reasonBytes is longer than 123 bytes, then throw a + // "SyntaxError" DOMException. + reasonByteLength = Buffer.byteLength(reason) + + if (reasonByteLength > 123) { + throw new DOMException( + `Reason must be less than 123 bytes; received ${reasonByteLength}`, + 'SyntaxError' + ) + } + } + + // 3. Run the first matching steps from the following list: + if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) { + // If this's ready state is CLOSING (2) or CLOSED (3) + // Do nothing. + } else if (!isEstablished(this)) { + // If the WebSocket connection is not yet established + // Fail the WebSocket connection and set this's ready state + // to CLOSING (2). + failWebsocketConnection(this, 'Connection was closed before it was established.') + this[kReadyState] = WebSocket.CLOSING + } else if (!isClosing(this)) { + // If the WebSocket closing handshake has not yet been started + // Start the WebSocket closing handshake and set this's ready + // state to CLOSING (2). + // - If neither code nor reason is present, the WebSocket Close + // message must not have a body. + // - If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + // - If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + + const frame = new WebsocketFrameSend() + + // If neither code nor reason is present, the WebSocket Close + // message must not have a body. + + // If code is present, then the status code to use in the + // WebSocket Close message must be the integer given by code. + if (code !== undefined && reason === undefined) { + frame.frameData = Buffer.allocUnsafe(2) + frame.frameData.writeUInt16BE(code, 0) + } else if (code !== undefined && reason !== undefined) { + // If reason is also present, then reasonBytes must be + // provided in the Close message after the status code. + frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) + frame.frameData.writeUInt16BE(code, 0) + // the body MAY contain UTF-8-encoded data with value /reason/ + frame.frameData.write(reason, 2, 'utf-8') + } else { + frame.frameData = emptyBuffer + } + + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + socket.write(frame.createFrame(opcodes.CLOSE), (err) => { + if (!err) { + this[kSentClose] = true + } + }) + + // Upon either sending or receiving a Close control frame, it is said + // that _The WebSocket Closing Handshake is Started_ and that the + // WebSocket connection is in the CLOSING state. + this[kReadyState] = states.CLOSING + } else { + // Otherwise + // Set this's ready state to CLOSING (2). + this[kReadyState] = WebSocket.CLOSING + } + } + + /** + * @see https://websockets.spec.whatwg.org/#dom-websocket-send + * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data + */ + send (data) { + webidl.brandCheck(this, WebSocket) + + webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) + + data = webidl.converters.WebSocketSendData(data) + + // 1. If this's ready state is CONNECTING, then throw an + // "InvalidStateError" DOMException. + if (this[kReadyState] === WebSocket.CONNECTING) { + throw new DOMException('Sent before connected.', 'InvalidStateError') + } + + // 2. Run the appropriate set of steps from the following list: + // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 + // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 + + if (!isEstablished(this) || isClosing(this)) { + return + } + + /** @type {import('stream').Duplex} */ + const socket = this[kResponse].socket + + // If data is a string + if (typeof data === 'string') { + // If the WebSocket connection is established and the WebSocket + // closing handshake has not yet started, then the user agent + // must send a WebSocket Message comprised of the data argument + // using a text frame opcode; if the data cannot be sent, e.g. + // because it would need to be buffered but the buffer is full, + // the user agent must flag the WebSocket as full and then close + // the WebSocket connection. Any invocation of this method with a + // string argument that does not throw an exception must increase + // the bufferedAmount attribute by the number of bytes needed to + // express the argument as UTF-8. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.TEXT) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (types.isArrayBuffer(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need + // to be buffered but the buffer is full, the user agent must flag + // the WebSocket as full and then close the WebSocket connection. + // The data to be sent is the data stored in the buffer described + // by the ArrayBuffer object. Any invocation of this method with an + // ArrayBuffer argument that does not throw an exception must + // increase the bufferedAmount attribute by the length of the + // ArrayBuffer in bytes. + + const value = Buffer.from(data) + const frame = new WebsocketFrameSend(value) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + } else if (ArrayBuffer.isView(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The + // data to be sent is the data stored in the section of the buffer + // described by the ArrayBuffer object that data references. Any + // invocation of this method with this kind of argument that does + // not throw an exception must increase the bufferedAmount attribute + // by the length of data’s buffer in bytes. + + const ab = Buffer.from(data, data.byteOffset, data.byteLength) + + const frame = new WebsocketFrameSend(ab) + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += ab.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= ab.byteLength + }) + } else if (isBlobLike(data)) { + // If the WebSocket connection is established, and the WebSocket + // closing handshake has not yet started, then the user agent must + // send a WebSocket Message comprised of data using a binary frame + // opcode; if the data cannot be sent, e.g. because it would need to + // be buffered but the buffer is full, the user agent must flag the + // WebSocket as full and then close the WebSocket connection. The data + // to be sent is the raw data represented by the Blob object. Any + // invocation of this method with a Blob argument that does not throw + // an exception must increase the bufferedAmount attribute by the size + // of the Blob object’s raw data, in bytes. + + const frame = new WebsocketFrameSend() + + data.arrayBuffer().then((ab) => { + const value = Buffer.from(ab) + frame.frameData = value + const buffer = frame.createFrame(opcodes.BINARY) + + this.#bufferedAmount += value.byteLength + socket.write(buffer, () => { + this.#bufferedAmount -= value.byteLength + }) + }) + } + } + + get readyState () { + webidl.brandCheck(this, WebSocket) + + // The readyState getter steps are to return this's ready state. + return this[kReadyState] + } + + get bufferedAmount () { + webidl.brandCheck(this, WebSocket) + + return this.#bufferedAmount + } + + get url () { + webidl.brandCheck(this, WebSocket) + + // The url getter steps are to return this's url, serialized. + return URLSerializer(this[kWebSocketURL]) + } + + get extensions () { + webidl.brandCheck(this, WebSocket) + + return this.#extensions + } + + get protocol () { + webidl.brandCheck(this, WebSocket) + + return this.#protocol + } + + get onopen () { + webidl.brandCheck(this, WebSocket) + + return this.#events.open + } + + set onopen (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.open) { + this.removeEventListener('open', this.#events.open) + } + + if (typeof fn === 'function') { + this.#events.open = fn + this.addEventListener('open', fn) + } else { + this.#events.open = null + } + } + + get onerror () { + webidl.brandCheck(this, WebSocket) + + return this.#events.error + } + + set onerror (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.error) { + this.removeEventListener('error', this.#events.error) + } + + if (typeof fn === 'function') { + this.#events.error = fn + this.addEventListener('error', fn) + } else { + this.#events.error = null + } + } + + get onclose () { + webidl.brandCheck(this, WebSocket) + + return this.#events.close + } + + set onclose (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.close) { + this.removeEventListener('close', this.#events.close) + } + + if (typeof fn === 'function') { + this.#events.close = fn + this.addEventListener('close', fn) + } else { + this.#events.close = null + } + } + + get onmessage () { + webidl.brandCheck(this, WebSocket) + + return this.#events.message + } + + set onmessage (fn) { + webidl.brandCheck(this, WebSocket) + + if (this.#events.message) { + this.removeEventListener('message', this.#events.message) + } + + if (typeof fn === 'function') { + this.#events.message = fn + this.addEventListener('message', fn) + } else { + this.#events.message = null + } + } + + get binaryType () { + webidl.brandCheck(this, WebSocket) + + return this[kBinaryType] + } + + set binaryType (type) { + webidl.brandCheck(this, WebSocket) + + if (type !== 'blob' && type !== 'arraybuffer') { + this[kBinaryType] = 'blob' + } else { + this[kBinaryType] = type + } + } + + /** + * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol + */ + #onConnectionEstablished (response) { + // processResponse is called when the "response’s header list has been received and initialized." + // once this happens, the connection is open + this[kResponse] = response + + const parser = new ByteParser(this) + parser.on('drain', function onParserDrain () { + this.ws[kResponse].socket.resume() + }) + + response.socket.ws = this + this[kByteParser] = parser + + // 1. Change the ready state to OPEN (1). + this[kReadyState] = states.OPEN + + // 2. Change the extensions attribute’s value to the extensions in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 + const extensions = response.headersList.get('sec-websocket-extensions') + + if (extensions !== null) { + this.#extensions = extensions + } + + // 3. Change the protocol attribute’s value to the subprotocol in use, if + // it is not the null value. + // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 + const protocol = response.headersList.get('sec-websocket-protocol') + + if (protocol !== null) { + this.#protocol = protocol + } + + // 4. Fire an event named open at the WebSocket object. + fireEvent('open', this) + } +} + +// https://websockets.spec.whatwg.org/#dom-websocket-connecting +WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING +// https://websockets.spec.whatwg.org/#dom-websocket-open +WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN +// https://websockets.spec.whatwg.org/#dom-websocket-closing +WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING +// https://websockets.spec.whatwg.org/#dom-websocket-closed +WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED + +Object.defineProperties(WebSocket.prototype, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors, + url: kEnumerableProperty, + readyState: kEnumerableProperty, + bufferedAmount: kEnumerableProperty, + onopen: kEnumerableProperty, + onerror: kEnumerableProperty, + onclose: kEnumerableProperty, + close: kEnumerableProperty, + onmessage: kEnumerableProperty, + binaryType: kEnumerableProperty, + send: kEnumerableProperty, + extensions: kEnumerableProperty, + protocol: kEnumerableProperty, + [Symbol.toStringTag]: { + value: 'WebSocket', + writable: false, + enumerable: false, + configurable: true + } +}) + +Object.defineProperties(WebSocket, { + CONNECTING: staticPropertyDescriptors, + OPEN: staticPropertyDescriptors, + CLOSING: staticPropertyDescriptors, + CLOSED: staticPropertyDescriptors +}) + +webidl.converters['sequence'] = webidl.sequenceConverter( + webidl.converters.DOMString +) + +webidl.converters['DOMString or sequence'] = function (V) { + if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { + return webidl.converters['sequence'](V) + } + + return webidl.converters.DOMString(V) +} + +// This implements the propsal made in https://github.com/whatwg/websockets/issues/42 +webidl.converters.WebSocketInit = webidl.dictionaryConverter([ + { + key: 'protocols', + converter: webidl.converters['DOMString or sequence'], + get defaultValue () { + return [] + } + }, + { + key: 'dispatcher', + converter: (V) => V, + get defaultValue () { + return getGlobalDispatcher() + } + }, + { + key: 'headers', + converter: webidl.nullableConverter(webidl.converters.HeadersInit) + } +]) + +webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { + if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { + return webidl.converters.WebSocketInit(V) + } + + return { protocols: webidl.converters['DOMString or sequence'](V) } +} + +webidl.converters.WebSocketSendData = function (V) { + if (webidl.util.Type(V) === 'Object') { + if (isBlobLike(V)) { + return webidl.converters.Blob(V, { strict: false }) + } + + if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { + return webidl.converters.BufferSource(V) + } + } + + return webidl.converters.USVString(V) +} + +module.exports = { + WebSocket +} + + +/***/ }), + +/***/ 3843: +/***/ ((__unused_webpack_module, exports) => { + + + +Object.defineProperty(exports, "__esModule", ({ value: true })); + +function getUserAgent() { + if (typeof navigator === "object" && "userAgent" in navigator) { + return navigator.userAgent; + } + + if (typeof process === "object" && process.version !== undefined) { + return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; + } + + return ""; +} + +exports.getUserAgent = getUserAgent; +//# sourceMappingURL=index.js.map + + +/***/ }), + +/***/ 2048: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + +var __webpack_unused_export__; + + +__webpack_unused_export__ = ({ + value: true +}); +Object.defineProperty(exports, "Zu", ({ + enumerable: true, + get: function () { + return _max.default; + } +})); +Object.defineProperty(exports, "wD", ({ + enumerable: true, + get: function () { + return _nil.default; + } +})); +Object.defineProperty(exports, "qg", ({ + enumerable: true, + get: function () { + return _parse.default; + } +})); +Object.defineProperty(exports, "As", ({ + enumerable: true, + get: function () { + return _stringify.default; + } +})); +Object.defineProperty(exports, "v1", ({ + enumerable: true, + get: function () { + return _v.default; + } +})); +Object.defineProperty(exports, "bV", ({ + enumerable: true, + get: function () { + return _v1ToV.default; + } +})); +Object.defineProperty(exports, "v3", ({ + enumerable: true, + get: function () { + return _v2.default; + } +})); +Object.defineProperty(exports, "v4", ({ + enumerable: true, + get: function () { + return _v3.default; + } +})); +Object.defineProperty(exports, "v5", ({ + enumerable: true, + get: function () { + return _v4.default; + } +})); +Object.defineProperty(exports, "v6", ({ + enumerable: true, + get: function () { + return _v5.default; + } +})); +Object.defineProperty(exports, "JE", ({ + enumerable: true, + get: function () { + return _v6ToV.default; + } +})); +Object.defineProperty(exports, "v7", ({ + enumerable: true, + get: function () { + return _v6.default; + } +})); +Object.defineProperty(exports, "tf", ({ + enumerable: true, + get: function () { + return _validate.default; + } +})); +Object.defineProperty(exports, "rE", ({ + enumerable: true, + get: function () { + return _version.default; + } +})); +var _max = _interopRequireDefault(__nccwpck_require__(242)); +var _nil = _interopRequireDefault(__nccwpck_require__(7723)); +var _parse = _interopRequireDefault(__nccwpck_require__(7267)); +var _stringify = _interopRequireDefault(__nccwpck_require__(7597)); +var _v = _interopRequireDefault(__nccwpck_require__(6415)); +var _v1ToV = _interopRequireDefault(__nccwpck_require__(9706)); +var _v2 = _interopRequireDefault(__nccwpck_require__(1697)); +var _v3 = _interopRequireDefault(__nccwpck_require__(4676)); +var _v4 = _interopRequireDefault(__nccwpck_require__(9771)); +var _v5 = _interopRequireDefault(__nccwpck_require__(8558)); +var _v6ToV = _interopRequireDefault(__nccwpck_require__(9558)); +var _v6 = _interopRequireDefault(__nccwpck_require__(9261)); +var _validate = _interopRequireDefault(__nccwpck_require__(6200)); +var _version = _interopRequireDefault(__nccwpck_require__(5868)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } + +/***/ }), + +/***/ 242: +/***/ ((__unused_webpack_module, exports) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = exports["default"] = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; + +/***/ }), + +/***/ 216: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function md5(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + return _nodeCrypto.default.createHash('md5').update(bytes).digest(); +} +var _default = exports["default"] = md5; + +/***/ }), + +/***/ 4221: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +var _default = exports["default"] = { + randomUUID: _nodeCrypto.default.randomUUID +}; + +/***/ }), + +/***/ 7723: +/***/ ((__unused_webpack_module, exports) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = exports["default"] = '00000000-0000-0000-0000-000000000000'; + +/***/ }), + +/***/ 7267: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _validate = _interopRequireDefault(__nccwpck_require__(6200)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function parse(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + let v; + const arr = new Uint8Array(16); + + // Parse ########-....-....-....-............ + arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; + arr[1] = v >>> 16 & 0xff; + arr[2] = v >>> 8 & 0xff; + arr[3] = v & 0xff; + + // Parse ........-####-....-....-............ + arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; + arr[5] = v & 0xff; + + // Parse ........-....-####-....-............ + arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; + arr[7] = v & 0xff; + + // Parse ........-....-....-####-............ + arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; + arr[9] = v & 0xff; + + // Parse ........-....-....-....-############ + // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) + arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; + arr[11] = v / 0x100000000 & 0xff; + arr[12] = v >>> 24 & 0xff; + arr[13] = v >>> 16 & 0xff; + arr[14] = v >>> 8 & 0xff; + arr[15] = v & 0xff; + return arr; +} +var _default = exports["default"] = parse; + +/***/ }), + +/***/ 7879: +/***/ ((__unused_webpack_module, exports) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _default = exports["default"] = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; + +/***/ }), + +/***/ 2973: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = rng; +var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate +let poolPtr = rnds8Pool.length; +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + _nodeCrypto.default.randomFillSync(rnds8Pool); + poolPtr = 0; + } + return rnds8Pool.slice(poolPtr, poolPtr += 16); +} + +/***/ }), + +/***/ 507: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function sha1(bytes) { + if (Array.isArray(bytes)) { + bytes = Buffer.from(bytes); + } else if (typeof bytes === 'string') { + bytes = Buffer.from(bytes, 'utf8'); + } + return _nodeCrypto.default.createHash('sha1').update(bytes).digest(); +} +var _default = exports["default"] = sha1; + +/***/ }), + +/***/ 7597: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +exports.unsafeStringify = unsafeStringify; +var _validate = _interopRequireDefault(__nccwpck_require__(6200)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +/** + * Convert array of 16 byte values to UUID string format of the form: + * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX + */ +const byteToHex = []; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} +function unsafeStringify(arr, offset = 0) { + // Note: Be careful editing this code! It's been tuned for performance + // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 + // + // Note to future-self: No, you can't remove the `toLowerCase()` call. + // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351 + return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); +} +function stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); + // Consistency check for valid UUID. If this throws, it's likely due to one + // of the following: + // - One or more input array values don't map to a hex octet (leading to + // "undefined" in the uuid) + // - Invalid input values for the RFC `version` or `variant` fields + if (!(0, _validate.default)(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + return uuid; +} +var _default = exports["default"] = stringify; + +/***/ }), + +/***/ 6415: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _rng = _interopRequireDefault(__nccwpck_require__(2973)); +var _stringify = __nccwpck_require__(7597); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +// **`v1()` - Generate time-based UUID** +// +// Inspired by https://github.com/LiosK/UUID.js +// and http://docs.python.org/library/uuid.html + +let _nodeId; +let _clockseq; + +// Previous uuid creation time +let _lastMSecs = 0; +let _lastNSecs = 0; + +// See https://github.com/uuidjs/uuid for API details +function v1(options, buf, offset) { + let i = buf && offset || 0; + const b = buf || new Array(16); + options = options || {}; + let node = options.node; + let clockseq = options.clockseq; + + // v1 only: Use cached `node` and `clockseq` values + if (!options._v6) { + if (!node) { + node = _nodeId; + } + if (clockseq == null) { + clockseq = _clockseq; + } + } + + // Handle cases where we need entropy. We do this lazily to minimize issues + // related to insufficient system entropy. See #189 + if (node == null || clockseq == null) { + const seedBytes = options.random || (options.rng || _rng.default)(); + + // Randomize node + if (node == null) { + node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; + + // v1 only: cache node value for reuse + if (!_nodeId && !options._v6) { + // per RFC4122 4.5: Set MAC multicast bit (v1 only) + node[0] |= 0x01; // Set multicast bit + + _nodeId = node; + } + } + + // Randomize clockseq + if (clockseq == null) { + // Per 4.2.2, randomize (14 bit) clockseq + clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; + if (_clockseq === undefined && !options._v6) { + _clockseq = clockseq; + } + } + } + + // v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch, + // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is + // handled internally as 'msecs' (integer milliseconds) and 'nsecs' + // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. + let msecs = options.msecs !== undefined ? options.msecs : Date.now(); + + // Per 4.2.1.2, use count of uuid's generated during the current clock + // cycle to simulate higher resolution clock + let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; + + // Time since last uuid creation (in msecs) + const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; + + // Per 4.2.1.2, Bump clockseq on clock regression + if (dt < 0 && options.clockseq === undefined) { + clockseq = clockseq + 1 & 0x3fff; + } + + // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new + // time interval + if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { + nsecs = 0; + } + + // Per 4.2.1.2 Throw error if too many uuids are requested + if (nsecs >= 10000) { + throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); + } + _lastMSecs = msecs; + _lastNSecs = nsecs; + _clockseq = clockseq; + + // Per 4.1.4 - Convert from unix epoch to Gregorian epoch + msecs += 12219292800000; + + // `time_low` + const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; + b[i++] = tl >>> 24 & 0xff; + b[i++] = tl >>> 16 & 0xff; + b[i++] = tl >>> 8 & 0xff; + b[i++] = tl & 0xff; + + // `time_mid` + const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; + b[i++] = tmh >>> 8 & 0xff; + b[i++] = tmh & 0xff; + + // `time_high_and_version` + b[i++] = tmh >>> 24 & 0xf | 0x10; // include version + b[i++] = tmh >>> 16 & 0xff; + + // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) + b[i++] = clockseq >>> 8 | 0x80; + + // `clock_seq_low` + b[i++] = clockseq & 0xff; + + // `node` + for (let n = 0; n < 6; ++n) { + b[i + n] = node[n]; + } + return buf || (0, _stringify.unsafeStringify)(b); +} +var _default = exports["default"] = v1; + +/***/ }), + +/***/ 9706: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = v1ToV6; +var _parse = _interopRequireDefault(__nccwpck_require__(7267)); +var _stringify = __nccwpck_require__(7597); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +/** + * Convert a v1 UUID to a v6 UUID + * + * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6 + * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg + * (string or Uint8Array) + */ +function v1ToV6(uuid) { + const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; + const v6Bytes = _v1ToV6(v1Bytes); + return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes; +} + +// Do the field transformation needed for v1 -> v6 +function _v1ToV6(v1Bytes, randomize = false) { + return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); +} + +/***/ }), + +/***/ 1697: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _v = _interopRequireDefault(__nccwpck_require__(2930)); +var _md = _interopRequireDefault(__nccwpck_require__(216)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const v3 = (0, _v.default)('v3', 0x30, _md.default); +var _default = exports["default"] = v3; + +/***/ }), + +/***/ 2930: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports.URL = exports.DNS = void 0; +exports["default"] = v35; +var _stringify = __nccwpck_require__(7597); +var _parse = _interopRequireDefault(__nccwpck_require__(7267)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function stringToBytes(str) { + str = unescape(encodeURIComponent(str)); // UTF8 escape + + const bytes = []; + for (let i = 0; i < str.length; ++i) { + bytes.push(str.charCodeAt(i)); + } + return bytes; +} +const DNS = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; +const URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; +function v35(name, version, hashfunc) { + function generateUUID(value, namespace, buf, offset) { + var _namespace; + if (typeof value === 'string') { + value = stringToBytes(value); + } + if (typeof namespace === 'string') { + namespace = (0, _parse.default)(namespace); + } + if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { + throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); + } + + // Compute hash of namespace and value, Per 4.3 + // Future: Use spread syntax when supported on all platforms, e.g. `bytes = + // hashfunc([...namespace, ... value])` + let bytes = new Uint8Array(16 + value.length); + bytes.set(namespace); + bytes.set(value, namespace.length); + bytes = hashfunc(bytes); + bytes[6] = bytes[6] & 0x0f | version; + bytes[8] = bytes[8] & 0x3f | 0x80; + if (buf) { + offset = offset || 0; + for (let i = 0; i < 16; ++i) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return (0, _stringify.unsafeStringify)(bytes); + } + + // Function#name is not settable on some platforms (#270) + try { + generateUUID.name = name; + } catch (err) {} + + // For CommonJS default export support + generateUUID.DNS = DNS; + generateUUID.URL = URL; + return generateUUID; +} + +/***/ }), + +/***/ 4676: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _native = _interopRequireDefault(__nccwpck_require__(4221)); +var _rng = _interopRequireDefault(__nccwpck_require__(2973)); +var _stringify = __nccwpck_require__(7597); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function v4(options, buf, offset) { + if (_native.default.randomUUID && !buf && !options) { + return _native.default.randomUUID(); + } + options = options || {}; + const rnds = options.random || (options.rng || _rng.default)(); + + // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` + rnds[6] = rnds[6] & 0x0f | 0x40; + rnds[8] = rnds[8] & 0x3f | 0x80; + + // Copy bytes to buffer, if provided + if (buf) { + offset = offset || 0; + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return (0, _stringify.unsafeStringify)(rnds); +} +var _default = exports["default"] = v4; + +/***/ }), + +/***/ 9771: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _v = _interopRequireDefault(__nccwpck_require__(2930)); +var _sha = _interopRequireDefault(__nccwpck_require__(507)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +const v5 = (0, _v.default)('v5', 0x50, _sha.default); +var _default = exports["default"] = v5; + +/***/ }), + +/***/ 8558: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = v6; +var _stringify = __nccwpck_require__(7597); +var _v = _interopRequireDefault(__nccwpck_require__(6415)); +var _v1ToV = _interopRequireDefault(__nccwpck_require__(9706)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +/** + * + * @param {object} options + * @param {Uint8Array=} buf + * @param {number=} offset + * @returns + */ +function v6(options = {}, buf, offset = 0) { + // v6 is v1 with different field layout, so we start with a v1 UUID, albeit + // with slightly different behavior around how the clock_seq and node fields + // are randomized, which is why we call v1 with _v6: true. + let bytes = (0, _v.default)({ + ...options, + _v6: true + }, new Uint8Array(16)); + + // Reorder the fields to v6 layout. + bytes = (0, _v1ToV.default)(bytes); + + // Return as a byte array if requested + if (buf) { + for (let i = 0; i < 16; i++) { + buf[offset + i] = bytes[i]; + } + return buf; + } + return (0, _stringify.unsafeStringify)(bytes); +} + +/***/ }), + +/***/ 9558: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = v6ToV1; +var _parse = _interopRequireDefault(__nccwpck_require__(7267)); +var _stringify = __nccwpck_require__(7597); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +/** + * Convert a v6 UUID to a v1 UUID + * + * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6 + * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg + * (string or Uint8Array) + */ +function v6ToV1(uuid) { + const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; + const v1Bytes = _v6ToV1(v6Bytes); + return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes; +} + +// Do the field transformation needed for v6 -> v1 +function _v6ToV1(v6Bytes) { + return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); +} + +/***/ }), + +/***/ 9261: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _rng = _interopRequireDefault(__nccwpck_require__(2973)); +var _stringify = __nccwpck_require__(7597); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +/** + * UUID V7 - Unix Epoch time-based UUID + * + * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This + * implementation of V7 is based on the accepted, though not yet approved, + * revisions. + * + * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique + * IDentifiers (UUIDs) + + * + * Sample V7 value: + * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value + * + * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref: + * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1 + * + * 0 1 2 3 0 1 2 3 4 5 6 + * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | unix_ts_ms | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | unix_ts_ms | ver | seq_hi | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * |var| seq_low | rand | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * | rand | + * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ + * + * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit + * seq_low, and randomly initialized upon timestamp change. 31 bit counter size + * was selected as any bitwise operations in node are done as _signed_ 32 bit + * ints. we exclude the sign bit. + */ + +let _seqLow = null; +let _seqHigh = null; +let _msecs = 0; +function v7(options, buf, offset) { + options = options || {}; + + // initialize buffer and pointer + let i = buf && offset || 0; + const b = buf || new Uint8Array(16); + + // rnds is Uint8Array(16) filled with random bytes + const rnds = options.random || (options.rng || _rng.default)(); + + // milliseconds since unix epoch, 1970-01-01 00:00 + const msecs = options.msecs !== undefined ? options.msecs : Date.now(); + + // seq is user provided 31 bit counter + let seq = options.seq !== undefined ? options.seq : null; + + // initialize local seq high/low parts + let seqHigh = _seqHigh; + let seqLow = _seqLow; + + // check if clock has advanced and user has not provided msecs + if (msecs > _msecs && options.msecs === undefined) { + _msecs = msecs; + + // unless user provided seq, reset seq parts + if (seq !== null) { + seqHigh = null; + seqLow = null; + } + } + + // if we have a user provided seq + if (seq !== null) { + // trim provided seq to 31 bits of value, avoiding overflow + if (seq > 0x7fffffff) { + seq = 0x7fffffff; + } + + // split provided seq into high/low parts + seqHigh = seq >>> 19 & 0xfff; + seqLow = seq & 0x7ffff; + } + + // randomly initialize seq + if (seqHigh === null || seqLow === null) { + seqHigh = rnds[6] & 0x7f; + seqHigh = seqHigh << 8 | rnds[7]; + seqLow = rnds[8] & 0x3f; // pad for var + seqLow = seqLow << 8 | rnds[9]; + seqLow = seqLow << 5 | rnds[10] >>> 3; + } + + // increment seq if within msecs window + if (msecs + 10000 > _msecs && seq === null) { + if (++seqLow > 0x7ffff) { + seqLow = 0; + if (++seqHigh > 0xfff) { + seqHigh = 0; + + // increment internal _msecs. this allows us to continue incrementing + // while staying monotonic. Note, once we hit 10k milliseconds beyond system + // clock, we will reset breaking monotonicity (after (2^31)*10000 generations) + _msecs++; + } + } + } else { + // resetting; we have advanced more than + // 10k milliseconds beyond system clock + _msecs = msecs; + } + _seqHigh = seqHigh; + _seqLow = seqLow; + + // [bytes 0-5] 48 bits of local timestamp + b[i++] = _msecs / 0x10000000000 & 0xff; + b[i++] = _msecs / 0x100000000 & 0xff; + b[i++] = _msecs / 0x1000000 & 0xff; + b[i++] = _msecs / 0x10000 & 0xff; + b[i++] = _msecs / 0x100 & 0xff; + b[i++] = _msecs & 0xff; + + // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi + b[i++] = seqHigh >>> 4 & 0x0f | 0x70; + + // [byte 7] remaining 8 bits of seq_hi + b[i++] = seqHigh & 0xff; + + // [byte 8] - variant (2 bits), first 6 bits seq_low + b[i++] = seqLow >>> 13 & 0x3f | 0x80; + + // [byte 9] 8 bits seq_low + b[i++] = seqLow >>> 5 & 0xff; + + // [byte 10] remaining 5 bits seq_low, 3 bits random + b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07; + + // [bytes 11-15] always random + b[i++] = rnds[11]; + b[i++] = rnds[12]; + b[i++] = rnds[13]; + b[i++] = rnds[14]; + b[i++] = rnds[15]; + return buf || (0, _stringify.unsafeStringify)(b); +} +var _default = exports["default"] = v7; + +/***/ }), + +/***/ 6200: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _regex = _interopRequireDefault(__nccwpck_require__(7879)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function validate(uuid) { + return typeof uuid === 'string' && _regex.default.test(uuid); +} +var _default = exports["default"] = validate; + +/***/ }), + +/***/ 5868: +/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { + + + +Object.defineProperty(exports, "__esModule", ({ + value: true +})); +exports["default"] = void 0; +var _validate = _interopRequireDefault(__nccwpck_require__(6200)); +function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } +function version(uuid) { + if (!(0, _validate.default)(uuid)) { + throw TypeError('Invalid UUID'); + } + return parseInt(uuid.slice(14, 15), 16); +} +var _default = exports["default"] = version; + +/***/ }), + +/***/ 8264: +/***/ ((module) => { + +// Returns a wrapper function that returns a wrapped callback +// The wrapper function should do some stuff, and return a +// presumably different callback function. +// This makes sure that own properties are retained, so that +// decorations and such are not lost along the way. +module.exports = wrappy +function wrappy (fn, cb) { + if (fn && cb) return wrappy(fn)(cb) + + if (typeof fn !== 'function') + throw new TypeError('need wrapper function') + + Object.keys(fn).forEach(function (k) { + wrapper[k] = fn[k] + }) + + return wrapper + + function wrapper() { + var args = new Array(arguments.length) + for (var i = 0; i < args.length; i++) { + args[i] = arguments[i] + } + var ret = fn.apply(this, args) + var cb = args[args.length-1] + if (typeof ret === 'function' && ret !== cb) { + Object.keys(cb).forEach(function (k) { + ret[k] = cb[k] + }) + } + return ret + } +} + + +/***/ }), + +/***/ 2613: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert"); + +/***/ }), + +/***/ 290: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks"); + +/***/ }), + +/***/ 181: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer"); + +/***/ }), + +/***/ 5317: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process"); + +/***/ }), + +/***/ 4236: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("console"); + +/***/ }), + +/***/ 6982: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto"); + +/***/ }), + +/***/ 1637: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("diagnostics_channel"); + +/***/ }), + +/***/ 4434: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events"); + +/***/ }), + +/***/ 9896: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs"); + +/***/ }), + +/***/ 8611: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http"); + +/***/ }), + +/***/ 5675: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2"); + +/***/ }), + +/***/ 5692: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https"); + +/***/ }), + +/***/ 9278: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net"); + +/***/ }), + +/***/ 7598: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"); + +/***/ }), + +/***/ 8474: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events"); + +/***/ }), + +/***/ 7075: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream"); + +/***/ }), + +/***/ 7975: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util"); + +/***/ }), + +/***/ 857: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os"); + +/***/ }), + +/***/ 6928: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path"); + +/***/ }), + +/***/ 2987: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks"); + +/***/ }), + +/***/ 3480: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring"); + +/***/ }), + +/***/ 2203: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream"); + +/***/ }), + +/***/ 3774: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/web"); + +/***/ }), + +/***/ 3193: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder"); + +/***/ }), + +/***/ 3557: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers"); + +/***/ }), + +/***/ 4756: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls"); + +/***/ }), + +/***/ 7016: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url"); + +/***/ }), + +/***/ 9023: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util"); + +/***/ }), + +/***/ 8253: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util/types"); + +/***/ }), + +/***/ 8167: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads"); + +/***/ }), + +/***/ 3106: +/***/ ((module) => { + +module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib"); + +/***/ }), + +/***/ 7182: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const WritableStream = (__nccwpck_require__(7075).Writable) +const inherits = (__nccwpck_require__(7975).inherits) + +const StreamSearch = __nccwpck_require__(4136) + +const PartStream = __nccwpck_require__(612) +const HeaderParser = __nccwpck_require__(2271) + +const DASH = 45 +const B_ONEDASH = Buffer.from('-') +const B_CRLF = Buffer.from('\r\n') +const EMPTY_FN = function () {} + +function Dicer (cfg) { + if (!(this instanceof Dicer)) { return new Dicer(cfg) } + WritableStream.call(this, cfg) + + if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } + + if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } + + this._headerFirst = cfg.headerFirst + + this._dashes = 0 + this._parts = 0 + this._finished = false + this._realFinish = false + this._isPreamble = true + this._justMatched = false + this._firstWrite = true + this._inHeader = true + this._part = undefined + this._cb = undefined + this._ignoreData = false + this._partOpts = { highWaterMark: cfg.partHwm } + this._pause = false + + const self = this + this._hparser = new HeaderParser(cfg) + this._hparser.on('header', function (header) { + self._inHeader = false + self._part.emit('header', header) + }) +} +inherits(Dicer, WritableStream) + +Dicer.prototype.emit = function (ev) { + if (ev === 'finish' && !this._realFinish) { + if (!this._finished) { + const self = this + process.nextTick(function () { + self.emit('error', new Error('Unexpected end of multipart data')) + if (self._part && !self._ignoreData) { + const type = (self._isPreamble ? 'Preamble' : 'Part') + self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) + self._part.push(null) + process.nextTick(function () { + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + return + } + self._realFinish = true + self.emit('finish') + self._realFinish = false + }) + } + } else { WritableStream.prototype.emit.apply(this, arguments) } +} + +Dicer.prototype._write = function (data, encoding, cb) { + // ignore unexpected data (e.g. extra trailer data after finished) + if (!this._hparser && !this._bparser) { return cb() } + + if (this._headerFirst && this._isPreamble) { + if (!this._part) { + this._part = new PartStream(this._partOpts) + if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } + } + const r = this._hparser.push(data) + if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } + } + + // allows for "easier" testing + if (this._firstWrite) { + this._bparser.push(B_CRLF) + this._firstWrite = false + } + + this._bparser.push(data) + + if (this._pause) { this._cb = cb } else { cb() } +} + +Dicer.prototype.reset = function () { + this._part = undefined + this._bparser = undefined + this._hparser = undefined +} + +Dicer.prototype.setBoundary = function (boundary) { + const self = this + this._bparser = new StreamSearch('\r\n--' + boundary) + this._bparser.on('info', function (isMatch, data, start, end) { + self._oninfo(isMatch, data, start, end) + }) +} + +Dicer.prototype._ignore = function () { + if (this._part && !this._ignoreData) { + this._ignoreData = true + this._part.on('error', EMPTY_FN) + // we must perform some kind of read on the stream even though we are + // ignoring the data, otherwise node's Readable stream will not emit 'end' + // after pushing null to the stream + this._part.resume() + } +} + +Dicer.prototype._oninfo = function (isMatch, data, start, end) { + let buf; const self = this; let i = 0; let r; let shouldWriteMore = true + + if (!this._part && this._justMatched && data) { + while (this._dashes < 2 && (start + i) < end) { + if (data[start + i] === DASH) { + ++i + ++this._dashes + } else { + if (this._dashes) { buf = B_ONEDASH } + this._dashes = 0 + break + } + } + if (this._dashes === 2) { + if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } + this.reset() + this._finished = true + // no more parts will be added + if (self._parts === 0) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } + } + if (this._dashes) { return } + } + if (this._justMatched) { this._justMatched = false } + if (!this._part) { + this._part = new PartStream(this._partOpts) + this._part._read = function (n) { + self._unpause() + } + if (this._isPreamble && this.listenerCount('preamble') !== 0) { + this.emit('preamble', this._part) + } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { + this.emit('part', this._part) + } else { + this._ignore() + } + if (!this._isPreamble) { this._inHeader = true } + } + if (data && start < end && !this._ignoreData) { + if (this._isPreamble || !this._inHeader) { + if (buf) { shouldWriteMore = this._part.push(buf) } + shouldWriteMore = this._part.push(data.slice(start, end)) + if (!shouldWriteMore) { this._pause = true } + } else if (!this._isPreamble && this._inHeader) { + if (buf) { this._hparser.push(buf) } + r = this._hparser.push(data.slice(start, end)) + if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } + } + } + if (isMatch) { + this._hparser.reset() + if (this._isPreamble) { this._isPreamble = false } else { + if (start !== end) { + ++this._parts + this._part.on('end', function () { + if (--self._parts === 0) { + if (self._finished) { + self._realFinish = true + self.emit('finish') + self._realFinish = false + } else { + self._unpause() + } + } + }) + } + } + this._part.push(null) + this._part = undefined + this._ignoreData = false + this._justMatched = true + this._dashes = 0 + } +} + +Dicer.prototype._unpause = function () { + if (!this._pause) { return } + + this._pause = false + if (this._cb) { + const cb = this._cb + this._cb = undefined + cb() + } +} + +module.exports = Dicer + + +/***/ }), + +/***/ 2271: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const EventEmitter = (__nccwpck_require__(8474).EventEmitter) +const inherits = (__nccwpck_require__(7975).inherits) +const getLimit = __nccwpck_require__(2393) + +const StreamSearch = __nccwpck_require__(4136) + +const B_DCRLF = Buffer.from('\r\n\r\n') +const RE_CRLF = /\r\n/g +const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex + +function HeaderParser (cfg) { + EventEmitter.call(this) + + cfg = cfg || {} + const self = this + this.nread = 0 + this.maxed = false + this.npairs = 0 + this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) + this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) + this.buffer = '' + this.header = {} + this.finished = false + this.ss = new StreamSearch(B_DCRLF) + this.ss.on('info', function (isMatch, data, start, end) { + if (data && !self.maxed) { + if (self.nread + end - start >= self.maxHeaderSize) { + end = self.maxHeaderSize - self.nread + start + self.nread = self.maxHeaderSize + self.maxed = true + } else { self.nread += (end - start) } + + self.buffer += data.toString('binary', start, end) + } + if (isMatch) { self._finish() } + }) +} +inherits(HeaderParser, EventEmitter) + +HeaderParser.prototype.push = function (data) { + const r = this.ss.push(data) + if (this.finished) { return r } +} + +HeaderParser.prototype.reset = function () { + this.finished = false + this.buffer = '' + this.header = {} + this.ss.reset() +} + +HeaderParser.prototype._finish = function () { + if (this.buffer) { this._parseHeader() } + this.ss.matches = this.ss.maxMatches + const header = this.header + this.header = {} + this.buffer = '' + this.finished = true + this.nread = this.npairs = 0 + this.maxed = false + this.emit('header', header) +} + +HeaderParser.prototype._parseHeader = function () { + if (this.npairs === this.maxHeaderPairs) { return } + + const lines = this.buffer.split(RE_CRLF) + const len = lines.length + let m, h + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (lines[i].length === 0) { continue } + if (lines[i][0] === '\t' || lines[i][0] === ' ') { + // folded header content + // RFC2822 says to just remove the CRLF and not the whitespace following + // it, so we follow the RFC and include the leading whitespace ... + if (h) { + this.header[h][this.header[h].length - 1] += lines[i] + continue + } + } + + const posColon = lines[i].indexOf(':') + if ( + posColon === -1 || + posColon === 0 + ) { + return + } + m = RE_HDR.exec(lines[i]) + h = m[1].toLowerCase() + this.header[h] = this.header[h] || [] + this.header[h].push((m[2] || '')) + if (++this.npairs === this.maxHeaderPairs) { break } + } +} + +module.exports = HeaderParser + + +/***/ }), + +/***/ 612: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const inherits = (__nccwpck_require__(7975).inherits) +const ReadableStream = (__nccwpck_require__(7075).Readable) + +function PartStream (opts) { + ReadableStream.call(this, opts) +} +inherits(PartStream, ReadableStream) + +PartStream.prototype._read = function (n) {} + +module.exports = PartStream + + +/***/ }), + +/***/ 4136: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +/** + * Copyright Brian White. All rights reserved. + * + * @see https://github.com/mscdex/streamsearch + * + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + * + * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation + * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool + */ +const EventEmitter = (__nccwpck_require__(8474).EventEmitter) +const inherits = (__nccwpck_require__(7975).inherits) + +function SBMH (needle) { + if (typeof needle === 'string') { + needle = Buffer.from(needle) + } + + if (!Buffer.isBuffer(needle)) { + throw new TypeError('The needle has to be a String or a Buffer.') + } + + const needleLength = needle.length + + if (needleLength === 0) { + throw new Error('The needle cannot be an empty String/Buffer.') + } + + if (needleLength > 256) { + throw new Error('The needle cannot have a length bigger than 256.') + } + + this.maxMatches = Infinity + this.matches = 0 + + this._occ = new Array(256) + .fill(needleLength) // Initialize occurrence table. + this._lookbehind_size = 0 + this._needle = needle + this._bufpos = 0 + + this._lookbehind = Buffer.alloc(needleLength) + + // Populate occurrence table with analysis of the needle, + // ignoring last letter. + for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var + this._occ[needle[i]] = needleLength - 1 - i + } +} +inherits(SBMH, EventEmitter) + +SBMH.prototype.reset = function () { + this._lookbehind_size = 0 + this.matches = 0 + this._bufpos = 0 +} + +SBMH.prototype.push = function (chunk, pos) { + if (!Buffer.isBuffer(chunk)) { + chunk = Buffer.from(chunk, 'binary') + } + const chlen = chunk.length + this._bufpos = pos || 0 + let r + while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } + return r +} + +SBMH.prototype._sbmh_feed = function (data) { + const len = data.length + const needle = this._needle + const needleLength = needle.length + const lastNeedleChar = needle[needleLength - 1] + + // Positive: points to a position in `data` + // pos == 3 points to data[3] + // Negative: points to a position in the lookbehind buffer + // pos == -2 points to lookbehind[lookbehind_size - 2] + let pos = -this._lookbehind_size + let ch + + if (pos < 0) { + // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool + // search with character lookup code that considers both the + // lookbehind buffer and the current round's haystack data. + // + // Loop until + // there is a match. + // or until + // we've moved past the position that requires the + // lookbehind buffer. In this case we switch to the + // optimized loop. + // or until + // the character to look at lies outside the haystack. + while (pos < 0 && pos <= len - needleLength) { + ch = this._sbmh_lookup_char(data, pos + needleLength - 1) + + if ( + ch === lastNeedleChar && + this._sbmh_memcmp(data, pos, needleLength - 1) + ) { + this._lookbehind_size = 0 + ++this.matches + this.emit('info', true) + + return (this._bufpos = pos + needleLength) + } + pos += this._occ[ch] + } + + // No match. + + if (pos < 0) { + // There's too few data for Boyer-Moore-Horspool to run, + // so let's use a different algorithm to skip as much as + // we can. + // Forward pos until + // the trailing part of lookbehind + data + // looks like the beginning of the needle + // or until + // pos == 0 + while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } + } + + if (pos >= 0) { + // Discard lookbehind buffer. + this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) + this._lookbehind_size = 0 + } else { + // Cut off part of the lookbehind buffer that has + // been processed and append the entire haystack + // into it. + const bytesToCutOff = this._lookbehind_size + pos + if (bytesToCutOff > 0) { + // The cut off data is guaranteed not to contain the needle. + this.emit('info', false, this._lookbehind, 0, bytesToCutOff) + } + + this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, + this._lookbehind_size - bytesToCutOff) + this._lookbehind_size -= bytesToCutOff + + data.copy(this._lookbehind, this._lookbehind_size) + this._lookbehind_size += len + + this._bufpos = len + return len + } + } + + pos += (pos >= 0) * this._bufpos + + // Lookbehind buffer is now empty. We only need to check if the + // needle is in the haystack. + if (data.indexOf(needle, pos) !== -1) { + pos = data.indexOf(needle, pos) + ++this.matches + if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } + + return (this._bufpos = pos + needleLength) + } else { + pos = len - needleLength + } + + // There was no match. If there's trailing haystack data that we cannot + // match yet using the Boyer-Moore-Horspool algorithm (because the trailing + // data is less than the needle size) then match using a modified + // algorithm that starts matching from the beginning instead of the end. + // Whatever trailing data is left after running this algorithm is added to + // the lookbehind buffer. + while ( + pos < len && + ( + data[pos] !== needle[0] || + ( + (Buffer.compare( + data.subarray(pos, pos + len - pos), + needle.subarray(0, len - pos) + ) !== 0) + ) + ) + ) { + ++pos + } + if (pos < len) { + data.copy(this._lookbehind, 0, pos, pos + (len - pos)) + this._lookbehind_size = len - pos + } + + // Everything until pos is guaranteed not to contain needle data. + if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } + + this._bufpos = len + return len +} + +SBMH.prototype._sbmh_lookup_char = function (data, pos) { + return (pos < 0) + ? this._lookbehind[this._lookbehind_size + pos] + : data[pos] +} + +SBMH.prototype._sbmh_memcmp = function (data, pos, len) { + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } + } + return true +} + +module.exports = SBMH + + +/***/ }), + +/***/ 9581: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const WritableStream = (__nccwpck_require__(7075).Writable) +const { inherits } = __nccwpck_require__(7975) +const Dicer = __nccwpck_require__(7182) + +const MultipartParser = __nccwpck_require__(1192) +const UrlencodedParser = __nccwpck_require__(855) +const parseParams = __nccwpck_require__(8929) + +function Busboy (opts) { + if (!(this instanceof Busboy)) { return new Busboy(opts) } + + if (typeof opts !== 'object') { + throw new TypeError('Busboy expected an options-Object.') + } + if (typeof opts.headers !== 'object') { + throw new TypeError('Busboy expected an options-Object with headers-attribute.') + } + if (typeof opts.headers['content-type'] !== 'string') { + throw new TypeError('Missing Content-Type-header.') + } + + const { + headers, + ...streamOptions + } = opts + + this.opts = { + autoDestroy: false, + ...streamOptions + } + WritableStream.call(this, this.opts) + + this._done = false + this._parser = this.getParserByHeaders(headers) + this._finished = false +} +inherits(Busboy, WritableStream) + +Busboy.prototype.emit = function (ev) { + if (ev === 'finish') { + if (!this._done) { + this._parser?.end() + return + } else if (this._finished) { + return + } + this._finished = true + } + WritableStream.prototype.emit.apply(this, arguments) +} + +Busboy.prototype.getParserByHeaders = function (headers) { + const parsed = parseParams(headers['content-type']) + + const cfg = { + defCharset: this.opts.defCharset, + fileHwm: this.opts.fileHwm, + headers, + highWaterMark: this.opts.highWaterMark, + isPartAFile: this.opts.isPartAFile, + limits: this.opts.limits, + parsedConType: parsed, + preservePath: this.opts.preservePath + } + + if (MultipartParser.detect.test(parsed[0])) { + return new MultipartParser(this, cfg) + } + if (UrlencodedParser.detect.test(parsed[0])) { + return new UrlencodedParser(this, cfg) + } + throw new Error('Unsupported Content-Type.') +} + +Busboy.prototype._write = function (chunk, encoding, cb) { + this._parser.write(chunk, cb) +} + +module.exports = Busboy +module.exports["default"] = Busboy +module.exports.Busboy = Busboy + +module.exports.Dicer = Dicer + + +/***/ }), + +/***/ 1192: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +// TODO: +// * support 1 nested multipart level +// (see second multipart example here: +// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) +// * support limits.fieldNameSize +// -- this will require modifications to utils.parseParams + +const { Readable } = __nccwpck_require__(7075) +const { inherits } = __nccwpck_require__(7975) + +const Dicer = __nccwpck_require__(7182) + +const parseParams = __nccwpck_require__(8929) +const decodeText = __nccwpck_require__(2747) +const basename = __nccwpck_require__(692) +const getLimit = __nccwpck_require__(2393) + +const RE_BOUNDARY = /^boundary$/i +const RE_FIELD = /^form-data$/i +const RE_CHARSET = /^charset$/i +const RE_FILENAME = /^filename$/i +const RE_NAME = /^name$/i + +Multipart.detect = /^multipart\/form-data/i +function Multipart (boy, cfg) { + let i + let len + const self = this + let boundary + const limits = cfg.limits + const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) + const parsedConType = cfg.parsedConType || [] + const defCharset = cfg.defCharset || 'utf8' + const preservePath = cfg.preservePath + const fileOpts = { highWaterMark: cfg.fileHwm } + + for (i = 0, len = parsedConType.length; i < len; ++i) { + if (Array.isArray(parsedConType[i]) && + RE_BOUNDARY.test(parsedConType[i][0])) { + boundary = parsedConType[i][1] + break + } + } + + function checkFinished () { + if (nends === 0 && finished && !boy._done) { + finished = false + self.end() + } + } + + if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } + + const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) + const filesLimit = getLimit(limits, 'files', Infinity) + const fieldsLimit = getLimit(limits, 'fields', Infinity) + const partsLimit = getLimit(limits, 'parts', Infinity) + const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) + const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) + + let nfiles = 0 + let nfields = 0 + let nends = 0 + let curFile + let curField + let finished = false + + this._needDrain = false + this._pause = false + this._cb = undefined + this._nparts = 0 + this._boy = boy + + const parserCfg = { + boundary, + maxHeaderPairs: headerPairsLimit, + maxHeaderSize: headerSizeLimit, + partHwm: fileOpts.highWaterMark, + highWaterMark: cfg.highWaterMark + } + + this.parser = new Dicer(parserCfg) + this.parser.on('drain', function () { + self._needDrain = false + if (self._cb && !self._pause) { + const cb = self._cb + self._cb = undefined + cb() + } + }).on('part', function onPart (part) { + if (++self._nparts > partsLimit) { + self.parser.removeListener('part', onPart) + self.parser.on('part', skipPart) + boy.hitPartsLimit = true + boy.emit('partsLimit') + return skipPart(part) + } + + // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let + // us emit 'end' early since we know the part has ended if we are already + // seeing the next part + if (curField) { + const field = curField + field.emit('end') + field.removeAllListeners('end') + } + + part.on('header', function (header) { + let contype + let fieldname + let parsed + let charset + let encoding + let filename + let nsize = 0 + + if (header['content-type']) { + parsed = parseParams(header['content-type'][0]) + if (parsed[0]) { + contype = parsed[0].toLowerCase() + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_CHARSET.test(parsed[i][0])) { + charset = parsed[i][1].toLowerCase() + break + } + } + } + } + + if (contype === undefined) { contype = 'text/plain' } + if (charset === undefined) { charset = defCharset } + + if (header['content-disposition']) { + parsed = parseParams(header['content-disposition'][0]) + if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } + for (i = 0, len = parsed.length; i < len; ++i) { + if (RE_NAME.test(parsed[i][0])) { + fieldname = parsed[i][1] + } else if (RE_FILENAME.test(parsed[i][0])) { + filename = parsed[i][1] + if (!preservePath) { filename = basename(filename) } + } + } + } else { return skipPart(part) } + + if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } + + let onData, + onEnd + + if (isPartAFile(fieldname, contype, filename)) { + // file/binary field + if (nfiles === filesLimit) { + if (!boy.hitFilesLimit) { + boy.hitFilesLimit = true + boy.emit('filesLimit') + } + return skipPart(part) + } + + ++nfiles + + if (boy.listenerCount('file') === 0) { + self.parser._ignore() + return + } + + ++nends + const file = new FileStream(fileOpts) + curFile = file + file.on('end', function () { + --nends + self._pause = false + checkFinished() + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + }) + file._read = function (n) { + if (!self._pause) { return } + self._pause = false + if (self._cb && !self._needDrain) { + const cb = self._cb + self._cb = undefined + cb() + } + } + boy.emit('file', fieldname, file, filename, encoding, contype) + + onData = function (data) { + if ((nsize += data.length) > fileSizeLimit) { + const extralen = fileSizeLimit - nsize + data.length + if (extralen > 0) { file.push(data.slice(0, extralen)) } + file.truncated = true + file.bytesRead = fileSizeLimit + part.removeAllListeners('data') + file.emit('limit') + return + } else if (!file.push(data)) { self._pause = true } + + file.bytesRead = nsize + } + + onEnd = function () { + curFile = undefined + file.push(null) + } + } else { + // non-file field + if (nfields === fieldsLimit) { + if (!boy.hitFieldsLimit) { + boy.hitFieldsLimit = true + boy.emit('fieldsLimit') + } + return skipPart(part) + } + + ++nfields + ++nends + let buffer = '' + let truncated = false + curField = part + + onData = function (data) { + if ((nsize += data.length) > fieldSizeLimit) { + const extralen = (fieldSizeLimit - (nsize - data.length)) + buffer += data.toString('binary', 0, extralen) + truncated = true + part.removeAllListeners('data') + } else { buffer += data.toString('binary') } + } + + onEnd = function () { + curField = undefined + if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } + boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) + --nends + checkFinished() + } + } + + /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become + broken. Streams2/streams3 is a huge black box of confusion, but + somehow overriding the sync state seems to fix things again (and still + seems to work for previous node versions). + */ + part._readableState.sync = false + + part.on('data', onData) + part.on('end', onEnd) + }).on('error', function (err) { + if (curFile) { curFile.emit('error', err) } + }) + }).on('error', function (err) { + boy.emit('error', err) + }).on('finish', function () { + finished = true + checkFinished() + }) +} + +Multipart.prototype.write = function (chunk, cb) { + const r = this.parser.write(chunk) + if (r && !this._pause) { + cb() + } else { + this._needDrain = !r + this._cb = cb + } +} + +Multipart.prototype.end = function () { + const self = this + + if (self.parser.writable) { + self.parser.end() + } else if (!self._boy._done) { + process.nextTick(function () { + self._boy._done = true + self._boy.emit('finish') + }) + } +} + +function skipPart (part) { + part.resume() +} + +function FileStream (opts) { + Readable.call(this, opts) + + this.bytesRead = 0 + + this.truncated = false +} + +inherits(FileStream, Readable) + +FileStream.prototype._read = function (n) {} + +module.exports = Multipart + + +/***/ }), + +/***/ 855: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + + + +const Decoder = __nccwpck_require__(1496) +const decodeText = __nccwpck_require__(2747) +const getLimit = __nccwpck_require__(2393) + +const RE_CHARSET = /^charset$/i + +UrlEncoded.detect = /^application\/x-www-form-urlencoded/i +function UrlEncoded (boy, cfg) { + const limits = cfg.limits + const parsedConType = cfg.parsedConType + this.boy = boy + + this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) + this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) + this.fieldsLimit = getLimit(limits, 'fields', Infinity) + + let charset + for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var + if (Array.isArray(parsedConType[i]) && + RE_CHARSET.test(parsedConType[i][0])) { + charset = parsedConType[i][1].toLowerCase() + break + } + } + + if (charset === undefined) { charset = cfg.defCharset || 'utf8' } + + this.decoder = new Decoder() + this.charset = charset + this._fields = 0 + this._state = 'key' + this._checkingBytes = true + this._bytesKey = 0 + this._bytesVal = 0 + this._key = '' + this._val = '' + this._keyTrunc = false + this._valTrunc = false + this._hitLimit = false +} + +UrlEncoded.prototype.write = function (data, cb) { + if (this._fields === this.fieldsLimit) { + if (!this.boy.hitFieldsLimit) { + this.boy.hitFieldsLimit = true + this.boy.emit('fieldsLimit') + } + return cb() + } + + let idxeq; let idxamp; let i; let p = 0; const len = data.length + + while (p < len) { + if (this._state === 'key') { + idxeq = idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x3D/* = */) { + idxeq = i + break + } else if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesKey } + } + + if (idxeq !== undefined) { + // key with assignment + if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } + this._state = 'val' + + this._hitLimit = false + this._checkingBytes = true + this._val = '' + this._bytesVal = 0 + this._valTrunc = false + this.decoder.reset() + + p = idxeq + 1 + } else if (idxamp !== undefined) { + // key with no assignment + ++this._fields + let key; const keyTrunc = this._keyTrunc + if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + if (key.length) { + this.boy.emit('field', decodeText(key, 'binary', this.charset), + '', + keyTrunc, + false) + } + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._keyTrunc = true + } + } else { + if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } + p = len + } + } else { + idxamp = undefined + for (i = p; i < len; ++i) { + if (!this._checkingBytes) { ++p } + if (data[i] === 0x26/* & */) { + idxamp = i + break + } + if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { + this._hitLimit = true + break + } else if (this._checkingBytes) { ++this._bytesVal } + } + + if (idxamp !== undefined) { + ++this._fields + if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + this._state = 'key' + + this._hitLimit = false + this._checkingBytes = true + this._key = '' + this._bytesKey = 0 + this._keyTrunc = false + this.decoder.reset() + + p = idxamp + 1 + if (this._fields === this.fieldsLimit) { return cb() } + } else if (this._hitLimit) { + // we may not have hit the actual limit if there are encoded bytes... + if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } + p = i + if ((this._val === '' && this.fieldSizeLimit === 0) || + (this._bytesVal = this._val.length) === this.fieldSizeLimit) { + // yep, we actually did hit the limit + this._checkingBytes = false + this._valTrunc = true + } + } else { + if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } + p = len + } + } + } + cb() +} + +UrlEncoded.prototype.end = function () { + if (this.boy._done) { return } + + if (this._state === 'key' && this._key.length > 0) { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + '', + this._keyTrunc, + false) + } else if (this._state === 'val') { + this.boy.emit('field', decodeText(this._key, 'binary', this.charset), + decodeText(this._val, 'binary', this.charset), + this._keyTrunc, + this._valTrunc) + } + this.boy._done = true + this.boy.emit('finish') +} + +module.exports = UrlEncoded + + +/***/ }), + +/***/ 1496: +/***/ ((module) => { + + + +const RE_PLUS = /\+/g + +const HEX = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 +] + +function Decoder () { + this.buffer = undefined +} +Decoder.prototype.write = function (str) { + // Replace '+' with ' ' before decoding + str = str.replace(RE_PLUS, ' ') + let res = '' + let i = 0; let p = 0; const len = str.length + for (; i < len; ++i) { + if (this.buffer !== undefined) { + if (!HEX[str.charCodeAt(i)]) { + res += '%' + this.buffer + this.buffer = undefined + --i // retry character + } else { + this.buffer += str[i] + ++p + if (this.buffer.length === 2) { + res += String.fromCharCode(parseInt(this.buffer, 16)) + this.buffer = undefined + } + } + } else if (str[i] === '%') { + if (i > p) { + res += str.substring(p, i) + p = i + } + this.buffer = '' + ++p + } + } + if (p < len && this.buffer === undefined) { res += str.substring(p) } + return res +} +Decoder.prototype.reset = function () { + this.buffer = undefined +} + +module.exports = Decoder + + +/***/ }), + +/***/ 692: +/***/ ((module) => { + + + +module.exports = function basename (path) { + if (typeof path !== 'string') { return '' } + for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var + switch (path.charCodeAt(i)) { + case 0x2F: // '/' + case 0x5C: // '\' + path = path.slice(i + 1) + return (path === '..' || path === '.' ? '' : path) + } + } + return (path === '..' || path === '.' ? '' : path) +} + + +/***/ }), + +/***/ 2747: +/***/ (function(module) { + + + +// Node has always utf-8 +const utf8Decoder = new TextDecoder('utf-8') +const textDecoders = new Map([ + ['utf-8', utf8Decoder], + ['utf8', utf8Decoder] +]) + +function getDecoder (charset) { + let lc + while (true) { + switch (charset) { + case 'utf-8': + case 'utf8': + return decoders.utf8 + case 'latin1': + case 'ascii': // TODO: Make these a separate, strict decoder? + case 'us-ascii': + case 'iso-8859-1': + case 'iso8859-1': + case 'iso88591': + case 'iso_8859-1': + case 'windows-1252': + case 'iso_8859-1:1987': + case 'cp1252': + case 'x-cp1252': + return decoders.latin1 + case 'utf16le': + case 'utf-16le': + case 'ucs2': + case 'ucs-2': + return decoders.utf16le + case 'base64': + return decoders.base64 + default: + if (lc === undefined) { + lc = true + charset = charset.toLowerCase() + continue + } + return decoders.other.bind(charset) + } + } +} + +const decoders = { + utf8: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.utf8Slice(0, data.length) + }, + + latin1: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + return data + } + return data.latin1Slice(0, data.length) + }, + + utf16le: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.ucs2Slice(0, data.length) + }, + + base64: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + return data.base64Slice(0, data.length) + }, + + other: (data, sourceEncoding) => { + if (data.length === 0) { + return '' + } + if (typeof data === 'string') { + data = Buffer.from(data, sourceEncoding) + } + + if (textDecoders.has(this.toString())) { + try { + return textDecoders.get(this).decode(data) + } catch {} + } + return typeof data === 'string' + ? data + : data.toString() + } +} + +function decodeText (text, sourceEncoding, destEncoding) { + if (text) { + return getDecoder(destEncoding)(text, sourceEncoding) + } + return text +} + +module.exports = decodeText + + +/***/ }), + +/***/ 2393: +/***/ ((module) => { + + + +module.exports = function getLimit (limits, name, defaultLimit) { + if ( + !limits || + limits[name] === undefined || + limits[name] === null + ) { return defaultLimit } + + if ( + typeof limits[name] !== 'number' || + isNaN(limits[name]) + ) { throw new TypeError('Limit ' + name + ' is not a valid number') } + + return limits[name] +} + + +/***/ }), + +/***/ 8929: +/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { + +/* eslint-disable object-property-newline */ + + +const decodeText = __nccwpck_require__(2747) + +const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g + +const EncodedLookup = { + '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', + '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', + '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', + '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', + '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', + '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', + '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', + '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', + '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', + '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', + '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', + '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', + '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', + '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', + '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', + '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', + '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', + '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', + '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', + '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', + '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', + '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', + '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', + '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', + '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', + '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', + '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', + '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', + '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', + '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', + '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', + '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', + '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', + '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', + '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', + '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', + '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', + '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', + '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', + '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', + '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', + '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', + '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', + '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', + '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', + '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', + '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', + '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', + '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', + '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', + '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', + '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', + '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', + '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', + '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', + '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', + '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', + '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', + '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', + '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', + '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', + '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', + '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', + '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', + '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', + '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', + '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', + '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', + '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', + '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', + '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', + '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', + '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', + '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', + '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', + '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', + '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', + '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', + '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', + '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', + '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', + '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', + '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', + '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', + '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', + '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', + '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', + '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', + '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', + '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', + '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', + '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', + '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', + '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', + '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', + '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', + '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' +} + +function encodedReplacer (match) { + return EncodedLookup[match] +} + +const STATE_KEY = 0 +const STATE_VALUE = 1 +const STATE_CHARSET = 2 +const STATE_LANG = 3 + +function parseParams (str) { + const res = [] + let state = STATE_KEY + let charset = '' + let inquote = false + let escaping = false + let p = 0 + let tmp = '' + const len = str.length + + for (var i = 0; i < len; ++i) { // eslint-disable-line no-var + const char = str[i] + if (char === '\\' && inquote) { + if (escaping) { escaping = false } else { + escaping = true + continue + } + } else if (char === '"') { + if (!escaping) { + if (inquote) { + inquote = false + state = STATE_KEY + } else { inquote = true } + continue + } else { escaping = false } + } else { + if (escaping && inquote) { tmp += '\\' } + escaping = false + if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { + if (state === STATE_CHARSET) { + state = STATE_LANG + charset = tmp.substring(1) + } else { state = STATE_VALUE } + tmp = '' + continue + } else if (state === STATE_KEY && + (char === '*' || char === '=') && + res.length) { + state = char === '*' + ? STATE_CHARSET + : STATE_VALUE + res[p] = [tmp, undefined] + tmp = '' + continue + } else if (!inquote && char === ';') { + state = STATE_KEY + if (charset) { + if (tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } + charset = '' + } else if (tmp.length) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } + tmp = '' + ++p + continue + } else if (!inquote && (char === ' ' || char === '\t')) { continue } + } + tmp += char + } + if (charset && tmp.length) { + tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), + 'binary', + charset) + } else if (tmp) { + tmp = decodeText(tmp, 'binary', 'utf8') + } + + if (res[p] === undefined) { + if (tmp) { res[p] = tmp } + } else { res[p][1] = tmp } + + return res +} + +module.exports = parseParams + + +/***/ }) + +/******/ }); +/************************************************************************/ +/******/ // The module cache +/******/ var __webpack_module_cache__ = {}; +/******/ +/******/ // The require function +/******/ function __nccwpck_require__(moduleId) { +/******/ // Check if module is in cache +/******/ var cachedModule = __webpack_module_cache__[moduleId]; +/******/ if (cachedModule !== undefined) { +/******/ return cachedModule.exports; +/******/ } +/******/ // Create a new module (and put it into the cache) +/******/ var module = __webpack_module_cache__[moduleId] = { +/******/ id: moduleId, +/******/ loaded: false, +/******/ exports: {} +/******/ }; +/******/ +/******/ // Execute the module function +/******/ var threw = true; +/******/ try { +/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); +/******/ threw = false; +/******/ } finally { +/******/ if(threw) delete __webpack_module_cache__[moduleId]; +/******/ } +/******/ +/******/ // Flag the module as loaded +/******/ module.loaded = true; +/******/ +/******/ // Return the exports of the module +/******/ return module.exports; +/******/ } +/******/ +/************************************************************************/ +/******/ /* webpack/runtime/define property getters */ +/******/ (() => { +/******/ // define getter functions for harmony exports +/******/ __nccwpck_require__.d = (exports, definition) => { +/******/ for(var key in definition) { +/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) { +/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); +/******/ } +/******/ } +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/hasOwnProperty shorthand */ +/******/ (() => { +/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) +/******/ })(); +/******/ +/******/ /* webpack/runtime/make namespace object */ +/******/ (() => { +/******/ // define __esModule on exports +/******/ __nccwpck_require__.r = (exports) => { +/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { +/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); +/******/ } +/******/ Object.defineProperty(exports, '__esModule', { value: true }); +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/node module decorator */ +/******/ (() => { +/******/ __nccwpck_require__.nmd = (module) => { +/******/ module.paths = []; +/******/ if (!module.children) module.children = []; +/******/ return module; +/******/ }; +/******/ })(); +/******/ +/******/ /* webpack/runtime/compat */ +/******/ +/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/"; +/******/ +/************************************************************************/ +var __webpack_exports__ = {}; + +// NAMESPACE OBJECT: ./node_modules/zod/v4/core/regexes.js +var regexes_namespaceObject = {}; +__nccwpck_require__.r(regexes_namespaceObject); +__nccwpck_require__.d(regexes_namespaceObject, { + base64: () => (base64), + base64url: () => (base64url), + bigint: () => (bigint), + boolean: () => (regexes_boolean), + browserEmail: () => (browserEmail), + cidrv4: () => (cidrv4), + cidrv6: () => (cidrv6), + cuid: () => (cuid), + cuid2: () => (cuid2), + date: () => (date), + datetime: () => (datetime), + domain: () => (domain), + duration: () => (duration), + e164: () => (e164), + email: () => (email), + emoji: () => (emoji), + extendedDuration: () => (extendedDuration), + guid: () => (guid), + hex: () => (hex), + hostname: () => (hostname), + html5Email: () => (html5Email), + idnEmail: () => (idnEmail), + integer: () => (integer), + ipv4: () => (ipv4), + ipv6: () => (ipv6), + ksuid: () => (ksuid), + lowercase: () => (lowercase), + mac: () => (mac), + md5_base64: () => (md5_base64), + md5_base64url: () => (md5_base64url), + md5_hex: () => (md5_hex), + nanoid: () => (nanoid), + "null": () => (_null), + number: () => (number), + rfc5322Email: () => (rfc5322Email), + sha1_base64: () => (sha1_base64), + sha1_base64url: () => (sha1_base64url), + sha1_hex: () => (sha1_hex), + sha256_base64: () => (sha256_base64), + sha256_base64url: () => (sha256_base64url), + sha256_hex: () => (sha256_hex), + sha384_base64: () => (sha384_base64), + sha384_base64url: () => (sha384_base64url), + sha384_hex: () => (sha384_hex), + sha512_base64: () => (sha512_base64), + sha512_base64url: () => (sha512_base64url), + sha512_hex: () => (sha512_hex), + string: () => (string), + time: () => (time), + ulid: () => (ulid), + undefined: () => (_undefined), + unicodeEmail: () => (unicodeEmail), + uppercase: () => (uppercase), + uuid: () => (uuid), + uuid4: () => (uuid4), + uuid6: () => (regexes_uuid6), + uuid7: () => (regexes_uuid7), + xid: () => (xid) +}); + +// NAMESPACE OBJECT: ./node_modules/zod/v4/classic/checks.js +var classic_checks_namespaceObject = {}; +__nccwpck_require__.r(classic_checks_namespaceObject); +__nccwpck_require__.d(classic_checks_namespaceObject, { + endsWith: () => (_endsWith), + gt: () => (_gt), + gte: () => (_gte), + includes: () => (_includes), + length: () => (_length), + lowercase: () => (_lowercase), + lt: () => (_lt), + lte: () => (_lte), + maxLength: () => (_maxLength), + maxSize: () => (_maxSize), + mime: () => (_mime), + minLength: () => (_minLength), + minSize: () => (_minSize), + multipleOf: () => (_multipleOf), + negative: () => (_negative), + nonnegative: () => (_nonnegative), + nonpositive: () => (_nonpositive), + normalize: () => (_normalize), + overwrite: () => (_overwrite), + positive: () => (_positive), + property: () => (_property), + regex: () => (_regex), + size: () => (_size), + slugify: () => (_slugify), + startsWith: () => (_startsWith), + toLowerCase: () => (_toLowerCase), + toUpperCase: () => (_toUpperCase), + trim: () => (_trim), + uppercase: () => (_uppercase) +}); + +// NAMESPACE OBJECT: ./node_modules/zod/v4/classic/iso.js +var iso_namespaceObject = {}; +__nccwpck_require__.r(iso_namespaceObject); +__nccwpck_require__.d(iso_namespaceObject, { + ZodISODate: () => (ZodISODate), + ZodISODateTime: () => (ZodISODateTime), + ZodISODuration: () => (ZodISODuration), + ZodISOTime: () => (ZodISOTime), + date: () => (iso_date), + datetime: () => (iso_datetime), + duration: () => (iso_duration), + time: () => (iso_time) +}); + +// NAMESPACE OBJECT: ./node_modules/zod/v4/classic/schemas.js +var classic_schemas_namespaceObject = {}; +__nccwpck_require__.r(classic_schemas_namespaceObject); +__nccwpck_require__.d(classic_schemas_namespaceObject, { + ZodAny: () => (schemas_ZodAny), + ZodArray: () => (schemas_ZodArray), + ZodBase64: () => (ZodBase64), + ZodBase64URL: () => (ZodBase64URL), + ZodBigInt: () => (schemas_ZodBigInt), + ZodBigIntFormat: () => (ZodBigIntFormat), + ZodBoolean: () => (schemas_ZodBoolean), + ZodCIDRv4: () => (ZodCIDRv4), + ZodCIDRv6: () => (ZodCIDRv6), + ZodCUID: () => (ZodCUID), + ZodCUID2: () => (ZodCUID2), + ZodCatch: () => (schemas_ZodCatch), + ZodCodec: () => (ZodCodec), + ZodCustom: () => (ZodCustom), + ZodCustomStringFormat: () => (ZodCustomStringFormat), + ZodDate: () => (schemas_ZodDate), + ZodDefault: () => (schemas_ZodDefault), + ZodDiscriminatedUnion: () => (schemas_ZodDiscriminatedUnion), + ZodE164: () => (ZodE164), + ZodEmail: () => (ZodEmail), + ZodEmoji: () => (ZodEmoji), + ZodEnum: () => (schemas_ZodEnum), + ZodFile: () => (ZodFile), + ZodFunction: () => (schemas_ZodFunction), + ZodGUID: () => (ZodGUID), + ZodIPv4: () => (ZodIPv4), + ZodIPv6: () => (ZodIPv6), + ZodIntersection: () => (schemas_ZodIntersection), + ZodJWT: () => (ZodJWT), + ZodKSUID: () => (ZodKSUID), + ZodLazy: () => (schemas_ZodLazy), + ZodLiteral: () => (schemas_ZodLiteral), + ZodMAC: () => (ZodMAC), + ZodMap: () => (schemas_ZodMap), + ZodNaN: () => (schemas_ZodNaN), + ZodNanoID: () => (ZodNanoID), + ZodNever: () => (schemas_ZodNever), + ZodNonOptional: () => (ZodNonOptional), + ZodNull: () => (schemas_ZodNull), + ZodNullable: () => (schemas_ZodNullable), + ZodNumber: () => (schemas_ZodNumber), + ZodNumberFormat: () => (ZodNumberFormat), + ZodObject: () => (schemas_ZodObject), + ZodOptional: () => (schemas_ZodOptional), + ZodPipe: () => (ZodPipe), + ZodPrefault: () => (ZodPrefault), + ZodPromise: () => (schemas_ZodPromise), + ZodReadonly: () => (schemas_ZodReadonly), + ZodRecord: () => (schemas_ZodRecord), + ZodSet: () => (schemas_ZodSet), + ZodString: () => (schemas_ZodString), + ZodStringFormat: () => (ZodStringFormat), + ZodSuccess: () => (ZodSuccess), + ZodSymbol: () => (schemas_ZodSymbol), + ZodTemplateLiteral: () => (ZodTemplateLiteral), + ZodTransform: () => (ZodTransform), + ZodTuple: () => (schemas_ZodTuple), + ZodType: () => (schemas_ZodType), + ZodULID: () => (ZodULID), + ZodURL: () => (ZodURL), + ZodUUID: () => (ZodUUID), + ZodUndefined: () => (schemas_ZodUndefined), + ZodUnion: () => (schemas_ZodUnion), + ZodUnknown: () => (schemas_ZodUnknown), + ZodVoid: () => (schemas_ZodVoid), + ZodXID: () => (ZodXID), + ZodXor: () => (ZodXor), + _ZodString: () => (_ZodString), + _default: () => (schemas_default), + _function: () => (_function), + any: () => (any), + array: () => (array), + base64: () => (schemas_base64), + base64url: () => (schemas_base64url), + bigint: () => (schemas_bigint), + boolean: () => (schemas_boolean), + "catch": () => (schemas_catch), + check: () => (check), + cidrv4: () => (schemas_cidrv4), + cidrv6: () => (schemas_cidrv6), + codec: () => (codec), + cuid: () => (schemas_cuid), + cuid2: () => (schemas_cuid2), + custom: () => (schemas_custom), + date: () => (schemas_date), + describe: () => (schemas_describe), + discriminatedUnion: () => (discriminatedUnion), + e164: () => (schemas_e164), + email: () => (schemas_email), + emoji: () => (schemas_emoji), + "enum": () => (schemas_enum), + file: () => (file), + float32: () => (float32), + float64: () => (float64), + "function": () => (_function), + guid: () => (schemas_guid), + hash: () => (hash), + hex: () => (schemas_hex), + hostname: () => (schemas_hostname), + httpUrl: () => (httpUrl), + "instanceof": () => (_instanceof), + int: () => (schemas_int), + int32: () => (int32), + int64: () => (int64), + intersection: () => (intersection), + ipv4: () => (schemas_ipv4), + ipv6: () => (schemas_ipv6), + json: () => (json), + jwt: () => (jwt), + keyof: () => (keyof), + ksuid: () => (schemas_ksuid), + lazy: () => (lazy), + literal: () => (literal), + looseObject: () => (looseObject), + looseRecord: () => (looseRecord), + mac: () => (schemas_mac), + map: () => (map), + meta: () => (schemas_meta), + nan: () => (nan), + nanoid: () => (schemas_nanoid), + nativeEnum: () => (nativeEnum), + never: () => (schemas_never), + nonoptional: () => (nonoptional), + "null": () => (schemas_null), + nullable: () => (nullable), + nullish: () => (schemas_nullish), + number: () => (schemas_number), + object: () => (object), + optional: () => (optional), + partialRecord: () => (partialRecord), + pipe: () => (pipe), + prefault: () => (prefault), + preprocess: () => (preprocess), + promise: () => (promise), + readonly: () => (readonly), + record: () => (record), + refine: () => (refine), + set: () => (set), + strictObject: () => (strictObject), + string: () => (schemas_string), + stringFormat: () => (stringFormat), + stringbool: () => (stringbool), + success: () => (success), + superRefine: () => (superRefine), + symbol: () => (symbol), + templateLiteral: () => (templateLiteral), + transform: () => (transform), + tuple: () => (tuple), + uint32: () => (uint32), + uint64: () => (uint64), + ulid: () => (schemas_ulid), + undefined: () => (schemas_undefined), + union: () => (union), + unknown: () => (unknown), + url: () => (url), + uuid: () => (schemas_uuid), + uuidv4: () => (uuidv4), + uuidv6: () => (uuidv6), + uuidv7: () => (schemas_uuidv7), + "void": () => (schemas_void), + xid: () => (schemas_xid), + xor: () => (xor) +}); + +// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js +var core = __nccwpck_require__(7484); +// EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js +var github = __nccwpck_require__(3228); +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/_virtual/rolldown_runtime.js +//#region rolldown:runtime +var __defProp = Object.defineProperty; +var __export = (target, all) => { + for (var name in all) __defProp(target, name, { + get: all[name], + enumerable: true + }); +}; + +//#endregion + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js +//#region src/singletons/async_local_storage/globals.ts +const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); +const globals_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); +const setGlobalAsyncLocalStorageInstance = (instance) => { + globalThis[TRACING_ALS_KEY] = instance; +}; +const globals_getGlobalAsyncLocalStorageInstance = () => { + return globalThis[TRACING_ALS_KEY]; +}; + +//#endregion + +//# sourceMappingURL=globals.js.map +// EXTERNAL MODULE: ./node_modules/decamelize/index.js +var decamelize = __nccwpck_require__(8203); +// EXTERNAL MODULE: ./node_modules/camelcase/index.js +var camelcase = __nccwpck_require__(9890); +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/map_keys.js + + + +//#region src/load/map_keys.ts +function keyToJson(key, map) { + return map?.[key] || decamelize(key); +} +function keyFromJson(key, map) { + return map?.[key] || camelcase(key); +} +function mapKeys(fields, mapper, map) { + const mapped = {}; + for (const key in fields) if (Object.hasOwn(fields, key)) mapped[mapper(key, map)] = fields[key]; + return mapped; +} + +//#endregion + +//# sourceMappingURL=map_keys.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/validation.js +//#region src/load/validation.ts +/** +* Sentinel key used to mark escaped user objects during serialization. +* +* When a plain object contains 'lc' key (which could be confused with LC objects), +* we wrap it as `{"__lc_escaped__": {...original...}}`. +*/ +const LC_ESCAPED_KEY = "__lc_escaped__"; +/** +* Check if an object needs escaping to prevent confusion with LC objects. +* +* An object needs escaping if: +* 1. It has an `'lc'` key (could be confused with LC serialization format) +* 2. It has only the escape key (would be mistaken for an escaped object) +*/ +function needsEscaping(obj) { + return "lc" in obj || Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj; +} +/** +* Wrap an object in the escape marker. +* +* @example +* ```typescript +* {"key": "value"} // becomes {"__lc_escaped__": {"key": "value"}} +* ``` +*/ +function escapeObject(obj) { + return { [LC_ESCAPED_KEY]: obj }; +} +/** +* Check if an object is an escaped user object. +* +* @example +* ```typescript +* {"__lc_escaped__": {...}} // is an escaped object +* ``` +*/ +function isEscapedObject(obj) { + return Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj; +} +/** +* Check if an object looks like a Serializable instance (duck typing). +*/ +function isSerializableLike(obj) { + return obj !== null && typeof obj === "object" && "lc_serializable" in obj && typeof obj.toJSON === "function"; +} +/** +* Escape a value if it needs escaping (contains `lc` key). +* +* This is a simpler version of `serializeValue` that doesn't handle Serializable +* objects - it's meant to be called on kwargs values that have already been +* processed by `toJSON()`. +* +* @param value - The value to potentially escape. +* @returns The value with any `lc`-containing objects wrapped in escape markers. +*/ +function escapeIfNeeded(value) { + if (value !== null && typeof value === "object" && !Array.isArray(value)) { + if (isSerializableLike(value)) return value; + const record = value; + if (needsEscaping(record)) return escapeObject(record); + const result = {}; + for (const [key, val] of Object.entries(record)) result[key] = escapeIfNeeded(val); + return result; + } + if (Array.isArray(value)) return value.map((item) => escapeIfNeeded(item)); + return value; +} +/** +* Unescape a value, processing escape markers in object values and arrays. +* +* When an escaped object is encountered (`{"__lc_escaped__": ...}`), it's +* unwrapped and the contents are returned AS-IS (no further processing). +* The contents represent user data that should not be modified. +* +* For regular objects and arrays, we recurse to find any nested escape markers. +* +* @param obj - The value to unescape. +* @returns The unescaped value. +*/ +function unescapeValue(obj) { + if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) { + const record = obj; + if (isEscapedObject(record)) return record[LC_ESCAPED_KEY]; + const result = {}; + for (const [key, value] of Object.entries(record)) result[key] = unescapeValue(value); + return result; + } + if (Array.isArray(obj)) return obj.map((item) => unescapeValue(item)); + return obj; +} + +//#endregion + +//# sourceMappingURL=validation.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/serializable.js + + + + +//#region src/load/serializable.ts +var serializable_exports = {}; +__export(serializable_exports, { + Serializable: () => Serializable, + get_lc_unique_name: () => get_lc_unique_name +}); +function shallowCopy(obj) { + return Array.isArray(obj) ? [...obj] : { ...obj }; +} +function replaceSecrets(root, secretsMap) { + const result = shallowCopy(root); + for (const [path, secretId] of Object.entries(secretsMap)) { + const [last, ...partsReverse] = path.split(".").reverse(); + let current = result; + for (const part of partsReverse.reverse()) { + if (current[part] === void 0) break; + current[part] = shallowCopy(current[part]); + current = current[part]; + } + if (current[last] !== void 0) current[last] = { + lc: 1, + type: "secret", + id: [secretId] + }; + } + return result; +} +/** +* Get a unique name for the module, rather than parent class implementations. +* Should not be subclassed, subclass lc_name above instead. +*/ +function get_lc_unique_name(serializableClass) { + const parentClass = Object.getPrototypeOf(serializableClass); + const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name()); + if (lcNameIsSubclassed) return serializableClass.lc_name(); + else return serializableClass.name; +} +var Serializable = class Serializable { + lc_serializable = false; + lc_kwargs; + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [...this.lc_namespace, get_lc_unique_name(this.constructor)]; + } + /** + * A map of secrets, which will be omitted from serialization. + * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". + * Values are the secret ids, which will be used when deserializing. + */ + get lc_secrets() { + return void 0; + } + /** + * A map of additional attributes to merge with constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the attribute values, which will be serialized. + * These attributes need to be accepted by the constructor as arguments. + */ + get lc_attributes() { + return void 0; + } + /** + * A map of aliases for constructor args. + * Keys are the attribute names, e.g. "foo". + * Values are the alias that will replace the key in serialization. + * This is used to eg. make argument names match Python. + */ + get lc_aliases() { + return void 0; + } + /** + * A manual list of keys that should be serialized. + * If not overridden, all fields passed into the constructor will be serialized. + */ + get lc_serializable_keys() { + return void 0; + } + constructor(kwargs, ..._args) { + if (this.lc_serializable_keys !== void 0) this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key))); + else this.lc_kwargs = kwargs ?? {}; + } + toJSON() { + if (!this.lc_serializable) return this.toJSONNotImplemented(); + if (this.lc_kwargs instanceof Serializable || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs)) return this.toJSONNotImplemented(); + const aliases = {}; + const secrets = {}; + const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { + acc[key] = key in this ? this[key] : this.lc_kwargs[key]; + return acc; + }, {}); + for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { + Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); + Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); + Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); + } + Object.keys(secrets).forEach((keyPath) => { + let read = this; + let write = kwargs; + const [last, ...partsReverse] = keyPath.split(".").reverse(); + for (const key of partsReverse.reverse()) { + if (!(key in read) || read[key] === void 0) return; + if (!(key in write) || write[key] === void 0) { + if (typeof read[key] === "object" && read[key] != null) write[key] = {}; + else if (Array.isArray(read[key])) write[key] = []; + } + read = read[key]; + write = write[key]; + } + if (last in read && read[last] !== void 0) write[last] = write[last] || read[last]; + }); + const escapedKwargs = {}; + for (const [key, value] of Object.entries(kwargs)) escapedKwargs[key] = escapeIfNeeded(value); + const kwargsWithSecrets = Object.keys(secrets).length ? replaceSecrets(escapedKwargs, secrets) : escapedKwargs; + const processedKwargs = mapKeys(kwargsWithSecrets, keyToJson, aliases); + return { + lc: 1, + type: "constructor", + id: this.lc_id, + kwargs: processedKwargs + }; + } + toJSONNotImplemented() { + return { + lc: 1, + type: "not_implemented", + id: this.lc_id + }; + } +}; + +//#endregion + +//# sourceMappingURL=serializable.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/data.js +//#region src/messages/content/data.ts +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function isDataContentBlock(content_block) { + return typeof content_block === "object" && content_block !== null && "type" in content_block && typeof content_block.type === "string" && "source_type" in content_block && (content_block.source_type === "url" || content_block.source_type === "base64" || content_block.source_type === "text" || content_block.source_type === "id"); +} +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function isURLContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "url" && "url" in content_block && typeof content_block.url === "string"; +} +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function isBase64ContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "base64" && "data" in content_block && typeof content_block.data === "string"; +} +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function isPlainTextContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "text" && "text" in content_block && typeof content_block.text === "string"; +} +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function isIDContentBlock(content_block) { + return isDataContentBlock(content_block) && content_block.source_type === "id" && "id" in content_block && typeof content_block.id === "string"; +} +/** +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function convertToOpenAIImageBlock(content_block) { + if (isDataContentBlock(content_block)) { + if (content_block.source_type === "url") return { + type: "image_url", + image_url: { url: content_block.url } + }; + if (content_block.source_type === "base64") { + if (!content_block.mime_type) throw new Error("mime_type key is required for base64 data."); + const mime_type = content_block.mime_type; + return { + type: "image_url", + image_url: { url: `data:${mime_type};base64,${content_block.data}` } + }; + } + } + throw new Error("Unsupported source type. Only 'url' and 'base64' are supported."); +} +/** +* Utility function for ChatModelProviders. Parses a mime type into a type, subtype, and parameters. +* +* @param mime_type - The mime type to parse. +* @returns An object containing the type, subtype, and parameters. +* +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function parseMimeType(mime_type) { + const parts = mime_type.split(";")[0].split("/"); + if (parts.length !== 2) throw new Error(`Invalid mime type: "${mime_type}" - does not match type/subtype format.`); + const type = parts[0].trim(); + const subtype = parts[1].trim(); + if (type === "" || subtype === "") throw new Error(`Invalid mime type: "${mime_type}" - type or subtype is empty.`); + const parameters = {}; + for (const parameterKvp of mime_type.split(";").slice(1)) { + const parameterParts = parameterKvp.split("="); + if (parameterParts.length !== 2) throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); + const key = parameterParts[0].trim(); + const value = parameterParts[1].trim(); + if (key === "") throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); + parameters[key] = value; + } + return { + type, + subtype, + parameters + }; +} +/** +* Utility function for ChatModelProviders. Parses a base64 data URL into a typed array or string. +* +* @param dataUrl - The base64 data URL to parse. +* @param asTypedArray - Whether to return the data as a typed array. +* @returns The parsed data and mime type, or undefined if the data URL is invalid. +* +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function parseBase64DataUrl({ dataUrl: data_url, asTypedArray = false }) { + const formatMatch = data_url.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/); + let mime_type; + if (formatMatch) { + mime_type = formatMatch[1].toLowerCase(); + const data = asTypedArray ? Uint8Array.from(atob(formatMatch[2]), (c) => c.charCodeAt(0)) : formatMatch[2]; + return { + mime_type, + data + }; + } + return void 0; +} +/** +* Convert from a standard data content block to a provider's proprietary data content block format. +* +* Don't override this method. Instead, override the more specific conversion methods and use this +* method unmodified. +* +* @param block - The standard data content block to convert. +* @returns The provider data content block. +* @throws An error if the standard data content block type is not supported. +* +* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. +*/ +function convertToProviderContentBlock(block, converter) { + if (block.type === "text") { + if (!converter.fromStandardTextBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardTextBlock\` method.`); + return converter.fromStandardTextBlock(block); + } + if (block.type === "image") { + if (!converter.fromStandardImageBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardImageBlock\` method.`); + return converter.fromStandardImageBlock(block); + } + if (block.type === "audio") { + if (!converter.fromStandardAudioBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardAudioBlock\` method.`); + return converter.fromStandardAudioBlock(block); + } + if (block.type === "file") { + if (!converter.fromStandardFileBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardFileBlock\` method.`); + return converter.fromStandardFileBlock(block); + } + throw new Error(`Unable to convert content block type '${block.type}' to provider-specific format: not recognized.`); +} + +//#endregion + +//# sourceMappingURL=data.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/utils.js +//#region src/messages/block_translators/utils.ts +function _isContentBlock(block, type) { + return _isObject(block) && block.type === type; +} +function _isObject(value) { + return typeof value === "object" && value !== null; +} +function _isArray(value) { + return Array.isArray(value); +} +function _isString(value) { + return typeof value === "string"; +} +function _isNumber(value) { + return typeof value === "number"; +} +function _isBytesArray(value) { + return value instanceof Uint8Array; +} +function safeParseJson(value) { + try { + return JSON.parse(value); + } catch { + return void 0; + } +} +const iife = (fn) => fn(); + +//#endregion + +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/anthropic.js + + +//#region src/messages/block_translators/anthropic.ts +function convertAnthropicAnnotation(citation) { + if (citation.type === "char_location" && _isString(citation.document_title) && _isNumber(citation.start_char_index) && _isNumber(citation.end_char_index) && _isString(citation.cited_text)) { + const { document_title, start_char_index, end_char_index, cited_text,...rest } = citation; + return { + ...rest, + type: "citation", + source: "char", + title: document_title ?? void 0, + startIndex: start_char_index, + endIndex: end_char_index, + citedText: cited_text + }; + } + if (citation.type === "page_location" && _isString(citation.document_title) && _isNumber(citation.start_page_number) && _isNumber(citation.end_page_number) && _isString(citation.cited_text)) { + const { document_title, start_page_number, end_page_number, cited_text,...rest } = citation; + return { + ...rest, + type: "citation", + source: "page", + title: document_title ?? void 0, + startIndex: start_page_number, + endIndex: end_page_number, + citedText: cited_text + }; + } + if (citation.type === "content_block_location" && _isString(citation.document_title) && _isNumber(citation.start_block_index) && _isNumber(citation.end_block_index) && _isString(citation.cited_text)) { + const { document_title, start_block_index, end_block_index, cited_text,...rest } = citation; + return { + ...rest, + type: "citation", + source: "block", + title: document_title ?? void 0, + startIndex: start_block_index, + endIndex: end_block_index, + citedText: cited_text + }; + } + if (citation.type === "web_search_result_location" && _isString(citation.url) && _isString(citation.title) && _isString(citation.encrypted_index) && _isString(citation.cited_text)) { + const { url, title, encrypted_index, cited_text,...rest } = citation; + return { + ...rest, + type: "citation", + source: "url", + url, + title, + startIndex: Number(encrypted_index), + endIndex: Number(encrypted_index), + citedText: cited_text + }; + } + if (citation.type === "search_result_location" && _isString(citation.source) && _isString(citation.title) && _isNumber(citation.start_block_index) && _isNumber(citation.end_block_index) && _isString(citation.cited_text)) { + const { source, title, start_block_index, end_block_index, cited_text,...rest } = citation; + return { + ...rest, + type: "citation", + source: "search", + url: source, + title: title ?? void 0, + startIndex: start_block_index, + endIndex: end_block_index, + citedText: cited_text + }; + } + return void 0; +} +/** +* Converts an Anthropic content block to a standard V1 content block. +* +* This function handles the conversion of Anthropic-specific content blocks +* (document and image blocks) to the standardized V1 format. It supports +* various source types including base64 data, URLs, file IDs, and text data. +* +* @param block - The Anthropic content block to convert +* @returns A standard V1 content block if conversion is successful, undefined otherwise +* +* @example +* ```typescript +* const anthropicBlock = { +* type: "image", +* source: { +* type: "base64", +* media_type: "image/png", +* data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" +* } +* }; +* +* const standardBlock = convertToV1FromAnthropicContentBlock(anthropicBlock); +* // Returns: { type: "image", mimeType: "image/png", data: "..." } +* ``` +*/ +function convertToV1FromAnthropicContentBlock(block) { + if (_isContentBlock(block, "document") && _isObject(block.source) && "type" in block.source) { + if (block.source.type === "base64" && _isString(block.source.media_type) && _isString(block.source.data)) return { + type: "file", + mimeType: block.source.media_type, + data: block.source.data + }; + else if (block.source.type === "url" && _isString(block.source.url)) return { + type: "file", + url: block.source.url + }; + else if (block.source.type === "file" && _isString(block.source.file_id)) return { + type: "file", + fileId: block.source.file_id + }; + else if (block.source.type === "text" && _isString(block.source.data)) return { + type: "file", + mimeType: String(block.source.media_type ?? "text/plain"), + data: block.source.data + }; + } else if (_isContentBlock(block, "image") && _isObject(block.source) && "type" in block.source) { + if (block.source.type === "base64" && _isString(block.source.media_type) && _isString(block.source.data)) return { + type: "image", + mimeType: block.source.media_type, + data: block.source.data + }; + else if (block.source.type === "url" && _isString(block.source.url)) return { + type: "image", + url: block.source.url + }; + else if (block.source.type === "file" && _isString(block.source.file_id)) return { + type: "image", + fileId: block.source.file_id + }; + } + return void 0; +} +/** +* Converts an array of content blocks from Anthropic format to v1 standard format. +* +* This function processes each content block in the input array, attempting to convert +* Anthropic-specific block formats (like image blocks with source objects, document blocks, etc.) +* to the standardized v1 content block format. If a block cannot be converted, it is +* passed through as-is with a type assertion to ContentBlock.Standard. +* +* @param content - Array of content blocks in Anthropic format to be converted +* @returns Array of content blocks in v1 standard format +*/ +function convertToV1FromAnthropicInput(content) { + function* iterateContent() { + for (const block of content) { + const stdBlock = convertToV1FromAnthropicContentBlock(block); + if (stdBlock) yield stdBlock; + else yield block; + } + } + return Array.from(iterateContent()); +} +/** +* Converts an Anthropic AI message to an array of v1 standard content blocks. +* +* This function processes an AI message containing Anthropic-specific content blocks +* and converts them to the standardized v1 content block format. +* +* @param message - The AI message containing Anthropic-formatted content blocks +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const message = new AIMessage([ +* { type: "text", text: "Hello world" }, +* { type: "thinking", text: "Let me think about this..." }, +* { type: "tool_use", id: "123", name: "calculator", input: { a: 1, b: 2 } } +* ]); +* +* const standardBlocks = convertToV1FromAnthropicMessage(message); +* // Returns: +* // [ +* // { type: "text", text: "Hello world" }, +* // { type: "reasoning", reasoning: "Let me think about this..." }, +* // { type: "tool_call", id: "123", name: "calculator", args: { a: 1, b: 2 } } +* // ] +* ``` +*/ +function convertToV1FromAnthropicMessage(message) { + function* iterateContent() { + const content = typeof message.content === "string" ? [{ + type: "text", + text: message.content + }] : message.content; + for (const block of content) { + if (_isContentBlock(block, "text") && _isString(block.text)) { + const { text, citations,...rest } = block; + if (_isArray(citations) && citations.length) { + const _citations = citations.reduce((acc, item) => { + const citation = convertAnthropicAnnotation(item); + if (citation) return [...acc, citation]; + return acc; + }, []); + yield { + ...rest, + type: "text", + text, + annotations: _citations + }; + continue; + } else { + yield { + ...rest, + type: "text", + text + }; + continue; + } + } else if (_isContentBlock(block, "thinking") && _isString(block.thinking)) { + const { thinking, signature,...rest } = block; + yield { + ...rest, + type: "reasoning", + reasoning: thinking, + signature + }; + continue; + } else if (_isContentBlock(block, "redacted_thinking")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "tool_use") && _isString(block.name) && _isString(block.id)) { + yield { + type: "tool_call", + id: block.id, + name: block.name, + args: block.input + }; + continue; + } else if (_isContentBlock(block, "input_json_delta")) { + if (_isAIMessageChunk(message) && message.tool_call_chunks?.length) { + const tool_call_chunk = message.tool_call_chunks[0]; + yield { + type: "tool_call_chunk", + id: tool_call_chunk.id, + name: tool_call_chunk.name, + args: tool_call_chunk.args, + index: tool_call_chunk.index + }; + continue; + } + } else if (_isContentBlock(block, "server_tool_use") && _isString(block.name) && _isString(block.id)) { + const { name, id } = block; + if (name === "web_search") { + const query = iife(() => { + if (typeof block.input === "string") return block.input; + else if (_isObject(block.input) && _isString(block.input.query)) return block.input.query; + else if (_isString(block.partial_json)) { + const json = safeParseJson(block.partial_json); + if (json?.query) return json.query; + } + return ""; + }); + yield { + id, + type: "server_tool_call", + name: "web_search", + args: { query } + }; + continue; + } else if (block.name === "code_execution") { + const code = iife(() => { + if (typeof block.input === "string") return block.input; + else if (_isObject(block.input) && _isString(block.input.code)) return block.input.code; + else if (_isString(block.partial_json)) { + const json = safeParseJson(block.partial_json); + if (json?.code) return json.code; + } + return ""; + }); + yield { + id, + type: "server_tool_call", + name: "code_execution", + args: { code } + }; + continue; + } + } else if (_isContentBlock(block, "web_search_tool_result") && _isString(block.tool_use_id) && _isArray(block.content)) { + const { content: content$1, tool_use_id } = block; + const urls = content$1.reduce((acc, content$2) => { + if (_isContentBlock(content$2, "web_search_result")) return [...acc, content$2.url]; + return acc; + }, []); + yield { + type: "server_tool_call_result", + name: "web_search", + toolCallId: tool_use_id, + status: "success", + output: { urls } + }; + continue; + } else if (_isContentBlock(block, "code_execution_tool_result") && _isString(block.tool_use_id) && _isObject(block.content)) { + yield { + type: "server_tool_call_result", + name: "code_execution", + toolCallId: block.tool_use_id, + status: "success", + output: block.content + }; + continue; + } else if (_isContentBlock(block, "mcp_tool_use")) { + yield { + id: block.id, + type: "server_tool_call", + name: "mcp_tool_use", + args: block.input + }; + continue; + } else if (_isContentBlock(block, "mcp_tool_result") && _isString(block.tool_use_id) && _isObject(block.content)) { + yield { + type: "server_tool_call_result", + name: "mcp_tool_use", + toolCallId: block.tool_use_id, + status: "success", + output: block.content + }; + continue; + } else if (_isContentBlock(block, "container_upload")) { + yield { + type: "server_tool_call", + name: "container_upload", + args: block.input + }; + continue; + } else if (_isContentBlock(block, "search_result")) { + yield { + id: block.id, + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "tool_result")) { + yield { + id: block.id, + type: "non_standard", + value: block + }; + continue; + } else { + const stdBlock = convertToV1FromAnthropicContentBlock(block); + if (stdBlock) { + yield stdBlock; + continue; + } + } + yield { + type: "non_standard", + value: block + }; + } + } + return Array.from(iterateContent()); +} +const ChatAnthropicTranslator = { + translateContent: convertToV1FromAnthropicMessage, + translateContentChunk: convertToV1FromAnthropicMessage +}; +function _isAIMessageChunk(message) { + return typeof message?._getType === "function" && typeof message.concat === "function" && message._getType() === "ai"; +} + +//#endregion + +//# sourceMappingURL=anthropic.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/data.js + + + +//#region src/messages/block_translators/data.ts +function convertToV1FromDataContentBlock(block) { + if (isURLContentBlock(block)) return { + type: block.type, + mimeType: block.mime_type, + url: block.url, + metadata: block.metadata + }; + if (isBase64ContentBlock(block)) return { + type: block.type, + mimeType: block.mime_type ?? "application/octet-stream", + data: block.data, + metadata: block.metadata + }; + if (isIDContentBlock(block)) return { + type: block.type, + mimeType: block.mime_type, + fileId: block.id, + metadata: block.metadata + }; + return block; +} +function convertToV1FromDataContent(content) { + return content.map(convertToV1FromDataContentBlock); +} +function isOpenAIDataBlock(block) { + if (_isContentBlock(block, "image_url") && _isObject(block.image_url)) return true; + if (_isContentBlock(block, "input_audio") && _isObject(block.input_audio)) return true; + if (_isContentBlock(block, "file") && _isObject(block.file)) return true; + return false; +} +function convertToV1FromOpenAIDataBlock(block) { + if (_isContentBlock(block, "image_url") && _isObject(block.image_url) && _isString(block.image_url.url)) { + const parsed = parseBase64DataUrl({ dataUrl: block.image_url.url }); + if (parsed) return { + type: "image", + mimeType: parsed.mime_type, + data: parsed.data + }; + else return { + type: "image", + url: block.image_url.url + }; + } else if (_isContentBlock(block, "input_audio") && _isObject(block.input_audio) && _isString(block.input_audio.data) && _isString(block.input_audio.format)) return { + type: "audio", + data: block.input_audio.data, + mimeType: `audio/${block.input_audio.format}` + }; + else if (_isContentBlock(block, "file") && _isObject(block.file) && _isString(block.file.data)) { + const parsed = parseBase64DataUrl({ dataUrl: block.file.data }); + if (parsed) return { + type: "file", + data: parsed.data, + mimeType: parsed.mime_type + }; + else if (_isString(block.file.file_id)) return { + type: "file", + fileId: block.file.file_id + }; + } + return block; +} + +//#endregion + +//# sourceMappingURL=data.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/openai.js + + + +//#region src/messages/block_translators/openai.ts +/** +* Converts a ChatOpenAICompletions message to an array of v1 standard content blocks. +* +* This function processes an AI message from ChatOpenAICompletions API format +* and converts it to the standardized v1 content block format. It handles both +* string content and structured content blocks, as well as tool calls. +* +* @param message - The AI message containing ChatOpenAICompletions formatted content +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const message = new AIMessage("Hello world"); +* const standardBlocks = convertToV1FromChatCompletions(message); +* // Returns: [{ type: "text", text: "Hello world" }] +* ``` +* +* @example +* ```typescript +* const message = new AIMessage([ +* { type: "text", text: "Hello" }, +* { type: "image_url", image_url: { url: "https://example.com/image.png" } } +* ]); +* message.tool_calls = [ +* { id: "call_123", name: "calculator", args: { a: 1, b: 2 } } +* ]; +* +* const standardBlocks = convertToV1FromChatCompletions(message); +* // Returns: +* // [ +* // { type: "text", text: "Hello" }, +* // { type: "image", url: "https://example.com/image.png" }, +* // { type: "tool_call", id: "call_123", name: "calculator", args: { a: 1, b: 2 } } +* // ] +* ``` +*/ +function convertToV1FromChatCompletions(message) { + const blocks = []; + if (typeof message.content === "string") blocks.push({ + type: "text", + text: message.content + }); + else blocks.push(...convertToV1FromChatCompletionsInput(message.content)); + for (const toolCall of message.tool_calls ?? []) blocks.push({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + return blocks; +} +/** +* Converts a ChatOpenAICompletions message chunk to an array of v1 standard content blocks. +* +* This function processes an AI message chunk from OpenAI's chat completions API and converts +* it to the standardized v1 content block format. It handles both string and array content, +* as well as tool calls that may be present in the chunk. +* +* @param message - The AI message chunk containing OpenAI-formatted content blocks +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const chunk = new AIMessage("Hello"); +* const standardBlocks = convertToV1FromChatCompletionsChunk(chunk); +* // Returns: [{ type: "text", text: "Hello" }] +* ``` +* +* @example +* ```typescript +* const chunk = new AIMessage([ +* { type: "text", text: "Processing..." } +* ]); +* chunk.tool_calls = [ +* { id: "call_456", name: "search", args: { query: "test" } } +* ]; +* +* const standardBlocks = convertToV1FromChatCompletionsChunk(chunk); +* // Returns: +* // [ +* // { type: "text", text: "Processing..." }, +* // { type: "tool_call", id: "call_456", name: "search", args: { query: "test" } } +* // ] +* ``` +*/ +function convertToV1FromChatCompletionsChunk(message) { + const blocks = []; + if (typeof message.content === "string") blocks.push({ + type: "text", + text: message.content + }); + else blocks.push(...convertToV1FromChatCompletionsInput(message.content)); + for (const toolCall of message.tool_calls ?? []) blocks.push({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + return blocks; +} +/** +* Converts an array of ChatOpenAICompletions content blocks to v1 standard content blocks. +* +* This function processes content blocks from OpenAI's Chat Completions API format +* and converts them to the standardized v1 content block format. It handles both +* OpenAI-specific data blocks (which require conversion) and standard blocks +* (which are passed through with type assertion). +* +* @param blocks - Array of content blocks in ChatOpenAICompletions format +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const openaiBlocks = [ +* { type: "text", text: "Hello world" }, +* { type: "image_url", image_url: { url: "https://example.com/image.png" } } +* ]; +* +* const standardBlocks = convertToV1FromChatCompletionsInput(openaiBlocks); +* // Returns: +* // [ +* // { type: "text", text: "Hello world" }, +* // { type: "image", url: "https://example.com/image.png" } +* // ] +* ``` +*/ +function convertToV1FromChatCompletionsInput(blocks) { + const convertedBlocks = []; + for (const block of blocks) if (isOpenAIDataBlock(block)) convertedBlocks.push(convertToV1FromOpenAIDataBlock(block)); + else convertedBlocks.push(block); + return convertedBlocks; +} +function convertResponsesAnnotation(annotation) { + if (annotation.type === "url_citation") { + const { url, title, start_index, end_index } = annotation; + return { + type: "citation", + url, + title, + startIndex: start_index, + endIndex: end_index + }; + } + if (annotation.type === "file_citation") { + const { file_id, filename, index } = annotation; + return { + type: "citation", + title: filename, + startIndex: index, + endIndex: index, + fileId: file_id + }; + } + return annotation; +} +/** +* Converts a ChatOpenAIResponses message to an array of v1 standard content blocks. +* +* This function processes an AI message containing OpenAI Responses-specific content blocks +* and converts them to the standardized v1 content block format. It handles reasoning summaries, +* text content with annotations, tool calls, and various tool outputs including code interpreter, +* web search, file search, computer calls, and MCP-related blocks. +* +* @param message - The AI message containing OpenAI Responses-formatted content blocks +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const message = new AIMessage({ +* content: [{ type: "text", text: "Hello world", annotations: [] }], +* tool_calls: [{ id: "123", name: "calculator", args: { a: 1, b: 2 } }], +* additional_kwargs: { +* reasoning: { summary: [{ text: "Let me calculate this..." }] }, +* tool_outputs: [ +* { +* type: "code_interpreter_call", +* code: "print('hello')", +* outputs: [{ type: "logs", logs: "hello" }] +* } +* ] +* } +* }); +* +* const standardBlocks = convertToV1FromResponses(message); +* // Returns: +* // [ +* // { type: "reasoning", reasoning: "Let me calculate this..." }, +* // { type: "text", text: "Hello world", annotations: [] }, +* // { type: "tool_call", id: "123", name: "calculator", args: { a: 1, b: 2 } }, +* // { type: "code_interpreter_call", code: "print('hello')" }, +* // { type: "code_interpreter_result", output: [{ type: "code_interpreter_output", returnCode: 0, stdout: "hello" }] } +* // ] +* ``` +*/ +function convertToV1FromResponses(message) { + function* iterateContent() { + if (_isObject(message.additional_kwargs?.reasoning) && _isArray(message.additional_kwargs.reasoning.summary)) { + const summary = message.additional_kwargs.reasoning.summary.reduce((acc, item) => { + if (_isObject(item) && _isString(item.text)) return `${acc}${item.text}`; + return acc; + }, ""); + yield { + type: "reasoning", + reasoning: summary + }; + } + const content = typeof message.content === "string" ? [{ + type: "text", + text: message.content + }] : message.content; + for (const block of content) if (_isContentBlock(block, "text")) { + const { text, annotations,...rest } = block; + if (Array.isArray(annotations)) yield { + ...rest, + type: "text", + text: String(text), + annotations: annotations.map(convertResponsesAnnotation) + }; + else yield { + ...rest, + type: "text", + text: String(text) + }; + } + for (const toolCall of message.tool_calls ?? []) yield { + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }; + if (_isObject(message.additional_kwargs) && _isArray(message.additional_kwargs.tool_outputs)) for (const toolOutput of message.additional_kwargs.tool_outputs) { + if (_isContentBlock(toolOutput, "web_search_call")) { + yield { + id: toolOutput.id, + type: "server_tool_call", + name: "web_search", + args: { query: toolOutput.query } + }; + continue; + } else if (_isContentBlock(toolOutput, "file_search_call")) { + yield { + id: toolOutput.id, + type: "server_tool_call", + name: "file_search", + args: { query: toolOutput.query } + }; + continue; + } else if (_isContentBlock(toolOutput, "computer_call")) { + yield { + type: "non_standard", + value: toolOutput + }; + continue; + } else if (_isContentBlock(toolOutput, "code_interpreter_call")) { + if (_isString(toolOutput.code)) yield { + id: toolOutput.id, + type: "server_tool_call", + name: "code_interpreter", + args: { code: toolOutput.code } + }; + if (_isArray(toolOutput.outputs)) { + const returnCode = iife(() => { + if (toolOutput.status === "in_progress") return void 0; + if (toolOutput.status === "completed") return 0; + if (toolOutput.status === "incomplete") return 127; + if (toolOutput.status === "interpreting") return void 0; + if (toolOutput.status === "failed") return 1; + return void 0; + }); + for (const output of toolOutput.outputs) if (_isContentBlock(output, "logs")) { + yield { + type: "server_tool_call_result", + toolCallId: toolOutput.id ?? "", + status: "success", + output: { + type: "code_interpreter_output", + returnCode: returnCode ?? 0, + stderr: [0, void 0].includes(returnCode) ? void 0 : String(output.logs), + stdout: [0, void 0].includes(returnCode) ? String(output.logs) : void 0 + } + }; + continue; + } + } + continue; + } else if (_isContentBlock(toolOutput, "mcp_call")) { + yield { + id: toolOutput.id, + type: "server_tool_call", + name: "mcp_call", + args: toolOutput.input + }; + continue; + } else if (_isContentBlock(toolOutput, "mcp_list_tools")) { + yield { + id: toolOutput.id, + type: "server_tool_call", + name: "mcp_list_tools", + args: toolOutput.input + }; + continue; + } else if (_isContentBlock(toolOutput, "mcp_approval_request")) { + yield { + type: "non_standard", + value: toolOutput + }; + continue; + } else if (_isContentBlock(toolOutput, "image_generation_call")) { + yield { + type: "non_standard", + value: toolOutput + }; + continue; + } + if (_isObject(toolOutput)) yield { + type: "non_standard", + value: toolOutput + }; + } + } + return Array.from(iterateContent()); +} +/** +* Converts a ChatOpenAIResponses message chunk to an array of v1 standard content blocks. +* +* This function processes an AI message chunk containing OpenAI-specific content blocks +* and converts them to the standardized v1 content block format. It handles both the +* regular message content and tool call chunks that are specific to streaming responses. +* +* @param message - The AI message chunk containing OpenAI-formatted content blocks +* @returns Array of content blocks in v1 standard format +* +* @example +* ```typescript +* const messageChunk = new AIMessageChunk({ +* content: [{ type: "text", text: "Hello" }], +* tool_call_chunks: [ +* { id: "call_123", name: "calculator", args: '{"a": 1' } +* ] +* }); +* +* const standardBlocks = convertToV1FromResponsesChunk(messageChunk); +* // Returns: +* // [ +* // { type: "text", text: "Hello" }, +* // { type: "tool_call_chunk", id: "call_123", name: "calculator", args: '{"a": 1' } +* // ] +* ``` +*/ +function convertToV1FromResponsesChunk(message) { + function* iterateContent() { + yield* convertToV1FromResponses(message); + for (const toolCallChunk of message.tool_call_chunks ?? []) yield { + type: "tool_call_chunk", + id: toolCallChunk.id, + name: toolCallChunk.name, + args: toolCallChunk.args + }; + } + return Array.from(iterateContent()); +} +const ChatOpenAITranslator = { + translateContent: (message) => { + if (typeof message.content === "string") return convertToV1FromChatCompletions(message); + return convertToV1FromResponses(message); + }, + translateContentChunk: (message) => { + if (typeof message.content === "string") return convertToV1FromChatCompletionsChunk(message); + return convertToV1FromResponsesChunk(message); + } +}; + +//#endregion + +//# sourceMappingURL=openai.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/message.js +//#region src/messages/message.ts +/** +* Type guard to check if a value is a valid Message object. +* +* @param message - The value to check +* @returns true if the value is a valid Message object, false otherwise +*/ +function isMessage(message) { + return typeof message === "object" && message !== null && "type" in message && "content" in message && (typeof message.content === "string" || Array.isArray(message.content)); +} + +//#endregion + +//# sourceMappingURL=message.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/format.js +//#region src/messages/format.ts +function convertToFormattedString(message, format = "pretty") { + if (format === "pretty") return convertToPrettyString(message); + return JSON.stringify(message); +} +function convertToPrettyString(message) { + const lines = []; + const title = ` ${message.type.charAt(0).toUpperCase() + message.type.slice(1)} Message `; + const sepLen = Math.floor((80 - title.length) / 2); + const sep = "=".repeat(sepLen); + const secondSep = title.length % 2 === 0 ? sep : `${sep}=`; + lines.push(`${sep}${title}${secondSep}`); + if (message.type === "ai") { + const aiMessage = message; + if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) { + lines.push("Tool Calls:"); + for (const tc of aiMessage.tool_calls) { + lines.push(` ${tc.name} (${tc.id})`); + lines.push(` Call ID: ${tc.id}`); + lines.push(" Args:"); + for (const [key, value] of Object.entries(tc.args)) lines.push(` ${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`); + } + } + } + if (message.type === "tool") { + const toolMessage = message; + if (toolMessage.name) lines.push(`Name: ${toolMessage.name}`); + } + if (typeof message.content === "string" && message.content.trim()) { + if (lines.length > 1) lines.push(""); + lines.push(message.content); + } + return lines.join("\n"); +} + +//#endregion + +//# sourceMappingURL=format.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/base.js + + + + + + + + +//#region src/messages/base.ts +/** @internal */ +const MESSAGE_SYMBOL = Symbol.for("langchain.message"); +function mergeContent(firstContent, secondContent) { + if (typeof firstContent === "string") { + if (firstContent === "") return secondContent; + if (typeof secondContent === "string") return firstContent + secondContent; + else if (Array.isArray(secondContent) && secondContent.length === 0) return firstContent; + else if (Array.isArray(secondContent) && secondContent.some((c) => isDataContentBlock(c))) return [{ + type: "text", + source_type: "text", + text: firstContent + }, ...secondContent]; + else return [{ + type: "text", + text: firstContent + }, ...secondContent]; + } else if (Array.isArray(secondContent)) return _mergeLists(firstContent, secondContent) ?? [...firstContent, ...secondContent]; + else if (secondContent === "") return firstContent; + else if (Array.isArray(firstContent) && firstContent.some((c) => isDataContentBlock(c))) return [...firstContent, { + type: "file", + source_type: "text", + text: secondContent + }]; + else return [...firstContent, { + type: "text", + text: secondContent + }]; +} +/** +* 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else +* it will return 'success'. +* +* @param {"success" | "error" | undefined} left The existing value to 'merge' with the new value. +* @param {"success" | "error" | undefined} right The new value to 'merge' with the existing value +* @returns {"success" | "error"} The 'merged' value. +*/ +function _mergeStatus(left, right) { + if (left === "error" || right === "error") return "error"; + return "success"; +} +function stringifyWithDepthLimit(obj, depthLimit) { + function helper(obj$1, currentDepth) { + if (typeof obj$1 !== "object" || obj$1 === null || obj$1 === void 0) return obj$1; + if (currentDepth >= depthLimit) { + if (Array.isArray(obj$1)) return "[Array]"; + return "[Object]"; + } + if (Array.isArray(obj$1)) return obj$1.map((item) => helper(item, currentDepth + 1)); + const result = {}; + for (const key of Object.keys(obj$1)) result[key] = helper(obj$1[key], currentDepth + 1); + return result; + } + return JSON.stringify(helper(obj, 0), null, 2); +} +/** +* Base class for all types of messages in a conversation. It includes +* properties like `content`, `name`, and `additional_kwargs`. It also +* includes methods like `toDict()` and `_getType()`. +*/ +var BaseMessage = class extends Serializable { + lc_namespace = ["langchain_core", "messages"]; + lc_serializable = true; + get lc_aliases() { + return { + additional_kwargs: "additional_kwargs", + response_metadata: "response_metadata" + }; + } + [MESSAGE_SYMBOL] = true; + id; + /** @inheritdoc */ + name; + content; + additional_kwargs; + response_metadata; + /** + * @deprecated Use .getType() instead or import the proper typeguard. + * For example: + * + * ```ts + * import { isAIMessage } from "@langchain/core/messages"; + * + * const message = new AIMessage("Hello!"); + * isAIMessage(message); // true + * ``` + */ + _getType() { + return this.type; + } + /** + * @deprecated Use .type instead + * The type of the message. + */ + getType() { + return this._getType(); + } + constructor(arg) { + const fields = typeof arg === "string" || Array.isArray(arg) ? { content: arg } : arg; + if (!fields.additional_kwargs) fields.additional_kwargs = {}; + if (!fields.response_metadata) fields.response_metadata = {}; + super(fields); + this.name = fields.name; + if (fields.content === void 0 && fields.contentBlocks !== void 0) { + this.content = fields.contentBlocks; + this.response_metadata = { + output_version: "v1", + ...fields.response_metadata + }; + } else if (fields.content !== void 0) { + this.content = fields.content ?? []; + this.response_metadata = fields.response_metadata; + } else { + this.content = []; + this.response_metadata = fields.response_metadata; + } + this.additional_kwargs = fields.additional_kwargs; + this.id = fields.id; + } + /** Get text content of the message. */ + get text() { + if (typeof this.content === "string") return this.content; + if (!Array.isArray(this.content)) return ""; + return this.content.map((c) => { + if (typeof c === "string") return c; + if (c.type === "text") return c.text; + return ""; + }).join(""); + } + get contentBlocks() { + const blocks = typeof this.content === "string" ? [{ + type: "text", + text: this.content + }] : this.content; + const parsingSteps = [ + convertToV1FromDataContent, + convertToV1FromChatCompletionsInput, + convertToV1FromAnthropicInput + ]; + const parsedBlocks = parsingSteps.reduce((blocks$1, step) => step(blocks$1), blocks); + return parsedBlocks; + } + toDict() { + return { + type: this.getType(), + data: this.toJSON().kwargs + }; + } + static lc_name() { + return "BaseMessage"; + } + get _printableFields() { + return { + id: this.id, + content: this.content, + name: this.name, + additional_kwargs: this.additional_kwargs, + response_metadata: this.response_metadata + }; + } + static isInstance(obj) { + return typeof obj === "object" && obj !== null && MESSAGE_SYMBOL in obj && obj[MESSAGE_SYMBOL] === true && isMessage(obj); + } + _updateId(value) { + this.id = value; + this.lc_kwargs.id = value; + } + get [Symbol.toStringTag]() { + return this.constructor.lc_name(); + } + [Symbol.for("nodejs.util.inspect.custom")](depth) { + if (depth === null) return this; + const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth)); + return `${this.constructor.lc_name()} ${printable}`; + } + toFormattedString(format = "pretty") { + return convertToFormattedString(this, format); + } +}; +function isOpenAIToolCallArray(value) { + return Array.isArray(value) && value.every((v) => typeof v.index === "number"); +} +function _mergeDicts(left = {}, right = {}) { + const merged = { ...left }; + for (const [key, value] of Object.entries(right)) if (merged[key] == null) merged[key] = value; + else if (value == null) continue; + else if (typeof merged[key] !== typeof value || Array.isArray(merged[key]) !== Array.isArray(value)) throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`); + else if (typeof merged[key] === "string") if (key === "type") continue; + else if ([ + "id", + "name", + "output_version", + "model_provider" + ].includes(key)) { + if (value) merged[key] = value; + } else merged[key] += value; + else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) merged[key] = _mergeDicts(merged[key], value); + else if (Array.isArray(merged[key])) merged[key] = _mergeLists(merged[key], value); + else if (merged[key] === value) continue; + else console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`); + return merged; +} +function _mergeLists(left, right) { + if (left === void 0 && right === void 0) return void 0; + else if (left === void 0 || right === void 0) return left || right; + else { + const merged = [...left]; + for (const item of right) if (typeof item === "object" && item !== null && "index" in item && typeof item.index === "number") { + const toMerge = merged.findIndex((leftItem) => { + const isObject = typeof leftItem === "object"; + const indiciesMatch = "index" in leftItem && leftItem.index === item.index; + const idsMatch = "id" in leftItem && "id" in item && leftItem?.id === item?.id; + const eitherItemMissingID = !("id" in leftItem) || !leftItem?.id || !("id" in item) || !item?.id; + return isObject && indiciesMatch && (idsMatch || eitherItemMissingID); + }); + if (toMerge !== -1 && typeof merged[toMerge] === "object" && merged[toMerge] !== null) merged[toMerge] = _mergeDicts(merged[toMerge], item); + else merged.push(item); + } else if (typeof item === "object" && item !== null && "text" in item && item.text === "") continue; + else merged.push(item); + return merged; + } +} +function _mergeObj(left, right) { + if (left === void 0 && right === void 0) return void 0; + if (left === void 0 || right === void 0) return left ?? right; + else if (typeof left !== typeof right) throw new Error(`Cannot merge objects of different types.\nLeft ${typeof left}\nRight ${typeof right}`); + else if (typeof left === "string" && typeof right === "string") return left + right; + else if (Array.isArray(left) && Array.isArray(right)) return _mergeLists(left, right); + else if (typeof left === "object" && typeof right === "object") return _mergeDicts(left, right); + else if (left === right) return left; + else throw new Error(`Can not merge objects of different types.\nLeft ${left}\nRight ${right}`); +} +/** +* Represents a chunk of a message, which can be concatenated with other +* message chunks. It includes a method `_merge_kwargs_dict()` for merging +* additional keyword arguments from another `BaseMessageChunk` into this +* one. It also overrides the `__add__()` method to support concatenation +* of `BaseMessageChunk` instances. +*/ +var BaseMessageChunk = class BaseMessageChunk extends BaseMessage { + static isInstance(obj) { + if (!super.isInstance(obj)) return false; + let proto = Object.getPrototypeOf(obj); + while (proto !== null) { + if (proto === BaseMessageChunk.prototype) return true; + proto = Object.getPrototypeOf(proto); + } + return false; + } +}; +function _isMessageFieldWithRole(x) { + return typeof x.role === "string"; +} +/** +* @deprecated Use {@link BaseMessage.isInstance} instead +*/ +function isBaseMessage(messageLike) { + return typeof messageLike?._getType === "function"; +} +/** +* @deprecated Use {@link BaseMessageChunk.isInstance} instead +*/ +function isBaseMessageChunk(messageLike) { + return BaseMessageChunk.isInstance(messageLike); +} + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/tool.js + + + +//#region src/messages/tool.ts +var tool_exports = {}; +__export(tool_exports, { + ToolMessage: () => ToolMessage, + ToolMessageChunk: () => ToolMessageChunk, + defaultToolCallParser: () => defaultToolCallParser, + isDirectToolOutput: () => isDirectToolOutput, + isToolMessage: () => isToolMessage, + isToolMessageChunk: () => isToolMessageChunk +}); +function isDirectToolOutput(x) { + return x != null && typeof x === "object" && "lc_direct_tool_output" in x && x.lc_direct_tool_output === true; +} +/** +* Represents a tool message in a conversation. +*/ +var ToolMessage = class extends BaseMessage { + static lc_name() { + return "ToolMessage"; + } + get lc_aliases() { + return { tool_call_id: "tool_call_id" }; + } + lc_direct_tool_output = true; + type = "tool"; + /** + * Status of the tool invocation. + * @version 0.2.19 + */ + status; + tool_call_id; + metadata; + /** + * Artifact of the Tool execution which is not meant to be sent to the model. + * + * Should only be specified if it is different from the message content, e.g. if only + * a subset of the full tool output is being passed as message content but the full + * output is needed in other parts of the code. + */ + artifact; + constructor(fields, tool_call_id, name) { + const toolMessageFields = typeof fields === "string" || Array.isArray(fields) ? { + content: fields, + name, + tool_call_id + } : fields; + super(toolMessageFields); + this.tool_call_id = toolMessageFields.tool_call_id; + this.artifact = toolMessageFields.artifact; + this.status = toolMessageFields.status; + this.metadata = toolMessageFields.metadata; + } + static isInstance(message) { + return super.isInstance(message) && message.type === "tool"; + } + get _printableFields() { + return { + ...super._printableFields, + tool_call_id: this.tool_call_id, + artifact: this.artifact + }; + } +}; +/** +* Represents a chunk of a tool message, which can be concatenated +* with other tool message chunks. +*/ +var ToolMessageChunk = class extends BaseMessageChunk { + type = "tool"; + tool_call_id; + /** + * Status of the tool invocation. + * @version 0.2.19 + */ + status; + /** + * Artifact of the Tool execution which is not meant to be sent to the model. + * + * Should only be specified if it is different from the message content, e.g. if only + * a subset of the full tool output is being passed as message content but the full + * output is needed in other parts of the code. + */ + artifact; + constructor(fields) { + super(fields); + this.tool_call_id = fields.tool_call_id; + this.artifact = fields.artifact; + this.status = fields.status; + } + static lc_name() { + return "ToolMessageChunk"; + } + concat(chunk) { + const Cls = this.constructor; + return new Cls({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + artifact: _mergeObj(this.artifact, chunk.artifact), + tool_call_id: this.tool_call_id, + id: this.id ?? chunk.id, + status: _mergeStatus(this.status, chunk.status) + }); + } + get _printableFields() { + return { + ...super._printableFields, + tool_call_id: this.tool_call_id, + artifact: this.artifact + }; + } +}; +function defaultToolCallParser(rawToolCalls) { + const toolCalls = []; + const invalidToolCalls = []; + for (const toolCall of rawToolCalls) if (!toolCall.function) continue; + else { + const functionName = toolCall.function.name; + try { + const functionArgs = JSON.parse(toolCall.function.arguments); + toolCalls.push({ + name: functionName || "", + args: functionArgs || {}, + id: toolCall.id + }); + } catch { + invalidToolCalls.push({ + name: functionName, + args: toolCall.function.arguments, + id: toolCall.id, + error: "Malformed args." + }); + } + } + return [toolCalls, invalidToolCalls]; +} +/** +* @deprecated Use {@link ToolMessage.isInstance} instead +*/ +function isToolMessage(x) { + return typeof x === "object" && x !== null && "getType" in x && typeof x.getType === "function" && x.getType() === "tool"; +} +/** +* @deprecated Use {@link ToolMessageChunk.isInstance} instead +*/ +function isToolMessageChunk(x) { + return x._getType() === "tool"; +} + +//#endregion + +//# sourceMappingURL=tool.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/errors/index.js +//#region src/errors/index.ts +function addLangChainErrorFields(error, lc_error_code) { + error.lc_error_code = lc_error_code; + error.message = `${error.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\n`; + return error; +} + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/utils.js +//#region src/tools/utils.ts +function _isToolCall(toolCall) { + return !!(toolCall && typeof toolCall === "object" && "type" in toolCall && toolCall.type === "tool_call"); +} +function _configHasToolCallId(config) { + return !!(config && typeof config === "object" && "toolCall" in config && config.toolCall != null && typeof config.toolCall === "object" && "id" in config.toolCall && typeof config.toolCall.id === "string"); +} +/** +* Custom error class used to handle exceptions related to tool input parsing. +* It extends the built-in `Error` class and adds an optional `output` +* property that can hold the output that caused the exception. +*/ +var ToolInputParsingException = class extends Error { + output; + constructor(message, output) { + super(message); + this.output = output; + } +}; + +//#endregion + +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json.js +//#region src/utils/json.ts +function parseJsonMarkdown(s, parser = parsePartialJson) { + s = s.trim(); + const firstFenceIndex = s.indexOf("```"); + if (firstFenceIndex === -1) return parser(s); + let contentAfterFence = s.substring(firstFenceIndex + 3); + if (contentAfterFence.startsWith("json\n")) contentAfterFence = contentAfterFence.substring(5); + else if (contentAfterFence.startsWith("json")) contentAfterFence = contentAfterFence.substring(4); + else if (contentAfterFence.startsWith("\n")) contentAfterFence = contentAfterFence.substring(1); + const closingFenceIndex = contentAfterFence.indexOf("```"); + let finalContent = contentAfterFence; + if (closingFenceIndex !== -1) finalContent = contentAfterFence.substring(0, closingFenceIndex); + return parser(finalContent.trim()); +} +/** +* Recursive descent partial JSON parser. +* @param s - The string to parse. +* @returns The parsed value. +* @throws Error if the input is a malformed JSON string. +*/ +function strictParsePartialJson(s) { + try { + return JSON.parse(s); + } catch {} + const buffer = s.trim(); + if (buffer.length === 0) throw new Error("Unexpected end of JSON input"); + let pos = 0; + function skipWhitespace() { + while (pos < buffer.length && /\s/.test(buffer[pos])) pos += 1; + } + function parseString() { + if (buffer[pos] !== "\"") throw new Error(`Expected '"' at position ${pos}, got '${buffer[pos]}'`); + pos += 1; + let result = ""; + let escaped = false; + while (pos < buffer.length) { + const char = buffer[pos]; + if (escaped) { + if (char === "n") result += "\n"; + else if (char === "t") result += " "; + else if (char === "r") result += "\r"; + else if (char === "\\") result += "\\"; + else if (char === "\"") result += "\""; + else if (char === "b") result += "\b"; + else if (char === "f") result += "\f"; + else if (char === "/") result += "/"; + else if (char === "u") { + const hex = buffer.substring(pos + 1, pos + 5); + if (/^[0-9A-Fa-f]{0,4}$/.test(hex)) { + if (hex.length === 4) result += String.fromCharCode(Number.parseInt(hex, 16)); + else result += `u${hex}`; + pos += hex.length; + } else throw new Error(`Invalid unicode escape sequence '\\u${hex}' at position ${pos}`); + } else throw new Error(`Invalid escape sequence '\\${char}' at position ${pos}`); + escaped = false; + } else if (char === "\\") escaped = true; + else if (char === "\"") { + pos += 1; + return result; + } else result += char; + pos += 1; + } + if (escaped) result += "\\"; + return result; + } + function parseNumber() { + const start = pos; + let numStr = ""; + if (buffer[pos] === "-") { + numStr += "-"; + pos += 1; + } + if (pos < buffer.length && buffer[pos] === "0") { + numStr += "0"; + pos += 1; + if (buffer[pos] >= "0" && buffer[pos] <= "9") throw new Error(`Invalid number at position ${start}`); + } + if (pos < buffer.length && buffer[pos] >= "1" && buffer[pos] <= "9") while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") { + numStr += buffer[pos]; + pos += 1; + } + if (pos < buffer.length && buffer[pos] === ".") { + numStr += "."; + pos += 1; + while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") { + numStr += buffer[pos]; + pos += 1; + } + } + if (pos < buffer.length && (buffer[pos] === "e" || buffer[pos] === "E")) { + numStr += buffer[pos]; + pos += 1; + if (pos < buffer.length && (buffer[pos] === "+" || buffer[pos] === "-")) { + numStr += buffer[pos]; + pos += 1; + } + while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") { + numStr += buffer[pos]; + pos += 1; + } + } + if (numStr === "-") return -0; + const num = Number.parseFloat(numStr); + if (Number.isNaN(num)) { + pos = start; + throw new Error(`Invalid number '${numStr}' at position ${start}`); + } + return num; + } + function parseValue() { + skipWhitespace(); + if (pos >= buffer.length) throw new Error(`Unexpected end of input at position ${pos}`); + const char = buffer[pos]; + if (char === "{") return parseObject(); + if (char === "[") return parseArray(); + if (char === "\"") return parseString(); + if ("null".startsWith(buffer.substring(pos, pos + 4))) { + pos += Math.min(4, buffer.length - pos); + return null; + } + if ("true".startsWith(buffer.substring(pos, pos + 4))) { + pos += Math.min(4, buffer.length - pos); + return true; + } + if ("false".startsWith(buffer.substring(pos, pos + 5))) { + pos += Math.min(5, buffer.length - pos); + return false; + } + if (char === "-" || char >= "0" && char <= "9") return parseNumber(); + throw new Error(`Unexpected character '${char}' at position ${pos}`); + } + function parseArray() { + if (buffer[pos] !== "[") throw new Error(`Expected '[' at position ${pos}, got '${buffer[pos]}'`); + const arr = []; + pos += 1; + skipWhitespace(); + if (pos >= buffer.length) return arr; + if (buffer[pos] === "]") { + pos += 1; + return arr; + } + while (pos < buffer.length) { + skipWhitespace(); + if (pos >= buffer.length) return arr; + arr.push(parseValue()); + skipWhitespace(); + if (pos >= buffer.length) return arr; + if (buffer[pos] === "]") { + pos += 1; + return arr; + } else if (buffer[pos] === ",") { + pos += 1; + continue; + } + throw new Error(`Expected ',' or ']' at position ${pos}, got '${buffer[pos]}'`); + } + return arr; + } + function parseObject() { + if (buffer[pos] !== "{") throw new Error(`Expected '{' at position ${pos}, got '${buffer[pos]}'`); + const obj = {}; + pos += 1; + skipWhitespace(); + if (pos >= buffer.length) return obj; + if (buffer[pos] === "}") { + pos += 1; + return obj; + } + while (pos < buffer.length) { + skipWhitespace(); + if (pos >= buffer.length) return obj; + const key = parseString(); + skipWhitespace(); + if (pos >= buffer.length) return obj; + if (buffer[pos] !== ":") throw new Error(`Expected ':' at position ${pos}, got '${buffer[pos]}'`); + pos += 1; + skipWhitespace(); + if (pos >= buffer.length) return obj; + obj[key] = parseValue(); + skipWhitespace(); + if (pos >= buffer.length) return obj; + if (buffer[pos] === "}") { + pos += 1; + return obj; + } else if (buffer[pos] === ",") { + pos += 1; + continue; + } + throw new Error(`Expected ',' or '}' at position ${pos}, got '${buffer[pos]}'`); + } + return obj; + } + const value = parseValue(); + skipWhitespace(); + if (pos < buffer.length) throw new Error(`Unexpected character '${buffer[pos]}' at position ${pos}`); + return value; +} +function parsePartialJson(s) { + try { + if (typeof s === "undefined") return null; + return strictParsePartialJson(s); + } catch { + return null; + } +} + +//#endregion + +//# sourceMappingURL=json.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/chat.js + + +//#region src/messages/chat.ts +/** +* Represents a chat message in a conversation. +*/ +var ChatMessage = class ChatMessage extends BaseMessage { + static lc_name() { + return "ChatMessage"; + } + type = "generic"; + role; + static _chatMessageClass() { + return ChatMessage; + } + constructor(fields, role) { + if (typeof fields === "string" || Array.isArray(fields)) fields = { + content: fields, + role + }; + super(fields); + this.role = fields.role; + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "generic"; + } + get _printableFields() { + return { + ...super._printableFields, + role: this.role + }; + } +}; +/** +* Represents a chunk of a chat message, which can be concatenated with +* other chat message chunks. +*/ +var ChatMessageChunk = class extends BaseMessageChunk { + static lc_name() { + return "ChatMessageChunk"; + } + type = "generic"; + role; + constructor(fields, role) { + if (typeof fields === "string" || Array.isArray(fields)) fields = { + content: fields, + role + }; + super(fields); + this.role = fields.role; + } + concat(chunk) { + const Cls = this.constructor; + return new Cls({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + role: this.role, + id: this.id ?? chunk.id + }); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "generic"; + } + get _printableFields() { + return { + ...super._printableFields, + role: this.role + }; + } +}; +/** +* @deprecated Use {@link ChatMessage.isInstance} instead +*/ +function isChatMessage(x) { + return x._getType() === "generic"; +} +/** +* @deprecated Use {@link ChatMessageChunk.isInstance} instead +*/ +function isChatMessageChunk(x) { + return x._getType() === "generic"; +} + +//#endregion + +//# sourceMappingURL=chat.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/function.js + + +//#region src/messages/function.ts +/** +* Represents a function message in a conversation. +*/ +var FunctionMessage = class extends BaseMessage { + static lc_name() { + return "FunctionMessage"; + } + type = "function"; + name; + constructor(fields) { + super(fields); + this.name = fields.name; + } +}; +/** +* Represents a chunk of a function message, which can be concatenated +* with other function message chunks. +*/ +var FunctionMessageChunk = class extends BaseMessageChunk { + static lc_name() { + return "FunctionMessageChunk"; + } + type = "function"; + concat(chunk) { + const Cls = this.constructor; + return new Cls({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + name: this.name ?? "", + id: this.id ?? chunk.id + }); + } +}; +function isFunctionMessage(x) { + return x._getType() === "function"; +} +function isFunctionMessageChunk(x) { + return x._getType() === "function"; +} + +//#endregion + +//# sourceMappingURL=function.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/human.js + + +//#region src/messages/human.ts +/** +* Represents a human message in a conversation. +*/ +var HumanMessage = class extends BaseMessage { + static lc_name() { + return "HumanMessage"; + } + type = "human"; + constructor(fields) { + super(fields); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "human"; + } +}; +/** +* Represents a chunk of a human message, which can be concatenated with +* other human message chunks. +*/ +var HumanMessageChunk = class extends BaseMessageChunk { + static lc_name() { + return "HumanMessageChunk"; + } + type = "human"; + constructor(fields) { + super(fields); + } + concat(chunk) { + const Cls = this.constructor; + return new Cls({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + id: this.id ?? chunk.id + }); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "human"; + } +}; +/** +* @deprecated Use {@link HumanMessage.isInstance} instead +*/ +function isHumanMessage(x) { + return x.getType() === "human"; +} +/** +* @deprecated Use {@link HumanMessageChunk.isInstance} instead +*/ +function isHumanMessageChunk(x) { + return x.getType() === "human"; +} + +//#endregion + +//# sourceMappingURL=human.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/modifier.js + + +//#region src/messages/modifier.ts +/** +* Message responsible for deleting other messages. +*/ +var RemoveMessage = class extends BaseMessage { + type = "remove"; + /** + * The ID of the message to remove. + */ + id; + constructor(fields) { + super({ + ...fields, + content: [] + }); + this.id = fields.id; + } + get _printableFields() { + return { + ...super._printableFields, + id: this.id + }; + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "remove"; + } +}; + +//#endregion + +//# sourceMappingURL=modifier.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/system.js + + +//#region src/messages/system.ts +/** +* Represents a system message in a conversation. +*/ +var SystemMessage = class SystemMessage extends BaseMessage { + static lc_name() { + return "SystemMessage"; + } + type = "system"; + constructor(fields) { + super(fields); + } + /** + * Concatenates a string or another system message with the current system message. + * @param chunk - The chunk to concatenate with the system message. + * @returns A new system message with the concatenated content. + */ + concat(chunk) { + if (typeof chunk === "string") return new SystemMessage({ + ...this, + content: mergeContent(this.content, chunk) + }); + if (SystemMessage.isInstance(chunk)) return new SystemMessage({ + ...this, + additional_kwargs: { + ...this.additional_kwargs, + ...chunk.additional_kwargs + }, + response_metadata: { + ...this.response_metadata, + ...chunk.response_metadata + }, + content: mergeContent(this.content, chunk.content) + }); + throw new Error("Unexpected chunk type for system message"); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "system"; + } +}; +/** +* Represents a chunk of a system message, which can be concatenated with +* other system message chunks. +*/ +var SystemMessageChunk = class extends BaseMessageChunk { + static lc_name() { + return "SystemMessageChunk"; + } + type = "system"; + constructor(fields) { + super(fields); + } + concat(chunk) { + const Cls = this.constructor; + return new Cls({ + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), + id: this.id ?? chunk.id + }); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "system"; + } +}; +/** +* @deprecated Use {@link SystemMessage.isInstance} instead +*/ +function isSystemMessage(x) { + return x._getType() === "system"; +} +/** +* @deprecated Use {@link SystemMessageChunk.isInstance} instead +*/ +function isSystemMessageChunk(x) { + return x._getType() === "system"; +} + +//#endregion + +//# sourceMappingURL=system.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/bedrock_converse.js + + +//#region src/messages/block_translators/bedrock_converse.ts +function convertFileFormatToMimeType(format) { + switch (format) { + case "csv": return "text/csv"; + case "doc": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; + case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; + case "html": return "text/html"; + case "md": return "text/markdown"; + case "pdf": return "application/pdf"; + case "txt": return "text/plain"; + case "xls": return "application/vnd.ms-excel"; + case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; + case "gif": return "image/gif"; + case "jpeg": return "image/jpeg"; + case "jpg": return "image/jpeg"; + case "png": return "image/png"; + case "webp": return "image/webp"; + case "flv": return "video/flv"; + case "mkv": return "video/mkv"; + case "mov": return "video/mov"; + case "mp4": return "video/mp4"; + case "mpeg": return "video/mpeg"; + case "mpg": return "video/mpg"; + case "three_gp": return "video/three_gp"; + case "webm": return "video/webm"; + case "wmv": return "video/wmv"; + default: return "application/octet-stream"; + } +} +function convertConverseDocumentBlock(block) { + if (_isObject(block.document) && _isObject(block.document.source)) { + const format = _isObject(block.document) && _isString(block.document.format) ? block.document.format : ""; + const mimeType = convertFileFormatToMimeType(format); + if (_isObject(block.document.source)) { + if (_isObject(block.document.source.s3Location) && _isString(block.document.source.s3Location.uri)) return { + type: "file", + mimeType, + fileId: block.document.source.s3Location.uri + }; + if (_isBytesArray(block.document.source.bytes)) return { + type: "file", + mimeType, + data: block.document.source.bytes + }; + if (_isString(block.document.source.text)) return { + type: "file", + mimeType, + data: Buffer.from(block.document.source.text).toString("base64") + }; + if (_isArray(block.document.source.content)) { + const data = block.document.source.content.reduce((acc, item) => { + if (_isObject(item) && _isString(item.text)) return acc + item.text; + return acc; + }, ""); + return { + type: "file", + mimeType, + data + }; + } + } + } + return { + type: "non_standard", + value: block + }; +} +function convertConverseImageBlock(block) { + if (_isContentBlock(block, "image") && _isObject(block.image)) { + const format = _isObject(block.image) && _isString(block.image.format) ? block.image.format : ""; + const mimeType = convertFileFormatToMimeType(format); + if (_isObject(block.image.source)) { + if (_isObject(block.image.source.s3Location) && _isString(block.image.source.s3Location.uri)) return { + type: "image", + mimeType, + fileId: block.image.source.s3Location.uri + }; + if (_isBytesArray(block.image.source.bytes)) return { + type: "image", + mimeType, + data: block.image.source.bytes + }; + } + } + return { + type: "non_standard", + value: block + }; +} +function convertConverseVideoBlock(block) { + if (_isContentBlock(block, "video") && _isObject(block.video)) { + const format = _isObject(block.video) && _isString(block.video.format) ? block.video.format : ""; + const mimeType = convertFileFormatToMimeType(format); + if (_isObject(block.video.source)) { + if (_isObject(block.video.source.s3Location) && _isString(block.video.source.s3Location.uri)) return { + type: "video", + mimeType, + fileId: block.video.source.s3Location.uri + }; + if (_isBytesArray(block.video.source.bytes)) return { + type: "video", + mimeType, + data: block.video.source.bytes + }; + } + } + return { + type: "non_standard", + value: block + }; +} +function convertToV1FromChatBedrockConverseMessage(message) { + function* iterateContent() { + const content = typeof message.content === "string" ? [{ + type: "text", + text: message.content + }] : message.content; + for (const block of content) { + if (_isContentBlock(block, "cache_point")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "citations_content") && _isObject(block.citationsContent)) { + const text = _isArray(block.citationsContent.content) ? block.citationsContent.content.reduce((acc, item) => { + if (_isObject(item) && _isString(item.text)) return acc + item.text; + return acc; + }, "") : ""; + const annotations = _isArray(block.citationsContent.citations) ? block.citationsContent.citations.reduce((acc, item) => { + if (_isObject(item)) { + const citedText = _isArray(item.sourceContent) ? item.sourceContent.reduce((acc$1, item$1) => { + if (_isObject(item$1) && _isString(item$1.text)) return acc$1 + item$1.text; + return acc$1; + }, "") : ""; + const properties = iife(() => { + if (_isObject(item.location)) { + const location = item.location.documentChar || item.location.documentPage || item.location.documentChunk; + if (_isObject(location)) return { + source: _isNumber(location.documentIndex) ? location.documentIndex.toString() : void 0, + startIndex: _isNumber(location.start) ? location.start : void 0, + endIndex: _isNumber(location.end) ? location.end : void 0 + }; + } + return {}; + }); + acc.push({ + type: "citation", + citedText, + ...properties + }); + } + return acc; + }, []) : []; + yield { + type: "text", + text, + annotations + }; + continue; + } else if (_isContentBlock(block, "document") && _isObject(block.document)) { + yield convertConverseDocumentBlock(block); + continue; + } else if (_isContentBlock(block, "guard_content")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "image") && _isObject(block.image)) { + yield convertConverseImageBlock(block); + continue; + } else if (_isContentBlock(block, "reasoning_content") && _isString(block.reasoningText)) { + yield { + type: "reasoning", + reasoning: block.reasoningText + }; + continue; + } else if (_isContentBlock(block, "text") && _isString(block.text)) { + yield { + type: "text", + text: block.text + }; + continue; + } else if (_isContentBlock(block, "tool_result")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "tool_call")) continue; + else if (_isContentBlock(block, "video") && _isObject(block.video)) { + yield convertConverseVideoBlock(block); + continue; + } + yield { + type: "non_standard", + value: block + }; + } + } + return Array.from(iterateContent()); +} +const ChatBedrockConverseTranslator = { + translateContent: convertToV1FromChatBedrockConverseMessage, + translateContentChunk: convertToV1FromChatBedrockConverseMessage +}; + +//#endregion + +//# sourceMappingURL=bedrock_converse.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/google_genai.js + + +//#region src/messages/block_translators/google_genai.ts +function convertToV1FromChatGoogleMessage(message) { + function* iterateContent() { + const content = typeof message.content === "string" ? [{ + type: "text", + text: message.content + }] : message.content; + for (const block of content) { + if (_isContentBlock(block, "text") && _isString(block.text)) { + yield { + type: "text", + text: block.text + }; + continue; + } else if (_isContentBlock(block, "inlineData") && _isObject(block.inlineData) && _isString(block.inlineData.mimeType) && _isString(block.inlineData.data)) { + yield { + type: "file", + mimeType: block.inlineData.mimeType, + data: block.inlineData.data + }; + continue; + } else if (_isContentBlock(block, "functionCall") && _isObject(block.functionCall) && _isString(block.functionCall.name) && _isObject(block.functionCall.args)) { + yield { + type: "tool_call", + id: message.id, + name: block.functionCall.name, + args: block.functionCall.args + }; + continue; + } else if (_isContentBlock(block, "functionResponse")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "fileData") && _isObject(block.fileData) && _isString(block.fileData.mimeType) && _isString(block.fileData.fileUri)) { + yield { + type: "file", + mimeType: block.fileData.mimeType, + fileId: block.fileData.fileUri + }; + continue; + } else if (_isContentBlock(block, "executableCode")) { + yield { + type: "non_standard", + value: block + }; + continue; + } else if (_isContentBlock(block, "codeExecutionResult")) { + yield { + type: "non_standard", + value: block + }; + continue; + } + yield { + type: "non_standard", + value: block + }; + } + } + return Array.from(iterateContent()); +} +const ChatGoogleGenAITranslator = { + translateContent: convertToV1FromChatGoogleMessage, + translateContentChunk: convertToV1FromChatGoogleMessage +}; + +//#endregion + +//# sourceMappingURL=google_genai.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/google_vertexai.js + + +//#region src/messages/block_translators/google_vertexai.ts +function convertToV1FromChatVertexMessage(message) { + function* iterateContent() { + const content = typeof message.content === "string" ? [{ + type: "text", + text: message.content + }] : message.content; + for (const block of content) { + if (_isContentBlock(block, "reasoning") && _isString(block.reasoning)) { + const signature = iife(() => { + const reasoningIndex = content.indexOf(block); + if (_isArray(message.additional_kwargs?.signatures) && reasoningIndex >= 0) return message.additional_kwargs.signatures.at(reasoningIndex); + return void 0; + }); + if (_isString(signature)) yield { + type: "reasoning", + reasoning: block.reasoning, + signature + }; + else yield { + type: "reasoning", + reasoning: block.reasoning + }; + continue; + } else if (_isContentBlock(block, "text") && _isString(block.text)) { + yield { + type: "text", + text: block.text + }; + continue; + } else if (_isContentBlock(block, "image_url")) { + if (_isString(block.image_url)) if (block.image_url.startsWith("data:")) { + const dataUrlRegex = /^data:([^;]+);base64,(.+)$/; + const match = block.image_url.match(dataUrlRegex); + if (match) yield { + type: "image", + data: match[2], + mimeType: match[1] + }; + else yield { + type: "image", + url: block.image_url + }; + } else yield { + type: "image", + url: block.image_url + }; + continue; + } else if (_isContentBlock(block, "media") && _isString(block.mimeType) && _isString(block.data)) { + yield { + type: "file", + mimeType: block.mimeType, + data: block.data + }; + continue; + } + yield { + type: "non_standard", + value: block + }; + } + } + return Array.from(iterateContent()); +} +const ChatVertexTranslator = { + translateContent: convertToV1FromChatVertexMessage, + translateContentChunk: convertToV1FromChatVertexMessage +}; + +//#endregion + +//# sourceMappingURL=google_vertexai.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/index.js + + + + + + +//#region src/messages/block_translators/index.ts +globalThis.lc_block_translators_registry ??= new Map([ + ["anthropic", ChatAnthropicTranslator], + ["bedrock-converse", ChatBedrockConverseTranslator], + ["google-genai", ChatGoogleGenAITranslator], + ["google-vertexai", ChatVertexTranslator], + ["openai", ChatOpenAITranslator] +]); +function getTranslator(modelProvider) { + return globalThis.lc_block_translators_registry.get(modelProvider); +} + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/metadata.js + + +//#region src/messages/metadata.ts +function mergeResponseMetadata(a, b) { + const output = _mergeDicts(a ?? {}, b ?? {}); + return output; +} +function mergeModalitiesTokenDetails(a, b) { + const output = {}; + if (a?.audio !== void 0 || b?.audio !== void 0) output.audio = (a?.audio ?? 0) + (b?.audio ?? 0); + if (a?.image !== void 0 || b?.image !== void 0) output.image = (a?.image ?? 0) + (b?.image ?? 0); + if (a?.video !== void 0 || b?.video !== void 0) output.video = (a?.video ?? 0) + (b?.video ?? 0); + if (a?.document !== void 0 || b?.document !== void 0) output.document = (a?.document ?? 0) + (b?.document ?? 0); + if (a?.text !== void 0 || b?.text !== void 0) output.text = (a?.text ?? 0) + (b?.text ?? 0); + return output; +} +function mergeInputTokenDetails(a, b) { + const output = { ...mergeModalitiesTokenDetails(a, b) }; + if (a?.cache_read !== void 0 || b?.cache_read !== void 0) output.cache_read = (a?.cache_read ?? 0) + (b?.cache_read ?? 0); + if (a?.cache_creation !== void 0 || b?.cache_creation !== void 0) output.cache_creation = (a?.cache_creation ?? 0) + (b?.cache_creation ?? 0); + return output; +} +function mergeOutputTokenDetails(a, b) { + const output = { ...mergeModalitiesTokenDetails(a, b) }; + if (a?.reasoning !== void 0 || b?.reasoning !== void 0) output.reasoning = (a?.reasoning ?? 0) + (b?.reasoning ?? 0); + return output; +} +function mergeUsageMetadata(a, b) { + return { + input_tokens: (a?.input_tokens ?? 0) + (b?.input_tokens ?? 0), + output_tokens: (a?.output_tokens ?? 0) + (b?.output_tokens ?? 0), + total_tokens: (a?.total_tokens ?? 0) + (b?.total_tokens ?? 0), + input_token_details: mergeInputTokenDetails(a?.input_token_details, b?.input_token_details), + output_token_details: mergeOutputTokenDetails(a?.output_token_details, b?.output_token_details) + }; +} + +//#endregion + +//# sourceMappingURL=metadata.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/ai.js + + + + + + +//#region src/messages/ai.ts +var AIMessage = class extends BaseMessage { + type = "ai"; + tool_calls = []; + invalid_tool_calls = []; + usage_metadata; + get lc_aliases() { + return { + ...super.lc_aliases, + tool_calls: "tool_calls", + invalid_tool_calls: "invalid_tool_calls" + }; + } + constructor(fields) { + let initParams; + if (typeof fields === "string" || Array.isArray(fields)) initParams = { + content: fields, + tool_calls: [], + invalid_tool_calls: [], + additional_kwargs: {} + }; + else { + initParams = fields; + const rawToolCalls = initParams.additional_kwargs?.tool_calls; + const toolCalls = initParams.tool_calls; + if (!(rawToolCalls == null) && rawToolCalls.length > 0 && (toolCalls === void 0 || toolCalls.length === 0)) console.warn([ + "New LangChain packages are available that more efficiently handle", + "tool calling.\n\nPlease upgrade your packages to versions that set", + "message tool calls. e.g., `pnpm install @langchain/anthropic`,", + "pnpm install @langchain/openai`, etc." + ].join(" ")); + try { + if (!(rawToolCalls == null) && toolCalls === void 0) { + const [toolCalls$1, invalidToolCalls] = defaultToolCallParser(rawToolCalls); + initParams.tool_calls = toolCalls$1 ?? []; + initParams.invalid_tool_calls = invalidToolCalls ?? []; + } else { + initParams.tool_calls = initParams.tool_calls ?? []; + initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? []; + } + } catch { + initParams.tool_calls = []; + initParams.invalid_tool_calls = []; + } + if (initParams.response_metadata !== void 0 && "output_version" in initParams.response_metadata && initParams.response_metadata.output_version === "v1") { + initParams.contentBlocks = initParams.content; + initParams.content = void 0; + } + if (initParams.contentBlocks !== void 0) { + initParams.contentBlocks.push(...initParams.tool_calls.map((toolCall) => ({ + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }))); + const missingToolCalls = initParams.contentBlocks.filter((block) => block.type === "tool_call").filter((block) => !initParams.tool_calls?.some((toolCall) => toolCall.id === block.id && toolCall.name === block.name)); + if (missingToolCalls.length > 0) initParams.tool_calls = missingToolCalls.map((block) => ({ + type: "tool_call", + id: block.id, + name: block.name, + args: block.args + })); + } + } + super(initParams); + if (typeof initParams !== "string") { + this.tool_calls = initParams.tool_calls ?? this.tool_calls; + this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; + } + this.usage_metadata = initParams.usage_metadata; + } + static lc_name() { + return "AIMessage"; + } + get contentBlocks() { + if (this.response_metadata && "output_version" in this.response_metadata && this.response_metadata.output_version === "v1") return this.content; + if (this.response_metadata && "model_provider" in this.response_metadata && typeof this.response_metadata.model_provider === "string") { + const translator = getTranslator(this.response_metadata.model_provider); + if (translator) return translator.translateContent(this); + } + const blocks = super.contentBlocks; + if (this.tool_calls) { + const missingToolCalls = this.tool_calls.filter((block) => !blocks.some((b) => b.id === block.id && b.name === block.name)); + blocks.push(...missingToolCalls.map((block) => ({ + ...block, + type: "tool_call", + id: block.id, + name: block.name, + args: block.args + }))); + } + return blocks; + } + get _printableFields() { + return { + ...super._printableFields, + tool_calls: this.tool_calls, + invalid_tool_calls: this.invalid_tool_calls, + usage_metadata: this.usage_metadata + }; + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "ai"; + } +}; +/** +* @deprecated Use {@link AIMessage.isInstance} instead +*/ +function isAIMessage(x) { + return x._getType() === "ai"; +} +/** +* @deprecated Use {@link AIMessageChunk.isInstance} instead +*/ +function isAIMessageChunk(x) { + return x._getType() === "ai"; +} +/** +* Represents a chunk of an AI message, which can be concatenated with +* other AI message chunks. +*/ +var AIMessageChunk = class extends BaseMessageChunk { + type = "ai"; + tool_calls = []; + invalid_tool_calls = []; + tool_call_chunks = []; + usage_metadata; + constructor(fields) { + let initParams; + if (typeof fields === "string" || Array.isArray(fields)) initParams = { + content: fields, + tool_calls: [], + invalid_tool_calls: [], + tool_call_chunks: [] + }; + else if (fields.tool_call_chunks === void 0 || fields.tool_call_chunks.length === 0) initParams = { + ...fields, + tool_calls: fields.tool_calls ?? [], + invalid_tool_calls: [], + tool_call_chunks: [], + usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 + }; + else initParams = { + ...fields, + ...collapseToolCallChunks(fields.tool_call_chunks ?? []), + usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 + }; + super(initParams); + this.tool_call_chunks = initParams.tool_call_chunks ?? this.tool_call_chunks; + this.tool_calls = initParams.tool_calls ?? this.tool_calls; + this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; + this.usage_metadata = initParams.usage_metadata; + } + get lc_aliases() { + return { + ...super.lc_aliases, + tool_calls: "tool_calls", + invalid_tool_calls: "invalid_tool_calls", + tool_call_chunks: "tool_call_chunks" + }; + } + static lc_name() { + return "AIMessageChunk"; + } + get contentBlocks() { + if (this.response_metadata && "output_version" in this.response_metadata && this.response_metadata.output_version === "v1") return this.content; + if (this.response_metadata && "model_provider" in this.response_metadata && typeof this.response_metadata.model_provider === "string") { + const translator = getTranslator(this.response_metadata.model_provider); + if (translator) return translator.translateContent(this); + } + const blocks = super.contentBlocks; + if (this.tool_calls) { + if (typeof this.content !== "string") { + const contentToolCalls = this.content.filter((block) => block.type === "tool_call").map((block) => block.id); + for (const toolCall of this.tool_calls) if (toolCall.id && !contentToolCalls.includes(toolCall.id)) blocks.push({ + ...toolCall, + type: "tool_call", + id: toolCall.id, + name: toolCall.name, + args: toolCall.args + }); + } + } + return blocks; + } + get _printableFields() { + return { + ...super._printableFields, + tool_calls: this.tool_calls, + tool_call_chunks: this.tool_call_chunks, + invalid_tool_calls: this.invalid_tool_calls, + usage_metadata: this.usage_metadata + }; + } + concat(chunk) { + const combinedFields = { + content: mergeContent(this.content, chunk.content), + additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), + response_metadata: mergeResponseMetadata(this.response_metadata, chunk.response_metadata), + tool_call_chunks: [], + id: this.id ?? chunk.id + }; + if (this.tool_call_chunks !== void 0 || chunk.tool_call_chunks !== void 0) { + const rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks); + if (rawToolCalls !== void 0 && rawToolCalls.length > 0) combinedFields.tool_call_chunks = rawToolCalls; + } + if (this.usage_metadata !== void 0 || chunk.usage_metadata !== void 0) combinedFields.usage_metadata = mergeUsageMetadata(this.usage_metadata, chunk.usage_metadata); + const Cls = this.constructor; + return new Cls(combinedFields); + } + static isInstance(obj) { + return super.isInstance(obj) && obj.type === "ai"; + } +}; + +//#endregion + +//# sourceMappingURL=ai.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/utils.js + + + + + + + + + + + + +//#region src/messages/utils.ts +/** +* Immediately-invoked function expression. +* +* @param fn - The function to execute +* @returns The result of the function +*/ +const utils_iife = (fn) => fn(); +function _coerceToolCall(toolCall) { + if (_isToolCall(toolCall)) return toolCall; + else if (typeof toolCall.id === "string" && toolCall.type === "function" && typeof toolCall.function === "object" && toolCall.function !== null && "arguments" in toolCall.function && typeof toolCall.function.arguments === "string" && "name" in toolCall.function && typeof toolCall.function.name === "string") return { + id: toolCall.id, + args: JSON.parse(toolCall.function.arguments), + name: toolCall.function.name, + type: "tool_call" + }; + else return toolCall; +} +function isSerializedConstructor(x) { + return typeof x === "object" && x != null && x.lc === 1 && Array.isArray(x.id) && x.kwargs != null && typeof x.kwargs === "object"; +} +function _constructMessageFromParams(params) { + let type; + let rest; + if (isSerializedConstructor(params)) { + const className = params.id.at(-1); + if (className === "HumanMessage" || className === "HumanMessageChunk") type = "user"; + else if (className === "AIMessage" || className === "AIMessageChunk") type = "assistant"; + else if (className === "SystemMessage" || className === "SystemMessageChunk") type = "system"; + else if (className === "FunctionMessage" || className === "FunctionMessageChunk") type = "function"; + else if (className === "ToolMessage" || className === "ToolMessageChunk") type = "tool"; + else type = "unknown"; + rest = params.kwargs; + } else { + const { type: extractedType,...otherParams } = params; + type = extractedType; + rest = otherParams; + } + if (type === "human" || type === "user") return new HumanMessage(rest); + else if (type === "ai" || type === "assistant") { + const { tool_calls: rawToolCalls,...other } = rest; + if (!Array.isArray(rawToolCalls)) return new AIMessage(rest); + const tool_calls = rawToolCalls.map(_coerceToolCall); + return new AIMessage({ + ...other, + tool_calls + }); + } else if (type === "system") return new SystemMessage(rest); + else if (type === "developer") return new SystemMessage({ + ...rest, + additional_kwargs: { + ...rest.additional_kwargs, + __openai_role__: "developer" + } + }); + else if (type === "tool" && "tool_call_id" in rest) return new ToolMessage({ + ...rest, + content: rest.content, + tool_call_id: rest.tool_call_id, + name: rest.name + }); + else if (type === "remove" && "id" in rest && typeof rest.id === "string") return new RemoveMessage({ + ...rest, + id: rest.id + }); + else { + const error = addLangChainErrorFields(/* @__PURE__ */ new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(params, null, 2)}`), "MESSAGE_COERCION_FAILURE"); + throw error; + } +} +function utils_coerceMessageLikeToMessage(messageLike) { + if (typeof messageLike === "string") return new HumanMessage(messageLike); + else if (isBaseMessage(messageLike)) return messageLike; + if (Array.isArray(messageLike)) { + const [type, content] = messageLike; + return _constructMessageFromParams({ + type, + content + }); + } else if (_isMessageFieldWithRole(messageLike)) { + const { role: type,...rest } = messageLike; + return _constructMessageFromParams({ + ...rest, + type + }); + } else return _constructMessageFromParams(messageLike); +} +/** +* This function is used by memory classes to get a string representation +* of the chat message history, based on the message content and role. +*/ +function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { + const string_messages = []; + for (const m of messages) { + let role; + if (m._getType() === "human") role = humanPrefix; + else if (m._getType() === "ai") role = aiPrefix; + else if (m._getType() === "system") role = "System"; + else if (m._getType() === "tool") role = "Tool"; + else if (m._getType() === "generic") role = m.role; + else throw new Error(`Got unsupported message type: ${m._getType()}`); + const nameStr = m.name ? `${m.name}, ` : ""; + const readableContent = typeof m.content === "string" ? m.content : JSON.stringify(m.content, null, 2); + string_messages.push(`${role}: ${nameStr}${readableContent}`); + } + return string_messages.join("\n"); +} +/** +* Maps messages from an older format (V1) to the current `StoredMessage` +* format. If the message is already in the `StoredMessage` format, it is +* returned as is. Otherwise, it transforms the V1 message into a +* `StoredMessage`. This function is important for maintaining +* compatibility with older message formats. +*/ +function mapV1MessageToStoredMessage(message) { + if (message.data !== void 0) return message; + else { + const v1Message = message; + return { + type: v1Message.type, + data: { + content: v1Message.text, + role: v1Message.role, + name: void 0, + tool_call_id: void 0 + } + }; + } +} +function mapStoredMessageToChatMessage(message) { + const storedMessage = mapV1MessageToStoredMessage(message); + switch (storedMessage.type) { + case "human": return new HumanMessage(storedMessage.data); + case "ai": return new AIMessage(storedMessage.data); + case "system": return new SystemMessage(storedMessage.data); + case "function": + if (storedMessage.data.name === void 0) throw new Error("Name must be defined for function messages"); + return new FunctionMessage(storedMessage.data); + case "tool": + if (storedMessage.data.tool_call_id === void 0) throw new Error("Tool call ID must be defined for tool messages"); + return new ToolMessage(storedMessage.data); + case "generic": + if (storedMessage.data.role === void 0) throw new Error("Role must be defined for chat messages"); + return new ChatMessage(storedMessage.data); + default: throw new Error(`Got unexpected type: ${storedMessage.type}`); + } +} +/** +* Transforms an array of `StoredMessage` instances into an array of +* `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage` +* function to ensure all messages are in the `StoredMessage` format, then +* creates new instances of the appropriate `BaseMessage` subclass based +* on the type of each message. This function is used to prepare stored +* messages for use in a chat context. +*/ +function mapStoredMessagesToChatMessages(messages) { + return messages.map(mapStoredMessageToChatMessage); +} +/** +* Transforms an array of `BaseMessage` instances into an array of +* `StoredMessage` instances. It does this by calling the `toDict` method +* on each `BaseMessage`, which returns a `StoredMessage`. This function +* is used to prepare chat messages for storage. +*/ +function mapChatMessagesToStoredMessages(messages) { + return messages.map((message) => message.toDict()); +} +function convertToChunk(message) { + const type = message._getType(); + if (type === "human") return new HumanMessageChunk({ ...message }); + else if (type === "ai") { + let aiChunkFields = { ...message }; + if ("tool_calls" in aiChunkFields) aiChunkFields = { + ...aiChunkFields, + tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ + ...tc, + type: "tool_call_chunk", + index: void 0, + args: JSON.stringify(tc.args) + })) + }; + return new AIMessageChunk({ ...aiChunkFields }); + } else if (type === "system") return new SystemMessageChunk({ ...message }); + else if (type === "function") return new FunctionMessageChunk({ ...message }); + else if (ChatMessage.isInstance(message)) return new ChatMessageChunk({ ...message }); + else throw new Error("Unknown message type."); +} +/** +* Collapses an array of tool call chunks into complete tool calls. +* +* This function groups tool call chunks by their id and/or index, then attempts to +* parse and validate the accumulated arguments for each group. Successfully parsed +* tool calls are returned as valid `ToolCall` objects, while malformed ones are +* returned as `InvalidToolCall` objects. +* +* @param chunks - An array of `ToolCallChunk` objects to collapse +* @returns An object containing: +* - `tool_call_chunks`: The original input chunks +* - `tool_calls`: An array of successfully parsed and validated tool calls +* - `invalid_tool_calls`: An array of tool calls that failed parsing or validation +* +* @remarks +* Chunks are grouped using the following matching logic: +* - If a chunk has both an id and index, it matches chunks with the same id and index +* - If a chunk has only an id, it matches chunks with the same id +* - If a chunk has only an index, it matches chunks with the same index +* +* For each group, the function: +* 1. Concatenates all `args` strings from the chunks +* 2. Attempts to parse the concatenated string as JSON +* 3. Validates that the result is a non-null object with a valid id +* 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid) +*/ +function collapseToolCallChunks(chunks) { + const groupedToolCallChunks = chunks.reduce((acc, chunk) => { + const matchedChunkIndex = acc.findIndex(([match]) => { + if ("id" in chunk && chunk.id && "index" in chunk && chunk.index !== void 0) return chunk.id === match.id && chunk.index === match.index; + if ("id" in chunk && chunk.id) return chunk.id === match.id; + if ("index" in chunk && chunk.index !== void 0) return chunk.index === match.index; + return false; + }); + if (matchedChunkIndex !== -1) acc[matchedChunkIndex].push(chunk); + else acc.push([chunk]); + return acc; + }, []); + const toolCalls = []; + const invalidToolCalls = []; + for (const chunks$1 of groupedToolCallChunks) { + let parsedArgs = null; + const name = chunks$1[0]?.name ?? ""; + const joinedArgs = chunks$1.map((c) => c.args || "").join("").trim(); + const argsStr = joinedArgs.length ? joinedArgs : "{}"; + const id = chunks$1[0]?.id; + try { + parsedArgs = parsePartialJson(argsStr); + if (!id || parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) throw new Error("Malformed tool call chunk args."); + toolCalls.push({ + name, + args: parsedArgs, + id, + type: "tool_call" + }); + } catch { + invalidToolCalls.push({ + name, + args: argsStr, + id, + error: "Malformed args.", + type: "invalid_tool_call" + }); + } + } + return { + tool_call_chunks: chunks, + tool_calls: toolCalls, + invalid_tool_calls: invalidToolCalls + }; +} + +//#endregion + +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/env.js + + +//#region src/utils/env.ts +var env_exports = {}; +__export(env_exports, { + getEnv: () => getEnv, + getEnvironmentVariable: () => getEnvironmentVariable, + getRuntimeEnvironment: () => getRuntimeEnvironment, + isBrowser: () => isBrowser, + isDeno: () => isDeno, + isJsDom: () => isJsDom, + isNode: () => isNode, + isWebWorker: () => isWebWorker +}); +const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; +const isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; +const isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom"); +const isDeno = () => typeof Deno !== "undefined"; +const isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno(); +const getEnv = () => { + let env; + if (isBrowser()) env = "browser"; + else if (isNode()) env = "node"; + else if (isWebWorker()) env = "webworker"; + else if (isJsDom()) env = "jsdom"; + else if (isDeno()) env = "deno"; + else env = "other"; + return env; +}; +let runtimeEnvironment; +function getRuntimeEnvironment() { + if (runtimeEnvironment === void 0) { + const env = getEnv(); + runtimeEnvironment = { + library: "langchain-js", + runtime: env + }; + } + return runtimeEnvironment; +} +function getEnvironmentVariable(name) { + try { + if (typeof process !== "undefined") return process.env?.[name]; + else if (isDeno()) return Deno?.env.get(name); + else return void 0; + } catch { + return void 0; + } +} + +//#endregion + +//# sourceMappingURL=env.js.map +// EXTERNAL MODULE: ./node_modules/uuid/dist/index.js +var dist = __nccwpck_require__(2048); +;// CONCATENATED MODULE: ./node_modules/uuid/wrapper.mjs + +const v1 = dist.v1; +const v1ToV6 = dist/* v1ToV6 */.bV; +const v3 = dist.v3; +const v4 = dist.v4; +const v5 = dist.v5; +const v6 = dist.v6; +const v6ToV1 = dist/* v6ToV1 */.JE; +const v7 = dist.v7; +const NIL = dist/* NIL */.wD; +const MAX = dist/* MAX */.Zu; +const version = dist/* version */.rE; +const wrapper_validate = dist/* validate */.tf; +const stringify = dist/* stringify */.As; +const parse = dist/* parse */.qg; + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/base.js + + + + + +//#region src/callbacks/base.ts +var base_exports = {}; +__export(base_exports, { + BaseCallbackHandler: () => BaseCallbackHandler, + callbackHandlerPrefersStreaming: () => callbackHandlerPrefersStreaming, + isBaseCallbackHandler: () => isBaseCallbackHandler +}); +/** +* Abstract class that provides a set of optional methods that can be +* overridden in derived classes to handle various events during the +* execution of a LangChain application. +*/ +var BaseCallbackHandlerMethodsClass = class {}; +function callbackHandlerPrefersStreaming(x) { + return "lc_prefer_streaming" in x && x.lc_prefer_streaming; +} +/** +* Abstract base class for creating callback handlers in the LangChain +* framework. It provides a set of optional methods that can be overridden +* in derived classes to handle various events during the execution of a +* LangChain application. +*/ +var BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass { + lc_serializable = false; + get lc_namespace() { + return [ + "langchain_core", + "callbacks", + this.name + ]; + } + get lc_secrets() { + return void 0; + } + get lc_attributes() { + return void 0; + } + get lc_aliases() { + return void 0; + } + get lc_serializable_keys() { + return void 0; + } + /** + * The name of the serializable. Override to provide an alias or + * to preserve the serialized module name in minified environments. + * + * Implemented as a static method to support loading logic. + */ + static lc_name() { + return this.name; + } + /** + * The final serialized identifier for the module. + */ + get lc_id() { + return [...this.lc_namespace, get_lc_unique_name(this.constructor)]; + } + lc_kwargs; + ignoreLLM = false; + ignoreChain = false; + ignoreAgent = false; + ignoreRetriever = false; + ignoreCustomEvent = false; + raiseError = false; + awaitHandlers = getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false"; + constructor(input) { + super(); + this.lc_kwargs = input || {}; + if (input) { + this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; + this.ignoreChain = input.ignoreChain ?? this.ignoreChain; + this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; + this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; + this.ignoreCustomEvent = input.ignoreCustomEvent ?? this.ignoreCustomEvent; + this.raiseError = input.raiseError ?? this.raiseError; + this.awaitHandlers = this.raiseError || (input._awaitHandler ?? this.awaitHandlers); + } + } + copy() { + return new this.constructor(this); + } + toJSON() { + return Serializable.prototype.toJSON.call(this); + } + toJSONNotImplemented() { + return Serializable.prototype.toJSONNotImplemented.call(this); + } + static fromMethods(methods) { + class Handler extends BaseCallbackHandler { + name = v7(); + constructor() { + super(); + Object.assign(this, methods); + } + } + return new Handler(); + } +}; +const isBaseCallbackHandler = (x) => { + const callbackHandler = x; + return callbackHandler !== void 0 && typeof callbackHandler.copy === "function" && typeof callbackHandler.name === "string" && typeof callbackHandler.awaitHandlers === "boolean"; +}; + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/experimental/otel/constants.js +// OpenTelemetry GenAI semantic convention attribute names +const GEN_AI_OPERATION_NAME = "gen_ai.operation.name"; +const GEN_AI_SYSTEM = "gen_ai.system"; +const GEN_AI_REQUEST_MODEL = "gen_ai.request.model"; +const GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"; +const GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"; +const GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"; +const GEN_AI_USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"; +const GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"; +const GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"; +const GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p"; +const GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty"; +const GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty"; +const GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"; +const GENAI_PROMPT = "gen_ai.prompt"; +const GENAI_COMPLETION = "gen_ai.completion"; +const GEN_AI_REQUEST_EXTRA_QUERY = "gen_ai.request.extra_query"; +const GEN_AI_REQUEST_EXTRA_BODY = "gen_ai.request.extra_body"; +const GEN_AI_SERIALIZED_NAME = "gen_ai.serialized.name"; +const GEN_AI_SERIALIZED_SIGNATURE = "gen_ai.serialized.signature"; +const GEN_AI_SERIALIZED_DOC = "gen_ai.serialized.doc"; +const GEN_AI_RESPONSE_ID = "gen_ai.response.id"; +const GEN_AI_RESPONSE_SERVICE_TIER = "gen_ai.response.service_tier"; +const GEN_AI_RESPONSE_SYSTEM_FINGERPRINT = "gen_ai.response.system_fingerprint"; +const GEN_AI_USAGE_INPUT_TOKEN_DETAILS = "gen_ai.usage.input_token_details"; +const GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS = "gen_ai.usage.output_token_details"; +// LangSmith custom attributes +const LANGSMITH_SESSION_ID = "langsmith.trace.session_id"; +const LANGSMITH_SESSION_NAME = "langsmith.trace.session_name"; +const LANGSMITH_RUN_TYPE = "langsmith.span.kind"; +const LANGSMITH_NAME = "langsmith.trace.name"; +const LANGSMITH_METADATA = "langsmith.metadata"; +const LANGSMITH_TAGS = "langsmith.span.tags"; +const LANGSMITH_RUNTIME = "langsmith.span.runtime"; +const LANGSMITH_REQUEST_STREAMING = "langsmith.request.streaming"; +const LANGSMITH_REQUEST_HEADERS = "langsmith.request.headers"; +const LANGSMITH_RUN_ID = "langsmith.span.id"; +const LANGSMITH_TRACE_ID = "langsmith.trace.id"; +const LANGSMITH_DOTTED_ORDER = "langsmith.span.dotted_order"; +const LANGSMITH_PARENT_RUN_ID = "langsmith.span.parent_id"; +const LANGSMITH_USAGE_METADATA = "langsmith.usage_metadata"; +const LANGSMITH_REFERENCE_EXAMPLE_ID = "langsmith.reference_example_id"; +const LANGSMITH_TRACEABLE = "langsmith.traceable"; +const LANGSMITH_IS_ROOT = "langsmith.is_root"; +const LANGSMITH_TRACEABLE_PARENT_OTEL_SPAN_ID = "langsmith.traceable_parent_otel_span_id"; +// GenAI event names +const GEN_AI_SYSTEM_MESSAGE = "gen_ai.system.message"; +const GEN_AI_USER_MESSAGE = "gen_ai.user.message"; +const GEN_AI_ASSISTANT_MESSAGE = "gen_ai.assistant.message"; +const GEN_AI_CHOICE = "gen_ai.choice"; +const AI_SDK_LLM_OPERATIONS = (/* unused pure expression or super */ null && ([ + "ai.generateText.doGenerate", + "ai.streamText.doStream", + "ai.generateObject.doGenerate", + "ai.streamObject.doStream", +])); +const AI_SDK_TOOL_OPERATIONS = (/* unused pure expression or super */ null && (["ai.toolCall"])); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/fetch.js + +// Wrap the default fetch call due to issues with illegal invocations +// in some environments: +// https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err +// @ts-expect-error Broad typing to support a range of fetch implementations +const DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); +const LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); +/** + * Overrides the fetch implementation used for LangSmith calls. + * You should use this if you need to use an implementation of fetch + * other than the default global (e.g. for dealing with proxies). + * @param fetch The new fetch functino to use. + */ +const overrideFetchImplementation = (fetch) => { + globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch; +}; +const clearFetchImplementation = () => { + delete globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; +}; +const _globalFetchImplementationIsNodeFetch = () => { + const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; + if (!fetchImpl) + return false; + // Check if the implementation has node-fetch specific properties + return (typeof fetchImpl === "function" && + "Headers" in fetchImpl && + "Request" in fetchImpl && + "Response" in fetchImpl); +}; +/** + * @internal + */ +const _getFetchImplementation = (debug) => { + return async (...args) => { + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + const [url, options] = args; + console.log(`→ ${options?.method || "GET"} ${url}`); + } + const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? + DEFAULT_FETCH_IMPLEMENTATION)(...args); + if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { + console.log(`← ${res.status} ${res.statusText} ${res.url}`); + } + return res; + }; +}; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/project.js + +const getDefaultProjectName = () => { + return (getLangSmithEnvironmentVariable("PROJECT") ?? + env_getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate + "default"); +}; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/warn.js +const warnedMessages = {}; +function warn_warnOnce(message) { + if (!warnedMessages[message]) { + console.warn(message); + warnedMessages[message] = true; + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/_uuid.js +// Relaxed UUID validation regex (allows any valid UUID format including nil UUIDs) +const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + + +let UUID7_WARNING_EMITTED = false; +function assertUuid(str, which) { + // Use relaxed regex validation instead of strict uuid.validate() + // This allows edge cases like nil UUIDs or test UUIDs that might not pass strict validation + if (!UUID_REGEX.test(str)) { + const msg = which !== undefined + ? `Invalid UUID for ${which}: ${str}` + : `Invalid UUID: ${str}`; + throw new Error(msg); + } + return str; +} +/** + * Generate a UUID v7 from a timestamp. + * + * @param timestamp - The timestamp in milliseconds + * @returns A UUID v7 string + */ +function uuid7FromTime(timestamp) { + const msecs = typeof timestamp === "string" ? Date.parse(timestamp) : timestamp; + // Work around uuid@10 behavior where providing only { msecs } + // may not set the internal timestamp used for stringification. + // Providing a seq ensures the implementation updates its internal state + // and encodes the provided milliseconds into the UUID bytes. + return v7({ msecs, seq: 0 }); +} +/** + * Get the version of a UUID string. + * @param uuidStr - The UUID string to check + * @returns The version number (1-7) or null if invalid + */ +function getUuidVersion(uuidStr) { + if (!UUID_REGEX.test(uuidStr)) { + return null; + } + // Version is in bits 48-51 + // Format: xxxxxxxx-xxxx-Vxxx-xxxx-xxxxxxxxxxxx + const versionChar = uuidStr[14]; + return parseInt(versionChar, 16); +} +/** + * Warn if a UUID is not version 7. + * + * @param uuidStr - The UUID string to check + * @param idType - The type of ID (e.g., "run_id", "trace_id") for the warning message + */ +function warnIfNotUuidV7(uuidStr, _idType) { + const version = getUuidVersion(uuidStr); + if (version !== null && version !== 7 && !UUID7_WARNING_EMITTED) { + UUID7_WARNING_EMITTED = true; + warnOnce(`LangSmith now uses UUID v7 for run and trace identifiers. ` + + `This warning appears when passing custom IDs. ` + + `Please use: import { uuidv7 } from 'langsmith'; const id = uuidv7(); ` + + `Future versions will require UUID v7.`); + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/uuid.js + + +/** + * Generate a random UUID v7 string. + */ +function uuid7() { + return uuidv7(); +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/index.js + + + + + +// Update using yarn bump-version +const __version__ = "0.4.2"; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/env.js +// Inlined from https://github.com/flexdinesh/browser-or-node + +let globalEnv; +const env_isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; +const env_isWebWorker = () => typeof globalThis === "object" && + globalThis.constructor && + globalThis.constructor.name === "DedicatedWorkerGlobalScope"; +const env_isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || + (typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom")); +// Supabase Edge Function provides a `Deno` global object +// without `version` property +const env_isDeno = () => typeof Deno !== "undefined"; +// Mark not-as-node if in Supabase Edge Function +const env_isNode = () => typeof process !== "undefined" && + typeof process.versions !== "undefined" && + typeof process.versions.node !== "undefined" && + !env_isDeno(); +const env_getEnv = () => { + if (globalEnv) { + return globalEnv; + } + // @ts-expect-error Bun types are not imported due to conflicts with Node types + if (typeof Bun !== "undefined") { + globalEnv = "bun"; + } + else if (env_isBrowser()) { + globalEnv = "browser"; + } + else if (env_isNode()) { + globalEnv = "node"; + } + else if (env_isWebWorker()) { + globalEnv = "webworker"; + } + else if (env_isJsDom()) { + globalEnv = "jsdom"; + } + else if (env_isDeno()) { + globalEnv = "deno"; + } + else { + globalEnv = "other"; + } + return globalEnv; +}; +let env_runtimeEnvironment; +function env_getRuntimeEnvironment() { + if (env_runtimeEnvironment === undefined) { + const env = env_getEnv(); + const releaseEnv = getShas(); + env_runtimeEnvironment = { + library: "langsmith", + runtime: env, + sdk: "langsmith-js", + sdk_version: __version__, + ...releaseEnv, + }; + } + return env_runtimeEnvironment; +} +/** + * Retrieves the LangSmith-specific metadata from the current runtime environment. + * + * @returns {Record} + * - A record of LangSmith-specific metadata environment variables. + */ +function getLangSmithEnvVarsMetadata() { + const allEnvVars = getLangSmithEnvironmentVariables(); + const envVars = {}; + const excluded = [ + "LANGCHAIN_API_KEY", + "LANGCHAIN_ENDPOINT", + "LANGCHAIN_TRACING_V2", + "LANGCHAIN_PROJECT", + "LANGCHAIN_SESSION", + "LANGSMITH_API_KEY", + "LANGSMITH_ENDPOINT", + "LANGSMITH_TRACING_V2", + "LANGSMITH_PROJECT", + "LANGSMITH_SESSION", + ]; + for (const [key, value] of Object.entries(allEnvVars)) { + if (typeof value === "string" && + !excluded.includes(key) && + !key.toLowerCase().includes("key") && + !key.toLowerCase().includes("secret") && + !key.toLowerCase().includes("token")) { + if (key === "LANGCHAIN_REVISION_ID") { + envVars["revision_id"] = value; + } + else { + envVars[key] = value; + } + } + } + return envVars; +} +/** + * Retrieves only the LangChain/LangSmith-prefixed environment variables from the current runtime environment. + * This is more efficient than copying all environment variables. + * + * @returns {Record} + * - A record of LangChain/LangSmith environment variables. + */ +function getLangSmithEnvironmentVariables() { + const envVars = {}; + try { + // Check for Node.js environment + // eslint-disable-next-line no-process-env + if (typeof process !== "undefined" && process.env) { + // eslint-disable-next-line no-process-env + for (const [key, value] of Object.entries(process.env)) { + if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && + value != null) { + if ((key.toLowerCase().includes("key") || + key.toLowerCase().includes("secret") || + key.toLowerCase().includes("token")) && + typeof value === "string") { + envVars[key] = + value.slice(0, 2) + + "*".repeat(value.length - 4) + + value.slice(-2); + } + else { + envVars[key] = value; + } + } + } + } + } + catch (e) { + // Catch any errors that might occur while trying to access environment variables + } + return envVars; +} +function env_getEnvironmentVariable(name) { + // Certain Deno setups will throw an error if you try to access environment variables + // https://github.com/hwchase17/langchainjs/issues/1412 + try { + return typeof process !== "undefined" + ? // eslint-disable-next-line no-process-env + process.env?.[name] + : undefined; + } + catch (e) { + return undefined; + } +} +function getLangSmithEnvironmentVariable(name) { + return (env_getEnvironmentVariable(`LANGSMITH_${name}`) || + env_getEnvironmentVariable(`LANGCHAIN_${name}`)); +} +function setEnvironmentVariable(name, value) { + if (typeof process !== "undefined") { + // eslint-disable-next-line no-process-env + process.env[name] = value; + } +} +let cachedCommitSHAs; +/** + * Get the Git commit SHA from common environment variables + * used by different CI/CD platforms. + * @returns {string | undefined} The Git commit SHA or undefined if not found. + */ +function getShas() { + if (cachedCommitSHAs !== undefined) { + return cachedCommitSHAs; + } + const common_release_envs = [ + "VERCEL_GIT_COMMIT_SHA", + "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", + "COMMIT_REF", + "RENDER_GIT_COMMIT", + "CI_COMMIT_SHA", + "CIRCLE_SHA1", + "CF_PAGES_COMMIT_SHA", + "REACT_APP_GIT_SHA", + "SOURCE_VERSION", + "GITHUB_SHA", + "TRAVIS_COMMIT", + "GIT_COMMIT", + "BUILD_VCS_NUMBER", + "bamboo_planRepository_revision", + "Build.SourceVersion", + "BITBUCKET_COMMIT", + "DRONE_COMMIT_SHA", + "SEMAPHORE_GIT_SHA", + "BUILDKITE_COMMIT", + ]; + const shas = {}; + for (const env of common_release_envs) { + const envVar = env_getEnvironmentVariable(env); + if (envVar !== undefined) { + shas[env] = envVar; + } + } + cachedCommitSHAs = shas; + return shas; +} +function getOtelEnabled() { + return (env_getEnvironmentVariable("OTEL_ENABLED") === "true" || + getLangSmithEnvironmentVariable("OTEL_ENABLED") === "true"); +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/otel.js +// Should not import any OTEL packages to avoid pulling in optional deps. + +class MockTracer { + constructor() { + Object.defineProperty(this, "hasWarned", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + } + startActiveSpan(_name, ...args) { + if (!this.hasWarned && getOtelEnabled()) { + console.warn("You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. " + + 'Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'); + this.hasWarned = true; + } + // Handle different overloads: + // startActiveSpan(name, fn) + // startActiveSpan(name, options, fn) + // startActiveSpan(name, options, context, fn) + let fn; + if (args.length === 1 && typeof args[0] === "function") { + fn = args[0]; + } + else if (args.length === 2 && typeof args[1] === "function") { + fn = args[1]; + } + else if (args.length === 3 && typeof args[2] === "function") { + fn = args[2]; + } + if (typeof fn === "function") { + return fn(); + } + return undefined; + } +} +class MockOTELTrace { + constructor() { + Object.defineProperty(this, "mockTracer", { + enumerable: true, + configurable: true, + writable: true, + value: new MockTracer() + }); + } + getTracer(_name, _version) { + return this.mockTracer; + } + getActiveSpan() { + return undefined; + } + setSpan(context, _span) { + return context; + } + getSpan(_context) { + return undefined; + } + setSpanContext(context, _spanContext) { + return context; + } + getTracerProvider() { + return undefined; + } + setGlobalTracerProvider(_tracerProvider) { + return false; + } +} +class MockOTELContext { + active() { + return {}; + } + with(_context, fn) { + return fn(); + } +} +const OTEL_TRACE_KEY = Symbol.for("ls:otel_trace"); +const OTEL_CONTEXT_KEY = Symbol.for("ls:otel_context"); +const OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY = Symbol.for("ls:otel_get_default_otlp_tracer_provider"); +const mockOTELTrace = new MockOTELTrace(); +const mockOTELContext = new MockOTELContext(); +class OTELProvider { + getTraceInstance() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return globalThis[OTEL_TRACE_KEY] ?? mockOTELTrace; + } + getContextInstance() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return globalThis[OTEL_CONTEXT_KEY] ?? mockOTELContext; + } + initializeGlobalInstances(otel) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (globalThis[OTEL_TRACE_KEY] === undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[OTEL_TRACE_KEY] = otel.trace; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (globalThis[OTEL_CONTEXT_KEY] === undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[OTEL_CONTEXT_KEY] = otel.context; + } + } + setDefaultOTLPTracerComponents(components) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] = components; + } + getDefaultOTLPTracerComponents() { + return (globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] ?? + undefined); + } +} +const OTELProviderSingleton = new OTELProvider(); +/** + * Get the current OTEL trace instance. + * Returns a mock implementation if OTEL is not available. + */ +function getOTELTrace() { + return OTELProviderSingleton.getTraceInstance(); +} +/** + * Get the current OTEL context instance. + * Returns a mock implementation if OTEL is not available. + */ +function getOTELContext() { + return OTELProviderSingleton.getContextInstance(); +} +/** + * Initialize the global OTEL instances. + * Should be called once when OTEL packages are available. + */ +function setOTELInstances(otel) { + OTELProviderSingleton.initializeGlobalInstances(otel); +} +/** + * Set a getter function for the default OTLP tracer provider. + * This allows lazy initialization of the tracer provider. + */ +function setDefaultOTLPTracerComponents(components) { + OTELProviderSingleton.setDefaultOTLPTracerComponents(components); +} +/** + * Get the default OTLP tracer provider instance. + * Returns undefined if not set. + */ +function getDefaultOTLPTracerComponents() { + return OTELProviderSingleton.getDefaultOTLPTracerComponents(); +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/experimental/otel/translator.js + + +const WELL_KNOWN_OPERATION_NAMES = { + llm: "chat", + tool: "execute_tool", + retriever: "embeddings", + embedding: "embeddings", + prompt: "chat", +}; +function getOperationName(runType) { + return WELL_KNOWN_OPERATION_NAMES[runType] || runType; +} +class LangSmithToOTELTranslator { + constructor() { + Object.defineProperty(this, "spans", { + enumerable: true, + configurable: true, + writable: true, + value: new Map() + }); + } + exportBatch(operations, otelContextMap) { + for (const op of operations) { + try { + if (!op.run) { + continue; + } + if (op.operation === "post") { + const span = this.createSpanForRun(op, op.run, otelContextMap.get(op.id)); + if (span && !op.run.end_time) { + this.spans.set(op.id, span); + } + } + else { + this.updateSpanForRun(op, op.run); + } + } + catch (e) { + console.error(`Error processing operation ${op.id}:`, e); + } + } + } + createSpanForRun(op, runInfo, otelContext) { + const activeSpan = otelContext && getOTELTrace().getSpan(otelContext); + if (!activeSpan) { + return; + } + try { + return this.finishSpanSetup(activeSpan, runInfo, op); + } + catch (e) { + console.error(`Failed to create span for run ${op.id}:`, e); + return undefined; + } + } + finishSpanSetup(span, runInfo, op) { + // Set all attributes + this.setSpanAttributes(span, runInfo, op); + // Set status based on error + if (runInfo.error) { + span.setStatus({ code: 2 }); // ERROR status + span.recordException(new Error(runInfo.error)); + } + else { + span.setStatus({ code: 1 }); // OK status + } + // End the span if end_time is present + if (runInfo.end_time) { + span.end(new Date(runInfo.end_time)); + } + return span; + } + updateSpanForRun(op, runInfo) { + try { + const span = this.spans.get(op.id); + if (!span) { + console.debug(`No span found for run ${op.id} during update`); + return; + } + // Update attributes + this.setSpanAttributes(span, runInfo, op); + // Update status based on error + if (runInfo.error) { + span.setStatus({ code: 2 }); // ERROR status + span.recordException(new Error(runInfo.error)); + } + else { + span.setStatus({ code: 1 }); // OK status + } + // End the span if end_time is present + const endTime = runInfo.end_time; + if (endTime) { + span.end(new Date(endTime)); + this.spans.delete(op.id); + } + } + catch (e) { + console.error(`Failed to update span for run ${op.id}:`, e); + } + } + extractModelName(runInfo) { + // Try to get model name from metadata + if (runInfo.extra?.metadata) { + const metadata = runInfo.extra.metadata; + // First check for ls_model_name in metadata + if (metadata.ls_model_name) { + return metadata.ls_model_name; + } + // Then check invocation_params for model info + if (metadata.invocation_params) { + const invocationParams = metadata.invocation_params; + if (invocationParams.model) { + return invocationParams.model; + } + else if (invocationParams.model_name) { + return invocationParams.model_name; + } + } + } + return; + } + setSpanAttributes(span, runInfo, op) { + if ("run_type" in runInfo && runInfo.run_type) { + span.setAttribute(LANGSMITH_RUN_TYPE, runInfo.run_type); + // Set GenAI attributes according to OTEL semantic conventions + const operationName = getOperationName(runInfo.run_type || "chain"); + span.setAttribute(GEN_AI_OPERATION_NAME, operationName); + } + if ("name" in runInfo && runInfo.name) { + span.setAttribute(LANGSMITH_NAME, runInfo.name); + } + if ("session_id" in runInfo && runInfo.session_id) { + span.setAttribute(LANGSMITH_SESSION_ID, runInfo.session_id); + } + if ("session_name" in runInfo && runInfo.session_name) { + span.setAttribute(LANGSMITH_SESSION_NAME, runInfo.session_name); + } + // Set gen_ai.system + this.setGenAiSystem(span, runInfo); + // Set model name if available + const modelName = this.extractModelName(runInfo); + if (modelName) { + span.setAttribute(GEN_AI_REQUEST_MODEL, modelName); + } + // Set token usage information + if ("prompt_tokens" in runInfo && + typeof runInfo.prompt_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, runInfo.prompt_tokens); + } + if ("completion_tokens" in runInfo && + typeof runInfo.completion_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, runInfo.completion_tokens); + } + if ("total_tokens" in runInfo && typeof runInfo.total_tokens === "number") { + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, runInfo.total_tokens); + } + // Set other parameters from invocation_params + this.setInvocationParameters(span, runInfo); + // Set metadata and tags if available + const metadata = runInfo.extra?.metadata || {}; + for (const [key, value] of Object.entries(metadata)) { + if (value !== null && value !== undefined) { + span.setAttribute(`${LANGSMITH_METADATA}.${key}`, String(value)); + } + } + const tags = runInfo.tags; + if (tags && Array.isArray(tags)) { + span.setAttribute(LANGSMITH_TAGS, tags.join(", ")); + } + else if (tags) { + span.setAttribute(LANGSMITH_TAGS, String(tags)); + } + // Support additional serialized attributes, if present + if ("serialized" in runInfo && typeof runInfo.serialized === "object") { + const serialized = runInfo.serialized; + if (serialized.name) { + span.setAttribute(GEN_AI_SERIALIZED_NAME, String(serialized.name)); + } + if (serialized.signature) { + span.setAttribute(GEN_AI_SERIALIZED_SIGNATURE, String(serialized.signature)); + } + if (serialized.doc) { + span.setAttribute(GEN_AI_SERIALIZED_DOC, String(serialized.doc)); + } + } + // Set inputs/outputs if available + this.setIOAttributes(span, op); + } + setGenAiSystem(span, runInfo) { + // Default to "langchain" if we can't determine the system + let system = "langchain"; + // Extract model name to determine the system + const modelName = this.extractModelName(runInfo); + if (modelName) { + const modelLower = modelName.toLowerCase(); + if (modelLower.includes("anthropic") || modelLower.startsWith("claude")) { + system = "anthropic"; + } + else if (modelLower.includes("bedrock")) { + system = "aws.bedrock"; + } + else if (modelLower.includes("azure") && + modelLower.includes("openai")) { + system = "az.ai.openai"; + } + else if (modelLower.includes("azure") && + modelLower.includes("inference")) { + system = "az.ai.inference"; + } + else if (modelLower.includes("cohere")) { + system = "cohere"; + } + else if (modelLower.includes("deepseek")) { + system = "deepseek"; + } + else if (modelLower.includes("gemini")) { + system = "gemini"; + } + else if (modelLower.includes("groq")) { + system = "groq"; + } + else if (modelLower.includes("watson") || modelLower.includes("ibm")) { + system = "ibm.watsonx.ai"; + } + else if (modelLower.includes("mistral")) { + system = "mistral_ai"; + } + else if (modelLower.includes("gpt") || modelLower.includes("openai")) { + system = "openai"; + } + else if (modelLower.includes("perplexity") || + modelLower.includes("sonar")) { + system = "perplexity"; + } + else if (modelLower.includes("vertex")) { + system = "vertex_ai"; + } + else if (modelLower.includes("xai") || modelLower.includes("grok")) { + system = "xai"; + } + } + span.setAttribute(GEN_AI_SYSTEM, system); + } + setInvocationParameters(span, runInfo) { + if (!runInfo.extra?.metadata?.invocation_params) { + return; + } + const invocationParams = runInfo.extra.metadata.invocation_params; + // Set relevant invocation parameters + if (invocationParams.max_tokens !== undefined) { + span.setAttribute(GEN_AI_REQUEST_MAX_TOKENS, invocationParams.max_tokens); + } + if (invocationParams.temperature !== undefined) { + span.setAttribute(GEN_AI_REQUEST_TEMPERATURE, invocationParams.temperature); + } + if (invocationParams.top_p !== undefined) { + span.setAttribute(GEN_AI_REQUEST_TOP_P, invocationParams.top_p); + } + if (invocationParams.frequency_penalty !== undefined) { + span.setAttribute(GEN_AI_REQUEST_FREQUENCY_PENALTY, invocationParams.frequency_penalty); + } + if (invocationParams.presence_penalty !== undefined) { + span.setAttribute(GEN_AI_REQUEST_PRESENCE_PENALTY, invocationParams.presence_penalty); + } + } + setIOAttributes(span, op) { + if (op.run.inputs) { + try { + const inputs = op.run.inputs; + if (typeof inputs === "object" && inputs !== null) { + if (inputs.model && Array.isArray(inputs.messages)) { + span.setAttribute(GEN_AI_REQUEST_MODEL, inputs.model); + } + // Set additional request attributes if available + if (inputs.stream !== undefined) { + span.setAttribute(LANGSMITH_REQUEST_STREAMING, inputs.stream); + } + if (inputs.extra_headers) { + span.setAttribute(LANGSMITH_REQUEST_HEADERS, JSON.stringify(inputs.extra_headers)); + } + if (inputs.extra_query) { + span.setAttribute(GEN_AI_REQUEST_EXTRA_QUERY, JSON.stringify(inputs.extra_query)); + } + if (inputs.extra_body) { + span.setAttribute(GEN_AI_REQUEST_EXTRA_BODY, JSON.stringify(inputs.extra_body)); + } + } + span.setAttribute(GENAI_PROMPT, JSON.stringify(inputs)); + } + catch (e) { + console.debug(`Failed to process inputs for run ${op.id}`, e); + } + } + if (op.run.outputs) { + try { + const outputs = op.run.outputs; + // Extract token usage from outputs (for LLM runs) + const tokenUsage = this.getUnifiedRunTokens(outputs); + if (tokenUsage) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, tokenUsage[0]); + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, tokenUsage[1]); + span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, tokenUsage[0] + tokenUsage[1]); + } + if (outputs && typeof outputs === "object") { + if (outputs.model) { + span.setAttribute(GEN_AI_RESPONSE_MODEL, String(outputs.model)); + } + // Extract additional response attributes + if (outputs.id) { + span.setAttribute(GEN_AI_RESPONSE_ID, outputs.id); + } + if (outputs.choices && Array.isArray(outputs.choices)) { + const finishReasons = outputs.choices + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .map((choice) => choice.finish_reason) + // eslint-disable-next-line @typescript-eslint/no-explicit-any + .filter((reason) => reason) + .map(String); + if (finishReasons.length > 0) { + span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, finishReasons.join(", ")); + } + } + if (outputs.service_tier) { + span.setAttribute(GEN_AI_RESPONSE_SERVICE_TIER, outputs.service_tier); + } + if (outputs.system_fingerprint) { + span.setAttribute(GEN_AI_RESPONSE_SYSTEM_FINGERPRINT, outputs.system_fingerprint); + } + if (outputs.usage_metadata && + typeof outputs.usage_metadata === "object") { + const usageMetadata = outputs.usage_metadata; + if (usageMetadata.input_token_details) { + span.setAttribute(GEN_AI_USAGE_INPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.input_token_details)); + } + if (usageMetadata.output_token_details) { + span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.output_token_details)); + } + } + } + span.setAttribute(GENAI_COMPLETION, JSON.stringify(outputs)); + } + catch (e) { + console.debug(`Failed to process outputs for run ${op.id}`, e); + } + } + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + getUnifiedRunTokens(outputs) { + if (!outputs) { + return null; + } + // Search in non-generations lists + let tokenUsage = this.extractUnifiedRunTokens(outputs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + // Find if direct kwarg in outputs + const keys = Object.keys(outputs); + for (const key of keys) { + const haystack = outputs[key]; + if (!haystack || typeof haystack !== "object") { + continue; + } + tokenUsage = this.extractUnifiedRunTokens(haystack.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + if (haystack.lc === 1 && + haystack.kwargs && + typeof haystack.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(haystack.kwargs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + } + } + // Find in generations + const generations = outputs.generations || []; + if (!Array.isArray(generations)) { + return null; + } + const flatGenerations = Array.isArray(generations[0]) + ? generations.flat() + : generations; + for (const generation of flatGenerations) { + if (typeof generation === "object" && + generation.message && + typeof generation.message === "object" && + generation.message.kwargs && + typeof generation.message.kwargs === "object") { + tokenUsage = this.extractUnifiedRunTokens(generation.message.kwargs.usage_metadata); + if (tokenUsage) { + return tokenUsage; + } + } + } + return null; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + extractUnifiedRunTokens(outputs) { + if (!outputs || typeof outputs !== "object") { + return null; + } + if (typeof outputs.input_tokens !== "number" || + typeof outputs.output_tokens !== "number") { + return null; + } + return [outputs.input_tokens, outputs.output_tokens]; + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/is-network-error/index.js +/* eslint-disable */ +// @ts-nocheck +// is-network-error vendored to avoid import issues +// Source: https://github.com/sindresorhus/is-network-error +const objectToString = Object.prototype.toString; +const isError = (value) => objectToString.call(value) === "[object Error]"; +const errorMessages = new Set([ + "network error", // Chrome + "Failed to fetch", // Chrome + "NetworkError when attempting to fetch resource.", // Firefox + "The Internet connection appears to be offline.", // Safari 16 + "Network request failed", // `cross-fetch` + "fetch failed", // Undici (Node.js) + "terminated", // Undici (Node.js) + " A network error occurred.", // Bun (WebKit) + "Network connection lost", // Cloudflare Workers (fetch) +]); +function isNetworkError(error) { + const isValid = error && + isError(error) && + error.name === "TypeError" && + typeof error.message === "string"; + if (!isValid) { + return false; + } + const { message, stack } = error; + // Safari 17+ has generic message but no stack for network errors + if (message === "Load failed") { + return (stack === undefined || + // Sentry adds its own stack trace to the fetch error, so also check for that + "__sentry_captured__" in error); + } + // Deno network errors start with specific text + if (message.startsWith("error sending request for url")) { + return true; + } + // Standard network error messages + return errorMessages.has(message); +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/p-retry/index.js +/* eslint-disable */ +// @ts-nocheck +// p-retry code vendored to avoid import issues +// Source: https://github.com/sindresorhus/p-retry + +function validateRetries(retries) { + if (typeof retries === "number") { + if (retries < 0) { + throw new TypeError("Expected `retries` to be a non-negative number."); + } + if (Number.isNaN(retries)) { + throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN."); + } + } + else if (retries !== undefined) { + throw new TypeError("Expected `retries` to be a number or Infinity."); + } +} +function validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) { + if (value === undefined) { + return; + } + if (typeof value !== "number" || Number.isNaN(value)) { + throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`); + } + if (!allowInfinity && !Number.isFinite(value)) { + throw new TypeError(`Expected \`${name}\` to be a finite number.`); + } + if (value < min) { + throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`); + } +} +class AbortError extends Error { + constructor(message) { + super(); + if (message instanceof Error) { + this.originalError = message; + ({ message } = message); + } + else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } + this.name = "AbortError"; + this.message = message; + } +} +function calculateDelay(retriesConsumed, options) { + const attempt = Math.max(1, retriesConsumed + 1); + const random = options.randomize ? Math.random() + 1 : 1; + let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1)); + timeout = Math.min(timeout, options.maxTimeout); + return timeout; +} +function calculateRemainingTime(start, max) { + if (!Number.isFinite(max)) { + return max; + } + return max - (performance.now() - start); +} +async function onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options, }) { + const normalizedError = error instanceof Error + ? error + : new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`); + if (normalizedError instanceof AbortError) { + throw normalizedError.originalError; + } + const retriesLeft = Number.isFinite(options.retries) + ? Math.max(0, options.retries - retriesConsumed) + : options.retries; + const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY; + const context = Object.freeze({ + error: normalizedError, + attemptNumber, + retriesLeft, + retriesConsumed, + }); + await options.onFailedAttempt(context); + if (calculateRemainingTime(startTime, maxRetryTime) <= 0) { + throw normalizedError; + } + const consumeRetry = await options.shouldConsumeRetry(context); + const remainingTime = calculateRemainingTime(startTime, maxRetryTime); + if (remainingTime <= 0 || retriesLeft <= 0) { + throw normalizedError; + } + if (normalizedError instanceof TypeError && + !isNetworkError(normalizedError)) { + if (consumeRetry) { + throw normalizedError; + } + options.signal?.throwIfAborted(); + return false; + } + if (!(await options.shouldRetry(context))) { + throw normalizedError; + } + if (!consumeRetry) { + options.signal?.throwIfAborted(); + return false; + } + const delayTime = calculateDelay(retriesConsumed, options); + const finalDelay = Math.min(delayTime, remainingTime); + if (finalDelay > 0) { + await new Promise((resolve, reject) => { + const onAbort = () => { + clearTimeout(timeoutToken); + options.signal?.removeEventListener("abort", onAbort); + reject(options.signal.reason); + }; + const timeoutToken = setTimeout(() => { + options.signal?.removeEventListener("abort", onAbort); + resolve(); + }, finalDelay); + if (options.unref) { + timeoutToken.unref?.(); + } + options.signal?.addEventListener("abort", onAbort, { once: true }); + }); + } + options.signal?.throwIfAborted(); + return true; +} +async function pRetry(input, options = {}) { + options = { ...options }; + validateRetries(options.retries); + if (Object.hasOwn(options, "forever")) { + throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead."); + } + options.retries ??= 10; + options.factor ??= 2; + options.minTimeout ??= 1000; + options.maxTimeout ??= Number.POSITIVE_INFINITY; + options.maxRetryTime ??= Number.POSITIVE_INFINITY; + options.randomize ??= false; + options.onFailedAttempt ??= () => { }; + options.shouldRetry ??= () => true; + options.shouldConsumeRetry ??= () => true; + // Validate numeric options and normalize edge cases + validateNumberOption("factor", options.factor, { + min: 0, + allowInfinity: false, + }); + validateNumberOption("minTimeout", options.minTimeout, { + min: 0, + allowInfinity: false, + }); + validateNumberOption("maxTimeout", options.maxTimeout, { + min: 0, + allowInfinity: true, + }); + validateNumberOption("maxRetryTime", options.maxRetryTime, { + min: 0, + allowInfinity: true, + }); + // Treat non-positive factor as 1 to avoid zero backoff or negative behavior + if (!(options.factor > 0)) { + options.factor = 1; + } + options.signal?.throwIfAborted(); + let attemptNumber = 0; + let retriesConsumed = 0; + const startTime = performance.now(); + while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) { + attemptNumber++; + try { + options.signal?.throwIfAborted(); + const result = await input(attemptNumber); + options.signal?.throwIfAborted(); + return result; + } + catch (error) { + if (await onAttemptFailure({ + error, + attemptNumber, + retriesConsumed, + startTime, + options, + })) { + retriesConsumed++; + } + } + } + // Should not reach here, but in case it does, throw an error + throw new Error("Retry attempts exhausted without throwing an error."); +} +function makeRetriable(function_, options) { + return function (...arguments_) { + return pRetry(() => function_.apply(this, arguments_), options); + }; +} + +// EXTERNAL MODULE: ./node_modules/p-queue/dist/index.js +var p_queue_dist = __nccwpck_require__(6459); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/async_caller.js + + +const STATUS_RETRYABLE = [ + 408, // Request Timeout + 425, // Too Early + 429, // Too Many Requests + 500, // Internal Server Error + 502, // Bad Gateway + 503, // Service Unavailable + 504, // Gateway Timeout +]; +/** + * A class that can be used to make async calls with concurrency and retry logic. + * + * This is useful for making calls to any kind of "expensive" external resource, + * be it because it's rate-limited, subject to network issues, etc. + * + * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults + * to `Infinity`. This means that by default, all calls will be made in parallel. + * + * Retries are limited by the `maxRetries` parameter, which defaults to 6. This + * means that by default, each call will be retried up to 6 times, with an + * exponential backoff between each attempt. + */ +class AsyncCaller { + constructor(params) { + Object.defineProperty(this, "maxConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "maxRetries", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "maxQueueSizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "queue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "onFailedResponseHook", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "queueSizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.maxQueueSizeBytes = params.maxQueueSizeBytes; + if ( true) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.queue = new p_queue_dist["default"]({ + concurrency: this.maxConcurrency, + }); + } + else { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + this.queue = new p_queue_dist({ concurrency: this.maxConcurrency }); + } + this.onFailedResponseHook = params?.onFailedResponseHook; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + call(callable, ...args) { + return this.callWithOptions({}, callable, ...args); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callWithOptions(options, callable, ...args) { + const sizeBytes = options.sizeBytes ?? 0; + // Check if adding this call would exceed the byte size limit + if (this.maxQueueSizeBytes !== undefined && + sizeBytes > 0 && + this.queueSizeBytes + sizeBytes > this.maxQueueSizeBytes) { + return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. ` + + `Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${sizeBytes} bytes.`)); + } + // Add to queue size tracking + if (sizeBytes > 0) { + this.queueSizeBytes += sizeBytes; + } + const onFailedResponseHook = this.onFailedResponseHook; + let promise = this.queue.add(() => pRetry(() => callable(...args).catch((error) => { + // eslint-disable-next-line no-instanceof/no-instanceof + if (error instanceof Error) { + throw error; + } + else { + throw new Error(error); + } + }), { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + async onFailedAttempt({ error }) { + if (error.message.startsWith("Cancel") || + error.message.startsWith("TimeoutError") || + error.name === "TimeoutError" || + error.message.startsWith("AbortError")) { + throw error; + } + if (error?.code === "ECONNABORTED") { + throw error; + } + const response = error?.response; + if (onFailedResponseHook) { + const handled = await onFailedResponseHook(response); + if (handled) { + return; + } + } + const status = response?.status ?? error?.status; + if (status) { + if (!STATUS_RETRYABLE.includes(+status)) { + throw error; + } + } + }, + retries: this.maxRetries, + randomize: true, + }), { throwOnTimeout: true }); + // Decrement queue size when the call completes (success or failure) + if (sizeBytes > 0) { + promise = promise.finally(() => { + this.queueSizeBytes -= sizeBytes; + }); + } + // Handle signal cancellation + if (options.signal) { + return Promise.race([ + promise, + new Promise((_, reject) => { + options.signal?.addEventListener("abort", () => { + reject(new Error("AbortError")); + }); + }), + ]); + } + return promise; + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/messages.js +function isLangChainMessage( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +message) { + return typeof message?._getType === "function"; +} +function convertLangChainMessageToExample(message) { + const converted = { + type: message._getType(), + data: { content: message.content }, + }; + // Check for presence of keys in additional_kwargs + if (message?.additional_kwargs && + Object.keys(message.additional_kwargs).length > 0) { + converted.data.additional_kwargs = { ...message.additional_kwargs }; + } + return converted; +} + +// EXTERNAL MODULE: ./node_modules/langsmith/node_modules/semver/index.js +var semver = __nccwpck_require__(1727); +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/prompts.js + +function isVersionGreaterOrEqual(current_version, target_version) { + const current = parseVersion(current_version); + const target = parseVersion(target_version); + if (!current || !target) { + throw new Error("Invalid version format."); + } + return current.compare(target) >= 0; +} +function parsePromptIdentifier(identifier) { + if (!identifier || + identifier.split("/").length > 2 || + identifier.startsWith("/") || + identifier.endsWith("/") || + identifier.split(":").length > 2) { + throw new Error(`Invalid identifier format: ${identifier}`); + } + const [ownerNamePart, commitPart] = identifier.split(":"); + const commit = commitPart || "latest"; + if (ownerNamePart.includes("/")) { + const [owner, name] = ownerNamePart.split("/", 2); + if (!owner || !name) { + throw new Error(`Invalid identifier format: ${identifier}`); + } + return [owner, name, commit]; + } + else { + if (!ownerNamePart) { + throw new Error(`Invalid identifier format: ${identifier}`); + } + return ["-", ownerNamePart, commit]; + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/error.js +function getErrorStackTrace(e) { + if (typeof e !== "object" || e == null) + return undefined; + if (!("stack" in e) || typeof e.stack !== "string") + return undefined; + let stack = e.stack; + const prevLine = `${e}`; + if (stack.startsWith(prevLine)) { + stack = stack.slice(prevLine.length); + } + if (stack.startsWith("\n")) { + stack = stack.slice(1); + } + return stack; +} +function printErrorStackTrace(e) { + const stack = getErrorStackTrace(e); + if (stack == null) + return; + console.error(stack); +} +/** + * LangSmithConflictError + * + * Represents an error that occurs when there's a conflict during an operation, + * typically corresponding to HTTP 409 status code responses. + * + * This error is thrown when an attempt to create or modify a resource conflicts + * with the current state of the resource on the server. Common scenarios include: + * - Attempting to create a resource that already exists + * - Trying to update a resource that has been modified by another process + * - Violating a uniqueness constraint in the data + * + * @extends Error + * + * @example + * try { + * await createProject("existingProject"); + * } catch (error) { + * if (error instanceof ConflictError) { + * console.log("A conflict occurred:", error.message); + * // Handle the conflict, e.g., by suggesting a different project name + * } else { + * // Handle other types of errors + * } + * } + * + * @property {string} name - Always set to 'ConflictError' for easy identification + * @property {string} message - Detailed error message including server response + * + * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 + */ +class LangSmithConflictError extends Error { + constructor(message) { + super(message); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = "LangSmithConflictError"; + this.status = 409; + } +} +/** + * LangSmithNotFoundError + * + * Represents an error that occurs when a requested resource is not found, + * typically corresponding to HTTP 404 status code responses. + * + * @extends Error + */ +class LangSmithNotFoundError extends Error { + constructor(message) { + super(message); + Object.defineProperty(this, "status", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.name = "LangSmithNotFoundError"; + this.status = 404; + } +} +function isLangSmithNotFoundError(error) { + return (error != null && + typeof error === "object" && + "name" in error && + error?.name === "LangSmithNotFoundError"); +} +/** + * Throws an appropriate error based on the response status and body. + * + * @param response - The fetch Response object + * @param context - Additional context to include in the error message (e.g., operation being performed) + * @throws {LangSmithConflictError} When the response status is 409 + * @throws {Error} For all other non-ok responses + */ +async function raiseForStatus(response, context, consumeOnSuccess) { + let errorBody; + if (response.ok) { + // consume the response body to release the connection + // https://undici.nodejs.org/#/?id=garbage-collection + if (consumeOnSuccess) { + errorBody = await response.text(); + } + return; + } + if (response.status === 403) { + try { + const errorData = await response.json(); + const errorCode = errorData?.error; + if (errorCode === "org_scoped_key_requires_workspace") { + errorBody = + "This API key is org-scoped and requires workspace specification. " + + "Please provide 'workspaceId' parameter, " + + "or set LANGSMITH_WORKSPACE_ID environment variable."; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + catch (e) { + const errorWithStatus = new Error(`${response.status} ${response.statusText}`); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + errorWithStatus.status = response?.status; + throw errorWithStatus; + } + } + if (errorBody === undefined) { + try { + errorBody = await response.text(); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + catch (e) { + errorBody = ""; + } + } + const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Message: ${errorBody}`; + if (response.status === 404) { + throw new LangSmithNotFoundError(fullMessage); + } + if (response.status === 409) { + throw new LangSmithConflictError(fullMessage); + } + const err = new Error(fullMessage); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + err.status = response.status; + throw err; +} +const ERR_CONFLICTING_ENDPOINTS = "ERR_CONFLICTING_ENDPOINTS"; +class ConflictingEndpointsError extends Error { + constructor() { + super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT " + + "and LANGSMITH_RUNS_ENDPOINTS."); + Object.defineProperty(this, "code", { + enumerable: true, + configurable: true, + writable: true, + value: ERR_CONFLICTING_ENDPOINTS + }); + this.name = "ConflictingEndpointsError"; // helpful in logs + } +} +function isConflictingEndpointsError(err) { + return (typeof err === "object" && + err !== null && + err.code === ERR_CONFLICTING_ENDPOINTS); +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/fast-safe-stringify/index.js +/* eslint-disable */ +// @ts-nocheck + +var LIMIT_REPLACE_NODE = "[...]"; +var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; +var arr = []; +var replacerStack = []; +const encoder = new TextEncoder(); +function defaultOptions() { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER, + }; +} +function encodeString(str) { + return encoder.encode(str); +} +// Shared function to handle well-known types +function serializeWellKnownTypes(val) { + if (val && typeof val === "object" && val !== null) { + if (val instanceof Map) { + return Object.fromEntries(val); + } + else if (val instanceof Set) { + return Array.from(val); + } + else if (val instanceof Date) { + return val.toISOString(); + } + else if (val instanceof RegExp) { + return val.toString(); + } + else if (val instanceof Error) { + return { + name: val.name, + message: val.message, + }; + } + } + else if (typeof val === "bigint") { + return val.toString(); + } + return val; +} +// Default replacer function to handle well-known types +function createDefaultReplacer(userReplacer) { + return function (key, val) { + // Apply user replacer first if provided + if (userReplacer) { + const userResult = userReplacer.call(this, key, val); + // If user replacer returned undefined, fall back to our serialization + if (userResult !== undefined) { + return userResult; + } + } + // Fall back to our well-known type handling + return serializeWellKnownTypes(val); + }; +} +// Regular stringify +function serialize(obj, errorContext, replacer, spacer, options) { + try { + const str = JSON.stringify(obj, createDefaultReplacer(replacer), spacer); + return encodeString(str); + } + catch (e) { + // Fall back to more complex stringify if circular reference + if (!e.message?.includes("Converting circular structure to JSON")) { + console.warn(`[WARNING]: LangSmith received unserializable value.${errorContext ? `\nContext: ${errorContext}` : ""}`); + return encodeString("[Unserializable]"); + } + getLangSmithEnvironmentVariable("SUPPRESS_CIRCULAR_JSON_WARNINGS") !== + "true" && + console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? `\nContext: ${errorContext}` : ""}`); + if (typeof options === "undefined") { + options = defaultOptions(); + } + decirc(obj, "", 0, [], undefined, 0, options); + let res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(obj, replacer, spacer); + } + else { + res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); + } + } + catch (_) { + return encodeString("[unable to serialize, circular reference is too complex to analyze]"); + } + finally { + while (arr.length !== 0) { + const part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); + } + else { + part[0][part[1]] = part[2]; + } + } + } + return encodeString(res); + } +} +function setReplace(replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); + if (propertyDescriptor.get !== undefined) { + if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }); + arr.push([parent, k, val, propertyDescriptor]); + } + else { + replacerStack.push([val, k, replace]); + } + } + else { + parent[k] = replace; + arr.push([parent, k, val]); + } +} +function decirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return; + } + } + if (typeof options.depthLimit !== "undefined" && + depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && + edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + stack.push(val); + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + decirc(val[i], i, i, stack, val, depth, options); + } + } + else { + // Handle well-known types before Object.keys iteration + val = serializeWellKnownTypes(val); + var keys = Object.keys(val); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + decirc(val[key], key, i, stack, val, depth, options); + } + } + stack.pop(); + } +} +// Stable-stringify +function compareFunction(a, b) { + if (a < b) { + return -1; + } + if (a > b) { + return 1; + } + return 0; +} +function deterministicStringify(obj, replacer, spacer, options) { + if (typeof options === "undefined") { + options = defaultOptions(); + } + var tmp = deterministicDecirc(obj, "", 0, [], undefined, 0, options) || obj; + var res; + try { + if (replacerStack.length === 0) { + res = JSON.stringify(tmp, replacer, spacer); + } + else { + res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); + } + } + catch (_) { + return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); + } + finally { + // Ensure that we restore the object as it was. + while (arr.length !== 0) { + var part = arr.pop(); + if (part.length === 4) { + Object.defineProperty(part[0], part[1], part[3]); + } + else { + part[0][part[1]] = part[2]; + } + } + } + return res; +} +function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) { + if (stack[i] === val) { + setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); + return; + } + } + try { + if (typeof val.toJSON === "function") { + return; + } + } + catch (_) { + return; + } + if (typeof options.depthLimit !== "undefined" && + depth > options.depthLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && + edgeIndex + 1 > options.edgesLimit) { + setReplace(LIMIT_REPLACE_NODE, val, k, parent); + return; + } + stack.push(val); + // Optimize for Arrays. Big arrays could kill the performance otherwise! + if (Array.isArray(val)) { + for (i = 0; i < val.length; i++) { + deterministicDecirc(val[i], i, i, stack, val, depth, options); + } + } + else { + // Handle well-known types before Object.keys iteration + val = serializeWellKnownTypes(val); + // Create a temporary object in the required way + var tmp = {}; + var keys = Object.keys(val).sort(compareFunction); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + deterministicDecirc(val[key], key, i, stack, val, depth, options); + tmp[key] = val[key]; + } + if (typeof parent !== "undefined") { + arr.push([parent, k, val]); + parent[k] = tmp; + } + else { + return tmp; + } + } + stack.pop(); + } +} +// wraps replacer function to handle values we couldn't replace +// and mark them as replaced value +function replaceGetterValues(replacer) { + replacer = + typeof replacer !== "undefined" + ? replacer + : function (k, v) { + return v; + }; + return function (key, val) { + if (replacerStack.length > 0) { + for (var i = 0; i < replacerStack.length; i++) { + var part = replacerStack[i]; + if (part[1] === key && part[0] === val) { + val = part[2]; + replacerStack.splice(i, 1); + break; + } + } + } + return replacer.call(this, key, val); + }; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/client.js + + + + + + + + + + + + + +function mergeRuntimeEnvIntoRun(run, cachedEnvVars, omitTracedRuntimeInfo) { + if (omitTracedRuntimeInfo) { + return run; + } + const runtimeEnv = env_getRuntimeEnvironment(); + const envVars = cachedEnvVars ?? getLangSmithEnvVarsMetadata(); + const extra = run.extra ?? {}; + const metadata = extra.metadata; + run.extra = { + ...extra, + runtime: { + ...runtimeEnv, + ...extra?.runtime, + }, + metadata: { + ...envVars, + ...(envVars.revision_id || ("revision_id" in run && run.revision_id) + ? { + revision_id: ("revision_id" in run ? run.revision_id : undefined) ?? + envVars.revision_id, + } + : {}), + ...metadata, + }, + }; + return run; +} +const getTracingSamplingRate = (configRate) => { + const samplingRateStr = configRate?.toString() ?? + getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); + if (samplingRateStr === undefined) { + return undefined; + } + const samplingRate = parseFloat(samplingRateStr); + if (samplingRate < 0 || samplingRate > 1) { + throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); + } + return samplingRate; +}; +// utility functions +const isLocalhost = (url) => { + const strippedUrl = url.replace("http://", "").replace("https://", ""); + const hostname = strippedUrl.split("/")[0].split(":")[0]; + return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"); +}; +async function toArray(iterable) { + const result = []; + for await (const item of iterable) { + result.push(item); + } + return result; +} +function trimQuotes(str) { + if (str === undefined) { + return undefined; + } + return str + .trim() + .replace(/^"(.*)"$/, "$1") + .replace(/^'(.*)'$/, "$1"); +} +const handle429 = async (response) => { + if (response?.status === 429) { + const retryAfter = parseInt(response.headers.get("retry-after") ?? "10", 10) * 1000; + if (retryAfter > 0) { + await new Promise((resolve) => setTimeout(resolve, retryAfter)); + // Return directly after calling this check + return true; + } + } + // Fall back to existing status checks + return false; +}; +function _formatFeedbackScore(score) { + if (typeof score === "number") { + // Truncate at 4 decimal places + return Number(score.toFixed(4)); + } + return score; +} +const DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES = 24 * 1024 * 1024; +/** Default maximum memory (1GB) for queue size limits. */ +const DEFAULT_MAX_SIZE_BYTES = 1024 * 1024 * 1024; // 1GB +const SERVER_INFO_REQUEST_TIMEOUT_MS = 10000; +/** Maximum number of operations to batch in a single request. */ +const DEFAULT_BATCH_SIZE_LIMIT = 100; +const DEFAULT_API_URL = "https://api.smith.langchain.com"; +class AutoBatchQueue { + constructor(maxSizeBytes) { + Object.defineProperty(this, "items", { + enumerable: true, + configurable: true, + writable: true, + value: [] + }); + Object.defineProperty(this, "sizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: 0 + }); + Object.defineProperty(this, "maxSizeBytes", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.maxSizeBytes = maxSizeBytes ?? DEFAULT_MAX_SIZE_BYTES; + } + peek() { + return this.items[0]; + } + push(item) { + let itemPromiseResolve; + const itemPromise = new Promise((resolve) => { + // Setting itemPromiseResolve is synchronous with promise creation: + // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise + itemPromiseResolve = resolve; + }); + const size = serialize(item.item, `Serializing run with id: ${item.item.id}`).length; + // Check if adding this item would exceed the size limit + // Allow the run if the queue is empty (to support large single traces) + if (this.sizeBytes + size > this.maxSizeBytes && this.items.length > 0) { + console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${item.item.id}. ` + + `Current queue size: ${this.sizeBytes} bytes, attempted addition: ${size} bytes.`); + // Resolve immediately to avoid blocking caller + itemPromiseResolve(); + return itemPromise; + } + this.items.push({ + action: item.action, + payload: item.item, + otelContext: item.otelContext, + apiKey: item.apiKey, + apiUrl: item.apiUrl, + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + itemPromiseResolve: itemPromiseResolve, + itemPromise, + size, + }); + this.sizeBytes += size; + return itemPromise; + } + pop({ upToSizeBytes, upToSize, }) { + if (upToSizeBytes < 1) { + throw new Error("Number of bytes to pop off may not be less than 1."); + } + const popped = []; + let poppedSizeBytes = 0; + // Pop items until we reach or exceed the size limit + while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && + this.items.length > 0 && + popped.length < upToSize) { + const item = this.items.shift(); + if (item) { + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } + } + // If there is an item on the queue we were unable to pop, + // just return it as a single batch. + if (popped.length === 0 && this.items.length > 0) { + const item = this.items.shift(); + popped.push(item); + poppedSizeBytes += item.size; + this.sizeBytes -= item.size; + } + return [ + popped.map((it) => ({ + action: it.action, + item: it.payload, + otelContext: it.otelContext, + apiKey: it.apiKey, + apiUrl: it.apiUrl, + size: it.size, + })), + () => popped.forEach((it) => it.itemPromiseResolve()), + ]; + } +} +class Client { + get _fetch() { + return this.fetchImplementation || _getFetchImplementation(this.debug); + } + constructor(config = {}) { + Object.defineProperty(this, "apiKey", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "apiUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "webUrl", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "workspaceId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "caller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "batchIngestCaller", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "timeout_ms", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_tenantId", { + enumerable: true, + configurable: true, + writable: true, + value: null + }); + Object.defineProperty(this, "hideInputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "hideOutputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "omitTracedRuntimeInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingSampleRate", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "filteredPostUuids", { + enumerable: true, + configurable: true, + writable: true, + value: new Set() + }); + Object.defineProperty(this, "autoBatchTracing", { + enumerable: true, + configurable: true, + writable: true, + value: true + }); + Object.defineProperty(this, "autoBatchQueue", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "autoBatchTimeout", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "autoBatchAggregationDelayMs", { + enumerable: true, + configurable: true, + writable: true, + value: 250 + }); + Object.defineProperty(this, "batchSizeBytesLimit", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "batchSizeLimit", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fetchOptions", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "settings", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "blockOnRootRunFinalization", { + enumerable: true, + configurable: true, + writable: true, + value: env_getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" + }); + Object.defineProperty(this, "traceBatchConcurrency", { + enumerable: true, + configurable: true, + writable: true, + value: 5 + }); + Object.defineProperty(this, "_serverInfo", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + Object.defineProperty(this, "_getServerInfoPromise", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "manualFlushMode", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "langSmithToOTELTranslator", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "fetchImplementation", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "cachedLSEnvVarsForMetadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "multipartStreamingDisabled", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "_multipartDisabled", { + enumerable: true, + configurable: true, + writable: true, + value: false + }); + Object.defineProperty(this, "debug", { + enumerable: true, + configurable: true, + writable: true, + value: env_getEnvironmentVariable("LANGSMITH_DEBUG") === "true" + }); + const defaultConfig = Client.getDefaultClientConfig(); + this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate); + this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; + if (this.apiUrl.endsWith("/")) { + this.apiUrl = this.apiUrl.slice(0, -1); + } + this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); + this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); + if (this.webUrl?.endsWith("/")) { + this.webUrl = this.webUrl.slice(0, -1); + } + this.workspaceId = trimQuotes(config.workspaceId ?? getLangSmithEnvironmentVariable("WORKSPACE_ID")); + this.timeout_ms = config.timeout_ms ?? 90_000; + this.caller = new AsyncCaller({ + ...(config.callerOptions ?? {}), + maxRetries: 4, + debug: config.debug ?? this.debug, + }); + this.traceBatchConcurrency = + config.traceBatchConcurrency ?? this.traceBatchConcurrency; + if (this.traceBatchConcurrency < 1) { + throw new Error("Trace batch concurrency must be positive."); + } + this.debug = config.debug ?? this.debug; + this.fetchImplementation = config.fetchImplementation; + // Use maxIngestMemoryBytes for both queues + const maxMemory = config.maxIngestMemoryBytes ?? DEFAULT_MAX_SIZE_BYTES; + this.batchIngestCaller = new AsyncCaller({ + maxRetries: 4, + maxConcurrency: this.traceBatchConcurrency, + maxQueueSizeBytes: maxMemory, + ...(config.callerOptions ?? {}), + onFailedResponseHook: handle429, + debug: config.debug ?? this.debug, + }); + this.hideInputs = + config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; + this.hideOutputs = + config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; + this.omitTracedRuntimeInfo = config.omitTracedRuntimeInfo ?? false; + this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; + this.autoBatchQueue = new AutoBatchQueue(maxMemory); + this.blockOnRootRunFinalization = + config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; + this.batchSizeBytesLimit = config.batchSizeBytesLimit; + this.batchSizeLimit = config.batchSizeLimit; + this.fetchOptions = config.fetchOptions || {}; + this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; + if (getOtelEnabled()) { + this.langSmithToOTELTranslator = new LangSmithToOTELTranslator(); + } + // Cache metadata env vars once during construction to avoid repeatedly scanning process.env + this.cachedLSEnvVarsForMetadata = getLangSmithEnvVarsMetadata(); + } + static getDefaultClientConfig() { + const apiKey = getLangSmithEnvironmentVariable("API_KEY"); + const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? DEFAULT_API_URL; + const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; + const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; + return { + apiUrl: apiUrl, + apiKey: apiKey, + webUrl: undefined, + hideInputs: hideInputs, + hideOutputs: hideOutputs, + }; + } + getHostUrl() { + if (this.webUrl) { + return this.webUrl; + } + else if (isLocalhost(this.apiUrl)) { + this.webUrl = "http://localhost:3000"; + return this.webUrl; + } + else if (this.apiUrl.endsWith("/api/v1")) { + this.webUrl = this.apiUrl.replace("/api/v1", ""); + return this.webUrl; + } + else if (this.apiUrl.includes("/api") && + !this.apiUrl.split(".", 1)[0].endsWith("api")) { + this.webUrl = this.apiUrl.replace("/api", ""); + return this.webUrl; + } + else if (this.apiUrl.split(".", 1)[0].includes("dev")) { + this.webUrl = "https://dev.smith.langchain.com"; + return this.webUrl; + } + else if (this.apiUrl.split(".", 1)[0].includes("eu")) { + this.webUrl = "https://eu.smith.langchain.com"; + return this.webUrl; + } + else if (this.apiUrl.split(".", 1)[0].includes("beta")) { + this.webUrl = "https://beta.smith.langchain.com"; + return this.webUrl; + } + else { + this.webUrl = "https://smith.langchain.com"; + return this.webUrl; + } + } + get headers() { + const headers = { + "User-Agent": `langsmith-js/${__version__}`, + }; + if (this.apiKey) { + headers["x-api-key"] = `${this.apiKey}`; + } + if (this.workspaceId) { + headers["x-tenant-id"] = this.workspaceId; + } + return headers; + } + _getPlatformEndpointPath(path) { + // Check if apiUrl already ends with /v1 or /v1/ to avoid double /v1/v1/ paths + const needsV1Prefix = this.apiUrl.slice(-3) !== "/v1" && this.apiUrl.slice(-4) !== "/v1/"; + return needsV1Prefix ? `/v1/platform/${path}` : `/platform/${path}`; + } + async processInputs(inputs) { + if (this.hideInputs === false) { + return inputs; + } + if (this.hideInputs === true) { + return {}; + } + if (typeof this.hideInputs === "function") { + return this.hideInputs(inputs); + } + return inputs; + } + async processOutputs(outputs) { + if (this.hideOutputs === false) { + return outputs; + } + if (this.hideOutputs === true) { + return {}; + } + if (typeof this.hideOutputs === "function") { + return this.hideOutputs(outputs); + } + return outputs; + } + async prepareRunCreateOrUpdateInputs(run) { + const runParams = { ...run }; + if (runParams.inputs !== undefined) { + runParams.inputs = await this.processInputs(runParams.inputs); + } + if (runParams.outputs !== undefined) { + runParams.outputs = await this.processOutputs(runParams.outputs); + } + return runParams; + } + async _getResponse(path, queryParams) { + const paramsString = queryParams?.toString() ?? ""; + const url = `${this.apiUrl}${path}?${paramsString}`; + const response = await this.caller.call(async () => { + const res = await this._fetch(url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, `fetch ${path}`); + return res; + }); + return response; + } + async _get(path, queryParams) { + const response = await this._getResponse(path, queryParams); + return response.json(); + } + async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { + let offset = Number(queryParams.get("offset")) || 0; + const limit = Number(queryParams.get("limit")) || 100; + while (true) { + queryParams.set("offset", String(offset)); + queryParams.set("limit", String(limit)); + const url = `${this.apiUrl}${path}?${queryParams}`; + const response = await this.caller.call(async () => { + const res = await this._fetch(url, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, `fetch ${path}`); + return res; + }); + const items = transform + ? transform(await response.json()) + : await response.json(); + if (items.length === 0) { + break; + } + yield items; + if (items.length < limit) { + break; + } + offset += items.length; + } + } + async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { + const bodyParams = body ? { ...body } : {}; + while (true) { + const body = JSON.stringify(bodyParams); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${path}`, { + method: requestMethod, + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, `fetch ${path}`); + return res; + }); + const responseBody = await response.json(); + if (!responseBody) { + break; + } + if (!responseBody[dataKey]) { + break; + } + yield responseBody[dataKey]; + const cursors = responseBody.cursors; + if (!cursors) { + break; + } + if (!cursors.next) { + break; + } + bodyParams.cursor = cursors.next; + } + } + // Allows mocking for tests + _shouldSample() { + if (this.tracingSampleRate === undefined) { + return true; + } + return Math.random() < this.tracingSampleRate; + } + _filterForSampling(runs, patch = false) { + if (this.tracingSampleRate === undefined) { + return runs; + } + if (patch) { + const sampled = []; + for (const run of runs) { + if (!this.filteredPostUuids.has(run.trace_id)) { + sampled.push(run); + } + else if (run.id === run.trace_id) { + this.filteredPostUuids.delete(run.trace_id); + } + } + return sampled; + } + else { + // For new runs, sample at trace level to maintain consistency + const sampled = []; + for (const run of runs) { + const traceId = run.trace_id ?? run.id; + // If we've already made a decision about this trace, follow it + if (this.filteredPostUuids.has(traceId)) { + continue; + } + // For new traces, apply sampling + if (run.id === traceId) { + if (this._shouldSample()) { + sampled.push(run); + } + else { + this.filteredPostUuids.add(traceId); + } + } + else { + // Child runs follow their trace's sampling decision + sampled.push(run); + } + } + return sampled; + } + } + async _getBatchSizeLimitBytes() { + const serverInfo = await this._ensureServerInfo(); + return (this.batchSizeBytesLimit ?? + serverInfo?.batch_ingest_config?.size_limit_bytes ?? + DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES); + } + /** + * Get the maximum number of operations to batch in a single request. + */ + async _getBatchSizeLimit() { + const serverInfo = await this._ensureServerInfo(); + return (this.batchSizeLimit ?? + serverInfo?.batch_ingest_config?.size_limit ?? + DEFAULT_BATCH_SIZE_LIMIT); + } + async _getDatasetExamplesMultiPartSupport() { + const serverInfo = await this._ensureServerInfo(); + return (serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false); + } + drainAutoBatchQueue({ batchSizeLimitBytes, batchSizeLimit, }) { + const promises = []; + while (this.autoBatchQueue.items.length > 0) { + const [batch, done] = this.autoBatchQueue.pop({ + upToSizeBytes: batchSizeLimitBytes, + upToSize: batchSizeLimit, + }); + if (!batch.length) { + done(); + break; + } + const batchesByDestination = batch.reduce((acc, item) => { + const apiUrl = item.apiUrl ?? this.apiUrl; + const apiKey = item.apiKey ?? this.apiKey; + const isDefault = item.apiKey === this.apiKey && item.apiUrl === this.apiUrl; + const batchKey = isDefault ? "default" : `${apiUrl}|${apiKey}`; + if (!acc[batchKey]) { + acc[batchKey] = []; + } + acc[batchKey].push(item); + return acc; + }, {}); + const batchPromises = []; + for (const [batchKey, batch] of Object.entries(batchesByDestination)) { + const batchPromise = this._processBatch(batch, { + apiUrl: batchKey === "default" ? undefined : batchKey.split("|")[0], + apiKey: batchKey === "default" ? undefined : batchKey.split("|")[1], + }); + batchPromises.push(batchPromise); + } + // Wait for all batches to complete, then call the overall done callback + const allBatchesPromise = Promise.all(batchPromises).finally(done); + promises.push(allBatchesPromise); + } + return Promise.all(promises); + } + async _processBatch(batch, options) { + if (!batch.length) { + return; + } + // Calculate total batch size for queue tracking + const batchSizeBytes = batch.reduce((sum, item) => sum + (item.size ?? 0), 0); + try { + if (this.langSmithToOTELTranslator !== undefined) { + this._sendBatchToOTELTranslator(batch); + } + else { + const ingestParams = { + runCreates: batch + .filter((item) => item.action === "create") + .map((item) => item.item), + runUpdates: batch + .filter((item) => item.action === "update") + .map((item) => item.item), + }; + const serverInfo = await this._ensureServerInfo(); + const useMultipart = !this._multipartDisabled && + (serverInfo?.batch_ingest_config?.use_multipart_endpoint ?? true); + if (useMultipart) { + const useGzip = serverInfo?.instance_flags?.gzip_body_enabled; + try { + await this.multipartIngestRuns(ingestParams, { + ...options, + useGzip, + sizeBytes: batchSizeBytes, + }); + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + catch (e) { + if (isLangSmithNotFoundError(e)) { + // Fallback to batch ingest if multipart endpoint returns 404 + // Disable multipart for future requests + this._multipartDisabled = true; + await this.batchIngestRuns(ingestParams, { + ...options, + sizeBytes: batchSizeBytes, + }); + } + else { + throw e; + } + } + } + else { + await this.batchIngestRuns(ingestParams, { + ...options, + sizeBytes: batchSizeBytes, + }); + } + } + } + catch (e) { + console.error("Error exporting batch:", e); + } + } + _sendBatchToOTELTranslator(batch) { + if (this.langSmithToOTELTranslator !== undefined) { + const otelContextMap = new Map(); + const operations = []; + for (const item of batch) { + if (item.item.id && item.otelContext) { + otelContextMap.set(item.item.id, item.otelContext); + if (item.action === "create") { + operations.push({ + operation: "post", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item, + }); + } + else { + operations.push({ + operation: "patch", + id: item.item.id, + trace_id: item.item.trace_id ?? item.item.id, + run: item.item, + }); + } + } + } + this.langSmithToOTELTranslator.exportBatch(operations, otelContextMap); + } + } + async processRunOperation(item) { + clearTimeout(this.autoBatchTimeout); + this.autoBatchTimeout = undefined; + item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo); + const itemPromise = this.autoBatchQueue.push(item); + if (this.manualFlushMode) { + // Rely on manual flushing in serverless environments + return itemPromise; + } + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + const sizeLimit = await this._getBatchSizeLimit(); + if (this.autoBatchQueue.sizeBytes > sizeLimitBytes || + this.autoBatchQueue.items.length > sizeLimit) { + void this.drainAutoBatchQueue({ + batchSizeLimitBytes: sizeLimitBytes, + batchSizeLimit: sizeLimit, + }); + } + if (this.autoBatchQueue.items.length > 0) { + this.autoBatchTimeout = setTimeout(() => { + this.autoBatchTimeout = undefined; + void this.drainAutoBatchQueue({ + batchSizeLimitBytes: sizeLimitBytes, + batchSizeLimit: sizeLimit, + }); + }, this.autoBatchAggregationDelayMs); + } + return itemPromise; + } + async _getServerInfo() { + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/info`, { + method: "GET", + headers: { Accept: "application/json" }, + signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT_MS), + ...this.fetchOptions, + }); + await raiseForStatus(res, "get server info"); + return res; + }); + const json = await response.json(); + if (this.debug) { + console.log("\n=== LangSmith Server Configuration ===\n" + + JSON.stringify(json, null, 2) + + "\n"); + } + return json; + } + async _ensureServerInfo() { + if (this._getServerInfoPromise === undefined) { + this._getServerInfoPromise = (async () => { + if (this._serverInfo === undefined) { + try { + this._serverInfo = await this._getServerInfo(); + } + catch (e) { + console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status ?? "Unspecified status code"} ${e.message}`); + } + } + return this._serverInfo ?? {}; + })(); + } + return this._getServerInfoPromise.then((serverInfo) => { + if (this._serverInfo === undefined) { + this._getServerInfoPromise = undefined; + } + return serverInfo; + }); + } + async _getSettings() { + if (!this.settings) { + this.settings = this._get("/settings"); + } + return await this.settings; + } + /** + * Flushes current queued traces. + */ + async flush() { + const sizeLimitBytes = await this._getBatchSizeLimitBytes(); + const sizeLimit = await this._getBatchSizeLimit(); + await this.drainAutoBatchQueue({ + batchSizeLimitBytes: sizeLimitBytes, + batchSizeLimit: sizeLimit, + }); + } + _cloneCurrentOTELContext() { + const otel_trace = getOTELTrace(); + const otel_context = getOTELContext(); + if (this.langSmithToOTELTranslator !== undefined) { + const currentSpan = otel_trace.getActiveSpan(); + if (currentSpan) { + return otel_trace.setSpan(otel_context.active(), currentSpan); + } + } + return undefined; + } + async createRun(run, options) { + if (!this._filterForSampling([run]).length) { + return; + } + const headers = { + ...this.headers, + "Content-Type": "application/json", + }; + const session_name = run.project_name; + delete run.project_name; + const runCreate = await this.prepareRunCreateOrUpdateInputs({ + session_name, + ...run, + start_time: run.start_time ?? Date.now(), + }); + if (this.autoBatchTracing && + runCreate.trace_id !== undefined && + runCreate.dotted_order !== undefined) { + const otelContext = this._cloneCurrentOTELContext(); + void this.processRunOperation({ + action: "create", + item: runCreate, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl, + }).catch(console.error); + return; + } + const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo); + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; + } + if (options?.workspaceId !== undefined) { + headers["x-tenant-id"] = options.workspaceId; + } + const body = serialize(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`); + await this.caller.call(async () => { + const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs`, { + method: "POST", + headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "create run", true); + return res; + }); + } + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async batchIngestRuns({ runCreates, runUpdates, }, options) { + if (runCreates === undefined && runUpdates === undefined) { + return; + } + let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []); + let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []); + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== undefined && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam, + }; + } + else { + standaloneUpdates.push(updateParam); + } + } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; + } + const rawBatch = { + post: preparedCreateParams, + patch: preparedUpdateParams, + }; + if (!rawBatch.post.length && !rawBatch.patch.length) { + return; + } + const batchChunks = { + post: [], + patch: [], + }; + for (const k of ["post", "patch"]) { + const key = k; + const batchItems = rawBatch[key].reverse(); + let batchItem = batchItems.pop(); + while (batchItem !== undefined) { + // Type is wrong but this is a deprecated code path anyway + batchChunks[key].push(batchItem); + batchItem = batchItems.pop(); + } + } + if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { + const runIds = batchChunks.post + .map((item) => item.id) + .concat(batchChunks.patch.map((item) => item.id)) + .join(","); + await this._postBatchIngestRuns(serialize(batchChunks, `Ingesting runs with ids: ${runIds}`), options); + } + } + async _postBatchIngestRuns(body, options) { + const headers = { + ...this.headers, + "Content-Type": "application/json", + Accept: "application/json", + }; + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; + } + await this.batchIngestCaller.callWithOptions({ sizeBytes: options?.sizeBytes }, async () => { + const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/batch`, { + method: "POST", + headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "batch create run", true); + return res; + }); + } + /** + * Batch ingest/upsert multiple runs in the Langsmith system. + * @param runs + */ + async multipartIngestRuns({ runCreates, runUpdates, }, options) { + if (runCreates === undefined && runUpdates === undefined) { + return; + } + // transform and convert to dicts + const allAttachments = {}; + let preparedCreateParams = []; + for (const create of runCreates ?? []) { + const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create); + if (preparedCreate.id !== undefined && + preparedCreate.attachments !== undefined) { + allAttachments[preparedCreate.id] = preparedCreate.attachments; + } + delete preparedCreate.attachments; + preparedCreateParams.push(preparedCreate); + } + let preparedUpdateParams = []; + for (const update of runUpdates ?? []) { + preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update)); + } + // require trace_id and dotted_order + const invalidRunCreate = preparedCreateParams.find((runCreate) => { + return (runCreate.trace_id === undefined || runCreate.dotted_order === undefined); + }); + if (invalidRunCreate !== undefined) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); + } + const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { + return (runUpdate.trace_id === undefined || runUpdate.dotted_order === undefined); + }); + if (invalidRunUpdate !== undefined) { + throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); + } + // combine post and patch dicts where possible + if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { + const createById = preparedCreateParams.reduce((params, run) => { + if (!run.id) { + return params; + } + params[run.id] = run; + return params; + }, {}); + const standaloneUpdates = []; + for (const updateParam of preparedUpdateParams) { + if (updateParam.id !== undefined && createById[updateParam.id]) { + createById[updateParam.id] = { + ...createById[updateParam.id], + ...updateParam, + }; + } + else { + standaloneUpdates.push(updateParam); + } + } + preparedCreateParams = Object.values(createById); + preparedUpdateParams = standaloneUpdates; + } + if (preparedCreateParams.length === 0 && + preparedUpdateParams.length === 0) { + return; + } + // send the runs in multipart requests + const accumulatedContext = []; + const accumulatedParts = []; + for (const [method, payloads] of [ + ["post", preparedCreateParams], + ["patch", preparedUpdateParams], + ]) { + for (const originalPayload of payloads) { + // collect fields to be sent as separate parts + const { inputs, outputs, events, extra, error, serialized, attachments, ...payload } = originalPayload; + const fields = { inputs, outputs, events, extra, error, serialized }; + // encode the main run payload + const stringifiedPayload = serialize(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}`, + payload: new Blob([stringifiedPayload], { + type: `application/json; length=${stringifiedPayload.length}`, // encoding=gzip + }), + }); + // encode the fields we collected + for (const [key, value] of Object.entries(fields)) { + if (value === undefined) { + continue; + } + const stringifiedValue = serialize(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`); + accumulatedParts.push({ + name: `${method}.${payload.id}.${key}`, + payload: new Blob([stringifiedValue], { + type: `application/json; length=${stringifiedValue.length}`, + }), + }); + } + // encode the attachments + if (payload.id !== undefined) { + const attachments = allAttachments[payload.id]; + if (attachments) { + delete allAttachments[payload.id]; + for (const [name, attachment] of Object.entries(attachments)) { + let contentType; + let content; + if (Array.isArray(attachment)) { + [contentType, content] = attachment; + } + else { + contentType = attachment.mimeType; + content = attachment.data; + } + // Validate that the attachment name doesn't contain a '.' + if (name.includes(".")) { + console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. ` + + `Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); + continue; + } + accumulatedParts.push({ + name: `attachment.${payload.id}.${name}`, + payload: new Blob([content], { + type: `${contentType}; length=${content.byteLength}`, + }), + }); + } + } + } + // compute context + accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); + } + } + await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; "), options); + } + async _createNodeFetchBody(parts, boundary) { + // Create multipart form data manually using Blobs + const chunks = []; + for (const part of parts) { + // Add field boundary + chunks.push(new Blob([`--${boundary}\r\n`])); + chunks.push(new Blob([ + `Content-Disposition: form-data; name="${part.name}"\r\n`, + `Content-Type: ${part.payload.type}\r\n\r\n`, + ])); + chunks.push(part.payload); + chunks.push(new Blob(["\r\n"])); + } + // Add final boundary + chunks.push(new Blob([`--${boundary}--\r\n`])); + // Combine all chunks into a single Blob + const body = new Blob(chunks); + // Convert Blob to ArrayBuffer for compatibility + const arrayBuffer = await body.arrayBuffer(); + return arrayBuffer; + } + async _createMultipartStream(parts, boundary) { + const encoder = new TextEncoder(); + // Create a ReadableStream for streaming the multipart data + // Only do special handling if we're using node-fetch + const stream = new ReadableStream({ + async start(controller) { + // Helper function to write a chunk to the stream + const writeChunk = async (chunk) => { + if (typeof chunk === "string") { + controller.enqueue(encoder.encode(chunk)); + } + else { + controller.enqueue(chunk); + } + }; + // Write each part to the stream + for (const part of parts) { + // Write boundary and headers + await writeChunk(`--${boundary}\r\n`); + await writeChunk(`Content-Disposition: form-data; name="${part.name}"\r\n`); + await writeChunk(`Content-Type: ${part.payload.type}\r\n\r\n`); + // Write the payload + const payloadStream = part.payload.stream(); + const reader = payloadStream.getReader(); + try { + let result; + while (!(result = await reader.read()).done) { + controller.enqueue(result.value); + } + } + finally { + reader.releaseLock(); + } + await writeChunk("\r\n"); + } + // Write final boundary + await writeChunk(`--${boundary}--\r\n`); + controller.close(); + }, + }); + return stream; + } + async _sendMultipartRequest(parts, context, options) { + // Create multipart form data boundary + const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); + const isNodeFetch = _globalFetchImplementationIsNodeFetch(); + const buildBuffered = () => this._createNodeFetchBody(parts, boundary); + const buildStream = () => this._createMultipartStream(parts, boundary); + const sendWithRetry = async (bodyFactory) => { + return this.batchIngestCaller.callWithOptions({ sizeBytes: options?.sizeBytes }, async () => { + const body = await bodyFactory(); + const headers = { + ...this.headers, + "Content-Type": `multipart/form-data; boundary=${boundary}`, + }; + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; + } + let transformedBody = body; + if (options?.useGzip && + typeof body === "object" && + "pipeThrough" in body) { + transformedBody = body.pipeThrough(new CompressionStream("gzip")); + headers["Content-Encoding"] = "gzip"; + } + const response = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/multipart`, { + method: "POST", + headers, + body: transformedBody, + duplex: "half", + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(response, `Failed to send multipart request`, true); + return response; + }); + }; + try { + let res; + let streamedAttempt = false; + // attempt stream only if not disabled and not using node-fetch or Bun + if (!isNodeFetch && + !this.multipartStreamingDisabled && + env_getEnv() !== "bun") { + streamedAttempt = true; + res = await sendWithRetry(buildStream); + } + else { + res = await sendWithRetry(buildBuffered); + } + // if stream fails, fallback to buffered body + if ((!this.multipartStreamingDisabled || streamedAttempt) && + res.status === 422 && + (options?.apiUrl ?? this.apiUrl) !== DEFAULT_API_URL) { + console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. ` + + `This usually means the host does not support chunked uploads. ` + + `Retrying with a buffered upload for operation "${context}".`); + // Disable streaming for future requests + this.multipartStreamingDisabled = true; + // retry with fully-buffered body + res = await sendWithRetry(buildBuffered); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + } + catch (e) { + // Re-throw 404 errors so caller can fall back to batch ingest + if (isLangSmithNotFoundError(e)) { + throw e; + } + console.warn(`${e.message.trim()}\n\nContext: ${context}`); + } + } + async updateRun(runId, run, options) { + assertUuid(runId); + if (run.inputs) { + run.inputs = await this.processInputs(run.inputs); + } + if (run.outputs) { + run.outputs = await this.processOutputs(run.outputs); + } + // TODO: Untangle types + const data = { ...run, id: runId }; + if (!this._filterForSampling([data], true).length) { + return; + } + if (this.autoBatchTracing && + data.trace_id !== undefined && + data.dotted_order !== undefined) { + const otelContext = this._cloneCurrentOTELContext(); + if (run.end_time !== undefined && + data.parent_run_id === undefined && + this.blockOnRootRunFinalization && + !this.manualFlushMode) { + // Trigger batches as soon as a root trace ends and wait to ensure trace finishes + // in serverless environments. + await this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl, + }).catch(console.error); + return; + } + else { + void this.processRunOperation({ + action: "update", + item: data, + otelContext, + apiKey: options?.apiKey, + apiUrl: options?.apiUrl, + }).catch(console.error); + } + return; + } + const headers = { + ...this.headers, + "Content-Type": "application/json", + }; + if (options?.apiKey !== undefined) { + headers["x-api-key"] = options.apiKey; + } + if (options?.workspaceId !== undefined) { + headers["x-tenant-id"] = options.workspaceId; + } + const body = serialize(run, `Serializing payload to update run with id: ${runId}`); + await this.caller.call(async () => { + const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/${runId}`, { + method: "PATCH", + headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "update run", true); + return res; + }); + } + async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { + assertUuid(runId); + let run = await this._get(`/runs/${runId}`); + if (loadChildRuns) { + run = await this._loadChildRuns(run); + } + return run; + } + async getRunUrl({ runId, run, projectOpts, }) { + if (run !== undefined) { + let sessionId; + if (run.session_id) { + sessionId = run.session_id; + } + else if (projectOpts?.projectName) { + sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; + } + else if (projectOpts?.projectId) { + sessionId = projectOpts?.projectId; + } + else { + const project = await this.readProject({ + projectName: getLangSmithEnvironmentVariable("PROJECT") || "default", + }); + sessionId = project.id; + } + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; + } + else if (runId !== undefined) { + const run_ = await this.readRun(runId); + if (!run_.app_path) { + throw new Error(`Run ${runId} has no app_path`); + } + const baseUrl = this.getHostUrl(); + return `${baseUrl}${run_.app_path}`; + } + else { + throw new Error("Must provide either runId or run"); + } + } + async _loadChildRuns(run) { + const childRuns = await toArray(this.listRuns({ + isRoot: false, + projectId: run.session_id, + traceId: run.trace_id, + })); + const treemap = {}; + const runs = {}; + // TODO: make dotted order required when the migration finishes + childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); + for (const childRun of childRuns) { + if (childRun.parent_run_id === null || + childRun.parent_run_id === undefined) { + throw new Error(`Child run ${childRun.id} has no parent`); + } + if (childRun.dotted_order?.startsWith(run.dotted_order ?? "") && + childRun.id !== run.id) { + if (!(childRun.parent_run_id in treemap)) { + treemap[childRun.parent_run_id] = []; + } + treemap[childRun.parent_run_id].push(childRun); + runs[childRun.id] = childRun; + } + } + run.child_runs = treemap[run.id] || []; + for (const runId in treemap) { + if (runId !== run.id) { + runs[runId].child_runs = treemap[runId]; + } + } + return run; + } + /** + * List runs from the LangSmith server. + * @param projectId - The ID of the project to filter by. + * @param projectName - The name of the project to filter by. + * @param parentRunId - The ID of the parent run to filter by. + * @param traceId - The ID of the trace to filter by. + * @param referenceExampleId - The ID of the reference example to filter by. + * @param startTime - The start time to filter by. + * @param isRoot - Indicates whether to only return root runs. + * @param runType - The run type to filter by. + * @param error - Indicates whether to filter by error runs. + * @param id - The ID of the run to filter by. + * @param query - The query string to filter by. + * @param filter - The filter string to apply to the run spans. + * @param traceFilter - The filter string to apply on the root run of the trace. + * @param treeFilter - The filter string to apply on other runs in the trace. + * @param limit - The maximum number of runs to retrieve. + * @returns {AsyncIterable} - The runs. + * + * @example + * // List all runs in a project + * const projectRuns = client.listRuns({ projectName: "" }); + * + * @example + * // List LLM and Chat runs in the last 24 hours + * const todaysLLMRuns = client.listRuns({ + * projectName: "", + * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), + * run_type: "llm", + * }); + * + * @example + * // List traces in a project + * const rootRuns = client.listRuns({ + * projectName: "", + * execution_order: 1, + * }); + * + * @example + * // List runs without errors + * const correctRuns = client.listRuns({ + * projectName: "", + * error: false, + * }); + * + * @example + * // List runs by run ID + * const runIds = [ + * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", + * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", + * ]; + * const selectedRuns = client.listRuns({ run_ids: runIds }); + * + * @example + * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 + * const chainRuns = client.listRuns({ + * projectName: "", + * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', + * }); + * + * @example + * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 + * const goodExtractorRuns = client.listRuns({ + * projectName: "", + * filter: 'eq(name, "extractor")', + * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', + * }); + * + * @example + * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 + * const complexRuns = client.listRuns({ + * projectName: "", + * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', + * }); + * + * @example + * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds + * const taggedRuns = client.listRuns({ + * projectName: "", + * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', + * }); + */ + async *listRuns(props) { + const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order, } = props; + let projectIds = []; + if (projectId) { + projectIds = Array.isArray(projectId) ? projectId : [projectId]; + } + if (projectName) { + const projectNames = Array.isArray(projectName) + ? projectName + : [projectName]; + const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); + projectIds.push(...projectIds_); + } + const default_select = [ + "app_path", + "completion_cost", + "completion_tokens", + "dotted_order", + "end_time", + "error", + "events", + "extra", + "feedback_stats", + "first_token_time", + "id", + "inputs", + "name", + "outputs", + "parent_run_id", + "parent_run_ids", + "prompt_cost", + "prompt_tokens", + "reference_example_id", + "run_type", + "session_id", + "start_time", + "status", + "tags", + "total_cost", + "total_tokens", + "trace_id", + ]; + const body = { + session: projectIds.length ? projectIds : null, + run_type: runType, + reference_example: referenceExampleId, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + execution_order: executionOrder, + parent_run: parentRunId, + start_time: startTime ? startTime.toISOString() : null, + error, + id, + limit, + trace: traceId, + select: select ? select : default_select, + is_root: isRoot, + order, + }; + if (body.select.includes("child_run_ids")) { + warn_warnOnce("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version."); + } + let runsYielded = 0; + for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { + if (limit) { + if (runsYielded >= limit) { + break; + } + if (runs.length + runsYielded > limit) { + const newRuns = runs.slice(0, limit - runsYielded); + yield* newRuns; + break; + } + runsYielded += runs.length; + yield* runs; + } + else { + yield* runs; + } + } + } + async *listGroupRuns(props) { + const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset, } = props; + const sessionId = projectId || (await this.readProject({ projectName })).id; + const baseBody = { + session_id: sessionId, + group_by: groupBy, + filter, + start_time: startTime ? startTime.toISOString() : null, + end_time: endTime ? endTime.toISOString() : null, + limit: Number(limit) || 100, + }; + let currentOffset = Number(offset) || 0; + const path = "/runs/group"; + const url = `${this.apiUrl}${path}`; + while (true) { + const currentBody = { + ...baseBody, + offset: currentOffset, + }; + // Remove undefined values from the payload + const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== undefined)); + const body = JSON.stringify(filteredPayload); + const response = await this.caller.call(async () => { + const res = await this._fetch(url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, `Failed to fetch ${path}`); + return res; + }); + const items = await response.json(); + const { groups, total } = items; + if (groups.length === 0) { + break; + } + for (const thread of groups) { + yield thread; + } + currentOffset += groups.length; + if (currentOffset >= total) { + break; + } + } + } + async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }) { + let projectIds_ = projectIds || []; + if (projectNames) { + projectIds_ = [ + ...(projectIds || []), + ...(await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))), + ]; + } + const payload = { + id, + trace, + parent_run: parentRun, + run_type: runType, + session: projectIds_, + reference_example: referenceExampleIds, + start_time: startTime, + end_time: endTime, + error, + query, + filter, + trace_filter: traceFilter, + tree_filter: treeFilter, + is_root: isRoot, + data_source_type: dataSourceType, + }; + // Remove undefined values from the payload + const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== undefined)); + const body = JSON.stringify(filteredPayload); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/runs/stats`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "get run stats"); + return res; + }); + const result = await response.json(); + return result; + } + async shareRun(runId, { shareId } = {}) { + const data = { + run_id: runId, + share_token: shareId || v4(), + }; + assertUuid(runId); + const body = JSON.stringify(data); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { + method: "PUT", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "share run"); + return res; + }); + const result = await response.json(); + if (result === null || !("share_token" in result)) { + throw new Error("Invalid response from server"); + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + } + async unshareRun(runId) { + assertUuid(runId); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "unshare run", true); + return res; + }); + } + async readRunSharedLink(runId) { + assertUuid(runId); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "read run shared link"); + return res; + }); + const result = await response.json(); + if (result === null || !("share_token" in result)) { + return undefined; + } + return `${this.getHostUrl()}/public/${result["share_token"]}/r`; + } + async listSharedRuns(shareToken, { runIds, } = {}) { + const queryParams = new URLSearchParams({ + share_token: shareToken, + }); + if (runIds !== undefined) { + for (const runId of runIds) { + queryParams.append("id", runId); + } + } + assertUuid(shareToken); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "list shared runs"); + return res; + }); + const runs = await response.json(); + return runs; + } + async readDatasetSharedSchema(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); + } + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; + } + assertUuid(datasetId); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "read dataset shared schema"); + return res; + }); + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async shareDataset(datasetId, datasetName) { + if (!datasetId && !datasetName) { + throw new Error("Either datasetId or datasetName must be given"); + } + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + datasetId = dataset.id; + } + const data = { + dataset_id: datasetId, + }; + assertUuid(datasetId); + const body = JSON.stringify(data); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { + method: "PUT", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "share dataset"); + return res; + }); + const shareSchema = await response.json(); + shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; + return shareSchema; + } + async unshareDataset(datasetId) { + assertUuid(datasetId); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "unshare dataset", true); + return res; + }); + } + async readSharedDataset(shareToken) { + assertUuid(shareToken); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/datasets`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "read shared dataset"); + return res; + }); + const dataset = await response.json(); + return dataset; + } + /** + * Get shared examples. + * + * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. + * @param {Object} [options] Additional options for listing the examples. + * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. + * @returns {Promise} The shared examples. + */ + async listSharedExamples(shareToken, options) { + const params = {}; + if (options?.exampleIds) { + params.id = options.exampleIds; + } + const urlParams = new URLSearchParams(); + Object.entries(params).forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((v) => urlParams.append(key, v)); + } + else { + urlParams.append(key, value); + } + }); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "list shared examples"); + return res; + }); + const result = await response.json(); + if (!response.ok) { + if ("detail" in result) { + throw new Error(`Failed to list shared examples.\nStatus: ${response.status}\nMessage: ${Array.isArray(result.detail) + ? result.detail.join("\n") + : "Unspecified error"}`); + } + throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); + } + return result.map((example) => ({ + ...example, + _hostUrl: this.getHostUrl(), + })); + } + async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, }) { + const upsert_ = upsert ? `?upsert=true` : ""; + const endpoint = `${this.apiUrl}/sessions${upsert_}`; + const extra = projectExtra || {}; + if (metadata) { + extra["metadata"] = metadata; + } + const body = { + name: projectName, + extra, + description, + }; + if (referenceDatasetId !== null) { + body["reference_dataset_id"] = referenceDatasetId; + } + const serializedBody = JSON.stringify(body); + const response = await this.caller.call(async () => { + const res = await this._fetch(endpoint, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: serializedBody, + }); + await raiseForStatus(res, "create project"); + return res; + }); + const result = await response.json(); + return result; + } + async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null, }) { + const endpoint = `${this.apiUrl}/sessions/${projectId}`; + let extra = projectExtra; + if (metadata) { + extra = { ...(extra || {}), metadata }; + } + const body = JSON.stringify({ + name, + extra, + description, + end_time: endTime ? new Date(endTime).toISOString() : null, + }); + const response = await this.caller.call(async () => { + const res = await this._fetch(endpoint, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "update project"); + return res; + }); + const result = await response.json(); + return result; + } + async hasProject({ projectId, projectName, }) { + // TODO: Add a head request + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); + } + else if (projectId !== undefined) { + assertUuid(projectId); + path += `/${projectId}`; + } + else if (projectName !== undefined) { + params.append("name", projectName); + } + else { + throw new Error("Must provide projectName or projectId"); + } + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${path}?${params}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "has project"); + return res; + }); + // consume the response body to release the connection + // https://undici.nodejs.org/#/?id=garbage-collection + try { + const result = await response.json(); + if (!response.ok) { + return false; + } + // If it's OK and we're querying by name, need to check the list is not empty + if (Array.isArray(result)) { + return result.length > 0; + } + // projectId querying + return true; + } + catch (e) { + return false; + } + } + async readProject({ projectId, projectName, includeStats, }) { + let path = "/sessions"; + const params = new URLSearchParams(); + if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); + } + else if (projectId !== undefined) { + assertUuid(projectId); + path += `/${projectId}`; + } + else if (projectName !== undefined) { + params.append("name", projectName); + } + else { + throw new Error("Must provide projectName or projectId"); + } + if (includeStats !== undefined) { + params.append("include_stats", includeStats.toString()); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); + } + result = response[0]; + } + else { + result = response; + } + return result; + } + async getProjectUrl({ projectId, projectName, }) { + if (projectId === undefined && projectName === undefined) { + throw new Error("Must provide either projectName or projectId"); + } + const project = await this.readProject({ projectId, projectName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; + } + async getDatasetUrl({ datasetId, datasetName, }) { + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + const dataset = await this.readDataset({ datasetId, datasetName }); + const tenantId = await this._getTenantId(); + return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; + } + async _getTenantId() { + if (this._tenantId !== null) { + return this._tenantId; + } + const queryParams = new URLSearchParams({ limit: "1" }); + for await (const projects of this._getPaginated("/sessions", queryParams)) { + this._tenantId = projects[0].tenant_id; + return projects[0].tenant_id; + } + throw new Error("No projects found to resolve tenant."); + } + async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, includeStats, datasetVersion, referenceFree, metadata, } = {}) { + const params = new URLSearchParams(); + if (projectIds !== undefined) { + for (const projectId of projectIds) { + params.append("id", projectId); + } + } + if (name !== undefined) { + params.append("name", name); + } + if (nameContains !== undefined) { + params.append("name_contains", nameContains); + } + if (referenceDatasetId !== undefined) { + params.append("reference_dataset", referenceDatasetId); + } + else if (referenceDatasetName !== undefined) { + const dataset = await this.readDataset({ + datasetName: referenceDatasetName, + }); + params.append("reference_dataset", dataset.id); + } + if (includeStats !== undefined) { + params.append("include_stats", includeStats.toString()); + } + if (datasetVersion !== undefined) { + params.append("dataset_version", datasetVersion); + } + if (referenceFree !== undefined) { + params.append("reference_free", referenceFree.toString()); + } + if (metadata !== undefined) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const projects of this._getPaginated("/sessions", params)) { + yield* projects; + } + } + async deleteProject({ projectId, projectName, }) { + let projectId_; + if (projectId === undefined && projectName === undefined) { + throw new Error("Must provide projectName or projectId"); + } + else if (projectId !== undefined && projectName !== undefined) { + throw new Error("Must provide either projectName or projectId, not both"); + } + else if (projectId === undefined) { + projectId_ = (await this.readProject({ projectName })).id; + } + else { + projectId_ = projectId; + } + assertUuid(projectId_); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/sessions/${projectId_}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, `delete session ${projectId_} (${projectName})`, true); + return res; + }); + } + async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) { + const url = `${this.apiUrl}/datasets/upload`; + const formData = new FormData(); + formData.append("file", csvFile, fileName); + inputKeys.forEach((key) => { + formData.append("input_keys", key); + }); + outputKeys.forEach((key) => { + formData.append("output_keys", key); + }); + if (description) { + formData.append("description", description); + } + if (dataType) { + formData.append("data_type", dataType); + } + if (name) { + formData.append("name", name); + } + const response = await this.caller.call(async () => { + const res = await this._fetch(url, { + method: "POST", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: formData, + }); + await raiseForStatus(res, "upload CSV"); + return res; + }); + const result = await response.json(); + return result; + } + async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata, } = {}) { + const body = { + name, + description, + extra: metadata ? { metadata } : undefined, + }; + if (dataType) { + body.data_type = dataType; + } + if (inputsSchema) { + body.inputs_schema_definition = inputsSchema; + } + if (outputsSchema) { + body.outputs_schema_definition = outputsSchema; + } + const serializedBody = JSON.stringify(body); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: serializedBody, + }); + await raiseForStatus(res, "create dataset"); + return res; + }); + const result = await response.json(); + return result; + } + async readDataset({ datasetId, datasetName, }) { + let path = "/datasets"; + // limit to 1 result + const params = new URLSearchParams({ limit: "1" }); + if (datasetId && datasetName) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId) { + assertUuid(datasetId); + path += `/${datasetId}`; + } + else if (datasetName) { + params.append("name", datasetName); + } + else { + throw new Error("Must provide datasetName or datasetId"); + } + const response = await this._get(path, params); + let result; + if (Array.isArray(response)) { + if (response.length === 0) { + throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); + } + result = response[0]; + } + else { + result = response; + } + return result; + } + async hasDataset({ datasetId, datasetName, }) { + try { + await this.readDataset({ datasetId, datasetName }); + return true; + } + catch (e) { + if ( + // eslint-disable-next-line no-instanceof/no-instanceof + e instanceof Error && + e.message.toLocaleLowerCase().includes("not found")) { + return false; + } + throw e; + } + } + async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }) { + let datasetId_ = datasetId; + if (datasetId_ === undefined && datasetName === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + const urlParams = new URLSearchParams({ + from_version: typeof fromVersion === "string" + ? fromVersion + : fromVersion.toISOString(), + to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString(), + }); + const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); + return response; + } + async readDatasetOpenaiFinetuning({ datasetId, datasetName, }) { + const path = "/datasets"; + if (datasetId !== undefined) { + // do nothing + } + else if (datasetName !== undefined) { + datasetId = (await this.readDataset({ datasetName })).id; + } + else { + throw new Error("Must provide either datasetName or datasetId"); + } + const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); + const datasetText = await response.text(); + const dataset = datasetText + .trim() + .split("\n") + .map((line) => JSON.parse(line)); + return dataset; + } + async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata, } = {}) { + const path = "/datasets"; + const params = new URLSearchParams({ + limit: limit.toString(), + offset: offset.toString(), + }); + if (datasetIds !== undefined) { + for (const id_ of datasetIds) { + params.append("id", id_); + } + } + if (datasetName !== undefined) { + params.append("name", datasetName); + } + if (datasetNameContains !== undefined) { + params.append("name_contains", datasetNameContains); + } + if (metadata !== undefined) { + params.append("metadata", JSON.stringify(metadata)); + } + for await (const datasets of this._getPaginated(path, params)) { + yield* datasets; + } + } + /** + * Update a dataset + * @param props The dataset details to update + * @returns The updated dataset + */ + async updateDataset(props) { + const { datasetId, datasetName, ...update } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); + } + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const body = JSON.stringify(update); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "update dataset"); + return res; + }); + return (await response.json()); + } + /** + * Updates a tag on a dataset. + * + * If the tag is already assigned to a different version of this dataset, + * the tag will be moved to the new version. The as_of parameter is used to + * determine which version of the dataset to apply the new tags to. + * + * It must be an exact version of the dataset to succeed. You can + * use the "readDatasetVersion" method to find the exact version + * to apply the tags to. + * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. + * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. + * @param params.asOf The timestamp of the dataset to apply the new tags to. + * @param params.tag The new tag to apply to the dataset. + */ + async updateDatasetTag(props) { + const { datasetId, datasetName, asOf, tag } = props; + if (!datasetId && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); + } + const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; + assertUuid(_datasetId); + const body = JSON.stringify({ + as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), + tag, + }); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}/tags`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "update dataset tags", true); + return res; + }); + } + async deleteDataset({ datasetId, datasetName, }) { + let path = "/datasets"; + let datasetId_ = datasetId; + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetName !== undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + if (datasetId_ !== undefined) { + assertUuid(datasetId_); + path += `/${datasetId_}`; + } + else { + throw new Error("Must provide datasetName or datasetId"); + } + await this.caller.call(async () => { + const res = await this._fetch(this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, `delete ${path}`, true); + return res; + }); + } + async indexDataset({ datasetId, datasetName, tag, }) { + let datasetId_ = datasetId; + if (!datasetId_ && !datasetName) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ && datasetName) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (!datasetId_) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + assertUuid(datasetId_); + const data = { + tag: tag, + }; + const body = JSON.stringify(data); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId_}/index`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "index dataset"); + return res; + }); + await response.json(); + } + /** + * Lets you run a similarity search query on a dataset. + * + * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. + * + * @param inputs The input on which to run the similarity search. Must have the + * same schema as the dataset. + * + * @param datasetId The dataset to search for similar examples. + * + * @param limit The maximum number of examples to return. Will return the top `limit` most + * similar examples in order of most similar to least similar. If no similar + * examples are found, random examples will be returned. + * + * @param filter A filter string to apply to the search. Only examples will be returned that + * match the filter string. Some examples of filters + * + * - eq(metadata.mykey, "value") + * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) + * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) + * + * @returns A list of similar examples. + * + * + * @example + * dataset_id = "123e4567-e89b-12d3-a456-426614174000" + * inputs = {"text": "How many people live in Berlin?"} + * limit = 5 + * examples = await client.similarExamples(inputs, dataset_id, limit) + */ + async similarExamples(inputs, datasetId, limit, { filter, } = {}) { + const data = { + limit: limit, + inputs: inputs, + }; + if (filter !== undefined) { + data["filter"] = filter; + } + assertUuid(datasetId); + const body = JSON.stringify(data); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/search`, { + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + method: "POST", + body, + }); + await raiseForStatus(res, "fetch similar examples"); + return res; + }); + const result = await response.json(); + return result["examples"]; + } + async createExample(inputsOrUpdate, outputs, options) { + if (isExampleCreate(inputsOrUpdate)) { + if (outputs !== undefined || options !== undefined) { + throw new Error("Cannot provide outputs or options when using ExampleCreate object"); + } + } + let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; + const datasetName_ = outputs + ? options?.datasetName + : inputsOrUpdate.dataset_name; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || new Date(); + let data; + if (!isExampleCreate(inputsOrUpdate)) { + data = { + inputs: inputsOrUpdate, + outputs, + created_at: createdAt_?.toISOString(), + id: options?.exampleId, + metadata: options?.metadata, + split: options?.split, + source_run_id: options?.sourceRunId, + use_source_run_io: options?.useSourceRunIO, + use_source_run_attachments: options?.useSourceRunAttachments, + attachments: options?.attachments, + }; + } + else { + data = inputsOrUpdate; + } + const response = await this._uploadExamplesMultipart(datasetId_, [data]); + const example = await this.readExample(response.example_ids?.[0] ?? v4()); + return example; + } + async createExamples(propsOrUploads) { + if (Array.isArray(propsOrUploads)) { + if (propsOrUploads.length === 0) { + return []; + } + const uploads = propsOrUploads; + let datasetId_ = uploads[0].dataset_id; + const datasetName_ = uploads[0].dataset_name; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const response = await this._uploadExamplesMultipart(datasetId_, uploads); + const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); + return examples; + } + const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName, } = propsOrUploads; + if (inputs === undefined) { + throw new Error("Must provide inputs when using legacy parameters"); + } + let datasetId_ = datasetId; + const datasetName_ = datasetName; + if (datasetId_ === undefined && datasetName_ === undefined) { + throw new Error("Must provide either datasetName or datasetId"); + } + else if (datasetId_ !== undefined && datasetName_ !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId_ === undefined) { + const dataset = await this.readDataset({ datasetName: datasetName_ }); + datasetId_ = dataset.id; + } + const formattedExamples = inputs.map((input, idx) => { + return { + dataset_id: datasetId_, + inputs: input, + outputs: outputs?.[idx], + metadata: metadata?.[idx], + split: splits?.[idx], + id: exampleIds?.[idx], + attachments: attachments?.[idx], + source_run_id: sourceRunIds?.[idx], + use_source_run_io: useSourceRunIOs?.[idx], + use_source_run_attachments: useSourceRunAttachments?.[idx], + }; + }); + const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); + const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); + return examples; + } + async createLLMExample(input, generation, options) { + return this.createExample({ input }, { output: generation }, options); + } + async createChatExample(input, generations, options) { + const finalInput = input.map((message) => { + if (isLangChainMessage(message)) { + return convertLangChainMessageToExample(message); + } + return message; + }); + const finalOutput = isLangChainMessage(generations) + ? convertLangChainMessageToExample(generations) + : generations; + return this.createExample({ input: finalInput }, { output: finalOutput }, options); + } + async readExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + const rawExample = await this._get(path); + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type, + }; + return acc; + }, {}); + } + return example; + } + async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments, } = {}) { + let datasetId_; + if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId !== undefined) { + datasetId_ = datasetId; + } + else if (datasetName !== undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + else { + throw new Error("Must provide a datasetName or datasetId"); + } + const params = new URLSearchParams({ dataset: datasetId_ }); + const dataset_version = asOf + ? typeof asOf === "string" + ? asOf + : asOf?.toISOString() + : undefined; + if (dataset_version) { + params.append("as_of", dataset_version); + } + const inlineS3Urls_ = inlineS3Urls ?? true; + params.append("inline_s3_urls", inlineS3Urls_.toString()); + if (exampleIds !== undefined) { + for (const id_ of exampleIds) { + params.append("id", id_); + } + } + if (splits !== undefined) { + for (const split of splits) { + params.append("splits", split); + } + } + if (metadata !== undefined) { + const serializedMetadata = JSON.stringify(metadata); + params.append("metadata", serializedMetadata); + } + if (limit !== undefined) { + params.append("limit", limit.toString()); + } + if (offset !== undefined) { + params.append("offset", offset.toString()); + } + if (filter !== undefined) { + params.append("filter", filter); + } + if (includeAttachments === true) { + ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); + } + let i = 0; + for await (const rawExamples of this._getPaginated("/examples", params)) { + for (const rawExample of rawExamples) { + const { attachment_urls, ...rest } = rawExample; + const example = rest; + if (attachment_urls) { + example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { + acc[key.slice("attachment.".length)] = { + presigned_url: value.presigned_url, + mime_type: value.mime_type || undefined, + }; + return acc; + }, {}); + } + yield example; + i++; + } + if (limit !== undefined && i >= limit) { + break; + } + } + } + async deleteExample(exampleId) { + assertUuid(exampleId); + const path = `/examples/${exampleId}`; + await this.caller.call(async () => { + const res = await this._fetch(this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, `delete ${path}`, true); + return res; + }); + } + /** + * Delete multiple examples by ID. + * @param exampleIds - The IDs of the examples to delete + * @param options - Optional settings for deletion + * @param options.hardDelete - If true, permanently delete examples. If false (default), soft delete them. + */ + async deleteExamples(exampleIds, options) { + // Validate all UUIDs + exampleIds.forEach((id) => assertUuid(id)); + if (options?.hardDelete) { + // Hard delete uses POST to a different platform endpoint + const path = this._getPlatformEndpointPath("datasets/examples/delete"); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${path}`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + body: JSON.stringify({ + example_ids: exampleIds, + hard_delete: true, + }), + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "hard delete examples", true); + return res; + }); + } + else { + // Soft delete uses DELETE with query params + const params = new URLSearchParams(); + exampleIds.forEach((id) => params.append("example_ids", id)); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/examples?${params.toString()}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "delete examples", true); + return res; + }); + } + } + async updateExample(exampleIdOrUpdate, update) { + let exampleId; + if (update) { + exampleId = exampleIdOrUpdate; + } + else { + exampleId = exampleIdOrUpdate.id; + } + assertUuid(exampleId); + let updateToUse; + if (update) { + updateToUse = { id: exampleId, ...update }; + } + else { + updateToUse = exampleIdOrUpdate; + } + let datasetId; + if (updateToUse.dataset_id !== undefined) { + datasetId = updateToUse.dataset_id; + } + else { + const example = await this.readExample(exampleId); + datasetId = example.dataset_id; + } + return this._updateExamplesMultipart(datasetId, [updateToUse]); + } + async updateExamples(update) { + // We will naively get dataset id from first example and assume it works for all + let datasetId; + if (update[0].dataset_id === undefined) { + const example = await this.readExample(update[0].id); + datasetId = example.dataset_id; + } + else { + datasetId = update[0].dataset_id; + } + return this._updateExamplesMultipart(datasetId, update); + } + /** + * Get dataset version by closest date or exact tag. + * + * Use this to resolve the nearest version to a given timestamp or for a given tag. + * + * @param options The options for getting the dataset version + * @param options.datasetId The ID of the dataset + * @param options.datasetName The name of the dataset + * @param options.asOf The timestamp of the dataset to retrieve + * @param options.tag The tag of the dataset to retrieve + * @returns The dataset version + */ + async readDatasetVersion({ datasetId, datasetName, asOf, tag, }) { + let resolvedDatasetId; + if (!datasetId) { + const dataset = await this.readDataset({ datasetName }); + resolvedDatasetId = dataset.id; + } + else { + resolvedDatasetId = datasetId; + } + assertUuid(resolvedDatasetId); + if ((asOf && tag) || (!asOf && !tag)) { + throw new Error("Exactly one of asOf and tag must be specified."); + } + const params = new URLSearchParams(); + if (asOf !== undefined) { + params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); + } + if (tag !== undefined) { + params.append("tag", tag); + } + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { + method: "GET", + headers: { ...this.headers }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "read dataset version"); + return res; + }); + return await response.json(); + } + async listDatasetSplits({ datasetId, datasetName, asOf, }) { + let datasetId_; + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide dataset name or ID"); + } + else if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + else { + datasetId_ = datasetId; + } + assertUuid(datasetId_); + const params = new URLSearchParams(); + const dataset_version = asOf + ? typeof asOf === "string" + ? asOf + : asOf?.toISOString() + : undefined; + if (dataset_version) { + params.append("as_of", dataset_version); + } + const response = await this._get(`/datasets/${datasetId_}/splits`, params); + return response; + } + async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false, }) { + let datasetId_; + if (datasetId === undefined && datasetName === undefined) { + throw new Error("Must provide dataset name or ID"); + } + else if (datasetId !== undefined && datasetName !== undefined) { + throw new Error("Must provide either datasetName or datasetId, not both"); + } + else if (datasetId === undefined) { + const dataset = await this.readDataset({ datasetName }); + datasetId_ = dataset.id; + } + else { + datasetId_ = datasetId; + } + assertUuid(datasetId_); + const data = { + split_name: splitName, + examples: exampleIds.map((id) => { + assertUuid(id); + return id; + }), + remove, + }; + const body = JSON.stringify(data); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId_}/splits`, { + method: "PUT", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "update dataset splits", true); + return res; + }); + } + async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }) { + if (!runId && !projectId) { + throw new Error("One of runId or projectId must be provided"); + } + if (runId && projectId) { + throw new Error("Only one of runId or projectId can be provided"); + } + const feedback_source = { + type: feedbackSourceType ?? "api", + metadata: sourceInfo ?? {}, + }; + if (sourceRunId !== undefined && + feedback_source?.metadata !== undefined && + !feedback_source.metadata["__run"]) { + feedback_source.metadata["__run"] = { run_id: sourceRunId }; + } + if (feedback_source?.metadata !== undefined && + feedback_source.metadata["__run"]?.run_id !== undefined) { + assertUuid(feedback_source.metadata["__run"].run_id); + } + const feedback = { + id: feedbackId ?? v4(), + run_id: runId, + key, + score: _formatFeedbackScore(score), + value, + correction, + comment, + feedback_source: feedback_source, + comparative_experiment_id: comparativeExperimentId, + feedbackConfig, + session_id: projectId, + }; + const body = JSON.stringify(feedback); + const url = `${this.apiUrl}/feedback`; + await this.caller.call(async () => { + const res = await this._fetch(url, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "create feedback", true); + return res; + }); + return feedback; + } + async updateFeedback(feedbackId, { score, value, correction, comment, }) { + const feedbackUpdate = {}; + if (score !== undefined && score !== null) { + feedbackUpdate["score"] = _formatFeedbackScore(score); + } + if (value !== undefined && value !== null) { + feedbackUpdate["value"] = value; + } + if (correction !== undefined && correction !== null) { + feedbackUpdate["correction"] = correction; + } + if (comment !== undefined && comment !== null) { + feedbackUpdate["comment"] = comment; + } + assertUuid(feedbackId); + const body = JSON.stringify(feedbackUpdate); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/feedback/${feedbackId}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "update feedback", true); + return res; + }); + } + async readFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + const response = await this._get(path); + return response; + } + async deleteFeedback(feedbackId) { + assertUuid(feedbackId); + const path = `/feedback/${feedbackId}`; + await this.caller.call(async () => { + const res = await this._fetch(this.apiUrl + path, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, `delete ${path}`, true); + return res; + }); + } + async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) { + const queryParams = new URLSearchParams(); + if (runIds) { + for (const runId of runIds) { + assertUuid(runId); + queryParams.append("run", runId); + } + } + if (feedbackKeys) { + for (const key of feedbackKeys) { + queryParams.append("key", key); + } + } + if (feedbackSourceTypes) { + for (const type of feedbackSourceTypes) { + queryParams.append("source", type); + } + } + for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { + yield* feedbacks; + } + } + /** + * Creates a presigned feedback token and URL. + * + * The token can be used to authorize feedback metrics without + * needing an API key. This is useful for giving browser-based + * applications the ability to submit feedback without needing + * to expose an API key. + * + * @param runId The ID of the run. + * @param feedbackKey The feedback key. + * @param options Additional options for the token. + * @param options.expiration The expiration time for the token. + * + * @returns A promise that resolves to a FeedbackIngestToken. + */ + async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig, } = {}) { + const body = { + run_id: runId, + feedback_key: feedbackKey, + feedback_config: feedbackConfig, + }; + if (expiration) { + if (typeof expiration === "string") { + body["expires_at"] = expiration; + } + else if (expiration?.hours || expiration?.minutes || expiration?.days) { + body["expires_in"] = expiration; + } + } + else { + body["expires_in"] = { + hours: 3, + }; + } + const serializedBody = JSON.stringify(body); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/feedback/tokens`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: serializedBody, + }); + await raiseForStatus(res, "create presigned feedback token"); + return res; + }); + return await response.json(); + } + async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }) { + if (experimentIds.length === 0) { + throw new Error("At least one experiment is required"); + } + if (!referenceDatasetId) { + referenceDatasetId = (await this.readProject({ + projectId: experimentIds[0], + })).reference_dataset_id; + } + if (!referenceDatasetId == null) { + throw new Error("A reference dataset is required"); + } + const body = { + id, + name, + experiment_ids: experimentIds, + reference_dataset_id: referenceDatasetId, + description, + created_at: (createdAt ?? new Date())?.toISOString(), + extra: {}, + }; + if (metadata) + body.extra["metadata"] = metadata; + const serializedBody = JSON.stringify(body); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/datasets/comparative`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: serializedBody, + }); + await raiseForStatus(res, "create comparative experiment"); + return res; + }); + return response.json(); + } + /** + * Retrieves a list of presigned feedback tokens for a given run ID. + * @param runId The ID of the run. + * @returns An async iterable of FeedbackIngestToken objects. + */ + async *listPresignedFeedbackTokens(runId) { + assertUuid(runId); + const params = new URLSearchParams({ run_id: runId }); + for await (const tokens of this._getPaginated("/feedback/tokens", params)) { + yield* tokens; + } + } + _selectEvalResults(results) { + let results_; + if ("results" in results) { + results_ = results.results; + } + else if (Array.isArray(results)) { + results_ = results; + } + else { + results_ = [results]; + } + return results_; + } + async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const evalResults = this._selectEvalResults(evaluatorResponse); + const feedbacks = []; + for (const res of evalResults) { + let sourceInfo_ = sourceInfo || {}; + if (res.evaluatorInfo) { + sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; + } + let runId_ = null; + if (res.targetRunId) { + runId_ = res.targetRunId; + } + else if (run) { + runId_ = run.id; + } + feedbacks.push(await this.createFeedback(runId_, res.key, { + score: res.score, + value: res.value, + comment: res.comment, + correction: res.correction, + sourceInfo: sourceInfo_, + sourceRunId: res.sourceRunId, + feedbackConfig: res.feedbackConfig, + feedbackSourceType: "model", + })); + } + return [evalResults, feedbacks]; + } + async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { + const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); + return results; + } + /** + * API for managing annotation queues + */ + /** + * List the annotation queues on the LangSmith API. + * @param options - The options for listing annotation queues + * @param options.queueIds - The IDs of the queues to filter by + * @param options.name - The name of the queue to filter by + * @param options.nameContains - The substring that the queue name should contain + * @param options.limit - The maximum number of queues to return + * @returns An iterator of AnnotationQueue objects + */ + async *listAnnotationQueues(options = {}) { + const { queueIds, name, nameContains, limit } = options; + const params = new URLSearchParams(); + if (queueIds) { + queueIds.forEach((id, i) => { + assertUuid(id, `queueIds[${i}]`); + params.append("ids", id); + }); + } + if (name) + params.append("name", name); + if (nameContains) + params.append("name_contains", nameContains); + params.append("limit", (limit !== undefined ? Math.min(limit, 100) : 100).toString()); + let count = 0; + for await (const queues of this._getPaginated("/annotation-queues", params)) { + yield* queues; + count++; + if (limit !== undefined && count >= limit) + break; + } + } + /** + * Create an annotation queue on the LangSmith API. + * @param options - The options for creating an annotation queue + * @param options.name - The name of the annotation queue + * @param options.description - The description of the annotation queue + * @param options.queueId - The ID of the annotation queue + * @returns The created AnnotationQueue object + */ + async createAnnotationQueue(options) { + const { name, description, queueId, rubricInstructions } = options; + const body = { + name, + description, + id: queueId || v4(), + rubric_instructions: rubricInstructions, + }; + const serializedBody = JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== undefined))); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: serializedBody, + }); + await raiseForStatus(res, "create annotation queue"); + return res; + }); + return response.json(); + } + /** + * Read an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to read + * @returns The AnnotationQueueWithDetails object + */ + async readAnnotationQueue(queueId) { + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "read annotation queue"); + return res; + }); + return response.json(); + } + /** + * Update an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to update + * @param options - The options for updating the annotation queue + * @param options.name - The new name for the annotation queue + * @param options.description - The new description for the annotation queue + */ + async updateAnnotationQueue(queueId, options) { + const { name, description, rubricInstructions } = options; + const body = JSON.stringify({ + name, + description, + rubric_instructions: rubricInstructions, + }); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "PATCH", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "update annotation queue", true); + return res; + }); + } + /** + * Delete an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue to delete + */ + async deleteAnnotationQueue(queueId) { + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { + method: "DELETE", + headers: { ...this.headers, Accept: "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "delete annotation queue", true); + return res; + }); + } + /** + * Add runs to an annotation queue with the specified queue ID. + * @param queueId - The ID of the annotation queue + * @param runIds - The IDs of the runs to be added to the annotation queue + */ + async addRunsToAnnotationQueue(queueId, runIds) { + const body = JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString())); + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "add runs to annotation queue", true); + return res; + }); + } + /** + * Get a run from an annotation queue at the specified index. + * @param queueId - The ID of the annotation queue + * @param index - The index of the run to retrieve + * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object + * @throws {Error} If the run is not found at the given index or for other API-related errors + */ + async getRunFromAnnotationQueue(queueId, index) { + const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${baseUrl}/${index}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "get run from annotation queue"); + return res; + }); + return response.json(); + } + /** + * Delete a run from an an annotation queue. + * @param queueId - The ID of the annotation queue to delete the run from + * @param queueRunId - The ID of the run to delete from the annotation queue + */ + async deleteRunFromAnnotationQueue(queueId, queueRunId) { + await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { + method: "DELETE", + headers: { ...this.headers, Accept: "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "delete run from annotation queue", true); + return res; + }); + } + /** + * Get the size of an annotation queue. + * @param queueId - The ID of the annotation queue + */ + async getSizeFromAnnotationQueue(queueId) { + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "get size from annotation queue"); + return res; + }); + return response.json(); + } + async _currentTenantIsOwner(owner) { + const settings = await this._getSettings(); + return owner == "-" || settings.tenant_handle === owner; + } + async _ownerConflictError(action, owner) { + const settings = await this._getSettings(); + return new Error(`Cannot ${action} for another tenant.\n + Current tenant: ${settings.tenant_handle}\n + Requested tenant: ${owner}`); + } + async _getLatestCommitHash(promptOwnerAndName) { + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "get latest commit hash"); + return res; + }); + const json = await response.json(); + if (json.commits.length === 0) { + return undefined; + } + return json.commits[0].commit_hash; + } + async _likeOrUnlikePrompt(promptIdentifier, like) { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const body = JSON.stringify({ like: like }); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/likes/${owner}/${promptName}`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, `${like ? "like" : "unlike"} prompt`); + return res; + }); + return response.json(); + } + async _getPromptUrl(promptIdentifier) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + if (commitHash !== "latest") { + return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; + } + else { + return `${this.getHostUrl()}/hub/${owner}/${promptName}`; + } + } + else { + const settings = await this._getSettings(); + if (commitHash !== "latest") { + return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; + } + else { + return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; + } + } + } + async promptExists(promptIdentifier) { + const prompt = await this.getPrompt(promptIdentifier); + return !!prompt; + } + async likePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, true); + } + async unlikePrompt(promptIdentifier) { + return this._likeOrUnlikePrompt(promptIdentifier, false); + } + async *listCommits(promptOwnerAndName) { + for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) { + yield* commits; + } + } + async *listPrompts(options) { + const params = new URLSearchParams(); + params.append("sort_field", options?.sortField ?? "updated_at"); + params.append("sort_direction", "desc"); + params.append("is_archived", (!!options?.isArchived).toString()); + if (options?.isPublic !== undefined) { + params.append("is_public", options.isPublic.toString()); + } + if (options?.query) { + params.append("query", options.query); + } + for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) { + yield* prompts; + } + } + async getPrompt(promptIdentifier) { + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + if (res?.status === 404) { + return null; + } + await raiseForStatus(res, "get prompt"); + return res; + }); + const result = await response?.json(); + if (result?.repo) { + return result.repo; + } + else { + return null; + } + } + async createPrompt(promptIdentifier, options) { + const settings = await this._getSettings(); + if (options?.isPublic && !settings.tenant_handle) { + throw new Error(`Cannot create a public prompt without first\n + creating a LangChain Hub handle. + You can add a handle by creating a public prompt at:\n + https://smith.langchain.com/prompts`); + } + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("create a prompt", owner); + } + const data = { + repo_handle: promptName, + ...(options?.description && { description: options.description }), + ...(options?.readme && { readme: options.readme }), + ...(options?.tags && { tags: options.tags }), + is_public: !!options?.isPublic, + }; + const body = JSON.stringify(data); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "create prompt"); + return res; + }); + const { repo } = await response.json(); + return repo; + } + async createCommit(promptIdentifier, object, options) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); + } + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash + ? await this._getLatestCommitHash(`${owner}/${promptName}`) + : options?.parentCommitHash; + const payload = { + manifest: JSON.parse(JSON.stringify(object)), + parent_commit: resolvedParentCommitHash, + }; + const body = JSON.stringify(payload); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}`, { + method: "POST", + headers: { ...this.headers, "Content-Type": "application/json" }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "create commit"); + return res; + }); + const result = await response.json(); + return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); + } + /** + * Update examples with attachments using multipart form data. + * @param updates List of ExampleUpdateWithAttachments objects to upsert + * @returns Promise with the update response + */ + async updateExamplesMultipart(datasetId, updates = []) { + return this._updateExamplesMultipart(datasetId, updates); + } + async _updateExamplesMultipart(datasetId, updates = []) { + if (!(await this._getDatasetExamplesMultiPartSupport())) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + } + const formData = new FormData(); + for (const example of updates) { + const exampleId = example.id; + // Prepare the main example body + const exampleBody = { + ...(example.metadata && { metadata: example.metadata }), + ...(example.split && { split: example.split }), + }; + // Add main example data + const stringifiedExample = serialize(exampleBody, `Serializing body for example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json", + }); + formData.append(exampleId, exampleBlob); + // Add inputs if present + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json", + }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + // Add outputs if present + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json", + }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + // Add attachments if present + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; + } + else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}`, + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + } + if (example.attachments_operations) { + const stringifiedAttachmentsOperations = serialize(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`); + const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { + type: "application/json", + }); + formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); + } + } + const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetIdToUse}/examples`)}`, { + method: "PATCH", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: formData, + }); + await raiseForStatus(res, "update examples"); + return res; + }); + return response.json(); + } + /** + * Upload examples with attachments using multipart form data. + * @param uploads List of ExampleUploadWithAttachments objects to upload + * @returns Promise with the upload response + * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead + */ + async uploadExamplesMultipart(datasetId, uploads = []) { + return this._uploadExamplesMultipart(datasetId, uploads); + } + async _uploadExamplesMultipart(datasetId, uploads = []) { + if (!(await this._getDatasetExamplesMultiPartSupport())) { + throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); + } + const formData = new FormData(); + for (const example of uploads) { + const exampleId = (example.id ?? v4()).toString(); + // Prepare the main example body + const exampleBody = { + created_at: example.created_at, + ...(example.metadata && { metadata: example.metadata }), + ...(example.split && { split: example.split }), + ...(example.source_run_id && { source_run_id: example.source_run_id }), + ...(example.use_source_run_io && { + use_source_run_io: example.use_source_run_io, + }), + ...(example.use_source_run_attachments && { + use_source_run_attachments: example.use_source_run_attachments, + }), + }; + // Add main example data + const stringifiedExample = serialize(exampleBody, `Serializing body for uploaded example with id: ${exampleId}`); + const exampleBlob = new Blob([stringifiedExample], { + type: "application/json", + }); + formData.append(exampleId, exampleBlob); + // Add inputs if present + if (example.inputs) { + const stringifiedInputs = serialize(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`); + const inputsBlob = new Blob([stringifiedInputs], { + type: "application/json", + }); + formData.append(`${exampleId}.inputs`, inputsBlob); + } + // Add outputs if present + if (example.outputs) { + const stringifiedOutputs = serialize(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`); + const outputsBlob = new Blob([stringifiedOutputs], { + type: "application/json", + }); + formData.append(`${exampleId}.outputs`, outputsBlob); + } + // Add attachments if present + if (example.attachments) { + for (const [name, attachment] of Object.entries(example.attachments)) { + let mimeType; + let data; + if (Array.isArray(attachment)) { + [mimeType, data] = attachment; + } + else { + mimeType = attachment.mimeType; + data = attachment.data; + } + const attachmentBlob = new Blob([data], { + type: `${mimeType}; length=${data.byteLength}`, + }); + formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); + } + } + } + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetId}/examples`)}`, { + method: "POST", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body: formData, + }); + await raiseForStatus(res, "upload examples"); + return res; + }); + return response.json(); + } + async updatePrompt(promptIdentifier, options) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); + } + const [owner, promptName] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("update a prompt", owner); + } + const payload = {}; + if (options?.description !== undefined) + payload.description = options.description; + if (options?.readme !== undefined) + payload.readme = options.readme; + if (options?.tags !== undefined) + payload.tags = options.tags; + if (options?.isPublic !== undefined) + payload.is_public = options.isPublic; + if (options?.isArchived !== undefined) + payload.is_archived = options.isArchived; + // Check if payload is empty + if (Object.keys(payload).length === 0) { + throw new Error("No valid update options provided"); + } + const body = JSON.stringify(payload); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "PATCH", + headers: { + ...this.headers, + "Content-Type": "application/json", + }, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + body, + }); + await raiseForStatus(res, "update prompt"); + return res; + }); + return response.json(); + } + async deletePrompt(promptIdentifier) { + if (!(await this.promptExists(promptIdentifier))) { + throw new Error("Prompt does not exist, you must create it first."); + } + const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); + if (!(await this._currentTenantIsOwner(owner))) { + throw await this._ownerConflictError("delete a prompt", owner); + } + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { + method: "DELETE", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "delete prompt"); + return res; + }); + return response.json(); + } + async pullPromptCommit(promptIdentifier, options) { + const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); + const response = await this.caller.call(async () => { + const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { + method: "GET", + headers: this.headers, + signal: AbortSignal.timeout(this.timeout_ms), + ...this.fetchOptions, + }); + await raiseForStatus(res, "pull prompt commit"); + return res; + }); + const result = await response.json(); + return { + owner, + repo: promptName, + commit_hash: result.commit_hash, + manifest: result.manifest, + examples: result.examples, + }; + } + /** + * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. + * Using this method directly returns the JSON string of the prompt rather than a LangChain object. + * @private + */ + async _pullPrompt(promptIdentifier, options) { + const promptObject = await this.pullPromptCommit(promptIdentifier, { + includeModel: options?.includeModel, + }); + const prompt = JSON.stringify(promptObject.manifest); + return prompt; + } + async pushPrompt(promptIdentifier, options) { + // Create or update prompt metadata + if (await this.promptExists(promptIdentifier)) { + if (options && Object.keys(options).some((key) => key !== "object")) { + await this.updatePrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic, + }); + } + } + else { + await this.createPrompt(promptIdentifier, { + description: options?.description, + readme: options?.readme, + tags: options?.tags, + isPublic: options?.isPublic, + }); + } + if (!options?.object) { + return await this._getPromptUrl(promptIdentifier); + } + // Create a commit with the new manifest + const url = await this.createCommit(promptIdentifier, options?.object, { + parentCommitHash: options?.parentCommitHash, + }); + return url; + } + /** + * Clone a public dataset to your own langsmith tenant. + * This operation is idempotent. If you already have a dataset with the given name, + * this function will do nothing. + + * @param {string} tokenOrUrl The token of the public dataset to clone. + * @param {Object} [options] Additional options for cloning the dataset. + * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. + * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. + * @returns {Promise} + */ + async clonePublicDataset(tokenOrUrl, options = {}) { + const { sourceApiUrl = this.apiUrl, datasetName } = options; + const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); + const sourceClient = new Client({ + apiUrl: parsedApiUrl, + // Placeholder API key not needed anymore in most cases, but + // some private deployments may have API key-based rate limiting + // that would cause this to fail if we provide no value. + apiKey: "placeholder", + }); + const ds = await sourceClient.readSharedDataset(tokenUuid); + const finalDatasetName = datasetName || ds.name; + try { + if (await this.hasDataset({ datasetId: finalDatasetName })) { + console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); + return; + } + } + catch (_) { + // `.hasDataset` will throw an error if the dataset does not exist. + // no-op in that case + } + // Fetch examples first, then create the dataset + const examples = await sourceClient.listSharedExamples(tokenUuid); + const dataset = await this.createDataset(finalDatasetName, { + description: ds.description, + dataType: ds.data_type || "kv", + inputsSchema: ds.inputs_schema_definition ?? undefined, + outputsSchema: ds.outputs_schema_definition ?? undefined, + }); + try { + await this.createExamples({ + inputs: examples.map((e) => e.inputs), + outputs: examples.flatMap((e) => (e.outputs ? [e.outputs] : [])), + datasetId: dataset.id, + }); + } + catch (e) { + console.error(`An error occurred while creating dataset ${finalDatasetName}. ` + + "You should delete it manually."); + throw e; + } + } + parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { + // Try parsing as UUID + try { + assertUuid(urlOrToken); // Will throw if it's not a UUID. + return [apiUrl, urlOrToken]; + } + catch (_) { + // no-op if it's not a uuid + } + // Parse as URL + try { + const parsedUrl = new URL(urlOrToken); + const pathParts = parsedUrl.pathname + .split("/") + .filter((part) => part !== ""); + if (pathParts.length >= numParts) { + const tokenUuid = pathParts[pathParts.length - numParts]; + return [apiUrl, tokenUuid]; + } + else { + throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); + } + } + catch (error) { + throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); + } + } + /** + * Awaits all pending trace batches. Useful for environments where + * you need to be sure that all tracing requests finish before execution ends, + * such as serverless environments. + * + * @example + * ``` + * import { Client } from "langsmith"; + * + * const client = new Client(); + * + * try { + * // Tracing happens here + * ... + * } finally { + * await client.awaitPendingTraceBatches(); + * } + * ``` + * + * @returns A promise that resolves once all currently pending traces have sent. + */ + async awaitPendingTraceBatches() { + if (this.manualFlushMode) { + console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); + return Promise.resolve(); + } + /** + * traceables use a backgrounded promise before updating runs to avoid blocking + * and to allow waiting for child runs to end. Waiting a small amount of time + * here ensures that they are able to enqueue their run operation before we await + * queued run operations below: + * + * ```ts + * const run = await traceable(async () => { + * return "Hello, world!"; + * }, { client })(); + * + * await client.awaitPendingTraceBatches(); + * ``` + */ + await new Promise((resolve) => setTimeout(resolve, 1)); + await Promise.all([ + ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), + this.batchIngestCaller.queue.onIdle(), + ]); + if (this.langSmithToOTELTranslator !== undefined) { + await getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush(); + } + } +} +function isExampleCreate(input) { + return "dataset_id" in input || "dataset_name" in input; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/env.js + +const isTracingEnabled = (tracingEnabled) => { + if (tracingEnabled !== undefined) { + return tracingEnabled; + } + const envVars = ["TRACING_V2", "TRACING"]; + return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); +}; + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/constants.js +const _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); +const _LC_CHILD_RUN_END_PROMISES_KEY = Symbol.for("lc:child_run_end_promises"); +const _REPLICA_TRACE_ROOTS_KEY = Symbol.for("langsmith:replica_trace_roots"); + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/context_vars.js + +/** + * Get a context variable from a run tree instance + */ +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function getContextVar(runTree, key) { + if (_LC_CONTEXT_VARIABLES_KEY in runTree) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + const contextVars = runTree[_LC_CONTEXT_VARIABLES_KEY]; + return contextVars[key]; + } + return undefined; +} +/** + * Set a context variable on a run tree instance + */ +function setContextVar( +// eslint-disable-next-line @typescript-eslint/no-explicit-any +runTree, key, value) { + const contextVars = _LC_CONTEXT_VARIABLES_KEY in runTree + ? // eslint-disable-next-line @typescript-eslint/no-explicit-any + runTree[_LC_CONTEXT_VARIABLES_KEY] + : {}; + contextVars[key] = value; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + runTree[_LC_CONTEXT_VARIABLES_KEY] = contextVars; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/run_trees.js + + + + + + + + + + + +const TIMESTAMP_LENGTH = 36; +// DNS namespace for UUID v5 (same as Python's uuid.NAMESPACE_DNS) +const UUID_NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; +function getReplicaKey(replica) { + // Generate a unique key by hashing the replica's identifying properties + // This ensures each unique replica (combination of projectName, apiUrl, workspaceId, apiKey) gets a unique key + // Sort keys to ensure consistent hashing + const sortedKeys = Object.keys(replica).sort(); + const keyData = sortedKeys + .map((key) => `${key}:${replica[key] ?? ""}`) + .join("|"); + return v5(keyData, UUID_NAMESPACE_DNS); +} +function stripNonAlphanumeric(input) { + return input.replace(/[-:.]/g, ""); +} +function getMicrosecondPrecisionDatestring(epoch, executionOrder = 1) { + // Date only has millisecond precision, so we use the microseconds to break + // possible ties, avoiding incorrect run order + const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); + return `${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`; +} +function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { + const microsecondPrecisionDatestring = getMicrosecondPrecisionDatestring(epoch, executionOrder); + return { + dottedOrder: stripNonAlphanumeric(microsecondPrecisionDatestring) + runId, + microsecondPrecisionDatestring, + }; +} +/** + * Baggage header information + */ +class Baggage { + constructor(metadata, tags, project_name, replicas) { + Object.defineProperty(this, "metadata", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + this.metadata = metadata; + this.tags = tags; + this.project_name = project_name; + this.replicas = replicas; + } + static fromHeader(value) { + const items = value.split(","); + let metadata = {}; + let tags = []; + let project_name; + let replicas; + for (const item of items) { + const [key, uriValue] = item.split("="); + const value = decodeURIComponent(uriValue); + if (key === "langsmith-metadata") { + metadata = JSON.parse(value); + } + else if (key === "langsmith-tags") { + tags = value.split(","); + } + else if (key === "langsmith-project") { + project_name = value; + } + else if (key === "langsmith-replicas") { + replicas = JSON.parse(value); + } + } + return new Baggage(metadata, tags, project_name, replicas); + } + toHeader() { + const items = []; + if (this.metadata && Object.keys(this.metadata).length > 0) { + items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); + } + if (this.tags && this.tags.length > 0) { + items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); + } + if (this.project_name) { + items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); + } + return items.join(","); + } +} +class run_trees_RunTree { + constructor(originalConfig) { + Object.defineProperty(this, "id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "run_type", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "project_name", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "parent_run_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_runs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "end_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "extra", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tags", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "error", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "serialized", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "inputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "outputs", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "reference_example_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "client", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "events", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "trace_id", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "dotted_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "tracingEnabled", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "child_execution_order", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Attachments associated with the run. + * Each entry is a tuple of [mime_type, bytes] + */ + Object.defineProperty(this, "attachments", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + /** + * Projects to replicate this run to with optional updates. + */ + Object.defineProperty(this, "replicas", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "distributedParentId", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + Object.defineProperty(this, "_serialized_start_time", { + enumerable: true, + configurable: true, + writable: true, + value: void 0 + }); + // If you pass in a run tree directly, return a shallow clone + if (run_trees_isRunTree(originalConfig)) { + Object.assign(this, { ...originalConfig }); + return; + } + const defaultConfig = run_trees_RunTree.getDefaultConfig(); + const { metadata, ...config } = originalConfig; + const client = config.client ?? run_trees_RunTree.getSharedClient(); + const dedupedMetadata = { + ...metadata, + ...config?.extra?.metadata, + }; + config.extra = { ...config.extra, metadata: dedupedMetadata }; + if ("id" in config && config.id == null) { + delete config.id; + } + Object.assign(this, { ...defaultConfig, ...config, client }); + this.execution_order ??= 1; + this.child_execution_order ??= 1; + // Generate serialized start time for ID generation + if (!this.dotted_order) { + this._serialized_start_time = getMicrosecondPrecisionDatestring(this.start_time, this.execution_order); + } + // Generate id from serialized start_time if not provided + if (!this.id) { + this.id = uuid7FromTime(this._serialized_start_time ?? this.start_time); + } + if (!this.trace_id) { + if (this.parent_run) { + this.trace_id = this.parent_run.trace_id ?? this.id; + } + else { + this.trace_id = this.id; + } + } + this.replicas = _ensureWriteReplicas(this.replicas); + // Now set the dotted order with the actual ID + if (!this.dotted_order) { + const { dottedOrder } = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); + if (this.parent_run) { + this.dotted_order = this.parent_run.dotted_order + "." + dottedOrder; + } + else { + this.dotted_order = dottedOrder; + } + } + } + set metadata(metadata) { + this.extra = { + ...this.extra, + metadata: { + ...this.extra?.metadata, + ...metadata, + }, + }; + } + get metadata() { + return this.extra?.metadata; + } + static getDefaultConfig() { + const start_time = Date.now(); + return { + run_type: "chain", + project_name: getDefaultProjectName(), + child_runs: [], + api_url: env_getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", + api_key: env_getEnvironmentVariable("LANGCHAIN_API_KEY"), + caller_options: {}, + start_time, + serialized: {}, + inputs: {}, + extra: {}, + }; + } + static getSharedClient() { + if (!run_trees_RunTree.sharedClient) { + run_trees_RunTree.sharedClient = new Client(); + } + return run_trees_RunTree.sharedClient; + } + createChild(config) { + const child_execution_order = this.child_execution_order + 1; + // Handle replicas: if child has its own replicas, use those; otherwise inherit parent's (with reroot stripped) + // Reroot should only apply to the run where it's explicitly configured, not propagate down + const inheritedReplicas = this.replicas?.map((replica) => { + const { reroot, ...rest } = replica; + return rest; + }); + const childReplicas = config.replicas ?? inheritedReplicas; + const child = new run_trees_RunTree({ + ...config, + parent_run: this, + project_name: this.project_name, + replicas: childReplicas, + client: this.client, + tracingEnabled: this.tracingEnabled, + execution_order: child_execution_order, + child_execution_order: child_execution_order, + }); + // Copy context vars over into the new run tree. + if (_LC_CONTEXT_VARIABLES_KEY in this) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + child[_LC_CONTEXT_VARIABLES_KEY] = + this[_LC_CONTEXT_VARIABLES_KEY]; + } + const LC_CHILD = Symbol.for("lc:child_config"); + const presentConfig = config.extra?.[LC_CHILD] ?? + this.extra[LC_CHILD]; + // tracing for LangChain is defined by the _parentRunId and runMap of the tracer + if (isRunnableConfigLike(presentConfig)) { + const newConfig = { ...presentConfig }; + const callbacks = isCallbackManagerLike(newConfig.callbacks) + ? newConfig.callbacks.copy?.() + : undefined; + if (callbacks) { + // update the parent run id + Object.assign(callbacks, { _parentRunId: child.id }); + // only populate if we're in a newer LC.JS version + callbacks.handlers + ?.find(isLangChainTracerLike) + ?.updateFromRunTree?.(child); + newConfig.callbacks = callbacks; + } + child.extra[LC_CHILD] = newConfig; + } + // propagate child_execution_order upwards + const visited = new Set(); + let current = this; + while (current != null && !visited.has(current.id)) { + visited.add(current.id); + current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); + current = current.parent_run; + } + this.child_runs.push(child); + return child; + } + async end(outputs, error, endTime = Date.now(), metadata) { + this.outputs = this.outputs ?? outputs; + this.error = this.error ?? error; + this.end_time = this.end_time ?? endTime; + if (metadata && Object.keys(metadata).length > 0) { + this.extra = this.extra + ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } + : { metadata }; + } + } + _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { + const runExtra = run.extra ?? {}; + // Avoid overwriting the runtime environment if it's already set + if (runExtra?.runtime?.library === undefined) { + if (!runExtra.runtime) { + runExtra.runtime = {}; + } + if (runtimeEnv) { + for (const [k, v] of Object.entries(runtimeEnv)) { + if (!runExtra.runtime[k]) { + runExtra.runtime[k] = v; + } + } + } + } + let child_runs; + let parent_run_id; + if (!excludeChildRuns) { + child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); + parent_run_id = undefined; + } + else { + parent_run_id = run.parent_run?.id ?? run.parent_run_id; + child_runs = []; + } + return { + id: run.id, + name: run.name, + start_time: run._serialized_start_time ?? run.start_time, + end_time: run.end_time, + run_type: run.run_type, + reference_example_id: run.reference_example_id, + extra: runExtra, + serialized: run.serialized, + error: run.error, + inputs: run.inputs, + outputs: run.outputs, + session_name: run.project_name, + child_runs: child_runs, + parent_run_id: parent_run_id, + trace_id: run.trace_id, + dotted_order: run.dotted_order, + tags: run.tags, + attachments: run.attachments, + events: run.events, + }; + } + _sliceParentId(parentId, run) { + /** + * Slice the parent id from dotted order. + * Additionally check if the current run is a child of the parent. If so, update + * the parent_run_id to undefined, and set the trace id to the new root id after + * parent_id. + */ + if (run.dotted_order) { + const segs = run.dotted_order.split("."); + let startIdx = null; + // Find the index of the parent ID in the dotted order + for (let idx = 0; idx < segs.length; idx++) { + const segId = segs[idx].slice(-TIMESTAMP_LENGTH); + if (segId === parentId) { + startIdx = idx; + break; + } + } + if (startIdx !== null) { + // Trim segments to start after parent_id (exclusive) + const trimmedSegs = segs.slice(startIdx + 1); + // Rebuild dotted_order + run.dotted_order = trimmedSegs.join("."); + if (trimmedSegs.length > 0) { + run.trace_id = trimmedSegs[0].slice(-TIMESTAMP_LENGTH); + } + else { + run.trace_id = run.id; + } + } + } + if (run.parent_run_id === parentId) { + // We've found the new root node. + run.parent_run_id = undefined; + } + } + _setReplicaTraceRoot(replicaKey, traceRootId) { + // Set the replica trace root in context vars on this run and all descendants + const replicaTraceRoots = getContextVar(this, _REPLICA_TRACE_ROOTS_KEY) ?? {}; + replicaTraceRoots[replicaKey] = traceRootId; + setContextVar(this, _REPLICA_TRACE_ROOTS_KEY, replicaTraceRoots); + // Recursively update all descendants to avoid race conditions + // around run tree creation vs processing time + for (const child of this.child_runs) { + child._setReplicaTraceRoot(replicaKey, traceRootId); + } + } + _remapForProject(params) { + const { projectName, runtimeEnv, excludeChildRuns = true, reroot = false, distributedParentId, apiUrl, apiKey, workspaceId, } = params; + const baseRun = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + // Skip remapping if project name is the same + if (projectName === this.project_name) { + return { + ...baseRun, + session_name: projectName, + }; + } + // Apply reroot logic before ID remapping + if (reroot) { + if (distributedParentId) { + // If we have a distributed parent ID, slice at that point + this._sliceParentId(distributedParentId, baseRun); + } + else { + // If no distributed parent ID, simply make this run a root run + // by removing parent_run_id and resetting trace info + baseRun.parent_run_id = undefined; + // Keep the current run as the trace root + if (baseRun.dotted_order) { + // Reset dotted order to just this run + const segs = baseRun.dotted_order.split("."); + if (segs.length > 0) { + baseRun.dotted_order = segs[segs.length - 1]; + baseRun.trace_id = baseRun.id; + } + } + } + // Store this run's original ID in context vars so descendants know the new trace root + // We store the original ID (before remapping) so it can be found in dotted_order + const replicaKey = getReplicaKey({ + projectName, + apiUrl, + apiKey, + workspaceId, + }); + this._setReplicaTraceRoot(replicaKey, baseRun.id); + } + // If an ancestor was rerooted for this replica, update trace_id and dotted_order + // to reflect the new trace hierarchy. This is tracked via context variables. + let ancestorRerootedTraceId; + if (!reroot) { + const replicaTraceRoots = getContextVar(this, _REPLICA_TRACE_ROOTS_KEY) ?? {}; + const replicaKey = getReplicaKey({ + projectName, + apiUrl, + apiKey, + workspaceId, + }); + ancestorRerootedTraceId = replicaTraceRoots[replicaKey]; + if (ancestorRerootedTraceId) { + // An ancestor was rerooted for this replica, so set our trace_id + // to the ancestor's original (unmapped) ID. It will be remapped along with other IDs. + baseRun.trace_id = ancestorRerootedTraceId; + // Also slice the dotted_order to start from the new trace root + // This ensures descendants of a rerooted ancestor have correct hierarchy + if (baseRun.dotted_order) { + const segs = baseRun.dotted_order.split("."); + let rootIdx = null; + // Find the new trace root's segment in dotted_order + for (let idx = 0; idx < segs.length; idx++) { + const segId = segs[idx].slice(-TIMESTAMP_LENGTH); + if (segId === ancestorRerootedTraceId) { + rootIdx = idx; + break; + } + } + if (rootIdx !== null) { + // Keep segments from new trace root onwards + const trimmedSegs = segs.slice(rootIdx); + baseRun.dotted_order = trimmedSegs.join("."); + } + } + } + } + // Remap IDs for the replica using uuid5 (deterministic) + // This ensures consistency across runs in the same replica + const oldId = baseRun.id; + const newId = v5(`${oldId}:${projectName}`, UUID_NAMESPACE_DNS); + // Remap trace_id + let newTraceId; + if (baseRun.trace_id) { + newTraceId = v5(`${baseRun.trace_id}:${projectName}`, UUID_NAMESPACE_DNS); + } + else { + newTraceId = newId; + } + // Remap parent_run_id + let newParentId; + if (baseRun.parent_run_id) { + newParentId = v5(`${baseRun.parent_run_id}:${projectName}`, UUID_NAMESPACE_DNS); + } + // Remap dotted_order segments + let newDottedOrder; + if (baseRun.dotted_order) { + const segs = baseRun.dotted_order.split("."); + const remappedSegs = segs.map((seg) => { + // Extract the UUID from the segment (last TIMESTAMP_LENGTH characters) + const segId = seg.slice(-TIMESTAMP_LENGTH); + const remappedId = v5(`${segId}:${projectName}`, UUID_NAMESPACE_DNS); + // Replace the UUID part while keeping the timestamp prefix + return seg.slice(0, -TIMESTAMP_LENGTH) + remappedId; + }); + newDottedOrder = remappedSegs.join("."); + } + return { + ...baseRun, + id: newId, + trace_id: newTraceId, + parent_run_id: newParentId, + dotted_order: newDottedOrder, + session_name: projectName, + }; + } + async postRun(excludeChildRuns = true) { + try { + const runtimeEnv = env_getRuntimeEnvironment(); + if (this.replicas && this.replicas.length > 0) { + for (const { projectName, apiKey, apiUrl, workspaceId, reroot } of this + .replicas) { + const runCreate = this._remapForProject({ + projectName: projectName ?? this.project_name, + runtimeEnv, + excludeChildRuns: true, + reroot, + distributedParentId: this.distributedParentId, + apiUrl, + apiKey, + workspaceId, + }); + await this.client.createRun(runCreate, { + apiKey, + apiUrl, + workspaceId, + }); + } + } + else { + const runCreate = this._convertToCreate(this, runtimeEnv, excludeChildRuns); + await this.client.createRun(runCreate); + } + if (!excludeChildRuns) { + warn_warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); + for (const childRun of this.child_runs) { + await childRun.postRun(false); + } + } + this.child_runs = []; + } + catch (error) { + console.error(`Error in postRun for run ${this.id}:`, error); + } + } + async patchRun(options) { + if (this.replicas && this.replicas.length > 0) { + for (const { projectName, apiKey, apiUrl, workspaceId, updates, reroot, } of this.replicas) { + const runData = this._remapForProject({ + projectName: projectName ?? this.project_name, + runtimeEnv: undefined, + excludeChildRuns: true, + reroot, + distributedParentId: this.distributedParentId, + apiUrl, + apiKey, + workspaceId, + }); + const updatePayload = { + id: runData.id, + name: runData.name, + run_type: runData.run_type, + start_time: runData.start_time, + outputs: runData.outputs, + error: runData.error, + parent_run_id: runData.parent_run_id, + session_name: runData.session_name, + reference_example_id: runData.reference_example_id, + end_time: runData.end_time, + dotted_order: runData.dotted_order, + trace_id: runData.trace_id, + events: runData.events, + tags: runData.tags, + extra: runData.extra, + attachments: this.attachments, + ...updates, + }; + // Important that inputs is not a key in the run update + // if excluded because it will overwrite the run create if the + // two operations are merged during batching + if (!options?.excludeInputs) { + updatePayload.inputs = runData.inputs; + } + await this.client.updateRun(runData.id, updatePayload, { + apiKey, + apiUrl, + workspaceId, + }); + } + } + else { + try { + const runUpdate = { + name: this.name, + run_type: this.run_type, + start_time: this._serialized_start_time ?? this.start_time, + end_time: this.end_time, + error: this.error, + outputs: this.outputs, + parent_run_id: this.parent_run?.id ?? this.parent_run_id, + reference_example_id: this.reference_example_id, + extra: this.extra, + events: this.events, + dotted_order: this.dotted_order, + trace_id: this.trace_id, + tags: this.tags, + attachments: this.attachments, + session_name: this.project_name, + }; + // Important that inputs is not a key in the run update + // if excluded because it will overwrite the run create if the + // two operations are merged during batching + if (!options?.excludeInputs) { + runUpdate.inputs = this.inputs; + } + await this.client.updateRun(this.id, runUpdate); + } + catch (error) { + console.error(`Error in patchRun for run ${this.id}`, error); + } + } + this.child_runs = []; + } + toJSON() { + return this._convertToCreate(this, undefined, false); + } + /** + * Add an event to the run tree. + * @param event - A single event or string to add + */ + addEvent(event) { + if (!this.events) { + this.events = []; + } + if (typeof event === "string") { + this.events.push({ + name: "event", + time: new Date().toISOString(), + message: event, + }); + } + else { + this.events.push({ + ...event, + time: event.time ?? new Date().toISOString(), + }); + } + } + static fromRunnableConfig(parentConfig, props) { + // We only handle the callback manager case for now + const callbackManager = parentConfig?.callbacks; + let parentRun; + let projectName; + let client; + let tracingEnabled = isTracingEnabled(); + if (callbackManager) { + const parentRunId = callbackManager?.getParentRunId?.() ?? ""; + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); + parentRun = langChainTracer?.getRun?.(parentRunId); + projectName = langChainTracer?.projectName; + client = langChainTracer?.client; + tracingEnabled = tracingEnabled || !!langChainTracer; + } + if (!parentRun) { + return new run_trees_RunTree({ + ...props, + client, + tracingEnabled, + project_name: projectName, + }); + } + const parentRunTree = new run_trees_RunTree({ + name: parentRun.name, + id: parentRun.id, + trace_id: parentRun.trace_id, + dotted_order: parentRun.dotted_order, + client, + tracingEnabled, + project_name: projectName, + tags: [ + ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])), + ], + extra: { + metadata: { + ...parentRun?.extra?.metadata, + ...parentConfig?.metadata, + }, + }, + }); + return parentRunTree.createChild(props); + } + static fromDottedOrder(dottedOrder) { + return this.fromHeaders({ "langsmith-trace": dottedOrder }); + } + static fromHeaders(headers, inheritArgs) { + const rawHeaders = "get" in headers && typeof headers.get === "function" + ? { + "langsmith-trace": headers.get("langsmith-trace"), + baggage: headers.get("baggage"), + } + : headers; + const headerTrace = rawHeaders["langsmith-trace"]; + if (!headerTrace || typeof headerTrace !== "string") + return undefined; + const parentDottedOrder = headerTrace.trim(); + const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { + const [strTime, uuid] = part.split("Z"); + return { strTime, time: Date.parse(strTime + "Z"), uuid }; + }); + const traceId = parsedDottedOrder[0].uuid; + const config = { + ...inheritArgs, + name: inheritArgs?.["name"] ?? "parent", + run_type: inheritArgs?.["run_type"] ?? "chain", + start_time: inheritArgs?.["start_time"] ?? Date.now(), + id: parsedDottedOrder.at(-1)?.uuid, + trace_id: traceId, + dotted_order: parentDottedOrder, + }; + if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { + const baggage = Baggage.fromHeader(rawHeaders["baggage"]); + config.metadata = baggage.metadata; + config.tags = baggage.tags; + config.project_name = baggage.project_name; + config.replicas = baggage.replicas; + } + const runTree = new run_trees_RunTree(config); + // Set the distributed parent ID to this run's ID for rerooting + runTree.distributedParentId = runTree.id; + return runTree; + } + toHeaders(headers) { + const result = { + "langsmith-trace": this.dotted_order, + baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name, this.replicas).toHeader(), + }; + if (headers) { + for (const [key, value] of Object.entries(result)) { + headers.set(key, value); + } + } + return result; + } +} +Object.defineProperty(run_trees_RunTree, "sharedClient", { + enumerable: true, + configurable: true, + writable: true, + value: null +}); +function run_trees_isRunTree(x) { + return (x != null && + typeof x.createChild === "function" && + typeof x.postRun === "function"); +} +function isLangChainTracerLike(x) { + return (typeof x === "object" && + x != null && + typeof x.name === "string" && + x.name === "langchain_tracer"); +} +function containsLangChainTracerLike(x) { + return (Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback))); +} +function isCallbackManagerLike(x) { + return (typeof x === "object" && + x != null && + Array.isArray(x.handlers)); +} +function isRunnableConfigLike(x) { + // Check that it's an object with a callbacks arg + // that has either a CallbackManagerLike object with a langchain tracer within it + // or an array with a LangChainTracerLike object within it + const callbacks = x?.callbacks; + return (x != null && + typeof callbacks === "object" && + // Callback manager with a langchain tracer + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (containsLangChainTracerLike(callbacks?.handlers) || + // Or it's an array with a LangChainTracerLike object within it + containsLangChainTracerLike(callbacks))); +} +function _getWriteReplicasFromEnv() { + const envVar = env_getEnvironmentVariable("LANGSMITH_RUNS_ENDPOINTS"); + if (!envVar) + return []; + try { + const parsed = JSON.parse(envVar); + if (Array.isArray(parsed)) { + const replicas = []; + for (const item of parsed) { + if (typeof item !== "object" || item === null) { + console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: ` + + `expected object, got ${typeof item}`); + continue; + } + if (typeof item.api_url !== "string") { + console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: ` + + `expected string, got ${typeof item.api_url}`); + continue; + } + if (typeof item.api_key !== "string") { + console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: ` + + `expected string, got ${typeof item.api_key}`); + continue; + } + replicas.push({ + apiUrl: item.api_url.replace(/\/$/, ""), + apiKey: item.api_key, + }); + } + return replicas; + } + else if (typeof parsed === "object" && parsed !== null) { + _checkEndpointEnvUnset(parsed); + const replicas = []; + for (const [url, key] of Object.entries(parsed)) { + const cleanUrl = url.replace(/\/$/, ""); + if (typeof key === "string") { + replicas.push({ + apiUrl: cleanUrl, + apiKey: key, + }); + } + else { + console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${url}: ` + + `expected string, got ${typeof key}`); + continue; + } + } + return replicas; + } + else { + console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of " + + `objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof parsed}`); + return []; + } + } + catch (e) { + if (isConflictingEndpointsError(e)) { + throw e; + } + console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of " + + "objects with api_url and api_key properties, or object mapping url->apiKey"); + return []; + } +} +function _ensureWriteReplicas(replicas) { + // If null -> fetch from env + if (replicas) { + return replicas.map((replica) => { + if (Array.isArray(replica)) { + return { + projectName: replica[0], + updates: replica[1], + }; + } + return replica; + }); + } + return _getWriteReplicasFromEnv(); +} +function _checkEndpointEnvUnset(parsed) { + if (Object.keys(parsed).length > 0 && + getLangSmithEnvironmentVariable("ENDPOINT")) { + throw new ConflictingEndpointsError(); + } +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/run_trees.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/base.js + + + + + +//#region src/tracers/base.ts +var base_base_exports = {}; +__export(base_base_exports, { + BaseTracer: () => BaseTracer, + isBaseTracer: () => isBaseTracer +}); +const convertRunTreeToRun = (runTree) => { + if (!runTree) return void 0; + runTree.events = runTree.events ?? []; + runTree.child_runs = runTree.child_runs ?? []; + return runTree; +}; +function convertRunToRunTree(run, parentRun) { + if (!run) return void 0; + return new run_trees_RunTree({ + ...run, + start_time: run._serialized_start_time ?? run.start_time, + parent_run: convertRunToRunTree(parentRun), + child_runs: run.child_runs.map((r) => convertRunToRunTree(r)).filter((r) => r !== void 0), + extra: { + ...run.extra, + runtime: getRuntimeEnvironment() + }, + tracingEnabled: false + }); +} +function _coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; +} +function isBaseTracer(x) { + return typeof x._addRunToRunMap === "function"; +} +var BaseTracer = class extends BaseCallbackHandler { + /** @deprecated Use `runTreeMap` instead. */ + runMap = /* @__PURE__ */ new Map(); + runTreeMap = /* @__PURE__ */ new Map(); + usesRunTreeMap = false; + constructor(_fields) { + super(...arguments); + } + copy() { + return this; + } + getRunById(runId) { + if (runId === void 0) return void 0; + return this.usesRunTreeMap ? convertRunTreeToRun(this.runTreeMap.get(runId)) : this.runMap.get(runId); + } + stringifyError(error) { + if (error instanceof Error) return error.message + (error?.stack ? `\n\n${error.stack}` : ""); + if (typeof error === "string") return error; + return `${error}`; + } + _addChildRun(parentRun, childRun) { + parentRun.child_runs.push(childRun); + } + _addRunToRunMap(run) { + const { dottedOrder: currentDottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(new Date(run.start_time).getTime(), run.id, run.execution_order); + const storedRun = { ...run }; + const parentRun = this.getRunById(storedRun.parent_run_id); + if (storedRun.parent_run_id !== void 0) if (parentRun) { + this._addChildRun(parentRun, storedRun); + parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); + storedRun.trace_id = parentRun.trace_id; + if (parentRun.dotted_order !== void 0) { + storedRun.dotted_order = [parentRun.dotted_order, currentDottedOrder].join("."); + storedRun._serialized_start_time = microsecondPrecisionDatestring; + } + } else storedRun.parent_run_id = void 0; + else { + storedRun.trace_id = storedRun.id; + storedRun.dotted_order = currentDottedOrder; + storedRun._serialized_start_time = microsecondPrecisionDatestring; + } + if (this.usesRunTreeMap) { + const runTree = convertRunToRunTree(storedRun, parentRun); + if (runTree !== void 0) this.runTreeMap.set(storedRun.id, runTree); + } else this.runMap.set(storedRun.id, storedRun); + return storedRun; + } + async _endTrace(run) { + const parentRun = run.parent_run_id !== void 0 && this.getRunById(run.parent_run_id); + if (parentRun) parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); + else await this.persistRun(run); + await this.onRunUpdate?.(run); + if (this.usesRunTreeMap) this.runTreeMap.delete(run.id); + else this.runMap.delete(run.id); + } + _getExecutionOrder(parentRunId) { + const parentRun = parentRunId !== void 0 && this.getRunById(parentRunId); + if (!parentRun) return 1; + return parentRun.child_execution_order + 1; + } + /** + * Create and add a run to the run map for LLM start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata ? { + ...extraParams, + metadata + } : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [{ + name: "start", + time: new Date(start_time).toISOString() + }], + inputs: { prompts }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; + } + /** + * Create and add a run to the run map for chat model start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const finalExtraParams = metadata ? { + ...extraParams, + metadata + } : extraParams; + const run = { + id: runId, + name: name ?? llm.id[llm.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: llm, + events: [{ + name: "start", + time: new Date(start_time).toISOString() + }], + inputs: { messages }, + execution_order, + child_runs: [], + child_execution_order: execution_order, + run_type: "llm", + extra: finalExtraParams ?? {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onLLMStart?.(run); + return run; + } + async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") throw new Error("No LLM run to end."); + run.end_time = Date.now(); + run.outputs = output; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + run.extra = { + ...run.extra, + ...extraParams + }; + await this.onLLMEnd?.(run); + await this._endTrace(run); + return run; + } + async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") throw new Error("No LLM run to end."); + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + run.extra = { + ...run.extra, + ...extraParams + }; + await this.onLLMError?.(run); + await this._endTrace(run); + return run; + } + /** + * Create and add a run to the run map for chain start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name, extra) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? chain.id[chain.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: chain, + events: [{ + name: "start", + time: new Date(start_time).toISOString() + }], + inputs, + execution_order, + child_execution_order: execution_order, + run_type: runType ?? "chain", + child_runs: [], + extra: metadata ? { + ...extra, + metadata + } : { ...extra }, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { + const run = this.getRunById(runId) ?? this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); + await this.onRunCreate?.(run); + await this.onChainStart?.(run); + return run; + } + async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { + const run = this.getRunById(runId); + if (!run) throw new Error("No chain run to end."); + run.end_time = Date.now(); + run.outputs = _coerceToDict(outputs, "output"); + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + if (kwargs?.inputs !== void 0) run.inputs = _coerceToDict(kwargs.inputs, "input"); + await this.onChainEnd?.(run); + await this._endTrace(run); + return run; + } + async handleChainError(error, runId, _parentRunId, _tags, kwargs) { + const run = this.getRunById(runId); + if (!run) throw new Error("No chain run to end."); + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + if (kwargs?.inputs !== void 0) run.inputs = _coerceToDict(kwargs.inputs, "input"); + await this.onChainError?.(run); + await this._endTrace(run); + return run; + } + /** + * Create and add a run to the run map for tool start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? tool.id[tool.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: tool, + events: [{ + name: "start", + time: new Date(start_time).toISOString() + }], + inputs: { input }, + execution_order, + child_execution_order: execution_order, + run_type: "tool", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onToolStart?.(run); + return run; + } + async handleToolEnd(output, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "tool") throw new Error("No tool run to end"); + run.end_time = Date.now(); + run.outputs = { output }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + await this.onToolEnd?.(run); + await this._endTrace(run); + return run; + } + async handleToolError(error, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "tool") throw new Error("No tool run to end"); + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + await this.onToolError?.(run); + await this._endTrace(run); + return run; + } + async handleAgentAction(action, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") return; + const agentRun = run; + agentRun.actions = agentRun.actions || []; + agentRun.actions.push(action); + agentRun.events.push({ + name: "agent_action", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { action } + }); + await this.onAgentAction?.(run); + } + async handleAgentEnd(action, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") return; + run.events.push({ + name: "agent_end", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { action } + }); + await this.onAgentEnd?.(run); + } + /** + * Create and add a run to the run map for retriever start events. + * This must sometimes be done synchronously to avoid race conditions + * when callbacks are backgrounded, so we expose it as a separate method here. + */ + _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const execution_order = this._getExecutionOrder(parentRunId); + const start_time = Date.now(); + const run = { + id: runId, + name: name ?? retriever.id[retriever.id.length - 1], + parent_run_id: parentRunId, + start_time, + serialized: retriever, + events: [{ + name: "start", + time: new Date(start_time).toISOString() + }], + inputs: { query }, + execution_order, + child_execution_order: execution_order, + run_type: "retriever", + child_runs: [], + extra: metadata ? { metadata } : {}, + tags: tags || [] + }; + return this._addRunToRunMap(run); + } + async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { + const run = this.getRunById(runId) ?? this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); + await this.onRunCreate?.(run); + await this.onRetrieverStart?.(run); + return run; + } + async handleRetrieverEnd(documents, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "retriever") throw new Error("No retriever run to end"); + run.end_time = Date.now(); + run.outputs = { documents }; + run.events.push({ + name: "end", + time: new Date(run.end_time).toISOString() + }); + await this.onRetrieverEnd?.(run); + await this._endTrace(run); + return run; + } + async handleRetrieverError(error, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "retriever") throw new Error("No retriever run to end"); + run.end_time = Date.now(); + run.error = this.stringifyError(error); + run.events.push({ + name: "error", + time: new Date(run.end_time).toISOString() + }); + await this.onRetrieverError?.(run); + await this._endTrace(run); + return run; + } + async handleText(text, runId) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "chain") return; + run.events.push({ + name: "text", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { text } + }); + await this.onText?.(run); + } + async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { + const run = this.getRunById(runId); + if (!run || run?.run_type !== "llm") throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); + run.events.push({ + name: "new_token", + time: (/* @__PURE__ */ new Date()).toISOString(), + kwargs: { + token, + idx, + chunk: fields?.chunk + } + }); + await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk }); + return run; + } +}; + +//#endregion + +//# sourceMappingURL=base.js.map +// EXTERNAL MODULE: ./node_modules/ansi-styles/index.js +var ansi_styles = __nccwpck_require__(4412); +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/console.js + + + + +//#region src/tracers/console.ts +var console_exports = {}; +__export(console_exports, { ConsoleCallbackHandler: () => ConsoleCallbackHandler }); +function wrap(style, text) { + return `${style.open}${text}${style.close}`; +} +function tryJsonStringify(obj, fallback) { + try { + return JSON.stringify(obj, null, 2); + } catch { + return fallback; + } +} +function formatKVMapItem(value) { + if (typeof value === "string") return value.trim(); + if (value === null || value === void 0) return value; + return tryJsonStringify(value, value.toString()); +} +function elapsed(run) { + if (!run.end_time) return ""; + const elapsed$1 = run.end_time - run.start_time; + if (elapsed$1 < 1e3) return `${elapsed$1}ms`; + return `${(elapsed$1 / 1e3).toFixed(2)}s`; +} +const { color } = ansi_styles; +/** +* A tracer that logs all events to the console. It extends from the +* `BaseTracer` class and overrides its methods to provide custom logging +* functionality. +* @example +* ```typescript +* +* const llm = new ChatAnthropic({ +* temperature: 0, +* tags: ["example", "callbacks", "constructor"], +* callbacks: [new ConsoleCallbackHandler()], +* }); +* +* ``` +*/ +var ConsoleCallbackHandler = class extends BaseTracer { + name = "console_callback_handler"; + /** + * Method used to persist the run. In this case, it simply returns a + * resolved promise as there's no persistence logic. + * @param _run The run to persist. + * @returns A resolved promise. + */ + persistRun(_run) { + return Promise.resolve(); + } + /** + * Method used to get all the parent runs of a given run. + * @param run The run whose parents are to be retrieved. + * @returns An array of parent runs. + */ + getParents(run) { + const parents = []; + let currentRun = run; + while (currentRun.parent_run_id) { + const parent = this.runMap.get(currentRun.parent_run_id); + if (parent) { + parents.push(parent); + currentRun = parent; + } else break; + } + return parents; + } + /** + * Method used to get a string representation of the run's lineage, which + * is used in logging. + * @param run The run whose lineage is to be retrieved. + * @returns A string representation of the run's lineage. + */ + getBreadcrumbs(run) { + const parents = this.getParents(run).reverse(); + const string = [...parents, run].map((parent, i, arr) => { + const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; + return i === arr.length - 1 ? wrap(ansi_styles.bold, name) : name; + }).join(" > "); + return wrap(color.grey, string); + } + /** + * Method used to log the start of a chain run. + * @param run The chain run that has started. + * @returns void + */ + onChainStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a chain run. + * @param run The chain run that has ended. + * @returns void + */ + onChainEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a chain run. + * @param run The chain run that has errored. + * @returns void + */ + onChainError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of an LLM run. + * @param run The LLM run that has started. + * @returns void + */ + onLLMStart(run) { + const crumbs = this.getBreadcrumbs(run); + const inputs = "prompts" in run.inputs ? { prompts: run.inputs.prompts.map((p) => p.trim()) } : run.inputs; + console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); + } + /** + * Method used to log the end of an LLM run. + * @param run The LLM run that has ended. + * @returns void + */ + onLLMEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); + } + /** + * Method used to log any errors of an LLM run. + * @param run The LLM run that has errored. + * @returns void + */ + onLLMError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of a tool run. + * @param run The tool run that has started. + * @returns void + */ + onToolStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`); + } + /** + * Method used to log the end of a tool run. + * @param run The tool run that has ended. + * @returns void + */ + onToolEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`); + } + /** + * Method used to log any errors of a tool run. + * @param run The tool run that has errored. + * @returns void + */ + onToolError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the start of a retriever run. + * @param run The retriever run that has started. + * @returns void + */ + onRetrieverStart(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); + } + /** + * Method used to log the end of a retriever run. + * @param run The retriever run that has ended. + * @returns void + */ + onRetrieverEnd(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); + } + /** + * Method used to log any errors of a retriever run. + * @param run The retriever run that has errored. + * @returns void + */ + onRetrieverError(run) { + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); + } + /** + * Method used to log the action selected by the agent. + * @param run The run in which the agent action occurred. + * @returns void + */ + onAgentAction(run) { + const agentRun = run; + const crumbs = this.getBreadcrumbs(run); + console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); + } +}; + +//#endregion + +//# sourceMappingURL=console.js.map +;// CONCATENATED MODULE: ./node_modules/langsmith/index.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/tracer.js + + + +//#region src/singletons/tracer.ts +let client; +const getDefaultLangChainClientSingleton = () => { + if (client === void 0) { + const clientParams = getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? { blockOnRootRunFinalization: true } : {}; + client = new Client(clientParams); + } + return client; +}; + +//#endregion + +//# sourceMappingURL=tracer.js.map +;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/traceable.js +class MockAsyncLocalStorage { + getStore() { + return undefined; + } + run(_, callback) { + return callback(); + } +} +const traceable_TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); +const mockAsyncLocalStorage = new MockAsyncLocalStorage(); +class AsyncLocalStorageProvider { + getInstance() { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return globalThis[traceable_TRACING_ALS_KEY] ?? mockAsyncLocalStorage; + } + initializeGlobalInstance(instance) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + if (globalThis[traceable_TRACING_ALS_KEY] === undefined) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + globalThis[traceable_TRACING_ALS_KEY] = instance; + } + } +} +const traceable_AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); +function getCurrentRunTree(permitAbsentRunTree = false) { + const runTree = traceable_AsyncLocalStorageProviderSingleton.getInstance().getStore(); + if (!permitAbsentRunTree && runTree === undefined) { + throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled."); + } + return runTree; +} +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function withRunTree(runTree, fn) { + const storage = traceable_AsyncLocalStorageProviderSingleton.getInstance(); + return new Promise((resolve, reject) => { + storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject)); + }); +} +const ROOT = Symbol.for("langsmith:traceable:root"); +function isTraceableFunction(x +// eslint-disable-next-line @typescript-eslint/no-explicit-any +) { + return typeof x === "function" && "langsmith:traceable" in x; +} + +;// CONCATENATED MODULE: ./node_modules/langsmith/singletons/traceable.js + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/tracer_langchain.js + + + + + + + + + +//#region src/tracers/tracer_langchain.ts +var tracer_langchain_exports = {}; +__export(tracer_langchain_exports, { LangChainTracer: () => LangChainTracer }); +/** +* Extract usage_metadata from chat generations. +* +* Iterates through generations to find and aggregates all usage_metadata +* found in chat messages. This is typically present in chat model outputs. +*/ +function _getUsageMetadataFromGenerations(generations) { + let output = void 0; + for (const generationBatch of generations) for (const generation of generationBatch) if (AIMessage.isInstance(generation.message) && generation.message.usage_metadata !== void 0) output = mergeUsageMetadata(output, generation.message.usage_metadata); + return output; +} +var LangChainTracer = class LangChainTracer extends BaseTracer { + name = "langchain_tracer"; + projectName; + exampleId; + client; + replicas; + usesRunTreeMap = true; + constructor(fields = {}) { + super(fields); + const { exampleId, projectName, client, replicas } = fields; + this.projectName = projectName ?? getDefaultProjectName(); + this.replicas = replicas; + this.exampleId = exampleId; + this.client = client ?? getDefaultLangChainClientSingleton(); + const traceableTree = LangChainTracer.getTraceableRunTree(); + if (traceableTree) this.updateFromRunTree(traceableTree); + } + async persistRun(_run) {} + async onRunCreate(run) { + if (!run.extra?.lc_defers_inputs) { + const runTree = this.getRunTreeWithTracingConfig(run.id); + await runTree?.postRun(); + } + } + async onRunUpdate(run) { + const runTree = this.getRunTreeWithTracingConfig(run.id); + if (run.extra?.lc_defers_inputs) await runTree?.postRun(); + else await runTree?.patchRun(); + } + onLLMEnd(run) { + const outputs = run.outputs; + if (outputs?.generations) { + const usageMetadata = _getUsageMetadataFromGenerations(outputs.generations); + if (usageMetadata !== void 0) { + run.extra = run.extra ?? {}; + const metadata = run.extra.metadata ?? {}; + metadata.usage_metadata = usageMetadata; + run.extra.metadata = metadata; + } + } + } + getRun(id) { + return this.runTreeMap.get(id); + } + updateFromRunTree(runTree) { + this.runTreeMap.set(runTree.id, runTree); + let rootRun = runTree; + const visited = /* @__PURE__ */ new Set(); + while (rootRun.parent_run) { + if (visited.has(rootRun.id)) break; + visited.add(rootRun.id); + if (!rootRun.parent_run) break; + rootRun = rootRun.parent_run; + } + visited.clear(); + const queue = [rootRun]; + while (queue.length > 0) { + const current = queue.shift(); + if (!current || visited.has(current.id)) continue; + visited.add(current.id); + this.runTreeMap.set(current.id, current); + if (current.child_runs) queue.push(...current.child_runs); + } + this.client = runTree.client ?? this.client; + this.replicas = runTree.replicas ?? this.replicas; + this.projectName = runTree.project_name ?? this.projectName; + this.exampleId = runTree.reference_example_id ?? this.exampleId; + } + getRunTreeWithTracingConfig(id) { + const runTree = this.runTreeMap.get(id); + if (!runTree) return void 0; + return new run_trees_RunTree({ + ...runTree, + client: this.client, + project_name: this.projectName, + replicas: this.replicas, + reference_example_id: this.exampleId, + tracingEnabled: true + }); + } + static getTraceableRunTree() { + try { + return getCurrentRunTree(true); + } catch { + return void 0; + } + } +}; + +//#endregion + +//# sourceMappingURL=tracer_langchain.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/callbacks.js + + + + +//#region src/singletons/callbacks.ts +let queue; +/** +* Creates a queue using the p-queue library. The queue is configured to +* auto-start and has a concurrency of 1, meaning it will process tasks +* one at a time. +*/ +function createQueue() { + const PQueue = true ? p_queue_dist["default"] : p_queue_dist; + return new PQueue({ + autoStart: true, + concurrency: 1 + }); +} +function getQueue() { + if (typeof queue === "undefined") queue = createQueue(); + return queue; +} +/** +* Consume a promise, either adding it to the queue or waiting for it to resolve +* @param promiseFn Promise to consume +* @param wait Whether to wait for the promise to resolve or resolve immediately +*/ +async function consumeCallback(promiseFn, wait) { + if (wait === true) { + const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== void 0) await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); + else await promiseFn(); + } else { + queue = getQueue(); + queue.add(async () => { + const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance !== void 0) await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); + else await promiseFn(); + }); + } +} +/** +* Waits for all promises in the queue to resolve. If the queue is +* undefined, it immediately resolves a promise. +*/ +async function awaitAllCallbacks() { + const defaultClient = getDefaultLangChainClientSingleton(); + await Promise.allSettled([typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(), defaultClient.awaitPendingTraceBatches()]); +} + +//#endregion + +//# sourceMappingURL=callbacks.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/promises.js + + + +//#region src/callbacks/promises.ts +var promises_exports = {}; +__export(promises_exports, { + awaitAllCallbacks: () => awaitAllCallbacks, + consumeCallback: () => consumeCallback +}); + +//#endregion + +//# sourceMappingURL=promises.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/callbacks.js + + +//#region src/utils/callbacks.ts +const callbacks_isTracingEnabled = (tracingEnabled) => { + if (tracingEnabled !== void 0) return tracingEnabled; + const envVars = [ + "LANGSMITH_TRACING_V2", + "LANGCHAIN_TRACING_V2", + "LANGSMITH_TRACING", + "LANGCHAIN_TRACING" + ]; + return !!envVars.find((envVar) => getEnvironmentVariable(envVar) === "true"); +}; + +//#endregion + +//# sourceMappingURL=callbacks.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/context.js + + + +//#region src/singletons/async_local_storage/context.ts +/** +* Set a context variable. Context variables are scoped to any +* child runnables called by the current runnable, or globally if set outside +* of any runnable. +* +* @remarks +* This function is only supported in environments that support AsyncLocalStorage, +* including Node.js, Deno, and Cloudflare Workers. +* +* @example +* ```ts +* import { RunnableLambda } from "@langchain/core/runnables"; +* import { +* getContextVariable, +* setContextVariable +* } from "@langchain/core/context"; +* +* const nested = RunnableLambda.from(() => { +* // "bar" because it was set by a parent +* console.log(getContextVariable("foo")); +* +* // Override to "baz", but only for child runnables +* setContextVariable("foo", "baz"); +* +* // Now "baz", but only for child runnables +* return getContextVariable("foo"); +* }); +* +* const runnable = RunnableLambda.from(async () => { +* // Set a context variable named "foo" +* setContextVariable("foo", "bar"); +* +* const res = await nested.invoke({}); +* +* // Still "bar" since child changes do not affect parents +* console.log(getContextVariable("foo")); +* +* return res; +* }); +* +* // undefined, because context variable has not been set yet +* console.log(getContextVariable("foo")); +* +* // Final return value is "baz" +* const result = await runnable.invoke({}); +* ``` +* +* @param name The name of the context variable. +* @param value The value to set. +*/ +function setContextVariable(name, value) { + const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance === void 0) throw new Error(`Internal error: Global shared async local storage instance has not been initialized.`); + const runTree = asyncLocalStorageInstance.getStore(); + const contextVars = { ...runTree?.[_CONTEXT_VARIABLES_KEY] }; + contextVars[name] = value; + let newValue = {}; + if (isRunTree(runTree)) newValue = new RunTree(runTree); + newValue[_CONTEXT_VARIABLES_KEY] = contextVars; + asyncLocalStorageInstance.enterWith(newValue); +} +/** +* Get the value of a previously set context variable. Context variables +* are scoped to any child runnables called by the current runnable, +* or globally if set outside of any runnable. +* +* @remarks +* This function is only supported in environments that support AsyncLocalStorage, +* including Node.js, Deno, and Cloudflare Workers. +* +* @example +* ```ts +* import { RunnableLambda } from "@langchain/core/runnables"; +* import { +* getContextVariable, +* setContextVariable +* } from "@langchain/core/context"; +* +* const nested = RunnableLambda.from(() => { +* // "bar" because it was set by a parent +* console.log(getContextVariable("foo")); +* +* // Override to "baz", but only for child runnables +* setContextVariable("foo", "baz"); +* +* // Now "baz", but only for child runnables +* return getContextVariable("foo"); +* }); +* +* const runnable = RunnableLambda.from(async () => { +* // Set a context variable named "foo" +* setContextVariable("foo", "bar"); +* +* const res = await nested.invoke({}); +* +* // Still "bar" since child changes do not affect parents +* console.log(getContextVariable("foo")); +* +* return res; +* }); +* +* // undefined, because context variable has not been set yet +* console.log(getContextVariable("foo")); +* +* // Final return value is "baz" +* const result = await runnable.invoke({}); +* ``` +* +* @param name The name of the context variable. +*/ +function getContextVariable(name) { + const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); + if (asyncLocalStorageInstance === void 0) return void 0; + const runTree = asyncLocalStorageInstance.getStore(); + return runTree?.[globals_CONTEXT_VARIABLES_KEY]?.[name]; +} +const LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); +const _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || []; +/** +* Register a callback configure hook to automatically add callback handlers to all runs. +* +* There are two ways to use this: +* +* 1. Using a context variable: +* - Set `contextVar` to specify the variable name +* - Use `setContextVariable()` to store your handler instance +* +* 2. Using an environment variable: +* - Set both `envVar` and `handlerClass` +* - The handler will be instantiated when the env var is set to "true". +* +* @example +* ```typescript +* // Method 1: Using context variable +* import { +* registerConfigureHook, +* setContextVariable +* } from "@langchain/core/context"; +* +* const tracer = new MyCallbackHandler(); +* registerConfigureHook({ +* contextVar: "my_tracer", +* }); +* setContextVariable("my_tracer", tracer); +* +* // ...run code here +* +* // Method 2: Using environment variable +* registerConfigureHook({ +* handlerClass: MyCallbackHandler, +* envVar: "MY_TRACER_ENABLED", +* }); +* process.env.MY_TRACER_ENABLED = "true"; +* +* // ...run code here +* ``` +* +* @param config Configuration object for the hook +* @param config.contextVar Name of the context variable containing the handler instance +* @param config.inheritable Whether child runs should inherit this handler +* @param config.handlerClass Optional callback handler class (required if using envVar) +* @param config.envVar Optional environment variable name to control handler activation +*/ +const registerConfigureHook = (config) => { + if (config.envVar && !config.handlerClass) throw new Error("If envVar is set, handlerClass must also be set to a non-None value."); + setContextVariable(LC_CONFIGURE_HOOKS_KEY, [..._getConfigureHooks(), config]); +}; + +//#endregion + +//# sourceMappingURL=context.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/manager.js + + + + + + + + + + + + + +//#region src/callbacks/manager.ts +var manager_exports = {}; +__export(manager_exports, { + BaseCallbackManager: () => BaseCallbackManager, + BaseRunManager: () => BaseRunManager, + CallbackManager: () => CallbackManager, + CallbackManagerForChainRun: () => CallbackManagerForChainRun, + CallbackManagerForLLMRun: () => CallbackManagerForLLMRun, + CallbackManagerForRetrieverRun: () => CallbackManagerForRetrieverRun, + CallbackManagerForToolRun: () => CallbackManagerForToolRun, + ensureHandler: () => ensureHandler, + parseCallbackConfigArg: () => parseCallbackConfigArg +}); +function parseCallbackConfigArg(arg) { + if (!arg) return {}; + else if (Array.isArray(arg) || "name" in arg) return { callbacks: arg }; + else return arg; +} +/** +* Manage callbacks from different components of LangChain. +*/ +var BaseCallbackManager = class { + setHandler(handler) { + return this.setHandlers([handler]); + } +}; +/** +* Base class for run manager in LangChain. +*/ +var BaseRunManager = class { + constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { + this.runId = runId; + this.handlers = handlers; + this.inheritableHandlers = inheritableHandlers; + this.tags = tags; + this.inheritableTags = inheritableTags; + this.metadata = metadata; + this.inheritableMetadata = inheritableMetadata; + this._parentRunId = _parentRunId; + } + get parentRunId() { + return this._parentRunId; + } + async handleText(text) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + async handleCustomEvent(eventName, data, _runId, _tags, _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + try { + await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } +}; +/** +* Manages callbacks for retriever runs. +*/ +var CallbackManagerForRetrieverRun = class extends BaseRunManager { + getChild(tag) { + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) manager.addTags([tag], false); + return manager; + } + async handleRetrieverEnd(documents) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) try { + await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetriever`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + async handleRetrieverError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreRetriever) try { + await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); + } catch (error) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } +}; +var CallbackManagerForLLMRun = class extends BaseRunManager { + async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) try { + await handler.handleLLMNewToken?.(token, idx ?? { + prompt: 0, + completion: 0 + }, this.runId, this._parentRunId, this.tags, fields); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) try { + await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams); + } catch (err$1) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err$1}`); + if (handler.raiseError) throw err$1; + } + }, handler.awaitHandlers))); + } + async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreLLM) try { + await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } +}; +var CallbackManagerForChainRun = class extends BaseRunManager { + getChild(tag) { + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) manager.addTags([tag], false); + return manager; + } + async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) try { + await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); + } catch (err$1) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err$1}`); + if (handler.raiseError) throw err$1; + } + }, handler.awaitHandlers))); + } + async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreChain) try { + await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + async handleAgentAction(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) try { + await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + async handleAgentEnd(action) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) try { + await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } +}; +var CallbackManagerForToolRun = class extends BaseRunManager { + getChild(tag) { + const manager = new CallbackManager(this.runId); + manager.setHandlers(this.inheritableHandlers); + manager.addTags(this.inheritableTags); + manager.addMetadata(this.inheritableMetadata); + if (tag) manager.addTags([tag], false); + return manager; + } + async handleToolError(err) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) try { + await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); + } catch (err$1) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err$1}`); + if (handler.raiseError) throw err$1; + } + }, handler.awaitHandlers))); + } + async handleToolEnd(output) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreAgent) try { + await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } +}; +/** +* @example +* ```typescript +* const prompt = PromptTemplate.fromTemplate("What is the answer to {question}?"); +* +* // Example of using LLMChain with OpenAI and a simple prompt +* const chain = new LLMChain({ +* llm: new ChatOpenAI({ model: "gpt-4o-mini", temperature: 0.9 }), +* prompt, +* }); +* +* // Running the chain with a single question +* const result = await chain.call({ +* question: "What is the airspeed velocity of an unladen swallow?", +* }); +* console.log("The answer is:", result); +* ``` +*/ +var CallbackManager = class CallbackManager extends BaseCallbackManager { + handlers = []; + inheritableHandlers = []; + tags = []; + inheritableTags = []; + metadata = {}; + inheritableMetadata = {}; + name = "callback_manager"; + _parentRunId; + constructor(parentRunId, options) { + super(); + this.handlers = options?.handlers ?? this.handlers; + this.inheritableHandlers = options?.inheritableHandlers ?? this.inheritableHandlers; + this.tags = options?.tags ?? this.tags; + this.inheritableTags = options?.inheritableTags ?? this.inheritableTags; + this.metadata = options?.metadata ?? this.metadata; + this.inheritableMetadata = options?.inheritableMetadata ?? this.inheritableMetadata; + this._parentRunId = parentRunId; + } + /** + * Gets the parent run ID, if any. + * + * @returns The parent run ID. + */ + getParentRunId() { + return this._parentRunId; + } + async handleLLMStart(llm, prompts, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + return Promise.all(prompts.map(async (prompt, idx) => { + const runId_ = idx === 0 && runId ? runId : v7(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) return; + if (isBaseTracer(handler)) handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + return consumeCallback(async () => { + try { + await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChatModelStart(llm, messages, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + return Promise.all(messages.map(async (messageGroup, idx) => { + const runId_ = idx === 0 && runId ? runId : v7(); + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreLLM) return; + if (isBaseTracer(handler)) handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + return consumeCallback(async () => { + try { + if (handler.handleChatModelStart) await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + else if (handler.handleLLMStart) { + const messageString = getBufferString(messageGroup); + await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); + } + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + })); + } + async handleChainStart(chain, inputs, runId = v7(), runType = void 0, _tags = void 0, _metadata = void 0, runName = void 0, _parentRunId = void 0, extra = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreChain) return; + if (isBaseTracer(handler)) handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName, extra); + return consumeCallback(async () => { + try { + await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName, extra); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleToolStart(tool, input, runId = v7(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreAgent) return; + if (isBaseTracer(handler)) handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); + return consumeCallback(async () => { + try { + await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleRetrieverStart(retriever, query, runId = v7(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { + await Promise.all(this.handlers.map((handler) => { + if (handler.ignoreRetriever) return; + if (isBaseTracer(handler)) handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + return consumeCallback(async () => { + try { + await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers); + })); + return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); + } + async handleCustomEvent(eventName, data, runId, _tags, _metadata) { + await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { + if (!handler.ignoreCustomEvent) try { + await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata); + } catch (err) { + const logFunction = handler.raiseError ? console.error : console.warn; + logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); + if (handler.raiseError) throw err; + } + }, handler.awaitHandlers))); + } + addHandler(handler, inherit = true) { + this.handlers.push(handler); + if (inherit) this.inheritableHandlers.push(handler); + } + removeHandler(handler) { + this.handlers = this.handlers.filter((_handler) => _handler !== handler); + this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); + } + setHandlers(handlers, inherit = true) { + this.handlers = []; + this.inheritableHandlers = []; + for (const handler of handlers) this.addHandler(handler, inherit); + } + addTags(tags, inherit = true) { + this.removeTags(tags); + this.tags.push(...tags); + if (inherit) this.inheritableTags.push(...tags); + } + removeTags(tags) { + this.tags = this.tags.filter((tag) => !tags.includes(tag)); + this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); + } + addMetadata(metadata, inherit = true) { + this.metadata = { + ...this.metadata, + ...metadata + }; + if (inherit) this.inheritableMetadata = { + ...this.inheritableMetadata, + ...metadata + }; + } + removeMetadata(metadata) { + for (const key of Object.keys(metadata)) { + delete this.metadata[key]; + delete this.inheritableMetadata[key]; + } + } + copy(additionalHandlers = [], inherit = true) { + const manager = new CallbackManager(this._parentRunId); + for (const handler of this.handlers) { + const inheritable = this.inheritableHandlers.includes(handler); + manager.addHandler(handler, inheritable); + } + for (const tag of this.tags) { + const inheritable = this.inheritableTags.includes(tag); + manager.addTags([tag], inheritable); + } + for (const key of Object.keys(this.metadata)) { + const inheritable = Object.keys(this.inheritableMetadata).includes(key); + manager.addMetadata({ [key]: this.metadata[key] }, inheritable); + } + for (const handler of additionalHandlers) { + if (manager.handlers.filter((h) => h.name === "console_callback_handler").some((h) => h.name === handler.name)) continue; + manager.addHandler(handler, inherit); + } + return manager; + } + static fromHandlers(handlers) { + class Handler extends BaseCallbackHandler { + name = v7(); + constructor() { + super(); + Object.assign(this, handlers); + } + } + const manager = new this(); + manager.addHandler(new Handler()); + return manager; + } + static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options); + } + static _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { + let callbackManager; + if (inheritableHandlers || localHandlers) { + if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { + callbackManager = new CallbackManager(); + callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); + } else callbackManager = inheritableHandlers; + callbackManager = callbackManager.copy(Array.isArray(localHandlers) ? localHandlers.map(ensureHandler) : localHandlers?.handlers, false); + } + const verboseEnabled = getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" || options?.verbose; + const tracingV2Enabled = LangChainTracer.getTraceableRunTree()?.tracingEnabled || callbacks_isTracingEnabled(); + const tracingEnabled = tracingV2Enabled || (getEnvironmentVariable("LANGCHAIN_TRACING") ?? false); + if (verboseEnabled || tracingEnabled) { + if (!callbackManager) callbackManager = new CallbackManager(); + if (verboseEnabled && !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { + const consoleHandler = new ConsoleCallbackHandler(); + callbackManager.addHandler(consoleHandler, true); + } + if (tracingEnabled && !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { + if (tracingV2Enabled) { + const tracerV2 = new LangChainTracer(); + callbackManager.addHandler(tracerV2, true); + } + } + if (tracingV2Enabled) { + const implicitRunTree = LangChainTracer.getTraceableRunTree(); + if (implicitRunTree && callbackManager._parentRunId === void 0) { + callbackManager._parentRunId = implicitRunTree.id; + const tracerV2 = callbackManager.handlers.find((handler) => handler.name === "langchain_tracer"); + tracerV2?.updateFromRunTree(implicitRunTree); + } + } + } + for (const { contextVar, inheritable = true, handlerClass, envVar } of _getConfigureHooks()) { + const createIfNotInContext = envVar && getEnvironmentVariable(envVar) === "true" && handlerClass; + let handler; + const contextVarValue = contextVar !== void 0 ? getContextVariable(contextVar) : void 0; + if (contextVarValue && isBaseCallbackHandler(contextVarValue)) handler = contextVarValue; + else if (createIfNotInContext) handler = new handlerClass({}); + if (handler !== void 0) { + if (!callbackManager) callbackManager = new CallbackManager(); + if (!callbackManager.handlers.some((h) => h.name === handler.name)) callbackManager.addHandler(handler, inheritable); + } + } + if (inheritableTags || localTags) { + if (callbackManager) { + callbackManager.addTags(inheritableTags ?? []); + callbackManager.addTags(localTags ?? [], false); + } + } + if (inheritableMetadata || localMetadata) { + if (callbackManager) { + callbackManager.addMetadata(inheritableMetadata ?? {}); + callbackManager.addMetadata(localMetadata ?? {}, false); + } + } + return callbackManager; + } +}; +function ensureHandler(handler) { + if ("name" in handler) return handler; + return BaseCallbackHandler.fromMethods(handler); +} + +//#endregion + +//# sourceMappingURL=manager.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/index.js + + + + +//#region src/singletons/async_local_storage/index.ts +var async_local_storage_MockAsyncLocalStorage = class { + getStore() { + return void 0; + } + run(_store, callback) { + return callback(); + } + enterWith(_store) { + return void 0; + } +}; +const async_local_storage_mockAsyncLocalStorage = new async_local_storage_MockAsyncLocalStorage(); +const LC_CHILD_KEY = Symbol.for("lc:child_config"); +var async_local_storage_AsyncLocalStorageProvider = class { + getInstance() { + return globals_getGlobalAsyncLocalStorageInstance() ?? async_local_storage_mockAsyncLocalStorage; + } + getRunnableConfig() { + const storage = this.getInstance(); + return storage.getStore()?.extra?.[LC_CHILD_KEY]; + } + runWithConfig(config, callback, avoidCreatingRootRunTree) { + const callbackManager = CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata); + const storage = this.getInstance(); + const previousValue = storage.getStore(); + const parentRunId = callbackManager?.getParentRunId(); + const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); + let runTree; + if (langChainTracer && parentRunId) runTree = langChainTracer.getRunTreeWithTracingConfig(parentRunId); + else if (!avoidCreatingRootRunTree) runTree = new run_trees_RunTree({ + name: "", + tracingEnabled: false + }); + if (runTree) runTree.extra = { + ...runTree.extra, + [LC_CHILD_KEY]: config + }; + if (previousValue !== void 0 && previousValue[globals_CONTEXT_VARIABLES_KEY] !== void 0) { + if (runTree === void 0) runTree = {}; + runTree[globals_CONTEXT_VARIABLES_KEY] = previousValue[globals_CONTEXT_VARIABLES_KEY]; + } + return storage.run(runTree, callback); + } + initializeGlobalInstance(instance) { + if (globals_getGlobalAsyncLocalStorageInstance() === void 0) setGlobalAsyncLocalStorageInstance(instance); + } +}; +const async_local_storage_AsyncLocalStorageProviderSingleton = new async_local_storage_AsyncLocalStorageProvider(); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/index.js + + + + +//#region src/singletons/index.ts +var singletons_exports = {}; +__export(singletons_exports, { + AsyncLocalStorageProviderSingleton: () => async_local_storage_AsyncLocalStorageProviderSingleton, + MockAsyncLocalStorage: () => async_local_storage_MockAsyncLocalStorage, + _CONTEXT_VARIABLES_KEY: () => globals_CONTEXT_VARIABLES_KEY +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: external "node:async_hooks" +const external_node_async_hooks_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:async_hooks"); +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/setup/async_local_storage.js + + + +//#region src/setup/async_local_storage.ts +function initializeAsyncLocalStorageSingleton() { + async_local_storage_AsyncLocalStorageProviderSingleton.initializeGlobalInstance(new external_node_async_hooks_namespaceObject.AsyncLocalStorage()); +} + +//#endregion + +//# sourceMappingURL=async_local_storage.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/errors.js +//#region src/errors.ts +/** @category Errors */ +var BaseLangGraphError = class extends Error { + lc_error_code; + constructor(message, fields) { + let finalMessage = message ?? ""; + if (fields?.lc_error_code) finalMessage = `${finalMessage}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${fields.lc_error_code}/\n`; + super(finalMessage); + this.lc_error_code = fields?.lc_error_code; + } +}; +var GraphBubbleUp = class extends BaseLangGraphError { + get is_bubble_up() { + return true; + } +}; +var GraphRecursionError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "GraphRecursionError"; + } + static get unminifiable_name() { + return "GraphRecursionError"; + } +}; +var GraphValueError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "GraphValueError"; + } + static get unminifiable_name() { + return "GraphValueError"; + } +}; +var GraphInterrupt = class extends GraphBubbleUp { + interrupts; + constructor(interrupts, fields) { + super(JSON.stringify(interrupts, null, 2), fields); + this.name = "GraphInterrupt"; + this.interrupts = interrupts ?? []; + } + static get unminifiable_name() { + return "GraphInterrupt"; + } +}; +/** Raised by a node to interrupt execution. */ +var NodeInterrupt = class extends GraphInterrupt { + constructor(message, fields) { + super([{ value: message }], fields); + this.name = "NodeInterrupt"; + } + static get unminifiable_name() { + return "NodeInterrupt"; + } +}; +var ParentCommand = class extends GraphBubbleUp { + command; + constructor(command) { + super(); + this.name = "ParentCommand"; + this.command = command; + } + static get unminifiable_name() { + return "ParentCommand"; + } +}; +function isParentCommand(e) { + return e !== void 0 && e.name === ParentCommand.unminifiable_name; +} +function isGraphBubbleUp(e) { + return e !== void 0 && e.is_bubble_up === true; +} +function isGraphInterrupt(e) { + return e !== void 0 && [GraphInterrupt.unminifiable_name, NodeInterrupt.unminifiable_name].includes(e.name); +} +var EmptyInputError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "EmptyInputError"; + } + static get unminifiable_name() { + return "EmptyInputError"; + } +}; +var EmptyChannelError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "EmptyChannelError"; + } + static get unminifiable_name() { + return "EmptyChannelError"; + } +}; +var InvalidUpdateError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "InvalidUpdateError"; + } + static get unminifiable_name() { + return "InvalidUpdateError"; + } +}; +/** +* @deprecated This exception type is no longer thrown. +*/ +var MultipleSubgraphsError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "MultipleSubgraphError"; + } + static get unminifiable_name() { + return "MultipleSubgraphError"; + } +}; +var UnreachableNodeError = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "UnreachableNodeError"; + } + static get unminifiable_name() { + return "UnreachableNodeError"; + } +}; +/** +* Exception raised when an error occurs in the remote graph. +*/ +var RemoteException = class extends BaseLangGraphError { + constructor(message, fields) { + super(message, fields); + this.name = "RemoteException"; + } + static get unminifiable_name() { + return "RemoteException"; + } +}; +/** +* Used for subgraph detection. +*/ +const getSubgraphsSeenSet = () => { + if (globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] === void 0) globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] = /* @__PURE__ */ new Set(); + return globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]; +}; + +//#endregion + +//# sourceMappingURL=errors.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/id.js + + +//#region src/id.ts +function uuid6(clockseq) { + return v6({ clockseq }); +} +function uuid5(name, namespace) { + const namespaceBytes = namespace.replace(/-/g, "").match(/.{2}/g).map((byte) => parseInt(byte, 16)); + return v5(name, new Uint8Array(namespaceBytes)); +} + +//#endregion + +//# sourceMappingURL=id.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/serde/types.js +//#region src/serde/types.ts +const TASKS = "__pregel_tasks"; +const types_ERROR = "__error__"; +const SCHEDULED = "__scheduled__"; +const INTERRUPT = "__interrupt__"; +const RESUME = "__resume__"; + +//#endregion + +//# sourceMappingURL=types.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/serde/utils/fast-safe-stringify/index.js +//#region src/serde/utils/fast-safe-stringify/index.ts +var fast_safe_stringify_LIMIT_REPLACE_NODE = "[...]"; +var fast_safe_stringify_CIRCULAR_REPLACE_NODE = "[Circular]"; +var fast_safe_stringify_arr = []; +var fast_safe_stringify_replacerStack = []; +function fast_safe_stringify_defaultOptions() { + return { + depthLimit: Number.MAX_SAFE_INTEGER, + edgesLimit: Number.MAX_SAFE_INTEGER + }; +} +function fast_safe_stringify_stringify(obj, replacer, spacer, options) { + if (typeof options === "undefined") options = fast_safe_stringify_defaultOptions(); + fast_safe_stringify_decirc(obj, "", 0, [], void 0, 0, options); + var res; + try { + if (fast_safe_stringify_replacerStack.length === 0) res = JSON.stringify(obj, replacer, spacer); + else res = JSON.stringify(obj, fast_safe_stringify_replaceGetterValues(replacer), spacer); + } catch (_) { + return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); + } finally { + while (fast_safe_stringify_arr.length !== 0) { + var part = fast_safe_stringify_arr.pop(); + if (part.length === 4) Object.defineProperty(part[0], part[1], part[3]); + else part[0][part[1]] = part[2]; + } + } + return res; +} +function fast_safe_stringify_setReplace(replace, val, k, parent) { + var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); + if (propertyDescriptor.get !== void 0) if (propertyDescriptor.configurable) { + Object.defineProperty(parent, k, { value: replace }); + fast_safe_stringify_arr.push([ + parent, + k, + val, + propertyDescriptor + ]); + } else fast_safe_stringify_replacerStack.push([ + val, + k, + replace + ]); + else { + parent[k] = replace; + fast_safe_stringify_arr.push([ + parent, + k, + val + ]); + } +} +function fast_safe_stringify_decirc(val, k, edgeIndex, stack, parent, depth, options) { + depth += 1; + var i; + if (typeof val === "object" && val !== null) { + for (i = 0; i < stack.length; i++) if (stack[i] === val) { + fast_safe_stringify_setReplace(fast_safe_stringify_CIRCULAR_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { + fast_safe_stringify_setReplace(fast_safe_stringify_LIMIT_REPLACE_NODE, val, k, parent); + return; + } + if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { + fast_safe_stringify_setReplace(fast_safe_stringify_LIMIT_REPLACE_NODE, val, k, parent); + return; + } + stack.push(val); + if (Array.isArray(val)) for (i = 0; i < val.length; i++) fast_safe_stringify_decirc(val[i], i, i, stack, val, depth, options); + else { + var keys = Object.keys(val); + for (i = 0; i < keys.length; i++) { + var key = keys[i]; + fast_safe_stringify_decirc(val[key], key, i, stack, val, depth, options); + } + } + stack.pop(); + } +} +function fast_safe_stringify_replaceGetterValues(replacer) { + replacer = typeof replacer !== "undefined" ? replacer : function(k, v) { + return v; + }; + return function(key, val) { + if (fast_safe_stringify_replacerStack.length > 0) for (var i = 0; i < fast_safe_stringify_replacerStack.length; i++) { + var part = fast_safe_stringify_replacerStack[i]; + if (part[1] === key && part[0] === val) { + val = part[2]; + fast_safe_stringify_replacerStack.splice(i, 1); + break; + } + } + return replacer.call(this, key, val); + }; +} + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/import_constants.js +//#region src/load/import_constants.ts +/** Auto-generated by import-constants plugin. Do not edit manually */ +const optionalImportEntrypoints = []; + +//#endregion + +//# sourceMappingURL=import_constants.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/agents.js +//#region src/agents.ts +var agents_exports = {}; + +//#endregion + +//# sourceMappingURL=agents.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/config.js + + + + +//#region src/runnables/config.ts +const DEFAULT_RECURSION_LIMIT = 25; +async function getCallbackManagerForConfig(config) { + return CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata); +} +function mergeConfigs(...configs) { + const copy = {}; + for (const options of configs.filter((c) => !!c)) for (const key of Object.keys(options)) if (key === "metadata") copy[key] = { + ...copy[key], + ...options[key] + }; + else if (key === "tags") { + const baseKeys = copy[key] ?? []; + copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))]; + } else if (key === "configurable") copy[key] = { + ...copy[key], + ...options[key] + }; + else if (key === "timeout") { + if (copy.timeout === void 0) copy.timeout = options.timeout; + else if (options.timeout !== void 0) copy.timeout = Math.min(copy.timeout, options.timeout); + } else if (key === "signal") { + if (copy.signal === void 0) copy.signal = options.signal; + else if (options.signal !== void 0) if ("any" in AbortSignal) copy.signal = AbortSignal.any([copy.signal, options.signal]); + else copy.signal = options.signal; + } else if (key === "callbacks") { + const baseCallbacks = copy.callbacks; + const providedCallbacks = options.callbacks; + if (Array.isArray(providedCallbacks)) if (!baseCallbacks) copy.callbacks = providedCallbacks; + else if (Array.isArray(baseCallbacks)) copy.callbacks = baseCallbacks.concat(providedCallbacks); + else { + const manager = baseCallbacks.copy(); + for (const callback of providedCallbacks) manager.addHandler(ensureHandler(callback), true); + copy.callbacks = manager; + } + else if (providedCallbacks) if (!baseCallbacks) copy.callbacks = providedCallbacks; + else if (Array.isArray(baseCallbacks)) { + const manager = providedCallbacks.copy(); + for (const callback of baseCallbacks) manager.addHandler(ensureHandler(callback), true); + copy.callbacks = manager; + } else copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, { + handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers), + inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers), + tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))), + inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))), + metadata: { + ...baseCallbacks.metadata, + ...providedCallbacks.metadata + } + }); + } else { + const typedKey = key; + copy[typedKey] = options[typedKey] ?? copy[typedKey]; + } + return copy; +} +const PRIMITIVES = new Set([ + "string", + "number", + "boolean" +]); +/** +* Ensure that a passed config is an object with all required keys present. +*/ +function ensureConfig(config) { + const implicitConfig = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); + let empty = { + tags: [], + metadata: {}, + recursionLimit: 25, + runId: void 0 + }; + if (implicitConfig) { + const { runId, runName,...rest } = implicitConfig; + empty = Object.entries(rest).reduce((currentConfig, [key, value]) => { + if (value !== void 0) currentConfig[key] = value; + return currentConfig; + }, empty); + } + if (config) empty = Object.entries(config).reduce((currentConfig, [key, value]) => { + if (value !== void 0) currentConfig[key] = value; + return currentConfig; + }, empty); + if (empty?.configurable) { + for (const key of Object.keys(empty.configurable)) if (PRIMITIVES.has(typeof empty.configurable[key]) && !empty.metadata?.[key]) { + if (!empty.metadata) empty.metadata = {}; + empty.metadata[key] = empty.configurable[key]; + } + } + if (empty.timeout !== void 0) { + if (empty.timeout <= 0) throw new Error("Timeout must be a positive number"); + const originalTimeoutMs = empty.timeout; + const timeoutSignal = AbortSignal.timeout(originalTimeoutMs); + if (!empty.metadata) empty.metadata = {}; + if (empty.metadata.timeoutMs === void 0) empty.metadata.timeoutMs = originalTimeoutMs; + if (empty.signal !== void 0) { + if ("any" in AbortSignal) empty.signal = AbortSignal.any([empty.signal, timeoutSignal]); + } else empty.signal = timeoutSignal; + /** + * We are deleting the timeout key for the following reasons: + * - Idempotent normalization: ensureConfig may be called multiple times down the stack. If timeout remains, + * each call would synthesize new timeout signals and combine them, changing the effective timeout unpredictably. + * - Single enforcement path: downstream code relies on signal to enforce cancellation. Leaving timeout means two + * competing mechanisms (numeric timeout and signal) can be applied, sometimes with different semantics. + * - Propagation to children: pickRunnableConfigKeys would keep forwarding timeout to nested runnables, causing + * repeated re-normalization and stacked timeouts. + * - Backward compatibility: a lot of components and tests assume ensureConfig removes timeout post-normalization; + * changing that would be a breaking change. + */ + delete empty.timeout; + } + return empty; +} +/** +* Helper function that patches runnable configs with updated properties. +*/ +function config_patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId } = {}) { + const newConfig = ensureConfig(config); + if (callbacks !== void 0) { + /** + * If we're replacing callbacks we need to unset runName + * since that should apply only to the same run as the original callbacks + */ + delete newConfig.runName; + newConfig.callbacks = callbacks; + } + if (recursionLimit !== void 0) newConfig.recursionLimit = recursionLimit; + if (maxConcurrency !== void 0) newConfig.maxConcurrency = maxConcurrency; + if (runName !== void 0) newConfig.runName = runName; + if (configurable !== void 0) newConfig.configurable = { + ...newConfig.configurable, + ...configurable + }; + if (runId !== void 0) delete newConfig.runId; + return newConfig; +} +function config_pickRunnableConfigKeys(config) { + if (!config) return void 0; + return { + configurable: config.configurable, + recursionLimit: config.recursionLimit, + callbacks: config.callbacks, + tags: config.tags, + metadata: config.metadata, + maxConcurrency: config.maxConcurrency, + timeout: config.timeout, + signal: config.signal, + store: config.store + }; +} + +//#endregion + +//# sourceMappingURL=config.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/signal.js +//#region src/utils/signal.ts +/** +* Race a promise with an abort signal. If the signal is aborted, the promise will +* be rejected with the error from the signal. If the promise is rejected, the signal will be aborted. +* +* @param promise - The promise to race. +* @param signal - The abort signal. +* @returns The result of the promise. +*/ +async function raceWithSignal(promise, signal) { + if (signal === void 0) return promise; + let listener; + return Promise.race([promise.catch((err) => { + if (!signal?.aborted) throw err; + else return void 0; + }), new Promise((_, reject) => { + listener = () => { + reject(getAbortSignalError(signal)); + }; + signal.addEventListener("abort", listener); + if (signal.aborted) reject(getAbortSignalError(signal)); + })]).finally(() => signal.removeEventListener("abort", listener)); +} +/** +* Get the error from an abort signal. Since you can set the reason to anything, +* we have to do some type gymnastics to get a proper error message. +* +* @param signal - The abort signal. +* @returns The error from the abort signal. +*/ +function getAbortSignalError(signal) { + if (signal?.reason instanceof Error) return signal.reason; + if (typeof signal?.reason === "string") return new Error(signal.reason); + return /* @__PURE__ */ new Error("Aborted"); +} + +//#endregion + +//# sourceMappingURL=signal.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/stream.js + + + + + + +//#region src/utils/stream.ts +var stream_exports = {}; +__export(stream_exports, { + AsyncGeneratorWithSetup: () => AsyncGeneratorWithSetup, + IterableReadableStream: () => IterableReadableStream, + atee: () => atee, + concat: () => concat, + pipeGeneratorWithSetup: () => pipeGeneratorWithSetup +}); +var IterableReadableStream = class IterableReadableStream extends ReadableStream { + reader; + ensureReader() { + if (!this.reader) this.reader = this.getReader(); + } + async next() { + this.ensureReader(); + try { + const result = await this.reader.read(); + if (result.done) { + this.reader.releaseLock(); + return { + done: true, + value: void 0 + }; + } else return { + done: false, + value: result.value + }; + } catch (e) { + this.reader.releaseLock(); + throw e; + } + } + async return() { + this.ensureReader(); + if (this.locked) { + const cancelPromise = this.reader.cancel(); + this.reader.releaseLock(); + await cancelPromise; + } + return { + done: true, + value: void 0 + }; + } + async throw(e) { + this.ensureReader(); + if (this.locked) { + const cancelPromise = this.reader.cancel(); + this.reader.releaseLock(); + await cancelPromise; + } + throw e; + } + [Symbol.asyncIterator]() { + return this; + } + async [Symbol.asyncDispose]() { + await this.return(); + } + static fromReadableStream(stream) { + const reader = stream.getReader(); + return new IterableReadableStream({ + start(controller) { + return pump(); + function pump() { + return reader.read().then(({ done, value }) => { + if (done) { + controller.close(); + return; + } + controller.enqueue(value); + return pump(); + }); + } + }, + cancel() { + reader.releaseLock(); + } + }); + } + static fromAsyncGenerator(generator) { + return new IterableReadableStream({ + async pull(controller) { + const { value, done } = await generator.next(); + if (done) controller.close(); + controller.enqueue(value); + }, + async cancel(reason) { + await generator.return(reason); + } + }); + } +}; +function atee(iter, length = 2) { + const buffers = Array.from({ length }, () => []); + return buffers.map(async function* makeIter(buffer) { + while (true) if (buffer.length === 0) { + const result = await iter.next(); + for (const buffer$1 of buffers) buffer$1.push(result); + } else if (buffer[0].done) return; + else yield buffer.shift().value; + }); +} +function concat(first, second) { + if (Array.isArray(first) && Array.isArray(second)) return first.concat(second); + else if (typeof first === "string" && typeof second === "string") return first + second; + else if (typeof first === "number" && typeof second === "number") return first + second; + else if ("concat" in first && typeof first.concat === "function") return first.concat(second); + else if (typeof first === "object" && typeof second === "object") { + const chunk = { ...first }; + for (const [key, value] of Object.entries(second)) if (key in chunk && !Array.isArray(chunk[key])) chunk[key] = concat(chunk[key], value); + else chunk[key] = value; + return chunk; + } else throw new Error(`Cannot concat ${typeof first} and ${typeof second}`); +} +var AsyncGeneratorWithSetup = class { + generator; + setup; + config; + signal; + firstResult; + firstResultUsed = false; + constructor(params) { + this.generator = params.generator; + this.config = params.config; + this.signal = params.signal ?? this.config?.signal; + this.setup = new Promise((resolve, reject) => { + async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(params.config), async () => { + this.firstResult = params.generator.next(); + if (params.startSetup) this.firstResult.then(params.startSetup).then(resolve, reject); + else this.firstResult.then((_result) => resolve(void 0), reject); + }, true); + }); + } + async next(...args) { + this.signal?.throwIfAborted(); + if (!this.firstResultUsed) { + this.firstResultUsed = true; + return this.firstResult; + } + return async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(this.config), this.signal ? async () => { + return raceWithSignal(this.generator.next(...args), this.signal); + } : async () => { + return this.generator.next(...args); + }, true); + } + async return(value) { + return this.generator.return(value); + } + async throw(e) { + return this.generator.throw(e); + } + [Symbol.asyncIterator]() { + return this; + } + async [Symbol.asyncDispose]() { + await this.return(); + } +}; +async function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) { + const gen = new AsyncGeneratorWithSetup({ + generator, + startSetup, + signal + }); + const setup = await gen.setup; + return { + output: to(gen, setup, ...args), + setup + }; +} + +//#endregion + +//# sourceMappingURL=stream.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js +//#region src/utils/fast-json-patch/src/helpers.ts +/*! +* https://github.com/Starcounter-Jack/JSON-Patch +* (c) 2017-2022 Joachim Wester +* MIT licensed +*/ +const _hasOwnProperty = Object.prototype.hasOwnProperty; +function helpers_hasOwnProperty(obj, key) { + return _hasOwnProperty.call(obj, key); +} +function _objectKeys(obj) { + if (Array.isArray(obj)) { + const keys$1 = new Array(obj.length); + for (let k = 0; k < keys$1.length; k++) keys$1[k] = "" + k; + return keys$1; + } + if (Object.keys) return Object.keys(obj); + let keys = []; + for (let i in obj) if (helpers_hasOwnProperty(obj, i)) keys.push(i); + return keys; +} +/** +* Deeply clone the object. +* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) +* @param {any} obj value to clone +* @return {any} cloned obj +*/ +function _deepClone(obj) { + switch (typeof obj) { + case "object": return JSON.parse(JSON.stringify(obj)); + case "undefined": return null; + default: return obj; + } +} +function isInteger(str) { + let i = 0; + const len = str.length; + let charCode; + while (i < len) { + charCode = str.charCodeAt(i); + if (charCode >= 48 && charCode <= 57) { + i++; + continue; + } + return false; + } + return true; +} +/** +* Escapes a json pointer path +* @param path The raw pointer +* @return the Escaped path +*/ +function escapePathComponent(path) { + if (path.indexOf("/") === -1 && path.indexOf("~") === -1) return path; + return path.replace(/~/g, "~0").replace(/\//g, "~1"); +} +/** +* Unescapes a json pointer path +* @param path The escaped pointer +* @return The unescaped path +*/ +function unescapePathComponent(path) { + return path.replace(/~1/g, "/").replace(/~0/g, "~"); +} +/** +* Recursively checks whether an object has any undefined values inside. +*/ +function hasUndefined(obj) { + if (obj === void 0) return true; + if (obj) { + if (Array.isArray(obj)) { + for (let i$1 = 0, len = obj.length; i$1 < len; i$1++) if (hasUndefined(obj[i$1])) return true; + } else if (typeof obj === "object") { + const objKeys = _objectKeys(obj); + const objKeysLength = objKeys.length; + for (var i = 0; i < objKeysLength; i++) if (hasUndefined(obj[objKeys[i]])) return true; + } + } + return false; +} +function patchErrorMessageFormatter(message, args) { + const messageParts = [message]; + for (const key in args) { + const value = typeof args[key] === "object" ? JSON.stringify(args[key], null, 2) : args[key]; + if (typeof value !== "undefined") messageParts.push(`${key}: ${value}`); + } + return messageParts.join("\n"); +} +var PatchError = class extends Error { + constructor(message, name, index, operation, tree) { + super(patchErrorMessageFormatter(message, { + name, + index, + operation, + tree + })); + this.name = name; + this.index = index; + this.operation = operation; + this.tree = tree; + Object.setPrototypeOf(this, new.target.prototype); + this.message = patchErrorMessageFormatter(message, { + name, + index, + operation, + tree + }); + } +}; + +//#endregion + +//# sourceMappingURL=helpers.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js + + + +//#region src/utils/fast-json-patch/src/core.ts +var core_exports = {}; +__export(core_exports, { + JsonPatchError: () => JsonPatchError, + _areEquals: () => _areEquals, + applyOperation: () => applyOperation, + applyPatch: () => applyPatch, + applyReducer: () => applyReducer, + deepClone: () => deepClone, + getValueByPointer: () => getValueByPointer, + validate: () => core_validate, + validator: () => validator +}); +const JsonPatchError = PatchError; +const deepClone = _deepClone; +/** +* Check if a key is a dangerous prototype property that could lead to prototype pollution. +* This provides defense-in-depth alongside the check in applyOperation. +*/ +function isDangerousKey(key) { + return Object.getOwnPropertyNames(Object.prototype).includes(key); +} +const objOps = { + add: function(obj, key, document) { + if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons"); + obj[key] = this.value; + return { newDocument: document }; + }, + remove: function(obj, key, document) { + if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons"); + var removed = obj[key]; + delete obj[key]; + return { + newDocument: document, + removed + }; + }, + replace: function(obj, key, document) { + if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons"); + var removed = obj[key]; + obj[key] = this.value; + return { + newDocument: document, + removed + }; + }, + move: function(obj, key, document) { + let removed = getValueByPointer(document, this.path); + if (removed) removed = _deepClone(removed); + const originalValue = applyOperation(document, { + op: "remove", + path: this.from + }).removed; + applyOperation(document, { + op: "add", + path: this.path, + value: originalValue + }); + return { + newDocument: document, + removed + }; + }, + copy: function(obj, key, document) { + const valueToCopy = getValueByPointer(document, this.from); + applyOperation(document, { + op: "add", + path: this.path, + value: _deepClone(valueToCopy) + }); + return { newDocument: document }; + }, + test: function(obj, key, document) { + return { + newDocument: document, + test: _areEquals(obj[key], this.value) + }; + }, + _get: function(obj, key, document) { + this.value = obj[key]; + return { newDocument: document }; + } +}; +var arrOps = { + add: function(arr, i, document) { + if (isInteger(i)) arr.splice(i, 0, this.value); + else arr[i] = this.value; + return { + newDocument: document, + index: i + }; + }, + remove: function(arr, i, document) { + var removedList = arr.splice(i, 1); + return { + newDocument: document, + removed: removedList[0] + }; + }, + replace: function(arr, i, document) { + var removed = arr[i]; + arr[i] = this.value; + return { + newDocument: document, + removed + }; + }, + move: objOps.move, + copy: objOps.copy, + test: objOps.test, + _get: objOps._get +}; +/** +* Retrieves a value from a JSON document by a JSON pointer. +* Returns the value. +* +* @param document The document to get the value from +* @param pointer an escaped JSON pointer +* @return The retrieved value +*/ +function getValueByPointer(document, pointer) { + if (pointer == "") return document; + var getOriginalDestination = { + op: "_get", + path: pointer + }; + applyOperation(document, getOriginalDestination); + return getOriginalDestination.value; +} +/** +* Apply a single JSON Patch Operation on a JSON document. +* Returns the {newDocument, result} of the operation. +* It modifies the `document` and `operation` objects - it gets the values by reference. +* If you would like to avoid touching your values, clone them: +* `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. +* +* @param document The document to patch +* @param operation The operation to apply +* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. +* @param mutateDocument Whether to mutate the original document or clone it before applying +* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. +* @return `{newDocument, result}` after the operation +*/ +function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { + if (validateOperation) if (typeof validateOperation == "function") validateOperation(operation, 0, document, operation.path); + else validator(operation, 0); + if (operation.path === "") { + let returnValue = { newDocument: document }; + if (operation.op === "add") { + returnValue.newDocument = operation.value; + return returnValue; + } else if (operation.op === "replace") { + returnValue.newDocument = operation.value; + returnValue.removed = document; + return returnValue; + } else if (operation.op === "move" || operation.op === "copy") { + returnValue.newDocument = getValueByPointer(document, operation.from); + if (operation.op === "move") returnValue.removed = document; + return returnValue; + } else if (operation.op === "test") { + returnValue.test = _areEquals(document, operation.value); + if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + returnValue.newDocument = document; + return returnValue; + } else if (operation.op === "remove") { + returnValue.removed = document; + returnValue.newDocument = null; + return returnValue; + } else if (operation.op === "_get") { + operation.value = document; + return returnValue; + } else if (validateOperation) throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); + else return returnValue; + } else { + if (!mutateDocument) document = _deepClone(document); + const path = operation.path || ""; + const keys = path.split("/"); + let obj = document; + let t = 1; + let len = keys.length; + let existingPathFragment = void 0; + let key; + let validateFunction; + if (typeof validateOperation == "function") validateFunction = validateOperation; + else validateFunction = validator; + while (true) { + key = keys[t]; + if (key && key.indexOf("~") != -1) key = unescapePathComponent(key); + if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t > 0 && keys[t - 1] == "constructor")) throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); + if (validateOperation) { + if (existingPathFragment === void 0) { + if (obj[key] === void 0) existingPathFragment = keys.slice(0, t).join("/"); + else if (t == len - 1) existingPathFragment = operation.path; + if (existingPathFragment !== void 0) validateFunction(operation, 0, document, existingPathFragment); + } + } + t++; + if (Array.isArray(obj)) { + if (key === "-") key = obj.length; + else if (validateOperation && !isInteger(key)) throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); + else if (isInteger(key)) key = ~~key; + if (t >= len) { + if (validateOperation && operation.op === "add" && key > obj.length) throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); + const returnValue = arrOps[operation.op].call(operation, obj, key, document); + if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + return returnValue; + } + } else if (t >= len) { + const returnValue = objOps[operation.op].call(operation, obj, key, document); + if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + return returnValue; + } + obj = obj[key]; + if (validateOperation && t < len && (!obj || typeof obj !== "object")) throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); + } + } +} +/** +* Apply a full JSON Patch array on a JSON document. +* Returns the {newDocument, result} of the patch. +* It modifies the `document` object and `patch` - it gets the values by reference. +* If you would like to avoid touching your values, clone them: +* `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. +* +* @param document The document to patch +* @param patch The patch to apply +* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. +* @param mutateDocument Whether to mutate the original document or clone it before applying +* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. +* @return An array of `{newDocument, result}` after the patch +*/ +function applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { + if (validateOperation) { + if (!Array.isArray(patch)) throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + } + if (!mutateDocument) document = _deepClone(document); + const results = new Array(patch.length); + for (let i = 0, length = patch.length; i < length; i++) { + results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); + document = results[i].newDocument; + } + results.newDocument = document; + return results; +} +/** +* Apply a single JSON Patch Operation on a JSON document. +* Returns the updated document. +* Suitable as a reducer. +* +* @param document The document to patch +* @param operation The operation to apply +* @return The updated document +*/ +function applyReducer(document, operation, index) { + const operationResult = applyOperation(document, operation); + if (operationResult.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); + return operationResult.newDocument; +} +/** +* Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. +* @param {object} operation - operation object (patch) +* @param {number} index - index of operation in the sequence +* @param {object} [document] - object where the operation is supposed to be applied +* @param {string} [existingPathFragment] - comes along with `document` +*/ +function validator(operation, index, document, existingPathFragment) { + if (typeof operation !== "object" || operation === null || Array.isArray(operation)) throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); + else if (!objOps[operation.op]) throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); + else if (typeof operation.path !== "string") throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); + else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) throw new JsonPatchError("Operation `path` property must start with \"/\"", "OPERATION_PATH_INVALID", index, operation, document); + else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document); + else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === void 0) throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document); + else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document); + else if (document) { + if (operation.op == "add") { + var pathLen = operation.path.split("/").length; + var existingPathLen = existingPathFragment.split("/").length; + if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document); + } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") { + if (operation.path !== existingPathFragment) throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); + } else if (operation.op === "move" || operation.op === "copy") { + var existingValue = { + op: "_get", + path: operation.from, + value: void 0 + }; + var error = core_validate([existingValue], document); + if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); + } + } +} +/** +* Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. +* If error is encountered, returns a JsonPatchError object +* @param sequence +* @param document +* @returns {JsonPatchError|undefined} +*/ +function core_validate(sequence, document, externalValidator) { + try { + if (!Array.isArray(sequence)) throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); + if (document) applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true); + else { + externalValidator = externalValidator || validator; + for (var i = 0; i < sequence.length; i++) externalValidator(sequence[i], i, document, void 0); + } + } catch (e) { + if (e instanceof JsonPatchError) return e; + else throw e; + } +} +function _areEquals(a, b) { + if (a === b) return true; + if (a && b && typeof a == "object" && typeof b == "object") { + var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; + if (arrA && arrB) { + length = a.length; + if (length != b.length) return false; + for (i = length; i-- !== 0;) if (!_areEquals(a[i], b[i])) return false; + return true; + } + if (arrA != arrB) return false; + var keys = Object.keys(a); + length = keys.length; + if (length !== Object.keys(b).length) return false; + for (i = length; i-- !== 0;) if (!b.hasOwnProperty(keys[i])) return false; + for (i = length; i-- !== 0;) { + key = keys[i]; + if (!_areEquals(a[key], b[key])) return false; + } + return true; + } + return a !== a && b !== b; +} + +//#endregion + +//# sourceMappingURL=core.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js + + + +//#region src/utils/fast-json-patch/src/duplex.ts +function _generate(mirror, obj, patches, path, invertible) { + if (obj === mirror) return; + if (typeof obj.toJSON === "function") obj = obj.toJSON(); + var newKeys = _objectKeys(obj); + var oldKeys = _objectKeys(mirror); + var changed = false; + var deleted = false; + for (var t = oldKeys.length - 1; t >= 0; t--) { + var key = oldKeys[t]; + var oldVal = mirror[key]; + if (helpers_hasOwnProperty(obj, key) && !(obj[key] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) { + var newVal = obj[key]; + if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); + else if (oldVal !== newVal) { + changed = true; + if (invertible) patches.push({ + op: "test", + path: path + "/" + escapePathComponent(key), + value: _deepClone(oldVal) + }); + patches.push({ + op: "replace", + path: path + "/" + escapePathComponent(key), + value: _deepClone(newVal) + }); + } + } else if (Array.isArray(mirror) === Array.isArray(obj)) { + if (invertible) patches.push({ + op: "test", + path: path + "/" + escapePathComponent(key), + value: _deepClone(oldVal) + }); + patches.push({ + op: "remove", + path: path + "/" + escapePathComponent(key) + }); + deleted = true; + } else { + if (invertible) patches.push({ + op: "test", + path, + value: mirror + }); + patches.push({ + op: "replace", + path, + value: obj + }); + changed = true; + } + } + if (!deleted && newKeys.length == oldKeys.length) return; + for (var t = 0; t < newKeys.length; t++) { + var key = newKeys[t]; + if (!helpers_hasOwnProperty(mirror, key) && obj[key] !== void 0) patches.push({ + op: "add", + path: path + "/" + escapePathComponent(key), + value: _deepClone(obj[key]) + }); + } +} +/** +* Create an array of patches from the differences in two objects +*/ +function compare(tree1, tree2, invertible = false) { + var patches = []; + _generate(tree1, tree2, patches, "", invertible); + return patches; +} + +//#endregion + +//# sourceMappingURL=duplex.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js + + + + +//#region src/utils/fast-json-patch/index.ts +var fast_json_patch_default = { + ...core_exports, + JsonPatchError: PatchError, + deepClone: _deepClone, + escapePathComponent: escapePathComponent, + unescapePathComponent: unescapePathComponent +}; + +//#endregion +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/log_stream.js + + + + + + + +//#region src/tracers/log_stream.ts +var log_stream_exports = {}; +__export(log_stream_exports, { + LogStreamCallbackHandler: () => LogStreamCallbackHandler, + RunLog: () => RunLog, + RunLogPatch: () => RunLogPatch, + isLogStreamHandler: () => isLogStreamHandler +}); +/** +* List of jsonpatch JSONPatchOperations, which describe how to create the run state +* from an empty dict. This is the minimal representation of the log, designed to +* be serialized as JSON and sent over the wire to reconstruct the log on the other +* side. Reconstruction of the state can be done with any jsonpatch-compliant library, +* see https://jsonpatch.com for more information. +*/ +var RunLogPatch = class { + ops; + constructor(fields) { + this.ops = fields.ops ?? []; + } + concat(other) { + const ops = this.ops.concat(other.ops); + const states = applyPatch({}, ops); + return new RunLog({ + ops, + state: states[states.length - 1].newDocument + }); + } +}; +var RunLog = class RunLog extends RunLogPatch { + state; + constructor(fields) { + super(fields); + this.state = fields.state; + } + concat(other) { + const ops = this.ops.concat(other.ops); + const states = applyPatch(this.state, other.ops); + return new RunLog({ + ops, + state: states[states.length - 1].newDocument + }); + } + static fromRunLogPatch(patch) { + const states = applyPatch({}, patch.ops); + return new RunLog({ + ops: patch.ops, + state: states[states.length - 1].newDocument + }); + } +}; +const isLogStreamHandler = (handler) => handler.name === "log_stream_tracer"; +/** +* Extract standardized inputs from a run. +* +* Standardizes the inputs based on the type of the runnable used. +* +* @param run - Run object +* @param schemaFormat - The schema format to use. +* +* @returns Valid inputs are only dict. By conventions, inputs always represented +* invocation using named arguments. +* A null means that the input is not yet known! +*/ +async function _getStandardizedInputs(run, schemaFormat) { + if (schemaFormat === "original") throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events."); + const { inputs } = run; + if ([ + "retriever", + "llm", + "prompt" + ].includes(run.run_type)) return inputs; + if (Object.keys(inputs).length === 1 && inputs?.input === "") return void 0; + return inputs.input; +} +async function _getStandardizedOutputs(run, schemaFormat) { + const { outputs } = run; + if (schemaFormat === "original") return outputs; + if ([ + "retriever", + "llm", + "prompt" + ].includes(run.run_type)) return outputs; + if (outputs !== void 0 && Object.keys(outputs).length === 1 && outputs?.output !== void 0) return outputs.output; + return outputs; +} +function isChatGenerationChunk(x) { + return x !== void 0 && x.message !== void 0; +} +/** +* Class that extends the `BaseTracer` class from the +* `langchain.callbacks.tracers.base` module. It represents a callback +* handler that logs the execution of runs and emits `RunLog` instances to a +* `RunLogStream`. +*/ +var LogStreamCallbackHandler = class extends BaseTracer { + autoClose = true; + includeNames; + includeTypes; + includeTags; + excludeNames; + excludeTypes; + excludeTags; + _schemaFormat = "original"; + rootId; + keyMapByRunId = {}; + counterMapByRunName = {}; + transformStream; + writer; + receiveStream; + name = "log_stream_tracer"; + lc_prefer_streaming = true; + constructor(fields) { + super({ + _awaitHandler: true, + ...fields + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat; + this.transformStream = new TransformStream(); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); + } + [Symbol.asyncIterator]() { + return this.receiveStream; + } + async persistRun(_run) {} + _includeRun(run) { + if (run.id === this.rootId) return false; + const runTags = run.tags ?? []; + let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0; + if (this.includeNames !== void 0) include = include || this.includeNames.includes(run.name); + if (this.includeTypes !== void 0) include = include || this.includeTypes.includes(run.run_type); + if (this.includeTags !== void 0) include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0; + if (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(run.name); + if (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(run.run_type); + if (this.excludeTags !== void 0) include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + return include; + } + async *tapOutputIterable(runId, output) { + for await (const chunk of output) { + if (runId !== this.rootId) { + const key = this.keyMapByRunId[runId]; + if (key) await this.writer.write(new RunLogPatch({ ops: [{ + op: "add", + path: `/logs/${key}/streamed_output/-`, + value: chunk + }] })); + } + yield chunk; + } + } + async onRunCreate(run) { + if (this.rootId === void 0) { + this.rootId = run.id; + await this.writer.write(new RunLogPatch({ ops: [{ + op: "replace", + path: "", + value: { + id: run.id, + name: run.name, + type: run.run_type, + streamed_output: [], + final_output: void 0, + logs: {} + } + }] })); + } + if (!this._includeRun(run)) return; + if (this.counterMapByRunName[run.name] === void 0) this.counterMapByRunName[run.name] = 0; + this.counterMapByRunName[run.name] += 1; + const count = this.counterMapByRunName[run.name]; + this.keyMapByRunId[run.id] = count === 1 ? run.name : `${run.name}:${count}`; + const logEntry = { + id: run.id, + name: run.name, + type: run.run_type, + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + start_time: new Date(run.start_time).toISOString(), + streamed_output: [], + streamed_output_str: [], + final_output: void 0, + end_time: void 0 + }; + if (this._schemaFormat === "streaming_events") logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat); + await this.writer.write(new RunLogPatch({ ops: [{ + op: "add", + path: `/logs/${this.keyMapByRunId[run.id]}`, + value: logEntry + }] })); + } + async onRunUpdate(run) { + try { + const runName = this.keyMapByRunId[run.id]; + if (runName === void 0) return; + const ops = []; + if (this._schemaFormat === "streaming_events") ops.push({ + op: "replace", + path: `/logs/${runName}/inputs`, + value: await _getStandardizedInputs(run, this._schemaFormat) + }); + ops.push({ + op: "add", + path: `/logs/${runName}/final_output`, + value: await _getStandardizedOutputs(run, this._schemaFormat) + }); + if (run.end_time !== void 0) ops.push({ + op: "add", + path: `/logs/${runName}/end_time`, + value: new Date(run.end_time).toISOString() + }); + const patch = new RunLogPatch({ ops }); + await this.writer.write(patch); + } finally { + if (run.id === this.rootId) { + const patch = new RunLogPatch({ ops: [{ + op: "replace", + path: "/final_output", + value: await _getStandardizedOutputs(run, this._schemaFormat) + }] }); + await this.writer.write(patch); + if (this.autoClose) await this.writer.close(); + } + } + } + async onLLMNewToken(run, token, kwargs) { + const runName = this.keyMapByRunId[run.id]; + if (runName === void 0) return; + const isChatModel = run.inputs.messages !== void 0; + let streamedOutputValue; + if (isChatModel) if (isChatGenerationChunk(kwargs?.chunk)) streamedOutputValue = kwargs?.chunk; + else streamedOutputValue = new AIMessageChunk({ + id: `run-${run.id}`, + content: token + }); + else streamedOutputValue = token; + const patch = new RunLogPatch({ ops: [{ + op: "add", + path: `/logs/${runName}/streamed_output_str/-`, + value: token + }, { + op: "add", + path: `/logs/${runName}/streamed_output/-`, + value: streamedOutputValue + }] }); + await this.writer.write(patch); + } +}; + +//#endregion + +//# sourceMappingURL=log_stream.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/outputs.js + + +//#region src/outputs.ts +var outputs_exports = {}; +__export(outputs_exports, { + ChatGenerationChunk: () => ChatGenerationChunk, + GenerationChunk: () => GenerationChunk, + RUN_KEY: () => RUN_KEY +}); +const RUN_KEY = "__run"; +/** +* Chunk of a single generation. Used for streaming. +*/ +var GenerationChunk = class GenerationChunk { + text; + generationInfo; + constructor(fields) { + this.text = fields.text; + this.generationInfo = fields.generationInfo; + } + concat(chunk) { + return new GenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo + } + }); + } +}; +var ChatGenerationChunk = class ChatGenerationChunk extends GenerationChunk { + message; + constructor(fields) { + super(fields); + this.message = fields.message; + } + concat(chunk) { + return new ChatGenerationChunk({ + text: this.text + chunk.text, + generationInfo: { + ...this.generationInfo, + ...chunk.generationInfo + }, + message: this.message.concat(chunk.message) + }); + } +}; + +//#endregion + +//# sourceMappingURL=outputs.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/is-network-error/index.js +//#region src/utils/is-network-error/index.js +const is_network_error_objectToString = Object.prototype.toString; +const is_network_error_isError = (value) => is_network_error_objectToString.call(value) === "[object Error]"; +const is_network_error_errorMessages = new Set([ + "network error", + "Failed to fetch", + "NetworkError when attempting to fetch resource.", + "The Internet connection appears to be offline.", + "Network request failed", + "fetch failed", + "terminated", + " A network error occurred.", + "Network connection lost" +]); +function is_network_error_isNetworkError(error) { + const isValid = error && is_network_error_isError(error) && error.name === "TypeError" && typeof error.message === "string"; + if (!isValid) return false; + const { message, stack } = error; + if (message === "Load failed") return stack === void 0 || "__sentry_captured__" in error; + if (message.startsWith("error sending request for url")) return true; + return is_network_error_errorMessages.has(message); +} + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/p-retry/index.js + + +//#region src/utils/p-retry/index.js +function p_retry_validateRetries(retries) { + if (typeof retries === "number") { + if (retries < 0) throw new TypeError("Expected `retries` to be a non-negative number."); + if (Number.isNaN(retries)) throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN."); + } else if (retries !== void 0) throw new TypeError("Expected `retries` to be a number or Infinity."); +} +function p_retry_validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) { + if (value === void 0) return; + if (typeof value !== "number" || Number.isNaN(value)) throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`); + if (!allowInfinity && !Number.isFinite(value)) throw new TypeError(`Expected \`${name}\` to be a finite number.`); + if (value < min) throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`); +} +var p_retry_AbortError = class extends Error { + constructor(message) { + super(); + if (message instanceof Error) { + this.originalError = message; + ({message} = message); + } else { + this.originalError = new Error(message); + this.originalError.stack = this.stack; + } + this.name = "AbortError"; + this.message = message; + } +}; +function p_retry_calculateDelay(retriesConsumed, options) { + const attempt = Math.max(1, retriesConsumed + 1); + const random = options.randomize ? Math.random() + 1 : 1; + let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1)); + timeout = Math.min(timeout, options.maxTimeout); + return timeout; +} +function p_retry_calculateRemainingTime(start, max) { + if (!Number.isFinite(max)) return max; + return max - (performance.now() - start); +} +async function p_retry_onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options }) { + const normalizedError = error instanceof Error ? error : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`); + if (normalizedError instanceof p_retry_AbortError) throw normalizedError.originalError; + const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries; + const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY; + const context = Object.freeze({ + error: normalizedError, + attemptNumber, + retriesLeft, + retriesConsumed + }); + await options.onFailedAttempt(context); + if (p_retry_calculateRemainingTime(startTime, maxRetryTime) <= 0) throw normalizedError; + const consumeRetry = await options.shouldConsumeRetry(context); + const remainingTime = p_retry_calculateRemainingTime(startTime, maxRetryTime); + if (remainingTime <= 0 || retriesLeft <= 0) throw normalizedError; + if (normalizedError instanceof TypeError && !is_network_error_isNetworkError(normalizedError)) { + if (consumeRetry) throw normalizedError; + options.signal?.throwIfAborted(); + return false; + } + if (!await options.shouldRetry(context)) throw normalizedError; + if (!consumeRetry) { + options.signal?.throwIfAborted(); + return false; + } + const delayTime = p_retry_calculateDelay(retriesConsumed, options); + const finalDelay = Math.min(delayTime, remainingTime); + if (finalDelay > 0) await new Promise((resolve, reject) => { + const onAbort = () => { + clearTimeout(timeoutToken); + options.signal?.removeEventListener("abort", onAbort); + reject(options.signal.reason); + }; + const timeoutToken = setTimeout(() => { + options.signal?.removeEventListener("abort", onAbort); + resolve(); + }, finalDelay); + if (options.unref) timeoutToken.unref?.(); + options.signal?.addEventListener("abort", onAbort, { once: true }); + }); + options.signal?.throwIfAborted(); + return true; +} +async function p_retry_pRetry(input, options = {}) { + options = { ...options }; + p_retry_validateRetries(options.retries); + if (Object.hasOwn(options, "forever")) throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead."); + options.retries ??= 10; + options.factor ??= 2; + options.minTimeout ??= 1e3; + options.maxTimeout ??= Number.POSITIVE_INFINITY; + options.maxRetryTime ??= Number.POSITIVE_INFINITY; + options.randomize ??= false; + options.onFailedAttempt ??= () => {}; + options.shouldRetry ??= () => true; + options.shouldConsumeRetry ??= () => true; + p_retry_validateNumberOption("factor", options.factor, { + min: 0, + allowInfinity: false + }); + p_retry_validateNumberOption("minTimeout", options.minTimeout, { + min: 0, + allowInfinity: false + }); + p_retry_validateNumberOption("maxTimeout", options.maxTimeout, { + min: 0, + allowInfinity: true + }); + p_retry_validateNumberOption("maxRetryTime", options.maxRetryTime, { + min: 0, + allowInfinity: true + }); + if (!(options.factor > 0)) options.factor = 1; + options.signal?.throwIfAborted(); + let attemptNumber = 0; + let retriesConsumed = 0; + const startTime = performance.now(); + while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) { + attemptNumber++; + try { + options.signal?.throwIfAborted(); + const result = await input(attemptNumber); + options.signal?.throwIfAborted(); + return result; + } catch (error) { + if (await p_retry_onAttemptFailure({ + error, + attemptNumber, + retriesConsumed, + startTime, + options + })) retriesConsumed++; + } + } + throw new Error("Retry attempts exhausted without throwing an error."); +} + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/async_caller.js + + + + + +//#region src/utils/async_caller.ts +var async_caller_exports = {}; +__export(async_caller_exports, { AsyncCaller: () => async_caller_AsyncCaller }); +const STATUS_NO_RETRY = [ + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 409 +]; +const defaultFailedAttemptHandler = (error) => { + if (error.message.startsWith("Cancel") || error.message.startsWith("AbortError") || error.name === "AbortError") throw error; + if (error?.code === "ECONNABORTED") throw error; + const status = error?.response?.status ?? error?.status; + if (status && STATUS_NO_RETRY.includes(+status)) throw error; + if (error?.error?.code === "insufficient_quota") { + const err = new Error(error?.message); + err.name = "InsufficientQuotaError"; + throw err; + } +}; +/** +* A class that can be used to make async calls with concurrency and retry logic. +* +* This is useful for making calls to any kind of "expensive" external resource, +* be it because it's rate-limited, subject to network issues, etc. +* +* Concurrent calls are limited by the `maxConcurrency` parameter, which defaults +* to `Infinity`. This means that by default, all calls will be made in parallel. +* +* Retries are limited by the `maxRetries` parameter, which defaults to 6. This +* means that by default, each call will be retried up to 6 times, with an +* exponential backoff between each attempt. +*/ +var async_caller_AsyncCaller = class { + maxConcurrency; + maxRetries; + onFailedAttempt; + queue; + constructor(params) { + this.maxConcurrency = params.maxConcurrency ?? Infinity; + this.maxRetries = params.maxRetries ?? 6; + this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler; + const PQueue = true ? p_queue_dist["default"] : p_queue_dist; + this.queue = new PQueue({ concurrency: this.maxConcurrency }); + } + async call(callable, ...args) { + return this.queue.add(() => p_retry_pRetry(() => callable(...args).catch((error) => { + if (error instanceof Error) throw error; + else throw new Error(error); + }), { + onFailedAttempt: ({ error }) => this.onFailedAttempt?.(error), + retries: this.maxRetries, + randomize: true + }), { throwOnTimeout: true }); + } + callWithOptions(options, callable, ...args) { + if (options.signal) { + let listener; + return Promise.race([this.call(callable, ...args), new Promise((_, reject) => { + listener = () => { + reject(getAbortSignalError(options.signal)); + }; + options.signal?.addEventListener("abort", listener); + })]).finally(() => { + if (options.signal && listener) options.signal.removeEventListener("abort", listener); + }); + } + return this.call(callable, ...args); + } + fetch(...args) { + return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); + } +}; + +//#endregion + +//# sourceMappingURL=async_caller.js.map +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/core.js +/** A special constant with type `never` */ +const NEVER = Object.freeze({ + status: "aborted", +}); +function $constructor(name, initializer, params) { + function init(inst, def) { + if (!inst._zod) { + Object.defineProperty(inst, "_zod", { + value: { + def, + constr: _, + traits: new Set(), + }, + enumerable: false, + }); + } + if (inst._zod.traits.has(name)) { + return; + } + inst._zod.traits.add(name); + initializer(inst, def); + // support prototype modifications + const proto = _.prototype; + const keys = Object.keys(proto); + for (let i = 0; i < keys.length; i++) { + const k = keys[i]; + if (!(k in inst)) { + inst[k] = proto[k].bind(inst); + } + } + } + // doesn't work if Parent has a constructor with arguments + const Parent = params?.Parent ?? Object; + class Definition extends Parent { + } + Object.defineProperty(Definition, "name", { value: name }); + function _(def) { + var _a; + const inst = params?.Parent ? new Definition() : this; + init(inst, def); + (_a = inst._zod).deferred ?? (_a.deferred = []); + for (const fn of inst._zod.deferred) { + fn(); + } + return inst; + } + Object.defineProperty(_, "init", { value: init }); + Object.defineProperty(_, Symbol.hasInstance, { + value: (inst) => { + if (params?.Parent && inst instanceof params.Parent) + return true; + return inst?._zod?.traits?.has(name); + }, + }); + Object.defineProperty(_, "name", { value: name }); + return _; +} +////////////////////////////// UTILITIES /////////////////////////////////////// +const $brand = Symbol("zod_brand"); +class $ZodAsyncError extends Error { + constructor() { + super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); + } +} +class $ZodEncodeError extends Error { + constructor(name) { + super(`Encountered unidirectional transform during encode: ${name}`); + this.name = "ZodEncodeError"; + } +} +const globalConfig = {}; +function config(newConfig) { + if (newConfig) + Object.assign(globalConfig, newConfig); + return globalConfig; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/util.js +// functions +function assertEqual(val) { + return val; +} +function assertNotEqual(val) { + return val; +} +function assertIs(_arg) { } +function assertNever(_x) { + throw new Error("Unexpected value in exhaustive check"); +} +function assert(_) { } +function getEnumValues(entries) { + const numericValues = Object.values(entries).filter((v) => typeof v === "number"); + const values = Object.entries(entries) + .filter(([k, _]) => numericValues.indexOf(+k) === -1) + .map(([_, v]) => v); + return values; +} +function joinValues(array, separator = "|") { + return array.map((val) => stringifyPrimitive(val)).join(separator); +} +function jsonStringifyReplacer(_, value) { + if (typeof value === "bigint") + return value.toString(); + return value; +} +function cached(getter) { + const set = false; + return { + get value() { + if (!set) { + const value = getter(); + Object.defineProperty(this, "value", { value }); + return value; + } + throw new Error("cached value already set"); + }, + }; +} +function nullish(input) { + return input === null || input === undefined; +} +function cleanRegex(source) { + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + return source.slice(start, end); +} +function floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepString = step.toString(); + let stepDecCount = (stepString.split(".")[1] || "").length; + if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { + const match = stepString.match(/\d?e-(\d?)/); + if (match?.[1]) { + stepDecCount = Number.parseInt(match[1]); + } + } + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; +} +const EVALUATING = Symbol("evaluating"); +function defineLazy(object, key, getter) { + let value = undefined; + Object.defineProperty(object, key, { + get() { + if (value === EVALUATING) { + // Circular reference detected, return undefined to break the cycle + return undefined; + } + if (value === undefined) { + value = EVALUATING; + value = getter(); + } + return value; + }, + set(v) { + Object.defineProperty(object, key, { + value: v, + // configurable: true, + }); + // object[key] = v; + }, + configurable: true, + }); +} +function objectClone(obj) { + return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); +} +function assignProp(target, prop, value) { + Object.defineProperty(target, prop, { + value, + writable: true, + enumerable: true, + configurable: true, + }); +} +function mergeDefs(...defs) { + const mergedDescriptors = {}; + for (const def of defs) { + const descriptors = Object.getOwnPropertyDescriptors(def); + Object.assign(mergedDescriptors, descriptors); + } + return Object.defineProperties({}, mergedDescriptors); +} +function cloneDef(schema) { + return mergeDefs(schema._zod.def); +} +function getElementAtPath(obj, path) { + if (!path) + return obj; + return path.reduce((acc, key) => acc?.[key], obj); +} +function promiseAllObject(promisesObj) { + const keys = Object.keys(promisesObj); + const promises = keys.map((key) => promisesObj[key]); + return Promise.all(promises).then((results) => { + const resolvedObj = {}; + for (let i = 0; i < keys.length; i++) { + resolvedObj[keys[i]] = results[i]; + } + return resolvedObj; + }); +} +function randomString(length = 10) { + const chars = "abcdefghijklmnopqrstuvwxyz"; + let str = ""; + for (let i = 0; i < length; i++) { + str += chars[Math.floor(Math.random() * chars.length)]; + } + return str; +} +function esc(str) { + return JSON.stringify(str); +} +function slugify(input) { + return input + .toLowerCase() + .trim() + .replace(/[^\w\s-]/g, "") + .replace(/[\s_-]+/g, "-") + .replace(/^-+|-+$/g, ""); +} +const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); +function util_isObject(data) { + return typeof data === "object" && data !== null && !Array.isArray(data); +} +const util_allowsEval = cached(() => { + // @ts-ignore + if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { + return false; + } + try { + const F = Function; + new F(""); + return true; + } + catch (_) { + return false; + } +}); +function isPlainObject(o) { + if (util_isObject(o) === false) + return false; + // modified constructor + const ctor = o.constructor; + if (ctor === undefined) + return true; + if (typeof ctor !== "function") + return true; + // modified prototype + const prot = ctor.prototype; + if (util_isObject(prot) === false) + return false; + // ctor doesn't have static `isPrototypeOf` + if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { + return false; + } + return true; +} +function shallowClone(o) { + if (isPlainObject(o)) + return { ...o }; + if (Array.isArray(o)) + return [...o]; + return o; +} +function numKeys(data) { + let keyCount = 0; + for (const key in data) { + if (Object.prototype.hasOwnProperty.call(data, key)) { + keyCount++; + } + } + return keyCount; +} +const getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return "undefined"; + case "string": + return "string"; + case "number": + return Number.isNaN(data) ? "nan" : "number"; + case "boolean": + return "boolean"; + case "function": + return "function"; + case "bigint": + return "bigint"; + case "symbol": + return "symbol"; + case "object": + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return "promise"; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return "map"; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return "set"; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return "date"; + } + // @ts-ignore + if (typeof File !== "undefined" && data instanceof File) { + return "file"; + } + return "object"; + default: + throw new Error(`Unknown data type: ${t}`); + } +}; +const propertyKeyTypes = new Set(["string", "number", "symbol"]); +const primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); +function escapeRegex(str) { + return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); +} +// zod-specific utils +function clone(inst, def, params) { + const cl = new inst._zod.constr(def ?? inst._zod.def); + if (!def || params?.parent) + cl._zod.parent = inst; + return cl; +} +function normalizeParams(_params) { + const params = _params; + if (!params) + return {}; + if (typeof params === "string") + return { error: () => params }; + if (params?.message !== undefined) { + if (params?.error !== undefined) + throw new Error("Cannot specify both `message` and `error` params"); + params.error = params.message; + } + delete params.message; + if (typeof params.error === "string") + return { ...params, error: () => params.error }; + return params; +} +function createTransparentProxy(getter) { + let target; + return new Proxy({}, { + get(_, prop, receiver) { + target ?? (target = getter()); + return Reflect.get(target, prop, receiver); + }, + set(_, prop, value, receiver) { + target ?? (target = getter()); + return Reflect.set(target, prop, value, receiver); + }, + has(_, prop) { + target ?? (target = getter()); + return Reflect.has(target, prop); + }, + deleteProperty(_, prop) { + target ?? (target = getter()); + return Reflect.deleteProperty(target, prop); + }, + ownKeys(_) { + target ?? (target = getter()); + return Reflect.ownKeys(target); + }, + getOwnPropertyDescriptor(_, prop) { + target ?? (target = getter()); + return Reflect.getOwnPropertyDescriptor(target, prop); + }, + defineProperty(_, prop, descriptor) { + target ?? (target = getter()); + return Reflect.defineProperty(target, prop, descriptor); + }, + }); +} +function stringifyPrimitive(value) { + if (typeof value === "bigint") + return value.toString() + "n"; + if (typeof value === "string") + return `"${value}"`; + return `${value}`; +} +function optionalKeys(shape) { + return Object.keys(shape).filter((k) => { + return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; + }); +} +const NUMBER_FORMAT_RANGES = { + safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], + int32: [-2147483648, 2147483647], + uint32: [0, 4294967295], + float32: [-3.4028234663852886e38, 3.4028234663852886e38], + float64: [-Number.MAX_VALUE, Number.MAX_VALUE], +}; +const BIGINT_FORMAT_RANGES = { + int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], + uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], +}; +function pick(schema, mask) { + const currDef = schema._zod.def; + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = {}; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + newShape[key] = currDef.shape[key]; + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function omit(schema, mask) { + const currDef = schema._zod.def; + const def = mergeDefs(schema._zod.def, { + get shape() { + const newShape = { ...schema._zod.def.shape }; + for (const key in mask) { + if (!(key in currDef.shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + delete newShape[key]; + } + assignProp(this, "shape", newShape); // self-caching + return newShape; + }, + checks: [], + }); + return clone(schema, def); +} +function extend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to extend: expected a plain object"); + } + const checks = schema._zod.def.checks; + const hasChecks = checks && checks.length > 0; + if (hasChecks) { + throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead."); + } + const def = mergeDefs(schema._zod.def, { + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + checks: [], + }); + return clone(schema, def); +} +function safeExtend(schema, shape) { + if (!isPlainObject(shape)) { + throw new Error("Invalid input to safeExtend: expected a plain object"); + } + const def = { + ...schema._zod.def, + get shape() { + const _shape = { ...schema._zod.def.shape, ...shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + checks: schema._zod.def.checks, + }; + return clone(schema, def); +} +function merge(a, b) { + const def = mergeDefs(a._zod.def, { + get shape() { + const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; + assignProp(this, "shape", _shape); // self-caching + return _shape; + }, + get catchall() { + return b._zod.def.catchall; + }, + checks: [], // delete existing checks + }); + return clone(a, def); +} +function partial(Class, schema, mask) { + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in oldShape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + else { + for (const key in oldShape) { + // if (oldShape[key]!._zod.optin === "optional") continue; + shape[key] = Class + ? new Class({ + type: "optional", + innerType: oldShape[key], + }) + : oldShape[key]; + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + checks: [], + }); + return clone(schema, def); +} +function required(Class, schema, mask) { + const def = mergeDefs(schema._zod.def, { + get shape() { + const oldShape = schema._zod.def.shape; + const shape = { ...oldShape }; + if (mask) { + for (const key in mask) { + if (!(key in shape)) { + throw new Error(`Unrecognized key: "${key}"`); + } + if (!mask[key]) + continue; + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + else { + for (const key in oldShape) { + // overwrite with non-optional + shape[key] = new Class({ + type: "nonoptional", + innerType: oldShape[key], + }); + } + } + assignProp(this, "shape", shape); // self-caching + return shape; + }, + checks: [], + }); + return clone(schema, def); +} +// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom +function aborted(x, startIndex = 0) { + if (x.aborted === true) + return true; + for (let i = startIndex; i < x.issues.length; i++) { + if (x.issues[i]?.continue !== true) { + return true; + } + } + return false; +} +function prefixIssues(path, issues) { + return issues.map((iss) => { + var _a; + (_a = iss).path ?? (_a.path = []); + iss.path.unshift(path); + return iss; + }); +} +function unwrapMessage(message) { + return typeof message === "string" ? message : message?.message; +} +function finalizeIssue(iss, ctx, config) { + const full = { ...iss, path: iss.path ?? [] }; + // for backwards compatibility + if (!iss.message) { + const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? + unwrapMessage(ctx?.error?.(iss)) ?? + unwrapMessage(config.customError?.(iss)) ?? + unwrapMessage(config.localeError?.(iss)) ?? + "Invalid input"; + full.message = message; + } + // delete (full as any).def; + delete full.inst; + delete full.continue; + if (!ctx?.reportInput) { + delete full.input; + } + return full; +} +function getSizableOrigin(input) { + if (input instanceof Set) + return "set"; + if (input instanceof Map) + return "map"; + // @ts-ignore + if (input instanceof File) + return "file"; + return "unknown"; +} +function getLengthableOrigin(input) { + if (Array.isArray(input)) + return "array"; + if (typeof input === "string") + return "string"; + return "unknown"; +} +function util_issue(...args) { + const [iss, input, inst] = args; + if (typeof iss === "string") { + return { + message: iss, + code: "custom", + input, + inst, + }; + } + return { ...iss }; +} +function cleanEnum(obj) { + return Object.entries(obj) + .filter(([k, _]) => { + // return true if NaN, meaning it's not a number, thus a string key + return Number.isNaN(Number.parseInt(k, 10)); + }) + .map((el) => el[1]); +} +// Codec utility functions +function base64ToUint8Array(base64) { + const binaryString = atob(base64); + const bytes = new Uint8Array(binaryString.length); + for (let i = 0; i < binaryString.length; i++) { + bytes[i] = binaryString.charCodeAt(i); + } + return bytes; +} +function uint8ArrayToBase64(bytes) { + let binaryString = ""; + for (let i = 0; i < bytes.length; i++) { + binaryString += String.fromCharCode(bytes[i]); + } + return btoa(binaryString); +} +function base64urlToUint8Array(base64url) { + const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); + const padding = "=".repeat((4 - (base64.length % 4)) % 4); + return base64ToUint8Array(base64 + padding); +} +function uint8ArrayToBase64url(bytes) { + return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); +} +function hexToUint8Array(hex) { + const cleanHex = hex.replace(/^0x/, ""); + if (cleanHex.length % 2 !== 0) { + throw new Error("Invalid hex string length"); + } + const bytes = new Uint8Array(cleanHex.length / 2); + for (let i = 0; i < cleanHex.length; i += 2) { + bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); + } + return bytes; +} +function uint8ArrayToHex(bytes) { + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, "0")) + .join(""); +} +// instanceof +class Class { + constructor(..._args) { } +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/errors.js + + +const initializer = (inst, def) => { + inst.name = "$ZodError"; + Object.defineProperty(inst, "_zod", { + value: inst._zod, + enumerable: false, + }); + Object.defineProperty(inst, "issues", { + value: def, + enumerable: false, + }); + inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); + Object.defineProperty(inst, "toString", { + value: () => inst.message, + enumerable: false, + }); +}; +const $ZodError = $constructor("$ZodError", initializer); +const $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); +function flattenError(error, mapper = (issue) => issue.message) { + const fieldErrors = {}; + const formErrors = []; + for (const sub of error.issues) { + if (sub.path.length > 0) { + fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; + fieldErrors[sub.path[0]].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; +} +function formatError(error, mapper = (issue) => issue.message) { + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + issue.errors.map((issues) => processError({ issues })); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(error); + return fieldErrors; +} +function treeifyError(error, mapper = (issue) => issue.message) { + const result = { errors: [] }; + const processError = (error, path = []) => { + var _a, _b; + for (const issue of error.issues) { + if (issue.code === "invalid_union" && issue.errors.length) { + // regular union error + issue.errors.map((issues) => processError({ issues }, issue.path)); + } + else if (issue.code === "invalid_key") { + processError({ issues: issue.issues }, issue.path); + } + else if (issue.code === "invalid_element") { + processError({ issues: issue.issues }, issue.path); + } + else { + const fullpath = [...path, ...issue.path]; + if (fullpath.length === 0) { + result.errors.push(mapper(issue)); + continue; + } + let curr = result; + let i = 0; + while (i < fullpath.length) { + const el = fullpath[i]; + const terminal = i === fullpath.length - 1; + if (typeof el === "string") { + curr.properties ?? (curr.properties = {}); + (_a = curr.properties)[el] ?? (_a[el] = { errors: [] }); + curr = curr.properties[el]; + } + else { + curr.items ?? (curr.items = []); + (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); + curr = curr.items[el]; + } + if (terminal) { + curr.errors.push(mapper(issue)); + } + i++; + } + } + } + }; + processError(error); + return result; +} +/** Format a ZodError as a human-readable string in the following form. + * + * From + * + * ```ts + * ZodError { + * issues: [ + * { + * expected: 'string', + * code: 'invalid_type', + * path: [ 'username' ], + * message: 'Invalid input: expected string' + * }, + * { + * expected: 'number', + * code: 'invalid_type', + * path: [ 'favoriteNumbers', 1 ], + * message: 'Invalid input: expected number' + * } + * ]; + * } + * ``` + * + * to + * + * ``` + * username + * ✖ Expected number, received string at "username + * favoriteNumbers[0] + * ✖ Invalid input: expected number + * ``` + */ +function toDotPath(_path) { + const segs = []; + const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); + for (const seg of path) { + if (typeof seg === "number") + segs.push(`[${seg}]`); + else if (typeof seg === "symbol") + segs.push(`[${JSON.stringify(String(seg))}]`); + else if (/[^\w$]/.test(seg)) + segs.push(`[${JSON.stringify(seg)}]`); + else { + if (segs.length) + segs.push("."); + segs.push(seg); + } + } + return segs.join(""); +} +function prettifyError(error) { + const lines = []; + // sort by path length + const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); + // Process each issue + for (const issue of issues) { + lines.push(`✖ ${issue.message}`); + if (issue.path?.length) + lines.push(` → at ${toDotPath(issue.path)}`); + } + // Convert Map to formatted string + return lines.join("\n"); +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/parse.js + + + +const _parse = (_Err) => (schema, value, _ctx, _params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + if (result.issues.length) { + const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, _params?.callee); + throw e; + } + return result.value; +}; +const parse_parse = /* @__PURE__*/ _parse($ZodRealError); +const _parseAsync = (_Err) => async (schema, value, _ctx, params) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + if (result.issues.length) { + const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); + captureStackTrace(e, params?.callee); + throw e; + } + return result.value; +}; +const parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError); +const _safeParse = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; + const result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) { + throw new $ZodAsyncError(); + } + return result.issues.length + ? { + success: false, + error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), + } + : { success: true, data: result.value }; +}; +const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); +const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; + let result = schema._zod.run({ value, issues: [] }, ctx); + if (result instanceof Promise) + result = await result; + return result.issues.length + ? { + success: false, + error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), + } + : { success: true, data: result.value }; +}; +const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); +const _encode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _parse(_Err)(schema, value, ctx); +}; +const encode = /* @__PURE__*/ _encode($ZodRealError); +const _decode = (_Err) => (schema, value, _ctx) => { + return _parse(_Err)(schema, value, _ctx); +}; +const decode = /* @__PURE__*/ _decode($ZodRealError); +const _encodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _parseAsync(_Err)(schema, value, ctx); +}; +const encodeAsync = /* @__PURE__*/ _encodeAsync($ZodRealError); +const _decodeAsync = (_Err) => async (schema, value, _ctx) => { + return _parseAsync(_Err)(schema, value, _ctx); +}; +const decodeAsync = /* @__PURE__*/ _decodeAsync($ZodRealError); +const _safeEncode = (_Err) => (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _safeParse(_Err)(schema, value, ctx); +}; +const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); +const _safeDecode = (_Err) => (schema, value, _ctx) => { + return _safeParse(_Err)(schema, value, _ctx); +}; +const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); +const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { + const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; + return _safeParseAsync(_Err)(schema, value, ctx); +}; +const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); +const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { + return _safeParseAsync(_Err)(schema, value, _ctx); +}; +const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/regexes.js + +const cuid = /^[cC][^\s-]{8,}$/; +const cuid2 = /^[0-9a-z]+$/; +const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; +const xid = /^[0-9a-vA-V]{20}$/; +const ksuid = /^[A-Za-z0-9]{27}$/; +const nanoid = /^[a-zA-Z0-9_-]{21}$/; +/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ +const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; +/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ +const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ +const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; +/** Returns a regex for validating an RFC 9562/4122 UUID. + * + * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ +const uuid = (version) => { + if (!version) + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; + return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); +}; +const uuid4 = /*@__PURE__*/ uuid(4); +const regexes_uuid6 = /*@__PURE__*/ uuid(6); +const regexes_uuid7 = /*@__PURE__*/ uuid(7); +/** Practical email validation */ +const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; +/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ +const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +/** The classic emailregex.com regex for RFC 5322-compliant emails */ +const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; +/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ +const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; +const idnEmail = unicodeEmail; +const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +function emoji() { + return new RegExp(_emoji, "u"); +} +const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; +const mac = (delimiter) => { + const escapedDelim = escapeRegex(delimiter ?? ":"); + return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); +}; +const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; +const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; +const base64url = /^[A-Za-z0-9_-]*$/; +// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address +// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; +const hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; +const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; +// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) +const e164 = /^\+(?:[0-9]){6,14}[0-9]$/; +// const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; +const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`); +function timeSource(args) { + const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; + const regex = typeof args.precision === "number" + ? args.precision === -1 + ? `${hhmm}` + : args.precision === 0 + ? `${hhmm}:[0-5]\\d` + : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` + : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; + return regex; +} +function time(args) { + return new RegExp(`^${timeSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +function datetime(args) { + const time = timeSource({ precision: args.precision }); + const opts = ["Z"]; + if (args.local) + opts.push(""); + // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); + if (args.offset) + opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); + const timeRegex = `${time}(?:${opts.join("|")})`; + return new RegExp(`^${dateSource}T(?:${timeRegex})$`); +} +const string = (params) => { + const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; + return new RegExp(`^${regex}$`); +}; +const bigint = /^-?\d+n?$/; +const integer = /^-?\d+$/; +const number = /^-?\d+(?:\.\d+)?/; +const regexes_boolean = /^(?:true|false)$/i; +const _null = /^null$/i; + +const _undefined = /^undefined$/i; + +// regex for string with no uppercase letters +const lowercase = /^[^A-Z]*$/; +// regex for string with no lowercase letters +const uppercase = /^[^a-z]*$/; +// regex for hexadecimal strings (any length) +const hex = /^[0-9a-fA-F]*$/; +// Hash regexes for different algorithms and encodings +// Helper function to create base64 regex with exact length and padding +function fixedBase64(bodyLength, padding) { + return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); +} +// Helper function to create base64url regex with exact length (no padding) +function fixedBase64url(length) { + return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); +} +// MD5 (16 bytes): base64 = 24 chars total (22 + "==") +const md5_hex = /^[0-9a-fA-F]{32}$/; +const md5_base64 = /*@__PURE__*/ fixedBase64(22, "=="); +const md5_base64url = /*@__PURE__*/ fixedBase64url(22); +// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") +const sha1_hex = /^[0-9a-fA-F]{40}$/; +const sha1_base64 = /*@__PURE__*/ fixedBase64(27, "="); +const sha1_base64url = /*@__PURE__*/ fixedBase64url(27); +// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") +const sha256_hex = /^[0-9a-fA-F]{64}$/; +const sha256_base64 = /*@__PURE__*/ fixedBase64(43, "="); +const sha256_base64url = /*@__PURE__*/ fixedBase64url(43); +// SHA384 (48 bytes): base64 = 64 chars total (no padding) +const sha384_hex = /^[0-9a-fA-F]{96}$/; +const sha384_base64 = /*@__PURE__*/ fixedBase64(64, ""); +const sha384_base64url = /*@__PURE__*/ fixedBase64url(64); +// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") +const sha512_hex = /^[0-9a-fA-F]{128}$/; +const sha512_base64 = /*@__PURE__*/ fixedBase64(86, "=="); +const sha512_base64url = /*@__PURE__*/ fixedBase64url(86); + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/checks.js +// import { $ZodType } from "./schemas.js"; + + + +const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { + var _a; + inst._zod ?? (inst._zod = {}); + inst._zod.def = def; + (_a = inst._zod).onattach ?? (_a.onattach = []); +}); +const numericOriginMap = { + number: "number", + bigint: "bigint", + object: "date", +}; +const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; + if (def.value < curr) { + if (def.inclusive) + bag.maximum = def.value; + else + bag.exclusiveMaximum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { + return; + } + payload.issues.push({ + origin, + code: "too_big", + maximum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { + $ZodCheck.init(inst, def); + const origin = numericOriginMap[typeof def.value]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; + if (def.value > curr) { + if (def.inclusive) + bag.minimum = def.value; + else + bag.exclusiveMinimum = def.value; + } + }); + inst._zod.check = (payload) => { + if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { + return; + } + payload.issues.push({ + origin, + code: "too_small", + minimum: def.value, + input: payload.value, + inclusive: def.inclusive, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMultipleOf = +/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + var _a; + (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); + }); + inst._zod.check = (payload) => { + if (typeof payload.value !== typeof def.value) + throw new Error("Cannot mix number and bigint in multiple_of check."); + const isMultiple = typeof payload.value === "bigint" + ? payload.value % def.value === BigInt(0) + : floatSafeRemainder(payload.value, def.value) === 0; + if (isMultiple) + return; + payload.issues.push({ + origin: typeof payload.value, + code: "not_multiple_of", + divisor: def.value, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + def.format = def.format || "float64"; + const isInt = def.format?.includes("int"); + const origin = isInt ? "int" : "number"; + const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + if (isInt) + bag.pattern = integer; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (isInt) { + if (!Number.isInteger(input)) { + // invalid_format issue + // payload.issues.push({ + // expected: def.format, + // format: def.format, + // code: "invalid_format", + // input, + // inst, + // }); + // invalid_type issue + payload.issues.push({ + expected: origin, + format: def.format, + code: "invalid_type", + continue: false, + input, + inst, + }); + return; + // not_multiple_of issue + // payload.issues.push({ + // code: "not_multiple_of", + // origin: "number", + // input, + // inst, + // divisor: 1, + // }); + } + if (!Number.isSafeInteger(input)) { + if (input > 0) { + // too_big + payload.issues.push({ + input, + code: "too_big", + maximum: Number.MAX_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort, + }); + } + else { + // too_small + payload.issues.push({ + input, + code: "too_small", + minimum: Number.MIN_SAFE_INTEGER, + note: "Integers must be within the safe integer range.", + inst, + origin, + continue: !def.abort, + }); + } + return; + } + } + if (input < minimum) { + payload.issues.push({ + origin: "number", + input, + code: "too_small", + minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "number", + input, + code: "too_big", + maximum, + inst, + }); + } + }; +}); +const $ZodCheckBigIntFormat = /*@__PURE__*/ $constructor("$ZodCheckBigIntFormat", (inst, def) => { + $ZodCheck.init(inst, def); // no format checks + const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + bag.minimum = minimum; + bag.maximum = maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + if (input < minimum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_small", + minimum: minimum, + inclusive: true, + inst, + continue: !def.abort, + }); + } + if (input > maximum) { + payload.issues.push({ + origin: "bigint", + input, + code: "too_big", + maximum, + inst, + }); + } + }; +}); +const $ZodCheckMaxSize = /*@__PURE__*/ $constructor("$ZodCheckMaxSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== undefined; + }); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size <= def.maximum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMinSize = /*@__PURE__*/ $constructor("$ZodCheckMinSize", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== undefined; + }); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size >= def.minimum) + return; + payload.issues.push({ + origin: getSizableOrigin(input), + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckSizeEquals = /*@__PURE__*/ $constructor("$ZodCheckSizeEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.size !== undefined; + }); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.size; + bag.maximum = def.size; + bag.size = def.size; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const size = input.size; + if (size === def.size) + return; + const tooBig = size > def.size; + payload.issues.push({ + origin: getSizableOrigin(input), + ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== undefined; + }); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); + if (def.maximum < curr) + inst._zod.bag.maximum = def.maximum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length <= def.maximum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_big", + maximum: def.maximum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== undefined; + }); + inst._zod.onattach.push((inst) => { + const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); + if (def.minimum > curr) + inst._zod.bag.minimum = def.minimum; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length >= def.minimum) + return; + const origin = getLengthableOrigin(input); + payload.issues.push({ + origin, + code: "too_small", + minimum: def.minimum, + inclusive: true, + input, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { + var _a; + $ZodCheck.init(inst, def); + (_a = inst._zod.def).when ?? (_a.when = (payload) => { + const val = payload.value; + return !nullish(val) && val.length !== undefined; + }); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.minimum = def.length; + bag.maximum = def.length; + bag.length = def.length; + }); + inst._zod.check = (payload) => { + const input = payload.value; + const length = input.length; + if (length === def.length) + return; + const origin = getLengthableOrigin(input); + const tooBig = length > def.length; + payload.issues.push({ + origin, + ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), + inclusive: true, + exact: true, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { + var _a, _b; + $ZodCheck.init(inst, def); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.format = def.format; + if (def.pattern) { + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(def.pattern); + } + }); + if (def.pattern) + (_a = inst._zod).check ?? (_a.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: def.format, + input: payload.value, + ...(def.pattern ? { pattern: def.pattern.toString() } : {}), + inst, + continue: !def.abort, + }); + }); + else + (_b = inst._zod).check ?? (_b.check = () => { }); +}); +const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { + $ZodCheckStringFormat.init(inst, def); + inst._zod.check = (payload) => { + def.pattern.lastIndex = 0; + if (def.pattern.test(payload.value)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "regex", + input: payload.value, + pattern: def.pattern.toString(), + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { + def.pattern ?? (def.pattern = lowercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { + def.pattern ?? (def.pattern = uppercase); + $ZodCheckStringFormat.init(inst, def); +}); +const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { + $ZodCheck.init(inst, def); + const escapedRegex = escapeRegex(def.includes); + const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); + def.pattern = pattern; + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.includes(def.includes, def.position)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "includes", + includes: def.includes, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.startsWith(def.prefix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "starts_with", + prefix: def.prefix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { + $ZodCheck.init(inst, def); + const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); + def.pattern ?? (def.pattern = pattern); + inst._zod.onattach.push((inst) => { + const bag = inst._zod.bag; + bag.patterns ?? (bag.patterns = new Set()); + bag.patterns.add(pattern); + }); + inst._zod.check = (payload) => { + if (payload.value.endsWith(def.suffix)) + return; + payload.issues.push({ + origin: "string", + code: "invalid_format", + format: "ends_with", + suffix: def.suffix, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +/////////////////////////////////// +///// $ZodCheckProperty ///// +/////////////////////////////////// +function handleCheckPropertyResult(result, payload, property) { + if (result.issues.length) { + payload.issues.push(...prefixIssues(property, result.issues)); + } +} +const $ZodCheckProperty = /*@__PURE__*/ $constructor("$ZodCheckProperty", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + const result = def.schema._zod.run({ + value: payload.value[def.property], + issues: [], + }, {}); + if (result instanceof Promise) { + return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); + } + handleCheckPropertyResult(result, payload, def.property); + return; + }; +}); +const $ZodCheckMimeType = /*@__PURE__*/ $constructor("$ZodCheckMimeType", (inst, def) => { + $ZodCheck.init(inst, def); + const mimeSet = new Set(def.mime); + inst._zod.onattach.push((inst) => { + inst._zod.bag.mime = def.mime; + }); + inst._zod.check = (payload) => { + if (mimeSet.has(payload.value.type)) + return; + payload.issues.push({ + code: "invalid_value", + values: def.mime, + input: payload.value.type, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { + $ZodCheck.init(inst, def); + inst._zod.check = (payload) => { + payload.value = def.tx(payload.value); + }; +}); + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/doc.js +class Doc { + constructor(args = []) { + this.content = []; + this.indent = 0; + if (this) + this.args = args; + } + indented(fn) { + this.indent += 1; + fn(this); + this.indent -= 1; + } + write(arg) { + if (typeof arg === "function") { + arg(this, { execution: "sync" }); + arg(this, { execution: "async" }); + return; + } + const content = arg; + const lines = content.split("\n").filter((x) => x); + const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); + const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); + for (const line of dedented) { + this.content.push(line); + } + } + compile() { + const F = Function; + const args = this?.args; + const content = this?.content ?? [``]; + const lines = [...content.map((x) => ` ${x}`)]; + // console.log(lines.join("\n")); + return new F(...args, lines.join("\n")); + } +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/versions.js +const versions_version = { + major: 4, + minor: 2, + patch: 1, +}; + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/schemas.js + + + + + + + +const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { + var _a; + inst ?? (inst = {}); + inst._zod.def = def; // set _def property + inst._zod.bag = inst._zod.bag || {}; // initialize _bag object + inst._zod.version = versions_version; + const checks = [...(inst._zod.def.checks ?? [])]; + // if inst is itself a checks.$ZodCheck, run it as a check + if (inst._zod.traits.has("$ZodCheck")) { + checks.unshift(inst); + } + for (const ch of checks) { + for (const fn of ch._zod.onattach) { + fn(inst); + } + } + if (checks.length === 0) { + // deferred initializer + // inst._zod.parse is not yet defined + (_a = inst._zod).deferred ?? (_a.deferred = []); + inst._zod.deferred?.push(() => { + inst._zod.run = inst._zod.parse; + }); + } + else { + const runChecks = (payload, checks, ctx) => { + let isAborted = aborted(payload); + let asyncResult; + for (const ch of checks) { + if (ch._zod.def.when) { + const shouldRun = ch._zod.def.when(payload); + if (!shouldRun) + continue; + } + else if (isAborted) { + continue; + } + const currLen = payload.issues.length; + const _ = ch._zod.check(payload); + if (_ instanceof Promise && ctx?.async === false) { + throw new $ZodAsyncError(); + } + if (asyncResult || _ instanceof Promise) { + asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { + await _; + const nextLen = payload.issues.length; + if (nextLen === currLen) + return; + if (!isAborted) + isAborted = aborted(payload, currLen); + }); + } + else { + const nextLen = payload.issues.length; + if (nextLen === currLen) + continue; + if (!isAborted) + isAborted = aborted(payload, currLen); + } + } + if (asyncResult) { + return asyncResult.then(() => { + return payload; + }); + } + return payload; + }; + const handleCanaryResult = (canary, payload, ctx) => { + // abort if the canary is aborted + if (aborted(canary)) { + canary.aborted = true; + return canary; + } + // run checks first, then + const checkResult = runChecks(payload, checks, ctx); + if (checkResult instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); + } + return inst._zod.parse(checkResult, ctx); + }; + inst._zod.run = (payload, ctx) => { + if (ctx.skipChecks) { + return inst._zod.parse(payload, ctx); + } + if (ctx.direction === "backward") { + // run canary + // initial pass (no checks) + const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); + if (canary instanceof Promise) { + return canary.then((canary) => { + return handleCanaryResult(canary, payload, ctx); + }); + } + return handleCanaryResult(canary, payload, ctx); + } + // forward + const result = inst._zod.parse(payload, ctx); + if (result instanceof Promise) { + if (ctx.async === false) + throw new $ZodAsyncError(); + return result.then((result) => runChecks(result, checks, ctx)); + } + return runChecks(result, checks, ctx); + }; + } + inst["~standard"] = { + validate: (value) => { + try { + const r = safeParse(inst, value); + return r.success ? { value: r.data } : { issues: r.error?.issues }; + } + catch (_) { + return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues })); + } + }, + vendor: "zod", + version: 1, + }; +}); + +const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string(inst._zod.bag); + inst._zod.parse = (payload, _) => { + if (def.coerce) + try { + payload.value = String(payload.value); + } + catch (_) { } + if (typeof payload.value === "string") + return payload; + payload.issues.push({ + expected: "string", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { + // check initialization must come first + $ZodCheckStringFormat.init(inst, def); + $ZodString.init(inst, def); +}); +const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { + def.pattern ?? (def.pattern = guid); + $ZodStringFormat.init(inst, def); +}); +const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { + if (def.version) { + const versionMap = { + v1: 1, + v2: 2, + v3: 3, + v4: 4, + v5: 5, + v6: 6, + v7: 7, + v8: 8, + }; + const v = versionMap[def.version]; + if (v === undefined) + throw new Error(`Invalid UUID version: "${def.version}"`); + def.pattern ?? (def.pattern = uuid(v)); + } + else + def.pattern ?? (def.pattern = uuid()); + $ZodStringFormat.init(inst, def); +}); +const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { + def.pattern ?? (def.pattern = email); + $ZodStringFormat.init(inst, def); +}); +const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + try { + // Trim whitespace from input + const trimmed = payload.value.trim(); + // @ts-ignore + const url = new URL(trimmed); + if (def.hostname) { + def.hostname.lastIndex = 0; + if (!def.hostname.test(url.hostname)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid hostname", + pattern: def.hostname.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + } + if (def.protocol) { + def.protocol.lastIndex = 0; + if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { + payload.issues.push({ + code: "invalid_format", + format: "url", + note: "Invalid protocol", + pattern: def.protocol.source, + input: payload.value, + inst, + continue: !def.abort, + }); + } + } + // Set the output value based on normalize flag + if (def.normalize) { + // Use normalized URL + payload.value = url.href; + } + else { + // Preserve the original input (trimmed) + payload.value = trimmed; + } + return; + } + catch (_) { + payload.issues.push({ + code: "invalid_format", + format: "url", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { + def.pattern ?? (def.pattern = emoji()); + $ZodStringFormat.init(inst, def); +}); +const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { + def.pattern ?? (def.pattern = nanoid); + $ZodStringFormat.init(inst, def); +}); +const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { + def.pattern ?? (def.pattern = cuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { + def.pattern ?? (def.pattern = cuid2); + $ZodStringFormat.init(inst, def); +}); +const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { + def.pattern ?? (def.pattern = ulid); + $ZodStringFormat.init(inst, def); +}); +const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { + def.pattern ?? (def.pattern = xid); + $ZodStringFormat.init(inst, def); +}); +const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { + def.pattern ?? (def.pattern = ksuid); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { + def.pattern ?? (def.pattern = datetime(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { + def.pattern ?? (def.pattern = date); + $ZodStringFormat.init(inst, def); +}); +const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { + def.pattern ?? (def.pattern = time(def)); + $ZodStringFormat.init(inst, def); +}); +const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { + def.pattern ?? (def.pattern = duration); + $ZodStringFormat.init(inst, def); +}); +const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { + def.pattern ?? (def.pattern = ipv4); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv4`; +}); +const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { + def.pattern ?? (def.pattern = ipv6); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `ipv6`; + inst._zod.check = (payload) => { + try { + // @ts-ignore + new URL(`http://[${payload.value}]`); + // return; + } + catch { + payload.issues.push({ + code: "invalid_format", + format: "ipv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +const $ZodMAC = /*@__PURE__*/ $constructor("$ZodMAC", (inst, def) => { + def.pattern ?? (def.pattern = mac(def.delimiter)); + $ZodStringFormat.init(inst, def); + inst._zod.bag.format = `mac`; +}); +const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { + def.pattern ?? (def.pattern = cidrv4); + $ZodStringFormat.init(inst, def); +}); +const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { + def.pattern ?? (def.pattern = cidrv6); // not used for validation + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + const parts = payload.value.split("/"); + try { + if (parts.length !== 2) + throw new Error(); + const [address, prefix] = parts; + if (!prefix) + throw new Error(); + const prefixNum = Number(prefix); + if (`${prefixNum}` !== prefix) + throw new Error(); + if (prefixNum < 0 || prefixNum > 128) + throw new Error(); + // @ts-ignore + new URL(`http://[${address}]`); + } + catch { + payload.issues.push({ + code: "invalid_format", + format: "cidrv6", + input: payload.value, + inst, + continue: !def.abort, + }); + } + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64(data) { + if (data === "") + return true; + if (data.length % 4 !== 0) + return false; + try { + // @ts-ignore + atob(data); + return true; + } + catch { + return false; + } +} +const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { + def.pattern ?? (def.pattern = base64); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64"; + inst._zod.check = (payload) => { + if (isValidBase64(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +////////////////////////////// ZodBase64 ////////////////////////////// +function isValidBase64URL(data) { + if (!base64url.test(data)) + return false; + const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); + const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); + return isValidBase64(padded); +} +const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { + def.pattern ?? (def.pattern = base64url); + $ZodStringFormat.init(inst, def); + inst._zod.bag.contentEncoding = "base64url"; + inst._zod.check = (payload) => { + if (isValidBase64URL(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: "base64url", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { + def.pattern ?? (def.pattern = e164); + $ZodStringFormat.init(inst, def); +}); +////////////////////////////// ZodJWT ////////////////////////////// +function isValidJWT(token, algorithm = null) { + try { + const tokensParts = token.split("."); + if (tokensParts.length !== 3) + return false; + const [header] = tokensParts; + if (!header) + return false; + // @ts-ignore + const parsedHeader = JSON.parse(atob(header)); + if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") + return false; + if (!parsedHeader.alg) + return false; + if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) + return false; + return true; + } + catch { + return false; + } +} +const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (isValidJWT(payload.value, def.alg)) + return; + payload.issues.push({ + code: "invalid_format", + format: "jwt", + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodCustomStringFormat = /*@__PURE__*/ $constructor("$ZodCustomStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + inst._zod.check = (payload) => { + if (def.fn(payload.value)) + return; + payload.issues.push({ + code: "invalid_format", + format: def.format, + input: payload.value, + inst, + continue: !def.abort, + }); + }; +}); +const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = inst._zod.bag.pattern ?? number; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Number(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { + return payload; + } + const received = typeof input === "number" + ? Number.isNaN(input) + ? "NaN" + : !Number.isFinite(input) + ? "Infinity" + : undefined + : undefined; + payload.issues.push({ + expected: "number", + code: "invalid_type", + input, + inst, + ...(received ? { received } : {}), + }); + return payload; + }; +}); +const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { + $ZodCheckNumberFormat.init(inst, def); + $ZodNumber.init(inst, def); // no format checks +}); +const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = regexes_boolean; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = Boolean(payload.value); + } + catch (_) { } + const input = payload.value; + if (typeof input === "boolean") + return payload; + payload.issues.push({ + expected: "boolean", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodBigInt = /*@__PURE__*/ $constructor("$ZodBigInt", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = bigint; + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) + try { + payload.value = BigInt(payload.value); + } + catch (_) { } + if (typeof payload.value === "bigint") + return payload; + payload.issues.push({ + expected: "bigint", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodBigIntFormat = /*@__PURE__*/ $constructor("$ZodBigIntFormat", (inst, def) => { + $ZodCheckBigIntFormat.init(inst, def); + $ZodBigInt.init(inst, def); // no format checks +}); +const $ZodSymbol = /*@__PURE__*/ $constructor("$ZodSymbol", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "symbol") + return payload; + payload.issues.push({ + expected: "symbol", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodUndefined = /*@__PURE__*/ $constructor("$ZodUndefined", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _undefined; + inst._zod.values = new Set([undefined]); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "undefined", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.pattern = _null; + inst._zod.values = new Set([null]); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (input === null) + return payload; + payload.issues.push({ + expected: "null", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload) => payload; +}); +const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + payload.issues.push({ + expected: "never", + code: "invalid_type", + input: payload.value, + inst, + }); + return payload; + }; +}); +const $ZodVoid = /*@__PURE__*/ $constructor("$ZodVoid", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (typeof input === "undefined") + return payload; + payload.issues.push({ + expected: "void", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodDate = /*@__PURE__*/ $constructor("$ZodDate", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (def.coerce) { + try { + payload.value = new Date(payload.value); + } + catch (_err) { } + } + const input = payload.value; + const isDate = input instanceof Date; + const isValidDate = isDate && !Number.isNaN(input.getTime()); + if (isValidDate) + return payload; + payload.issues.push({ + expected: "date", + code: "invalid_type", + input, + ...(isDate ? { received: "Invalid Date" } : {}), + inst, + }); + return payload; + }; +}); +function handleArrayResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + expected: "array", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = Array(input.length); + const proms = []; + for (let i = 0; i < input.length; i++) { + const item = input[i]; + const result = def.element._zod.run({ + value: item, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleArrayResult(result, payload, i))); + } + else { + handleArrayResult(result, payload, i); + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; //handleArrayResultsAsync(parseResults, final); + }; +}); +function handlePropertyResult(result, final, key, input) { + if (result.issues.length) { + final.issues.push(...prefixIssues(key, result.issues)); + } + if (result.value === undefined) { + if (key in input) { + final.value[key] = undefined; + } + } + else { + final.value[key] = result.value; + } +} +function normalizeDef(def) { + const keys = Object.keys(def.shape); + for (const k of keys) { + if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { + throw new Error(`Invalid element at key "${k}": expected a Zod schema`); + } + } + const okeys = optionalKeys(def.shape); + return { + ...def, + keys, + keySet: new Set(keys), + numKeys: keys.length, + optionalKeys: new Set(okeys), + }; +} +function handleCatchall(proms, input, payload, ctx, def, inst) { + const unrecognized = []; + // iterate over input keys + const keySet = def.keySet; + const _catchall = def.catchall._zod; + const t = _catchall.def.type; + for (const key in input) { + if (keySet.has(key)) + continue; + if (t === "never") { + unrecognized.push(key); + continue; + } + const r = _catchall.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input))); + } + else { + handlePropertyResult(r, payload, key, input); + } + } + if (unrecognized.length) { + payload.issues.push({ + code: "unrecognized_keys", + keys: unrecognized, + input, + inst, + }); + } + if (!proms.length) + return payload; + return Promise.all(proms).then(() => { + return payload; + }); +} +const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodType.init(inst, def); + // const sh = def.shape; + const desc = Object.getOwnPropertyDescriptor(def, "shape"); + if (!desc?.get) { + const sh = def.shape; + Object.defineProperty(def, "shape", { + get: () => { + const newSh = { ...sh }; + Object.defineProperty(def, "shape", { + value: newSh, + }); + return newSh; + }, + }); + } + const _normalized = cached(() => normalizeDef(def)); + defineLazy(inst._zod, "propValues", () => { + const shape = def.shape; + const propValues = {}; + for (const key in shape) { + const field = shape[key]._zod; + if (field.values) { + propValues[key] ?? (propValues[key] = new Set()); + for (const v of field.values) + propValues[key].add(v); + } + } + return propValues; + }); + const isObject = util_isObject; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + payload.value = {}; + const proms = []; + const shape = value.shape; + for (const key of value.keys) { + const el = shape[key]; + const r = el._zod.run({ value: input[key], issues: [] }, ctx); + if (r instanceof Promise) { + proms.push(r.then((r) => handlePropertyResult(r, payload, key, input))); + } + else { + handlePropertyResult(r, payload, key, input); + } + } + if (!catchall) { + return proms.length ? Promise.all(proms).then(() => payload) : payload; + } + return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); + }; +}); +const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { + // requires cast because technically $ZodObject doesn't extend + $ZodObject.init(inst, def); + const superParse = inst._zod.parse; + const _normalized = cached(() => normalizeDef(def)); + const generateFastpass = (shape) => { + const doc = new Doc(["shape", "payload", "ctx"]); + const normalized = _normalized.value; + const parseStr = (key) => { + const k = esc(key); + return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; + }; + doc.write(`const input = payload.value;`); + const ids = Object.create(null); + let counter = 0; + for (const key of normalized.keys) { + ids[key] = `key_${counter++}`; + } + // A: preserve key order { + doc.write(`const newResult = {};`); + for (const key of normalized.keys) { + const id = ids[key]; + const k = esc(key); + doc.write(`const ${id} = ${parseStr(key)};`); + doc.write(` + if (${id}.issues.length) { + payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ + ...iss, + path: iss.path ? [${k}, ...iss.path] : [${k}] + }))); + } + + + if (${id}.value === undefined) { + if (${k} in input) { + newResult[${k}] = undefined; + } + } else { + newResult[${k}] = ${id}.value; + } + + `); + } + doc.write(`payload.value = newResult;`); + doc.write(`return payload;`); + const fn = doc.compile(); + return (payload, ctx) => fn(shape, payload, ctx); + }; + let fastpass; + const isObject = util_isObject; + const jit = !globalConfig.jitless; + const allowsEval = util_allowsEval; + const fastEnabled = jit && allowsEval.value; // && !def.catchall; + const catchall = def.catchall; + let value; + inst._zod.parse = (payload, ctx) => { + value ?? (value = _normalized.value); + const input = payload.value; + if (!isObject(input)) { + payload.issues.push({ + expected: "object", + code: "invalid_type", + input, + inst, + }); + return payload; + } + if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { + // always synchronous + if (!fastpass) + fastpass = generateFastpass(def.shape); + payload = fastpass(payload, ctx); + if (!catchall) + return payload; + return handleCatchall([], input, payload, ctx, value, inst); + } + return superParse(payload, ctx); + }; +}); +function handleUnionResults(results, final, inst, ctx) { + for (const result of results) { + if (result.issues.length === 0) { + final.value = result.value; + return final; + } + } + const nonaborted = results.filter((r) => !aborted(r)); + if (nonaborted.length === 1) { + final.value = nonaborted[0].value; + return nonaborted[0]; + } + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), + }); + return final; +} +const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined); + defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); + defineLazy(inst._zod, "values", () => { + if (def.options.every((o) => o._zod.values)) { + return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); + } + return undefined; + }); + defineLazy(inst._zod, "pattern", () => { + if (def.options.every((o) => o._zod.pattern)) { + const patterns = def.options.map((o) => o._zod.pattern); + return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); + } + return undefined; + }); + const single = def.options.length === 1; + const first = def.options[0]._zod.run; + inst._zod.parse = (payload, ctx) => { + if (single) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + if (result.issues.length === 0) + return result; + results.push(result); + } + } + if (!async) + return handleUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleUnionResults(results, payload, inst, ctx); + }); + }; +}); +function handleExclusiveUnionResults(results, final, inst, ctx) { + const successes = results.filter((r) => r.issues.length === 0); + if (successes.length === 1) { + final.value = successes[0].value; + return final; + } + if (successes.length === 0) { + // No matches - same as regular union + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), + }); + } + else { + // Multiple matches - exclusive union failure + final.issues.push({ + code: "invalid_union", + input: final.value, + inst, + errors: [], + inclusive: false, + }); + } + return final; +} +const $ZodXor = /*@__PURE__*/ $constructor("$ZodXor", (inst, def) => { + $ZodUnion.init(inst, def); + def.inclusive = false; + const single = def.options.length === 1; + const first = def.options[0]._zod.run; + inst._zod.parse = (payload, ctx) => { + if (single) { + return first(payload, ctx); + } + let async = false; + const results = []; + for (const option of def.options) { + const result = option._zod.run({ + value: payload.value, + issues: [], + }, ctx); + if (result instanceof Promise) { + results.push(result); + async = true; + } + else { + results.push(result); + } + } + if (!async) + return handleExclusiveUnionResults(results, payload, inst, ctx); + return Promise.all(results).then((results) => { + return handleExclusiveUnionResults(results, payload, inst, ctx); + }); + }; +}); +const $ZodDiscriminatedUnion = +/*@__PURE__*/ +$constructor("$ZodDiscriminatedUnion", (inst, def) => { + def.inclusive = false; + $ZodUnion.init(inst, def); + const _super = inst._zod.parse; + defineLazy(inst._zod, "propValues", () => { + const propValues = {}; + for (const option of def.options) { + const pv = option._zod.propValues; + if (!pv || Object.keys(pv).length === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); + for (const [k, v] of Object.entries(pv)) { + if (!propValues[k]) + propValues[k] = new Set(); + for (const val of v) { + propValues[k].add(val); + } + } + } + return propValues; + }); + const disc = cached(() => { + const opts = def.options; + const map = new Map(); + for (const o of opts) { + const values = o._zod.propValues?.[def.discriminator]; + if (!values || values.size === 0) + throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); + for (const v of values) { + if (map.has(v)) { + throw new Error(`Duplicate discriminator value "${String(v)}"`); + } + map.set(v, o); + } + } + return map; + }); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!util_isObject(input)) { + payload.issues.push({ + code: "invalid_type", + expected: "object", + input, + inst, + }); + return payload; + } + const opt = disc.value.get(input?.[def.discriminator]); + if (opt) { + return opt._zod.run(payload, ctx); + } + if (def.unionFallback) { + return _super(payload, ctx); + } + // no matching discriminator + payload.issues.push({ + code: "invalid_union", + errors: [], + note: "No matching discriminator", + discriminator: def.discriminator, + input, + path: [def.discriminator], + inst, + }); + return payload; + }; +}); +const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + const left = def.left._zod.run({ value: input, issues: [] }, ctx); + const right = def.right._zod.run({ value: input, issues: [] }, ctx); + const async = left instanceof Promise || right instanceof Promise; + if (async) { + return Promise.all([left, right]).then(([left, right]) => { + return handleIntersectionResults(payload, left, right); + }); + } + return handleIntersectionResults(payload, left, right); + }; +}); +function mergeValues(a, b) { + // const aType = parse.t(a); + // const bType = parse.t(b); + if (a === b) { + return { valid: true, data: a }; + } + if (a instanceof Date && b instanceof Date && +a === +b) { + return { valid: true, data: a }; + } + if (isPlainObject(a) && isPlainObject(b)) { + const bKeys = Object.keys(b); + const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [key, ...sharedValue.mergeErrorPath], + }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + if (Array.isArray(a) && Array.isArray(b)) { + if (a.length !== b.length) { + return { valid: false, mergeErrorPath: [] }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { + valid: false, + mergeErrorPath: [index, ...sharedValue.mergeErrorPath], + }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + return { valid: false, mergeErrorPath: [] }; +} +function handleIntersectionResults(result, left, right) { + if (left.issues.length) { + result.issues.push(...left.issues); + } + if (right.issues.length) { + result.issues.push(...right.issues); + } + if (aborted(result)) + return result; + const merged = mergeValues(left.value, right.value); + if (!merged.valid) { + throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); + } + result.value = merged.data; + return result; +} +const $ZodTuple = /*@__PURE__*/ $constructor("$ZodTuple", (inst, def) => { + $ZodType.init(inst, def); + const items = def.items; + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!Array.isArray(input)) { + payload.issues.push({ + input, + inst, + expected: "tuple", + code: "invalid_type", + }); + return payload; + } + payload.value = []; + const proms = []; + const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); + const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex; + if (!def.rest) { + const tooBig = input.length > items.length; + const tooSmall = input.length < optStart - 1; + if (tooBig || tooSmall) { + payload.issues.push({ + ...(tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }), + input, + inst, + origin: "array", + }); + return payload; + } + } + let i = -1; + for (const item of items) { + i++; + if (i >= input.length) + if (i >= optStart) + continue; + const result = item._zod.run({ + value: input[i], + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleTupleResult(result, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } + } + if (def.rest) { + const rest = input.slice(items.length); + for (const el of rest) { + i++; + const result = def.rest._zod.run({ + value: el, + issues: [], + }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleTupleResult(result, payload, i))); + } + else { + handleTupleResult(result, payload, i); + } + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handleTupleResult(result, final, index) { + if (result.issues.length) { + final.issues.push(...prefixIssues(index, result.issues)); + } + final.value[index] = result.value; +} +const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!isPlainObject(input)) { + payload.issues.push({ + expected: "record", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + const values = def.keyType._zod.values; + if (values) { + payload.value = {}; + const recordKeys = new Set(); + for (const key of values) { + if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { + recordKeys.add(typeof key === "number" ? key.toString() : key); + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[key] = result.value; + } + } + } + let unrecognized; + for (const key in input) { + if (!recordKeys.has(key)) { + unrecognized = unrecognized ?? []; + unrecognized.push(key); + } + } + if (unrecognized && unrecognized.length > 0) { + payload.issues.push({ + code: "unrecognized_keys", + input, + inst, + keys: unrecognized, + }); + } + } + else { + payload.value = {}; + for (const key of Reflect.ownKeys(input)) { + if (key === "__proto__") + continue; + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + if (keyResult instanceof Promise) { + throw new Error("Async schemas not supported in object keys currently"); + } + if (keyResult.issues.length) { + if (def.mode === "loose") { + // Pass through unchanged + payload.value[key] = input[key]; + } + else { + // Default "strict" behavior: error on invalid key + payload.issues.push({ + code: "invalid_key", + origin: "record", + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + input: key, + path: [key], + inst, + }); + } + continue; + } + const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; + })); + } + else { + if (result.issues.length) { + payload.issues.push(...prefixIssues(key, result.issues)); + } + payload.value[keyResult.value] = result.value; + } + } + } + if (proms.length) { + return Promise.all(proms).then(() => payload); + } + return payload; + }; +}); +const $ZodMap = /*@__PURE__*/ $constructor("$ZodMap", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Map)) { + payload.issues.push({ + expected: "map", + code: "invalid_type", + input, + inst, + }); + return payload; + } + const proms = []; + payload.value = new Map(); + for (const [key, value] of input) { + const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); + const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); + if (keyResult instanceof Promise || valueResult instanceof Promise) { + proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + })); + } + else { + handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); + } + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { + if (keyResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, keyResult.issues)); + } + else { + final.issues.push({ + code: "invalid_key", + origin: "map", + input, + inst, + issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + }); + } + } + if (valueResult.issues.length) { + if (propertyKeyTypes.has(typeof key)) { + final.issues.push(...prefixIssues(key, valueResult.issues)); + } + else { + final.issues.push({ + origin: "map", + code: "invalid_element", + input, + inst, + key: key, + issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), + }); + } + } + final.value.set(keyResult.value, valueResult.value); +} +const $ZodSet = /*@__PURE__*/ $constructor("$ZodSet", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + const input = payload.value; + if (!(input instanceof Set)) { + payload.issues.push({ + input, + inst, + expected: "set", + code: "invalid_type", + }); + return payload; + } + const proms = []; + payload.value = new Set(); + for (const item of input) { + const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); + if (result instanceof Promise) { + proms.push(result.then((result) => handleSetResult(result, payload))); + } + else + handleSetResult(result, payload); + } + if (proms.length) + return Promise.all(proms).then(() => payload); + return payload; + }; +}); +function handleSetResult(result, final) { + if (result.issues.length) { + final.issues.push(...result.issues); + } + final.value.add(result.value); +} +const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { + $ZodType.init(inst, def); + const values = getEnumValues(def.entries); + const valuesSet = new Set(values); + inst._zod.values = valuesSet; + inst._zod.pattern = new RegExp(`^(${values + .filter((k) => propertyKeyTypes.has(typeof k)) + .map((o) => (typeof o === "string" ? escapeRegex(o) : o.toString())) + .join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (valuesSet.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values, + input, + inst, + }); + return payload; + }; +}); +const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { + $ZodType.init(inst, def); + if (def.values.length === 0) { + throw new Error("Cannot create literal schema with no valid values"); + } + const values = new Set(def.values); + inst._zod.values = values; + inst._zod.pattern = new RegExp(`^(${def.values + .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) + .join("|")})$`); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + if (values.has(input)) { + return payload; + } + payload.issues.push({ + code: "invalid_value", + values: def.values, + input, + inst, + }); + return payload; + }; +}); +const $ZodFile = /*@__PURE__*/ $constructor("$ZodFile", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + const input = payload.value; + // @ts-ignore + if (input instanceof File) + return payload; + payload.issues.push({ + expected: "file", + code: "invalid_type", + input, + inst, + }); + return payload; + }; +}); +const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + const _out = def.transform(payload.value, payload); + if (ctx.async) { + const output = _out instanceof Promise ? _out : Promise.resolve(_out); + return output.then((output) => { + payload.value = output; + return payload; + }); + } + if (_out instanceof Promise) { + throw new $ZodAsyncError(); + } + payload.value = _out; + return payload; + }; +}); +function handleOptionalResult(result, input) { + if (result.issues.length && input === undefined) { + return { issues: [], value: undefined }; + } + return result; +} +const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + inst._zod.optout = "optional"; + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined; + }); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + if (def.innerType._zod.optin === "optional") { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) + return result.then((r) => handleOptionalResult(r, payload.value)); + return handleOptionalResult(result, payload.value); + } + if (payload.value === undefined) { + return payload; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "pattern", () => { + const pattern = def.innerType._zod.pattern; + return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; + }); + defineLazy(inst._zod, "values", () => { + return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + // Forward direction (decode): allow null to pass through + if (payload.value === null) + return payload; + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { + $ZodType.init(inst, def); + // inst._zod.qin = "true"; + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply defaults for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + /** + * $ZodDefault returns the default value immediately in forward direction. + * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ + return payload; + } + // Forward direction: continue with default handling + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleDefaultResult(result, def)); + } + return handleDefaultResult(result, def); + }; +}); +function handleDefaultResult(payload, def) { + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return payload; +} +const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.optin = "optional"; + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply prefault for undefined input + if (payload.value === undefined) { + payload.value = def.defaultValue; + } + return def.innerType._zod.run(payload, ctx); + }; +}); +const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => { + const v = def.innerType._zod.values; + return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; + }); + inst._zod.parse = (payload, ctx) => { + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => handleNonOptionalResult(result, inst)); + } + return handleNonOptionalResult(result, inst); + }; +}); +function handleNonOptionalResult(payload, inst) { + if (!payload.issues.length && payload.value === undefined) { + payload.issues.push({ + code: "invalid_type", + expected: "nonoptional", + input: payload.value, + inst, + }); + } + return payload; +} +const $ZodSuccess = /*@__PURE__*/ $constructor("$ZodSuccess", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + throw new $ZodEncodeError("ZodSuccess"); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.issues.length === 0; + return payload; + }); + } + payload.value = result.issues.length === 0; + return payload; + }; +}); +const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); + defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + // Forward direction (decode): apply catch logic + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then((result) => { + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())), + }, + input: payload.value, + }); + payload.issues = []; + } + return payload; + }); + } + payload.value = result.value; + if (result.issues.length) { + payload.value = def.catchValue({ + ...payload, + error: { + issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())), + }, + input: payload.value, + }); + payload.issues = []; + } + return payload; + }; +}); +const $ZodNaN = /*@__PURE__*/ $constructor("$ZodNaN", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + expected: "nan", + code: "invalid_type", + }); + return payload; + } + return payload; + }; +}); +const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handlePipeResult(right, def.in, ctx)); + } + return handlePipeResult(right, def.in, ctx); + } + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handlePipeResult(left, def.out, ctx)); + } + return handlePipeResult(left, def.out, ctx); + }; +}); +function handlePipeResult(left, next, ctx) { + if (left.issues.length) { + // prevent further checks + left.aborted = true; + return left; + } + return next._zod.run({ value: left.value, issues: left.issues }, ctx); +} +const $ZodCodec = /*@__PURE__*/ $constructor("$ZodCodec", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "values", () => def.in._zod.values); + defineLazy(inst._zod, "optin", () => def.in._zod.optin); + defineLazy(inst._zod, "optout", () => def.out._zod.optout); + defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); + inst._zod.parse = (payload, ctx) => { + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const left = def.in._zod.run(payload, ctx); + if (left instanceof Promise) { + return left.then((left) => handleCodecAResult(left, def, ctx)); + } + return handleCodecAResult(left, def, ctx); + } + else { + const right = def.out._zod.run(payload, ctx); + if (right instanceof Promise) { + return right.then((right) => handleCodecAResult(right, def, ctx)); + } + return handleCodecAResult(right, def, ctx); + } + }; +}); +function handleCodecAResult(result, def, ctx) { + if (result.issues.length) { + // prevent further checks + result.aborted = true; + return result; + } + const direction = ctx.direction || "forward"; + if (direction === "forward") { + const transformed = def.transform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); + } + return handleCodecTxResult(result, transformed, def.out, ctx); + } + else { + const transformed = def.reverseTransform(result.value, result); + if (transformed instanceof Promise) { + return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); + } + return handleCodecTxResult(result, transformed, def.in, ctx); + } +} +function handleCodecTxResult(left, value, nextSchema, ctx) { + // Check if transform added any issues + if (left.issues.length) { + left.aborted = true; + return left; + } + return nextSchema._zod.run({ value, issues: left.issues }, ctx); +} +const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { + $ZodType.init(inst, def); + defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); + defineLazy(inst._zod, "values", () => def.innerType._zod.values); + defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); + defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); + inst._zod.parse = (payload, ctx) => { + if (ctx.direction === "backward") { + return def.innerType._zod.run(payload, ctx); + } + const result = def.innerType._zod.run(payload, ctx); + if (result instanceof Promise) { + return result.then(handleReadonlyResult); + } + return handleReadonlyResult(result); + }; +}); +function handleReadonlyResult(payload) { + payload.value = Object.freeze(payload.value); + return payload; +} +const $ZodTemplateLiteral = /*@__PURE__*/ $constructor("$ZodTemplateLiteral", (inst, def) => { + $ZodType.init(inst, def); + const regexParts = []; + for (const part of def.parts) { + if (typeof part === "object" && part !== null) { + // is Zod schema + if (!part._zod.pattern) { + // if (!source) + throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); + } + const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; + if (!source) + throw new Error(`Invalid template literal part: ${part._zod.traits}`); + const start = source.startsWith("^") ? 1 : 0; + const end = source.endsWith("$") ? source.length - 1 : source.length; + regexParts.push(source.slice(start, end)); + } + else if (part === null || primitiveTypes.has(typeof part)) { + regexParts.push(escapeRegex(`${part}`)); + } + else { + throw new Error(`Invalid template literal part: ${part}`); + } + } + inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "string") { + payload.issues.push({ + input: payload.value, + inst, + expected: "template_literal", + code: "invalid_type", + }); + return payload; + } + inst._zod.pattern.lastIndex = 0; + if (!inst._zod.pattern.test(payload.value)) { + payload.issues.push({ + input: payload.value, + inst, + code: "invalid_format", + format: def.format ?? "template_literal", + pattern: inst._zod.pattern.source, + }); + return payload; + } + return payload; + }; +}); +const $ZodFunction = /*@__PURE__*/ $constructor("$ZodFunction", (inst, def) => { + $ZodType.init(inst, def); + inst._def = def; + inst._zod.def = def; + inst.implement = (func) => { + if (typeof func !== "function") { + throw new Error("implement() must be called with a function"); + } + return function (...args) { + const parsedArgs = inst._def.input ? parse_parse(inst._def.input, args) : args; + const result = Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return parse_parse(inst._def.output, result); + } + return result; + }; + }; + inst.implementAsync = (func) => { + if (typeof func !== "function") { + throw new Error("implementAsync() must be called with a function"); + } + return async function (...args) { + const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; + const result = await Reflect.apply(func, this, parsedArgs); + if (inst._def.output) { + return await parseAsync(inst._def.output, result); + } + return result; + }; + }; + inst._zod.parse = (payload, _ctx) => { + if (typeof payload.value !== "function") { + payload.issues.push({ + code: "invalid_type", + expected: "function", + input: payload.value, + inst, + }); + return payload; + } + // Check if output is a promise type to determine if we should use async implementation + const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; + if (hasPromiseOutput) { + payload.value = inst.implementAsync(payload.value); + } + else { + payload.value = inst.implement(payload.value); + } + return payload; + }; + inst.input = (...args) => { + const F = inst.constructor; + if (Array.isArray(args[0])) { + return new F({ + type: "function", + input: new $ZodTuple({ + type: "tuple", + items: args[0], + rest: args[1], + }), + output: inst._def.output, + }); + } + return new F({ + type: "function", + input: args[0], + output: inst._def.output, + }); + }; + inst.output = (output) => { + const F = inst.constructor; + return new F({ + type: "function", + input: inst._def.input, + output, + }); + }; + return inst; +}); +const $ZodPromise = /*@__PURE__*/ $constructor("$ZodPromise", (inst, def) => { + $ZodType.init(inst, def); + inst._zod.parse = (payload, ctx) => { + return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); + }; +}); +const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { + $ZodType.init(inst, def); + // let _innerType!: any; + // util.defineLazy(def, "getter", () => { + // if (!_innerType) { + // _innerType = def.getter(); + // } + // return () => _innerType; + // }); + defineLazy(inst._zod, "innerType", () => def.getter()); + defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); + defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); + defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? undefined); + defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? undefined); + inst._zod.parse = (payload, ctx) => { + const inner = inst._zod.innerType; + return inner._zod.run(payload, ctx); + }; +}); +const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { + $ZodCheck.init(inst, def); + $ZodType.init(inst, def); + inst._zod.parse = (payload, _) => { + return payload; + }; + inst._zod.check = (payload) => { + const input = payload.value; + const r = def.fn(input); + if (r instanceof Promise) { + return r.then((r) => handleRefineResult(r, payload, input, inst)); + } + handleRefineResult(r, payload, input, inst); + return; + }; +}); +function handleRefineResult(result, payload, input, inst) { + if (!result) { + const _iss = { + code: "custom", + input, + inst, // incorporates params.error into issue reporting + path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting + continue: !inst._zod.def.abort, + // params: inst._zod.def.params, + }; + if (inst._zod.def.params) + _iss.params = inst._zod.def.params; + payload.issues.push(util_issue(_iss)); + } +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ar.js + +const error = () => { + const Sizable = { + string: { unit: "حرف", verb: "أن يحوي" }, + file: { unit: "بايت", verb: "أن يحوي" }, + array: { unit: "عنصر", verb: "أن يحوي" }, + set: { unit: "عنصر", verb: "أن يحوي" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "مدخل", + email: "بريد إلكتروني", + url: "رابط", + emoji: "إيموجي", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "تاريخ ووقت بمعيار ISO", + date: "تاريخ بمعيار ISO", + time: "وقت بمعيار ISO", + duration: "مدة بمعيار ISO", + ipv4: "عنوان IPv4", + ipv6: "عنوان IPv6", + cidrv4: "مدى عناوين بصيغة IPv4", + cidrv6: "مدى عناوين بصيغة IPv6", + base64: "نَص بترميز base64-encoded", + base64url: "نَص بترميز base64url-encoded", + json_string: "نَص على هيئة JSON", + e164: "رقم هاتف بمعيار E.164", + jwt: "JWT", + template_literal: "مدخل", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `مدخلات غير مقبولة: يفترض إدخال ${issue.expected}، ولكن تم إدخال ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive(issue.values[0])}`; + return `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return ` أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "عنصر"}`; + return `أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `نَص غير مقبول: يجب أن يبدأ بـ "${issue.prefix}"`; + if (_issue.format === "ends_with") + return `نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`; + if (_issue.format === "includes") + return `نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`; + if (_issue.format === "regex") + return `نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} غير مقبول`; + } + case "not_multiple_of": + return `رقم غير مقبول: يجب أن يكون من مضاعفات ${issue.divisor}`; + case "unrecognized_keys": + return `معرف${issue.keys.length > 1 ? "ات" : ""} غريب${issue.keys.length > 1 ? "ة" : ""}: ${joinValues(issue.keys, "، ")}`; + case "invalid_key": + return `معرف غير مقبول في ${issue.origin}`; + case "invalid_union": + return "مدخل غير مقبول"; + case "invalid_element": + return `مدخل غير مقبول في ${issue.origin}`; + default: + return "مدخل غير مقبول"; + } + }; +}; +/* harmony default export */ function ar() { + return { + localeError: error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/az.js + +const az_error = () => { + const Sizable = { + string: { unit: "simvol", verb: "olmalıdır" }, + file: { unit: "bayt", verb: "olmalıdır" }, + array: { unit: "element", verb: "olmalıdır" }, + set: { unit: "element", verb: "olmalıdır" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Yanlış dəyər: gözlənilən ${issue.expected}, daxil olan ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Yanlış dəyər: gözlənilən ${stringifyPrimitive(issue.values[0])}`; + return `Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çox böyük: gözlənilən ${issue.origin ?? "dəyər"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`; + return `Çox böyük: gözlənilən ${issue.origin ?? "dəyər"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`; + if (_issue.format === "ends_with") + return `Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`; + if (_issue.format === "includes") + return `Yanlış mətn: "${_issue.includes}" daxil olmalıdır`; + if (_issue.format === "regex") + return `Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`; + return `Yanlış ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Yanlış ədəd: ${issue.divisor} ilə bölünə bilən olmalıdır`; + case "unrecognized_keys": + return `Tanınmayan açar${issue.keys.length > 1 ? "lar" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} daxilində yanlış açar`; + case "invalid_union": + return "Yanlış dəyər"; + case "invalid_element": + return `${issue.origin} daxilində yanlış dəyər`; + default: + return `Yanlış dəyər`; + } + }; +}; +/* harmony default export */ function az() { + return { + localeError: az_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/be.js + +function getBelarusianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +const be_error = () => { + const Sizable = { + string: { + unit: { + one: "сімвал", + few: "сімвалы", + many: "сімвалаў", + }, + verb: "мець", + }, + array: { + unit: { + one: "элемент", + few: "элементы", + many: "элементаў", + }, + verb: "мець", + }, + set: { + unit: { + one: "элемент", + few: "элементы", + many: "элементаў", + }, + verb: "мець", + }, + file: { + unit: { + one: "байт", + few: "байты", + many: "байтаў", + }, + verb: "мець", + }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "лік"; + } + case "object": { + if (Array.isArray(data)) { + return "масіў"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "увод", + email: "email адрас", + url: "URL", + emoji: "эмодзі", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO дата і час", + date: "ISO дата", + time: "ISO час", + duration: "ISO працягласць", + ipv4: "IPv4 адрас", + ipv6: "IPv6 адрас", + cidrv4: "IPv4 дыяпазон", + cidrv6: "IPv6 дыяпазон", + base64: "радок у фармаце base64", + base64url: "радок у фармаце base64url", + json_string: "JSON радок", + e164: "нумар E.164", + jwt: "JWT", + template_literal: "увод", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Няправільны ўвод: чакаўся ${issue.expected}, атрымана ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Няправільны ўвод: чакалася ${stringifyPrimitive(issue.values[0])}`; + return `Няправільны варыянт: чакаўся адзін з ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + const maxValue = Number(issue.maximum); + const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна ${sizing.verb} ${adj}${issue.maximum.toString()} ${unit}`; + } + return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна быць ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + const minValue = Number(issue.minimum); + const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Занадта малы: чакалася, што ${issue.origin} павінна ${sizing.verb} ${adj}${issue.minimum.toString()} ${unit}`; + } + return `Занадта малы: чакалася, што ${issue.origin} павінна быць ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Няправільны радок: павінен пачынацца з "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Няправільны радок: павінен змяшчаць "${_issue.includes}"`; + if (_issue.format === "regex") + return `Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`; + return `Няправільны ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Няправільны лік: павінен быць кратным ${issue.divisor}`; + case "unrecognized_keys": + return `Нераспазнаны ${issue.keys.length > 1 ? "ключы" : "ключ"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Няправільны ключ у ${issue.origin}`; + case "invalid_union": + return "Няправільны ўвод"; + case "invalid_element": + return `Няправільнае значэнне ў ${issue.origin}`; + default: + return `Няправільны ўвод`; + } + }; +}; +/* harmony default export */ function be() { + return { + localeError: be_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/bg.js + +const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "число"; + } + case "object": { + if (Array.isArray(data)) { + return "масив"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; +}; +const bg_error = () => { + const Sizable = { + string: { unit: "символа", verb: "да съдържа" }, + file: { unit: "байта", verb: "да съдържа" }, + array: { unit: "елемента", verb: "да съдържа" }, + set: { unit: "елемента", verb: "да съдържа" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "вход", + email: "имейл адрес", + url: "URL", + emoji: "емоджи", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO време", + date: "ISO дата", + time: "ISO време", + duration: "ISO продължителност", + ipv4: "IPv4 адрес", + ipv6: "IPv6 адрес", + cidrv4: "IPv4 диапазон", + cidrv6: "IPv6 диапазон", + base64: "base64-кодиран низ", + base64url: "base64url-кодиран низ", + json_string: "JSON низ", + e164: "E.164 номер", + jwt: "JWT", + template_literal: "вход", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Невалиден вход: очакван ${issue.expected}, получен ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Невалиден вход: очакван ${stringifyPrimitive(issue.values[0])}`; + return `Невалидна опция: очаквано едно от ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Твърде голямо: очаква се ${issue.origin ?? "стойност"} да съдържа ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елемента"}`; + return `Твърде голямо: очаква се ${issue.origin ?? "стойност"} да бъде ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Твърде малко: очаква се ${issue.origin} да съдържа ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Твърде малко: очаква се ${issue.origin} да бъде ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Невалиден низ: трябва да започва с "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Невалиден низ: трябва да завършва с "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Невалиден низ: трябва да включва "${_issue.includes}"`; + if (_issue.format === "regex") + return `Невалиден низ: трябва да съвпада с ${_issue.pattern}`; + let invalid_adj = "Невалиден"; + if (_issue.format === "emoji") + invalid_adj = "Невалидно"; + if (_issue.format === "datetime") + invalid_adj = "Невалидно"; + if (_issue.format === "date") + invalid_adj = "Невалидна"; + if (_issue.format === "time") + invalid_adj = "Невалидно"; + if (_issue.format === "duration") + invalid_adj = "Невалидна"; + return `${invalid_adj} ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Невалидно число: трябва да бъде кратно на ${issue.divisor}`; + case "unrecognized_keys": + return `Неразпознат${issue.keys.length > 1 ? "и" : ""} ключ${issue.keys.length > 1 ? "ове" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Невалиден ключ в ${issue.origin}`; + case "invalid_union": + return "Невалиден вход"; + case "invalid_element": + return `Невалидна стойност в ${issue.origin}`; + default: + return `Невалиден вход`; + } + }; +}; +/* harmony default export */ function bg() { + return { + localeError: bg_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ca.js + +const ca_error = () => { + const Sizable = { + string: { unit: "caràcters", verb: "contenir" }, + file: { unit: "bytes", verb: "contenir" }, + array: { unit: "elements", verb: "contenir" }, + set: { unit: "elements", verb: "contenir" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "entrada", + email: "adreça electrònica", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "durada ISO", + ipv4: "adreça IPv4", + ipv6: "adreça IPv6", + cidrv4: "rang IPv4", + cidrv6: "rang IPv6", + base64: "cadena codificada en base64", + base64url: "cadena codificada en base64url", + json_string: "cadena JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${parsedType(issue.input)}`; + // return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Valor invàlid: s'esperava ${stringifyPrimitive(issue.values[0])}`; + return `Opció invàlida: s'esperava una de ${joinValues(issue.values, " o ")}`; + case "too_big": { + const adj = issue.inclusive ? "com a màxim" : "menys de"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} contingués ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} fos ${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? "com a mínim" : "més de"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Massa petit: s'esperava que ${issue.origin} contingués ${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `Massa petit: s'esperava que ${issue.origin} fos ${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Format invàlid: ha de començar amb "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Format invàlid: ha d'acabar amb "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Format invàlid: ha d'incloure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`; + return `Format invàlid per a ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Número invàlid: ha de ser múltiple de ${issue.divisor}`; + case "unrecognized_keys": + return `Clau${issue.keys.length > 1 ? "s" : ""} no reconeguda${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Clau invàlida a ${issue.origin}`; + case "invalid_union": + return "Entrada invàlida"; // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general + case "invalid_element": + return `Element invàlid a ${issue.origin}`; + default: + return `Entrada invàlida`; + } + }; +}; +/* harmony default export */ function ca() { + return { + localeError: ca_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/cs.js + +const cs_error = () => { + const Sizable = { + string: { unit: "znaků", verb: "mít" }, + file: { unit: "bajtů", verb: "mít" }, + array: { unit: "prvků", verb: "mít" }, + set: { unit: "prvků", verb: "mít" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "číslo"; + } + case "string": { + return "řetězec"; + } + case "boolean": { + return "boolean"; + } + case "bigint": { + return "bigint"; + } + case "function": { + return "funkce"; + } + case "symbol": { + return "symbol"; + } + case "undefined": { + return "undefined"; + } + case "object": { + if (Array.isArray(data)) { + return "pole"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "regulární výraz", + email: "e-mailová adresa", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "datum a čas ve formátu ISO", + date: "datum ve formátu ISO", + time: "čas ve formátu ISO", + duration: "doba trvání ISO", + ipv4: "IPv4 adresa", + ipv6: "IPv6 adresa", + cidrv4: "rozsah IPv4", + cidrv6: "rozsah IPv6", + base64: "řetězec zakódovaný ve formátu base64", + base64url: "řetězec zakódovaný ve formátu base64url", + json_string: "řetězec ve formátu JSON", + e164: "číslo E.164", + jwt: "JWT", + template_literal: "vstup", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Neplatný vstup: očekáváno ${issue.expected}, obdrženo ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Neplatný vstup: očekáváno ${stringifyPrimitive(issue.values[0])}`; + return `Neplatná možnost: očekávána jedna z hodnot ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Hodnota je příliš velká: ${issue.origin ?? "hodnota"} musí mít ${adj}${issue.maximum.toString()} ${sizing.unit ?? "prvků"}`; + } + return `Hodnota je příliš velká: ${issue.origin ?? "hodnota"} musí být ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Hodnota je příliš malá: ${issue.origin ?? "hodnota"} musí mít ${adj}${issue.minimum.toString()} ${sizing.unit ?? "prvků"}`; + } + return `Hodnota je příliš malá: ${issue.origin ?? "hodnota"} musí být ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Neplatný řetězec: musí začínat na "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Neplatný řetězec: musí končit na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neplatný řetězec: musí obsahovat "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`; + return `Neplatný formát ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Neplatné číslo: musí být násobkem ${issue.divisor}`; + case "unrecognized_keys": + return `Neznámé klíče: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Neplatný klíč v ${issue.origin}`; + case "invalid_union": + return "Neplatný vstup"; + case "invalid_element": + return `Neplatná hodnota v ${issue.origin}`; + default: + return `Neplatný vstup`; + } + }; +}; +/* harmony default export */ function cs() { + return { + localeError: cs_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/da.js + +const da_error = () => { + const Sizable = { + string: { unit: "tegn", verb: "havde" }, + file: { unit: "bytes", verb: "havde" }, + array: { unit: "elementer", verb: "indeholdt" }, + set: { unit: "elementer", verb: "indeholdt" }, + }; + const TypeNames = { + string: "streng", + number: "tal", + boolean: "boolean", + array: "liste", + object: "objekt", + set: "sæt", + file: "fil", + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + function getTypeName(type) { + return TypeNames[type] ?? type; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "tal"; + } + case "object": { + if (Array.isArray(data)) { + return "liste"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + return "objekt"; + } + } + return t; + }; + const Nouns = { + regex: "input", + email: "e-mailadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslæt", + date: "ISO-dato", + time: "ISO-klokkeslæt", + duration: "ISO-varighed", + ipv4: "IPv4-område", + ipv6: "IPv6-område", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodet streng", + base64url: "base64url-kodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ugyldigt input: forventede ${getTypeName(issue.expected)}, fik ${getTypeName(parsedType(issue.input))}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ugyldig værdi: forventede ${stringifyPrimitive(issue.values[0])}`; + return `Ugyldigt valg: forventede en af følgende ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + const origin = getTypeName(issue.origin); + if (sizing) + return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + const origin = getTypeName(issue.origin); + if (sizing) { + return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `For lille: forventede ${origin} havde ${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Ugyldig streng: skal starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: skal ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: skal indeholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: skal matche mønsteret ${_issue.pattern}`; + return `Ugyldig ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ugyldigt tal: skal være deleligt med ${issue.divisor}`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Ukendte nøgler" : "Ukendt nøgle"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ugyldig nøgle i ${issue.origin}`; + case "invalid_union": + return "Ugyldigt input: matcher ingen af de tilladte typer"; + case "invalid_element": + return `Ugyldig værdi i ${issue.origin}`; + default: + return `Ugyldigt input`; + } + }; +}; +/* harmony default export */ function da() { + return { + localeError: da_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/de.js + +const de_error = () => { + const Sizable = { + string: { unit: "Zeichen", verb: "zu haben" }, + file: { unit: "Bytes", verb: "zu haben" }, + array: { unit: "Elemente", verb: "zu haben" }, + set: { unit: "Elemente", verb: "zu haben" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "Zahl"; + } + case "object": { + if (Array.isArray(data)) { + return "Array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "Eingabe", + email: "E-Mail-Adresse", + url: "URL", + emoji: "Emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-Datum und -Uhrzeit", + date: "ISO-Datum", + time: "ISO-Uhrzeit", + duration: "ISO-Dauer", + ipv4: "IPv4-Adresse", + ipv6: "IPv6-Adresse", + cidrv4: "IPv4-Bereich", + cidrv6: "IPv6-Bereich", + base64: "Base64-codierter String", + base64url: "Base64-URL-codierter String", + json_string: "JSON-String", + e164: "E.164-Nummer", + jwt: "JWT", + template_literal: "Eingabe", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ungültige Eingabe: erwartet ${issue.expected}, erhalten ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ungültige Eingabe: erwartet ${stringifyPrimitive(issue.values[0])}`; + return `Ungültige Option: erwartet eine von ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; + return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ist`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} hat`; + } + return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ist`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Ungültiger String: muss mit "${_issue.prefix}" beginnen`; + if (_issue.format === "ends_with") + return `Ungültiger String: muss mit "${_issue.suffix}" enden`; + if (_issue.format === "includes") + return `Ungültiger String: muss "${_issue.includes}" enthalten`; + if (_issue.format === "regex") + return `Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`; + return `Ungültig: ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ungültige Zahl: muss ein Vielfaches von ${issue.divisor} sein`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Unbekannte Schlüssel" : "Unbekannter Schlüssel"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ungültiger Schlüssel in ${issue.origin}`; + case "invalid_union": + return "Ungültige Eingabe"; + case "invalid_element": + return `Ungültiger Wert in ${issue.origin}`; + default: + return `Ungültige Eingabe`; + } + }; +}; +/* harmony default export */ function de() { + return { + localeError: de_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/en.js + +const en_parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; +}; +const en_error = () => { + const Sizable = { + string: { unit: "characters", verb: "to have" }, + file: { unit: "bytes", verb: "to have" }, + array: { unit: "items", verb: "to have" }, + set: { unit: "items", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "input", + email: "email address", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datetime", + date: "ISO date", + time: "ISO time", + duration: "ISO duration", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + mac: "MAC address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded string", + base64url: "base64url-encoded string", + json_string: "JSON string", + e164: "E.164 number", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Invalid input: expected ${issue.expected}, received ${en_parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; + return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; + return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Invalid string: must start with "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Invalid string: must end with "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Invalid string: must include "${_issue.includes}"`; + if (_issue.format === "regex") + return `Invalid string: must match pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Invalid number: must be a multiple of ${issue.divisor}`; + case "unrecognized_keys": + return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Invalid key in ${issue.origin}`; + case "invalid_union": + return "Invalid input"; + case "invalid_element": + return `Invalid value in ${issue.origin}`; + default: + return `Invalid input`; + } + }; +}; +/* harmony default export */ function en() { + return { + localeError: en_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/eo.js + +const eo_parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombro"; + } + case "object": { + if (Array.isArray(data)) { + return "tabelo"; + } + if (data === null) { + return "senvalora"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; +}; +const eo_error = () => { + const Sizable = { + string: { unit: "karaktrojn", verb: "havi" }, + file: { unit: "bajtojn", verb: "havi" }, + array: { unit: "elementojn", verb: "havi" }, + set: { unit: "elementojn", verb: "havi" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "enigo", + email: "retadreso", + url: "URL", + emoji: "emoĝio", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datotempo", + date: "ISO-dato", + time: "ISO-tempo", + duration: "ISO-daŭro", + ipv4: "IPv4-adreso", + ipv6: "IPv6-adreso", + cidrv4: "IPv4-rango", + cidrv6: "IPv6-rango", + base64: "64-ume kodita karaktraro", + base64url: "URL-64-ume kodita karaktraro", + json_string: "JSON-karaktraro", + e164: "E.164-nombro", + jwt: "JWT", + template_literal: "enigo", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Nevalida enigo: atendiĝis ${issue.expected}, riceviĝis ${eo_parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Nevalida enigo: atendiĝis ${stringifyPrimitive(issue.values[0])}`; + return `Nevalida opcio: atendiĝis unu el ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Tro granda: atendiĝis ke ${issue.origin ?? "valoro"} havu ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementojn"}`; + return `Tro granda: atendiĝis ke ${issue.origin ?? "valoro"} havu ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Tro malgranda: atendiĝis ke ${issue.origin} havu ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Tro malgranda: atendiĝis ke ${issue.origin} estu ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Nevalida karaktraro: devas komenciĝi per "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nevalida karaktraro: devas finiĝi per "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; + return `Nevalida ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Nevalida nombro: devas esti oblo de ${issue.divisor}`; + case "unrecognized_keys": + return `Nekonata${issue.keys.length > 1 ? "j" : ""} ŝlosilo${issue.keys.length > 1 ? "j" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Nevalida ŝlosilo en ${issue.origin}`; + case "invalid_union": + return "Nevalida enigo"; + case "invalid_element": + return `Nevalida valoro en ${issue.origin}`; + default: + return `Nevalida enigo`; + } + }; +}; +/* harmony default export */ function eo() { + return { + localeError: eo_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/es.js + +const es_error = () => { + const Sizable = { + string: { unit: "caracteres", verb: "tener" }, + file: { unit: "bytes", verb: "tener" }, + array: { unit: "elementos", verb: "tener" }, + set: { unit: "elementos", verb: "tener" }, + }; + const TypeNames = { + string: "texto", + number: "número", + boolean: "booleano", + array: "arreglo", + object: "objeto", + set: "conjunto", + file: "archivo", + date: "fecha", + bigint: "número grande", + symbol: "símbolo", + undefined: "indefinido", + null: "nulo", + function: "función", + map: "mapa", + record: "registro", + tuple: "tupla", + enum: "enumeración", + union: "unión", + literal: "literal", + promise: "promesa", + void: "vacío", + never: "nunca", + unknown: "desconocido", + any: "cualquiera", + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + function getTypeName(type) { + return TypeNames[type] ?? type; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype) { + return data.constructor.name; + } + return "object"; + } + } + return t; + }; + const Nouns = { + regex: "entrada", + email: "dirección de correo electrónico", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "fecha y hora ISO", + date: "fecha ISO", + time: "hora ISO", + duration: "duración ISO", + ipv4: "dirección IPv4", + ipv6: "dirección IPv6", + cidrv4: "rango IPv4", + cidrv6: "rango IPv6", + base64: "cadena codificada en base64", + base64url: "URL codificada en base64", + json_string: "cadena JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Entrada inválida: se esperaba ${getTypeName(issue.expected)}, recibido ${getTypeName(parsedType(issue.input))}`; + // return `Entrada inválida: se esperaba ${issue.expected}, recibido ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrada inválida: se esperaba ${stringifyPrimitive(issue.values[0])}`; + return `Opción inválida: se esperaba una de ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + const origin = getTypeName(issue.origin); + if (sizing) + return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + const origin = getTypeName(issue.origin); + if (sizing) { + return `Demasiado pequeño: se esperaba que ${origin} tuviera ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Demasiado pequeño: se esperaba que ${origin} fuera ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Cadena inválida: debe comenzar con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Cadena inválida: debe terminar en "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Cadena inválida: debe incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`; + return `Inválido ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Número inválido: debe ser múltiplo de ${issue.divisor}`; + case "unrecognized_keys": + return `Llave${issue.keys.length > 1 ? "s" : ""} desconocida${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Llave inválida en ${getTypeName(issue.origin)}`; + case "invalid_union": + return "Entrada inválida"; + case "invalid_element": + return `Valor inválido en ${getTypeName(issue.origin)}`; + default: + return `Entrada inválida`; + } + }; +}; +/* harmony default export */ function es() { + return { + localeError: es_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/fa.js + +const fa_error = () => { + const Sizable = { + string: { unit: "کاراکتر", verb: "داشته باشد" }, + file: { unit: "بایت", verb: "داشته باشد" }, + array: { unit: "آیتم", verb: "داشته باشد" }, + set: { unit: "آیتم", verb: "داشته باشد" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "عدد"; + } + case "object": { + if (Array.isArray(data)) { + return "آرایه"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ورودی", + email: "آدرس ایمیل", + url: "URL", + emoji: "ایموجی", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "تاریخ و زمان ایزو", + date: "تاریخ ایزو", + time: "زمان ایزو", + duration: "مدت زمان ایزو", + ipv4: "IPv4 آدرس", + ipv6: "IPv6 آدرس", + cidrv4: "IPv4 دامنه", + cidrv6: "IPv6 دامنه", + base64: "base64-encoded رشته", + base64url: "base64url-encoded رشته", + json_string: "JSON رشته", + e164: "E.164 عدد", + jwt: "JWT", + template_literal: "ورودی", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ورودی نامعتبر: می‌بایست ${issue.expected} می‌بود، ${parsedType(issue.input)} دریافت شد`; + case "invalid_value": + if (issue.values.length === 1) { + return `ورودی نامعتبر: می‌بایست ${stringifyPrimitive(issue.values[0])} می‌بود`; + } + return `گزینه نامعتبر: می‌بایست یکی از ${joinValues(issue.values, "|")} می‌بود`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصر"} باشد`; + } + return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} باشد`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} باشد`; + } + return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} باشد`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`; + } + if (_issue.format === "ends_with") { + return `رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`; + } + if (_issue.format === "includes") { + return `رشته نامعتبر: باید شامل "${_issue.includes}" باشد`; + } + if (_issue.format === "regex") { + return `رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`; + } + return `${Nouns[_issue.format] ?? issue.format} نامعتبر`; + } + case "not_multiple_of": + return `عدد نامعتبر: باید مضرب ${issue.divisor} باشد`; + case "unrecognized_keys": + return `کلید${issue.keys.length > 1 ? "های" : ""} ناشناس: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `کلید ناشناس در ${issue.origin}`; + case "invalid_union": + return `ورودی نامعتبر`; + case "invalid_element": + return `مقدار نامعتبر در ${issue.origin}`; + default: + return `ورودی نامعتبر`; + } + }; +}; +/* harmony default export */ function fa() { + return { + localeError: fa_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/fi.js + +const fi_error = () => { + const Sizable = { + string: { unit: "merkkiä", subject: "merkkijonon" }, + file: { unit: "tavua", subject: "tiedoston" }, + array: { unit: "alkiota", subject: "listan" }, + set: { unit: "alkiota", subject: "joukon" }, + number: { unit: "", subject: "luvun" }, + bigint: { unit: "", subject: "suuren kokonaisluvun" }, + int: { unit: "", subject: "kokonaisluvun" }, + date: { unit: "", subject: "päivämäärän" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "säännöllinen lauseke", + email: "sähköpostiosoite", + url: "URL-osoite", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-aikaleima", + date: "ISO-päivämäärä", + time: "ISO-aika", + duration: "ISO-kesto", + ipv4: "IPv4-osoite", + ipv6: "IPv6-osoite", + cidrv4: "IPv4-alue", + cidrv6: "IPv6-alue", + base64: "base64-koodattu merkkijono", + base64url: "base64url-koodattu merkkijono", + json_string: "JSON-merkkijono", + e164: "E.164-luku", + jwt: "JWT", + template_literal: "templaattimerkkijono", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Virheellinen tyyppi: odotettiin ${issue.expected}, oli ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Virheellinen syöte: täytyy olla ${stringifyPrimitive(issue.values[0])}`; + return `Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue.maximum.toString()} ${sizing.unit}`.trim(); + } + return `Liian suuri: arvon täytyy olla ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue.minimum.toString()} ${sizing.unit}`.trim(); + } + return `Liian pieni: arvon täytyy olla ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Virheellinen syöte: täytyy loppua "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Virheellinen syöte: täytyy sisältää "${_issue.includes}"`; + if (_issue.format === "regex") { + return `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`; + } + return `Virheellinen ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Virheellinen luku: täytyy olla luvun ${issue.divisor} monikerta`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return "Virheellinen avain tietueessa"; + case "invalid_union": + return "Virheellinen unioni"; + case "invalid_element": + return "Virheellinen arvo joukossa"; + default: + return `Virheellinen syöte`; + } + }; +}; +/* harmony default export */ function fi() { + return { + localeError: fi_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/fr.js + +const fr_error = () => { + const Sizable = { + string: { unit: "caractères", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "éléments", verb: "avoir" }, + set: { unit: "éléments", verb: "avoir" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombre"; + } + case "object": { + if (Array.isArray(data)) { + return "tableau"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "entrée", + email: "adresse e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date et heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "durée ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "chaîne encodée en base64", + base64url: "chaîne encodée en base64url", + json_string: "chaîne JSON", + e164: "numéro E.164", + jwt: "JWT", + template_literal: "entrée", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Entrée invalide : ${issue.expected} attendu, ${parsedType(issue.input)} reçu`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrée invalide : ${stringifyPrimitive(issue.values[0])} attendu`; + return `Option invalide : une valeur parmi ${joinValues(issue.values, "|")} attendue`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Trop grand : ${issue.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "élément(s)"}`; + return `Trop grand : ${issue.origin ?? "valeur"} doit être ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Trop petit : ${issue.origin} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : ${issue.origin} doit être ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chaîne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit être un multiple de ${issue.divisor}`; + case "unrecognized_keys": + return `Clé${issue.keys.length > 1 ? "s" : ""} non reconnue${issue.keys.length > 1 ? "s" : ""} : ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Clé invalide dans ${issue.origin}`; + case "invalid_union": + return "Entrée invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue.origin}`; + default: + return `Entrée invalide`; + } + }; +}; +/* harmony default export */ function fr() { + return { + localeError: fr_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/fr-CA.js + +const fr_CA_error = () => { + const Sizable = { + string: { unit: "caractères", verb: "avoir" }, + file: { unit: "octets", verb: "avoir" }, + array: { unit: "éléments", verb: "avoir" }, + set: { unit: "éléments", verb: "avoir" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "entrée", + email: "adresse courriel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "date-heure ISO", + date: "date ISO", + time: "heure ISO", + duration: "durée ISO", + ipv4: "adresse IPv4", + ipv6: "adresse IPv6", + cidrv4: "plage IPv4", + cidrv6: "plage IPv6", + base64: "chaîne encodée en base64", + base64url: "chaîne encodée en base64url", + json_string: "chaîne JSON", + e164: "numéro E.164", + jwt: "JWT", + template_literal: "entrée", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Entrée invalide : attendu ${issue.expected}, reçu ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrée invalide : attendu ${stringifyPrimitive(issue.values[0])}`; + return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "≤" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Trop grand : attendu que ${issue.origin ?? "la valeur"} ait ${adj}${issue.maximum.toString()} ${sizing.unit}`; + return `Trop grand : attendu que ${issue.origin ?? "la valeur"} soit ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? "≥" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Trop petit : attendu que ${issue.origin} ait ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Trop petit : attendu que ${issue.origin} soit ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chaîne invalide : doit inclure "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chaîne invalide : doit correspondre au motif ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} invalide`; + } + case "not_multiple_of": + return `Nombre invalide : doit être un multiple de ${issue.divisor}`; + case "unrecognized_keys": + return `Clé${issue.keys.length > 1 ? "s" : ""} non reconnue${issue.keys.length > 1 ? "s" : ""} : ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Clé invalide dans ${issue.origin}`; + case "invalid_union": + return "Entrée invalide"; + case "invalid_element": + return `Valeur invalide dans ${issue.origin}`; + default: + return `Entrée invalide`; + } + }; +}; +/* harmony default export */ function fr_CA() { + return { + localeError: fr_CA_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/he.js + +const he_error = () => { + // Hebrew labels + grammatical gender + const TypeNames = { + string: { label: "מחרוזת", gender: "f" }, + number: { label: "מספר", gender: "m" }, + boolean: { label: "ערך בוליאני", gender: "m" }, + bigint: { label: "BigInt", gender: "m" }, + date: { label: "תאריך", gender: "m" }, + array: { label: "מערך", gender: "m" }, + object: { label: "אובייקט", gender: "m" }, + null: { label: "ערך ריק (null)", gender: "m" }, + undefined: { label: "ערך לא מוגדר (undefined)", gender: "m" }, + symbol: { label: "סימבול (Symbol)", gender: "m" }, + function: { label: "פונקציה", gender: "f" }, + map: { label: "מפה (Map)", gender: "f" }, + set: { label: "קבוצה (Set)", gender: "f" }, + file: { label: "קובץ", gender: "m" }, + promise: { label: "Promise", gender: "m" }, + NaN: { label: "NaN", gender: "m" }, + unknown: { label: "ערך לא ידוע", gender: "m" }, + value: { label: "ערך", gender: "m" }, + }; + // Sizing units for size-related messages + localized origin labels + const Sizable = { + string: { unit: "תווים", shortLabel: "קצר", longLabel: "ארוך" }, + file: { unit: "בייטים", shortLabel: "קטן", longLabel: "גדול" }, + array: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" }, + set: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" }, + number: { unit: "", shortLabel: "קטן", longLabel: "גדול" }, // no unit + }; + // Helpers — labels, articles, and verbs + const typeEntry = (t) => (t ? TypeNames[t] : undefined); + const typeLabel = (t) => { + const e = typeEntry(t); + if (e) + return e.label; + // fallback: show raw string if unknown + return t ?? TypeNames.unknown.label; + }; + const withDefinite = (t) => `ה${typeLabel(t)}`; + const verbFor = (t) => { + const e = typeEntry(t); + const gender = e?.gender ?? "m"; + return gender === "f" ? "צריכה להיות" : "צריך להיות"; + }; + const getSizing = (origin) => { + if (!origin) + return null; + return Sizable[origin] ?? null; + }; + // Robust type parser for "received" — returns a key we understand or a constructor name + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": + return Number.isNaN(data) ? "NaN" : "number"; + case "object": { + if (Array.isArray(data)) + return "array"; + if (data === null) + return "null"; + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; // keep as-is (e.g., "Date") + } + return "object"; + } + default: + return t; + } + }; + const Nouns = { + regex: { label: "קלט", gender: "m" }, + email: { label: "כתובת אימייל", gender: "f" }, + url: { label: "כתובת רשת", gender: "f" }, + emoji: { label: "אימוג'י", gender: "m" }, + uuid: { label: "UUID", gender: "m" }, + nanoid: { label: "nanoid", gender: "m" }, + guid: { label: "GUID", gender: "m" }, + cuid: { label: "cuid", gender: "m" }, + cuid2: { label: "cuid2", gender: "m" }, + ulid: { label: "ULID", gender: "m" }, + xid: { label: "XID", gender: "m" }, + ksuid: { label: "KSUID", gender: "m" }, + datetime: { label: "תאריך וזמן ISO", gender: "m" }, + date: { label: "תאריך ISO", gender: "m" }, + time: { label: "זמן ISO", gender: "m" }, + duration: { label: "משך זמן ISO", gender: "m" }, + ipv4: { label: "כתובת IPv4", gender: "f" }, + ipv6: { label: "כתובת IPv6", gender: "f" }, + cidrv4: { label: "טווח IPv4", gender: "m" }, + cidrv6: { label: "טווח IPv6", gender: "m" }, + base64: { label: "מחרוזת בבסיס 64", gender: "f" }, + base64url: { label: "מחרוזת בבסיס 64 לכתובות רשת", gender: "f" }, + json_string: { label: "מחרוזת JSON", gender: "f" }, + e164: { label: "מספר E.164", gender: "m" }, + jwt: { label: "JWT", gender: "m" }, + ends_with: { label: "קלט", gender: "m" }, + includes: { label: "קלט", gender: "m" }, + lowercase: { label: "קלט", gender: "m" }, + starts_with: { label: "קלט", gender: "m" }, + uppercase: { label: "קלט", gender: "m" }, + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": { + // Expected type: show without definite article for clearer Hebrew + const expectedKey = issue.expected; + const expected = typeLabel(expectedKey); + // Received: show localized label if known, otherwise constructor/raw + const receivedKey = parsedType(issue.input); + const received = TypeNames[receivedKey]?.label ?? receivedKey; + return `קלט לא תקין: צריך להיות ${expected}, התקבל ${received}`; + } + case "invalid_value": { + if (issue.values.length === 1) { + return `ערך לא תקין: הערך חייב להיות ${stringifyPrimitive(issue.values[0])}`; + } + // Join values with proper Hebrew formatting + const stringified = issue.values.map((v) => stringifyPrimitive(v)); + if (issue.values.length === 2) { + return `ערך לא תקין: האפשרויות המתאימות הן ${stringified[0]} או ${stringified[1]}`; + } + // For 3+ values: "a", "b" או "c" + const lastValue = stringified[stringified.length - 1]; + const restValues = stringified.slice(0, -1).join(", "); + return `ערך לא תקין: האפשרויות המתאימות הן ${restValues} או ${lastValue}`; + } + case "too_big": { + const sizing = getSizing(issue.origin); + const subject = withDefinite(issue.origin ?? "value"); + if (issue.origin === "string") { + // Special handling for strings - more natural Hebrew + return `${sizing?.longLabel ?? "ארוך"} מדי: ${subject} צריכה להכיל ${issue.maximum.toString()} ${sizing?.unit ?? ""} ${issue.inclusive ? "או פחות" : "לכל היותר"}`.trim(); + } + if (issue.origin === "number") { + // Natural Hebrew for numbers + const comparison = issue.inclusive ? `קטן או שווה ל-${issue.maximum}` : `קטן מ-${issue.maximum}`; + return `גדול מדי: ${subject} צריך להיות ${comparison}`; + } + if (issue.origin === "array" || issue.origin === "set") { + // Natural Hebrew for arrays and sets + const verb = issue.origin === "set" ? "צריכה" : "צריך"; + const comparison = issue.inclusive + ? `${issue.maximum} ${sizing?.unit ?? ""} או פחות` + : `פחות מ-${issue.maximum} ${sizing?.unit ?? ""}`; + return `גדול מדי: ${subject} ${verb} להכיל ${comparison}`.trim(); + } + const adj = issue.inclusive ? "<=" : "<"; + const be = verbFor(issue.origin ?? "value"); + if (sizing?.unit) { + return `${sizing.longLabel} מדי: ${subject} ${be} ${adj}${issue.maximum.toString()} ${sizing.unit}`; + } + return `${sizing?.longLabel ?? "גדול"} מדי: ${subject} ${be} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const sizing = getSizing(issue.origin); + const subject = withDefinite(issue.origin ?? "value"); + if (issue.origin === "string") { + // Special handling for strings - more natural Hebrew + return `${sizing?.shortLabel ?? "קצר"} מדי: ${subject} צריכה להכיל ${issue.minimum.toString()} ${sizing?.unit ?? ""} ${issue.inclusive ? "או יותר" : "לפחות"}`.trim(); + } + if (issue.origin === "number") { + // Natural Hebrew for numbers + const comparison = issue.inclusive ? `גדול או שווה ל-${issue.minimum}` : `גדול מ-${issue.minimum}`; + return `קטן מדי: ${subject} צריך להיות ${comparison}`; + } + if (issue.origin === "array" || issue.origin === "set") { + // Natural Hebrew for arrays and sets + const verb = issue.origin === "set" ? "צריכה" : "צריך"; + // Special case for singular (minimum === 1) + if (issue.minimum === 1 && issue.inclusive) { + const singularPhrase = issue.origin === "set" ? "לפחות פריט אחד" : "לפחות פריט אחד"; + return `קטן מדי: ${subject} ${verb} להכיל ${singularPhrase}`; + } + const comparison = issue.inclusive + ? `${issue.minimum} ${sizing?.unit ?? ""} או יותר` + : `יותר מ-${issue.minimum} ${sizing?.unit ?? ""}`; + return `קטן מדי: ${subject} ${verb} להכיל ${comparison}`.trim(); + } + const adj = issue.inclusive ? ">=" : ">"; + const be = verbFor(issue.origin ?? "value"); + if (sizing?.unit) { + return `${sizing.shortLabel} מדי: ${subject} ${be} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `${sizing?.shortLabel ?? "קטן"} מדי: ${subject} ${be} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + // These apply to strings — use feminine grammar + ה׳ הידיעה + if (_issue.format === "starts_with") + return `המחרוזת חייבת להתחיל ב "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `המחרוזת חייבת להסתיים ב "${_issue.suffix}"`; + if (_issue.format === "includes") + return `המחרוזת חייבת לכלול "${_issue.includes}"`; + if (_issue.format === "regex") + return `המחרוזת חייבת להתאים לתבנית ${_issue.pattern}`; + // Handle gender agreement for formats + const nounEntry = Nouns[_issue.format]; + const noun = nounEntry?.label ?? _issue.format; + const gender = nounEntry?.gender ?? "m"; + const adjective = gender === "f" ? "תקינה" : "תקין"; + return `${noun} לא ${adjective}`; + } + case "not_multiple_of": + return `מספר לא תקין: חייב להיות מכפלה של ${issue.divisor}`; + case "unrecognized_keys": + return `מפתח${issue.keys.length > 1 ? "ות" : ""} לא מזוה${issue.keys.length > 1 ? "ים" : "ה"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": { + return `שדה לא תקין באובייקט`; + } + case "invalid_union": + return "קלט לא תקין"; + case "invalid_element": { + const place = withDefinite(issue.origin ?? "array"); + return `ערך לא תקין ב${place}`; + } + default: + return `קלט לא תקין`; + } + }; +}; +/* harmony default export */ function he() { + return { + localeError: he_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/hu.js + +const hu_error = () => { + const Sizable = { + string: { unit: "karakter", verb: "legyen" }, + file: { unit: "byte", verb: "legyen" }, + array: { unit: "elem", verb: "legyen" }, + set: { unit: "elem", verb: "legyen" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "szám"; + } + case "object": { + if (Array.isArray(data)) { + return "tömb"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "bemenet", + email: "email cím", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO időbélyeg", + date: "ISO dátum", + time: "ISO idő", + duration: "ISO időintervallum", + ipv4: "IPv4 cím", + ipv6: "IPv6 cím", + cidrv4: "IPv4 tartomány", + cidrv6: "IPv6 tartomány", + base64: "base64-kódolt string", + base64url: "base64url-kódolt string", + json_string: "JSON string", + e164: "E.164 szám", + jwt: "JWT", + template_literal: "bemenet", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Érvénytelen bemenet: a várt érték ${issue.expected}, a kapott érték ${parsedType(issue.input)}`; + // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Érvénytelen bemenet: a várt érték ${stringifyPrimitive(issue.values[0])}`; + return `Érvénytelen opció: valamelyik érték várt ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Túl nagy: ${issue.origin ?? "érték"} mérete túl nagy ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elem"}`; + return `Túl nagy: a bemeneti érték ${issue.origin ?? "érték"} túl nagy: ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Túl kicsi: a bemeneti érték ${issue.origin} mérete túl kicsi ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Túl kicsi: a bemeneti érték ${issue.origin} túl kicsi ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`; + if (_issue.format === "ends_with") + return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`; + if (_issue.format === "includes") + return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`; + if (_issue.format === "regex") + return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`; + return `Érvénytelen ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Érvénytelen szám: ${issue.divisor} többszörösének kell lennie`; + case "unrecognized_keys": + return `Ismeretlen kulcs${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Érvénytelen kulcs ${issue.origin}`; + case "invalid_union": + return "Érvénytelen bemenet"; + case "invalid_element": + return `Érvénytelen érték: ${issue.origin}`; + default: + return `Érvénytelen bemenet`; + } + }; +}; +/* harmony default export */ function hu() { + return { + localeError: hu_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/id.js + +const id_error = () => { + const Sizable = { + string: { unit: "karakter", verb: "memiliki" }, + file: { unit: "byte", verb: "memiliki" }, + array: { unit: "item", verb: "memiliki" }, + set: { unit: "item", verb: "memiliki" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "input", + email: "alamat email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tanggal dan waktu format ISO", + date: "tanggal format ISO", + time: "jam format ISO", + duration: "durasi format ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "rentang alamat IPv4", + cidrv6: "rentang alamat IPv6", + base64: "string dengan enkode base64", + base64url: "string dengan enkode base64url", + json_string: "string JSON", + e164: "angka E.164", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Input tidak valid: diharapkan ${issue.expected}, diterima ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Input tidak valid: diharapkan ${stringifyPrimitive(issue.values[0])}`; + return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Terlalu besar: diharapkan ${issue.origin ?? "value"} memiliki ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: diharapkan ${issue.origin ?? "value"} menjadi ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Terlalu kecil: diharapkan ${issue.origin} memiliki ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: diharapkan ${issue.origin} menjadi ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak valid: harus menyertakan "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak valid: harus sesuai pola ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} tidak valid`; + } + case "not_multiple_of": + return `Angka tidak valid: harus kelipatan dari ${issue.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali ${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak valid di ${issue.origin}`; + case "invalid_union": + return "Input tidak valid"; + case "invalid_element": + return `Nilai tidak valid di ${issue.origin}`; + default: + return `Input tidak valid`; + } + }; +}; +/* harmony default export */ function id() { + return { + localeError: id_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/is.js + +const is_parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "númer"; + } + case "object": { + if (Array.isArray(data)) { + return "fylki"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; +}; +const is_error = () => { + const Sizable = { + string: { unit: "stafi", verb: "að hafa" }, + file: { unit: "bæti", verb: "að hafa" }, + array: { unit: "hluti", verb: "að hafa" }, + set: { unit: "hluti", verb: "að hafa" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "gildi", + email: "netfang", + url: "vefslóð", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dagsetning og tími", + date: "ISO dagsetning", + time: "ISO tími", + duration: "ISO tímalengd", + ipv4: "IPv4 address", + ipv6: "IPv6 address", + cidrv4: "IPv4 range", + cidrv6: "IPv6 range", + base64: "base64-encoded strengur", + base64url: "base64url-encoded strengur", + json_string: "JSON strengur", + e164: "E.164 tölugildi", + jwt: "JWT", + template_literal: "gildi", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Rangt gildi: Þú slóst inn ${is_parsedType(issue.input)} þar sem á að vera ${issue.expected}`; + case "invalid_value": + if (issue.values.length === 1) + return `Rangt gildi: gert ráð fyrir ${stringifyPrimitive(issue.values[0])}`; + return `Ógilt val: má vera eitt af eftirfarandi ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Of stórt: gert er ráð fyrir að ${issue.origin ?? "gildi"} hafi ${adj}${issue.maximum.toString()} ${sizing.unit ?? "hluti"}`; + return `Of stórt: gert er ráð fyrir að ${issue.origin ?? "gildi"} sé ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Of lítið: gert er ráð fyrir að ${issue.origin} hafi ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Of lítið: gert er ráð fyrir að ${issue.origin} sé ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Ógildur strengur: verður að byrja á "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Ógildur strengur: verður að enda á "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ógildur strengur: verður að innihalda "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ógildur strengur: verður að fylgja mynstri ${_issue.pattern}`; + return `Rangt ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Röng tala: verður að vera margfeldi af ${issue.divisor}`; + case "unrecognized_keys": + return `Óþekkt ${issue.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Rangur lykill í ${issue.origin}`; + case "invalid_union": + return "Rangt gildi"; + case "invalid_element": + return `Rangt gildi í ${issue.origin}`; + default: + return `Rangt gildi`; + } + }; +}; +/* harmony default export */ function is() { + return { + localeError: is_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/it.js + +const it_error = () => { + const Sizable = { + string: { unit: "caratteri", verb: "avere" }, + file: { unit: "byte", verb: "avere" }, + array: { unit: "elementi", verb: "avere" }, + set: { unit: "elementi", verb: "avere" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "numero"; + } + case "object": { + if (Array.isArray(data)) { + return "vettore"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "input", + email: "indirizzo email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e ora ISO", + date: "data ISO", + time: "ora ISO", + duration: "durata ISO", + ipv4: "indirizzo IPv4", + ipv6: "indirizzo IPv6", + cidrv4: "intervallo IPv4", + cidrv6: "intervallo IPv6", + base64: "stringa codificata in base64", + base64url: "URL codificata in base64", + json_string: "stringa JSON", + e164: "numero E.164", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Input non valido: atteso ${issue.expected}, ricevuto ${parsedType(issue.input)}`; + // return `Input non valido: atteso ${issue.expected}, ricevuto ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Input non valido: atteso ${stringifyPrimitive(issue.values[0])}`; + return `Opzione non valida: atteso uno tra ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Troppo grande: ${issue.origin ?? "valore"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementi"}`; + return `Troppo grande: ${issue.origin ?? "valore"} deve essere ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Stringa non valida: deve terminare con "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Stringa non valida: deve includere "${_issue.includes}"`; + if (_issue.format === "regex") + return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Numero non valido: deve essere un multiplo di ${issue.divisor}`; + case "unrecognized_keys": + return `Chiav${issue.keys.length > 1 ? "i" : "e"} non riconosciut${issue.keys.length > 1 ? "e" : "a"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Chiave non valida in ${issue.origin}`; + case "invalid_union": + return "Input non valido"; + case "invalid_element": + return `Valore non valido in ${issue.origin}`; + default: + return `Input non valido`; + } + }; +}; +/* harmony default export */ function it() { + return { + localeError: it_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ja.js + +const ja_error = () => { + const Sizable = { + string: { unit: "文字", verb: "である" }, + file: { unit: "バイト", verb: "である" }, + array: { unit: "要素", verb: "である" }, + set: { unit: "要素", verb: "である" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "数値"; + } + case "object": { + if (Array.isArray(data)) { + return "配列"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "入力値", + email: "メールアドレス", + url: "URL", + emoji: "絵文字", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO日時", + date: "ISO日付", + time: "ISO時刻", + duration: "ISO期間", + ipv4: "IPv4アドレス", + ipv6: "IPv6アドレス", + cidrv4: "IPv4範囲", + cidrv6: "IPv6範囲", + base64: "base64エンコード文字列", + base64url: "base64urlエンコード文字列", + json_string: "JSON文字列", + e164: "E.164番号", + jwt: "JWT", + template_literal: "入力値", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `無効な入力: ${issue.expected}が期待されましたが、${parsedType(issue.input)}が入力されました`; + case "invalid_value": + if (issue.values.length === 1) + return `無効な入力: ${stringifyPrimitive(issue.values[0])}が期待されました`; + return `無効な選択: ${joinValues(issue.values, "、")}のいずれかである必要があります`; + case "too_big": { + const adj = issue.inclusive ? "以下である" : "より小さい"; + const sizing = getSizing(issue.origin); + if (sizing) + return `大きすぎる値: ${issue.origin ?? "値"}は${issue.maximum.toString()}${sizing.unit ?? "要素"}${adj}必要があります`; + return `大きすぎる値: ${issue.origin ?? "値"}は${issue.maximum.toString()}${adj}必要があります`; + } + case "too_small": { + const adj = issue.inclusive ? "以上である" : "より大きい"; + const sizing = getSizing(issue.origin); + if (sizing) + return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${sizing.unit}${adj}必要があります`; + return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${adj}必要があります`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `無効な文字列: "${_issue.prefix}"で始まる必要があります`; + if (_issue.format === "ends_with") + return `無効な文字列: "${_issue.suffix}"で終わる必要があります`; + if (_issue.format === "includes") + return `無効な文字列: "${_issue.includes}"を含む必要があります`; + if (_issue.format === "regex") + return `無効な文字列: パターン${_issue.pattern}に一致する必要があります`; + return `無効な${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `無効な数値: ${issue.divisor}の倍数である必要があります`; + case "unrecognized_keys": + return `認識されていないキー${issue.keys.length > 1 ? "群" : ""}: ${joinValues(issue.keys, "、")}`; + case "invalid_key": + return `${issue.origin}内の無効なキー`; + case "invalid_union": + return "無効な入力"; + case "invalid_element": + return `${issue.origin}内の無効な値`; + default: + return `無効な入力`; + } + }; +}; +/* harmony default export */ function ja() { + return { + localeError: ja_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ka.js + +const ka_parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "რიცხვი"; + } + case "object": { + if (Array.isArray(data)) { + return "მასივი"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + const typeMap = { + string: "სტრინგი", + boolean: "ბულეანი", + undefined: "undefined", + bigint: "bigint", + symbol: "symbol", + function: "ფუნქცია", + }; + return typeMap[t] ?? t; +}; +const ka_error = () => { + const Sizable = { + string: { unit: "სიმბოლო", verb: "უნდა შეიცავდეს" }, + file: { unit: "ბაიტი", verb: "უნდა შეიცავდეს" }, + array: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" }, + set: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "შეყვანა", + email: "ელ-ფოსტის მისამართი", + url: "URL", + emoji: "ემოჯი", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "თარიღი-დრო", + date: "თარიღი", + time: "დრო", + duration: "ხანგრძლივობა", + ipv4: "IPv4 მისამართი", + ipv6: "IPv6 მისამართი", + cidrv4: "IPv4 დიაპაზონი", + cidrv6: "IPv6 დიაპაზონი", + base64: "base64-კოდირებული სტრინგი", + base64url: "base64url-კოდირებული სტრინგი", + json_string: "JSON სტრინგი", + e164: "E.164 ნომერი", + jwt: "JWT", + template_literal: "შეყვანა", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `არასწორი შეყვანა: მოსალოდნელი ${issue.expected}, მიღებული ${ka_parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `არასწორი შეყვანა: მოსალოდნელი ${stringifyPrimitive(issue.values[0])}`; + return `არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${joinValues(issue.values, "|")}-დან`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `ზედმეტად დიდი: მოსალოდნელი ${issue.origin ?? "მნიშვნელობა"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit}`; + return `ზედმეტად დიდი: მოსალოდნელი ${issue.origin ?? "მნიშვნელობა"} იყოს ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `ზედმეტად პატარა: მოსალოდნელი ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `ზედმეტად პატარა: მოსალოდნელი ${issue.origin} იყოს ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `არასწორი სტრინგი: უნდა იწყებოდეს "${_issue.prefix}"-ით`; + } + if (_issue.format === "ends_with") + return `არასწორი სტრინგი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`; + if (_issue.format === "includes") + return `არასწორი სტრინგი: უნდა შეიცავდეს "${_issue.includes}"-ს`; + if (_issue.format === "regex") + return `არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`; + return `არასწორი ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `არასწორი რიცხვი: უნდა იყოს ${issue.divisor}-ის ჯერადი`; + case "unrecognized_keys": + return `უცნობი გასაღებ${issue.keys.length > 1 ? "ები" : "ი"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `არასწორი გასაღები ${issue.origin}-ში`; + case "invalid_union": + return "არასწორი შეყვანა"; + case "invalid_element": + return `არასწორი მნიშვნელობა ${issue.origin}-ში`; + default: + return `არასწორი შეყვანა`; + } + }; +}; +/* harmony default export */ function ka() { + return { + localeError: ka_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/km.js + +const km_error = () => { + const Sizable = { + string: { unit: "តួអក្សរ", verb: "គួរមាន" }, + file: { unit: "បៃ", verb: "គួរមាន" }, + array: { unit: "ធាតុ", verb: "គួរមាន" }, + set: { unit: "ធាតុ", verb: "គួរមាន" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "មិនមែនជាលេខ (NaN)" : "លេខ"; + } + case "object": { + if (Array.isArray(data)) { + return "អារេ (Array)"; + } + if (data === null) { + return "គ្មានតម្លៃ (null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ទិន្នន័យបញ្ចូល", + email: "អាសយដ្ឋានអ៊ីមែល", + url: "URL", + emoji: "សញ្ញាអារម្មណ៍", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "កាលបរិច្ឆេទ និងម៉ោង ISO", + date: "កាលបរិច្ឆេទ ISO", + time: "ម៉ោង ISO", + duration: "រយៈពេល ISO", + ipv4: "អាសយដ្ឋាន IPv4", + ipv6: "អាសយដ្ឋាន IPv6", + cidrv4: "ដែនអាសយដ្ឋាន IPv4", + cidrv6: "ដែនអាសយដ្ឋាន IPv6", + base64: "ខ្សែអក្សរអ៊ិកូដ base64", + base64url: "ខ្សែអក្សរអ៊ិកូដ base64url", + json_string: "ខ្សែអក្សរ JSON", + e164: "លេខ E.164", + jwt: "JWT", + template_literal: "ទិន្នន័យបញ្ចូល", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${issue.expected} ប៉ុន្តែទទួលបាន ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive(issue.values[0])}`; + return `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "ធាតុ"}`; + return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`; + if (_issue.format === "includes") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`; + if (_issue.format === "regex") + return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`; + return `មិនត្រឹមត្រូវ៖ ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue.divisor}`; + case "unrecognized_keys": + return `រកឃើញសោមិនស្គាល់៖ ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `សោមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`; + case "invalid_union": + return `ទិន្នន័យមិនត្រឹមត្រូវ`; + case "invalid_element": + return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`; + default: + return `ទិន្នន័យមិនត្រឹមត្រូវ`; + } + }; +}; +/* harmony default export */ function km() { + return { + localeError: km_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/kh.js + +/** @deprecated Use `km` instead. */ +/* harmony default export */ function kh() { + return km(); +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ko.js + +const ko_error = () => { + const Sizable = { + string: { unit: "문자", verb: "to have" }, + file: { unit: "바이트", verb: "to have" }, + array: { unit: "개", verb: "to have" }, + set: { unit: "개", verb: "to have" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "입력", + email: "이메일 주소", + url: "URL", + emoji: "이모지", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO 날짜시간", + date: "ISO 날짜", + time: "ISO 시간", + duration: "ISO 기간", + ipv4: "IPv4 주소", + ipv6: "IPv6 주소", + cidrv4: "IPv4 범위", + cidrv6: "IPv6 범위", + base64: "base64 인코딩 문자열", + base64url: "base64url 인코딩 문자열", + json_string: "JSON 문자열", + e164: "E.164 번호", + jwt: "JWT", + template_literal: "입력", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `잘못된 입력: 예상 타입은 ${issue.expected}, 받은 타입은 ${parsedType(issue.input)}입니다`; + case "invalid_value": + if (issue.values.length === 1) + return `잘못된 입력: 값은 ${stringifyPrimitive(issue.values[0])} 이어야 합니다`; + return `잘못된 옵션: ${joinValues(issue.values, "또는 ")} 중 하나여야 합니다`; + case "too_big": { + const adj = issue.inclusive ? "이하" : "미만"; + const suffix = adj === "미만" ? "이어야 합니다" : "여야 합니다"; + const sizing = getSizing(issue.origin); + const unit = sizing?.unit ?? "요소"; + if (sizing) + return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()}${unit} ${adj}${suffix}`; + return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()} ${adj}${suffix}`; + } + case "too_small": { + const adj = issue.inclusive ? "이상" : "초과"; + const suffix = adj === "이상" ? "이어야 합니다" : "여야 합니다"; + const sizing = getSizing(issue.origin); + const unit = sizing?.unit ?? "요소"; + if (sizing) { + return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()}${unit} ${adj}${suffix}`; + } + return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()} ${adj}${suffix}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`; + } + if (_issue.format === "ends_with") + return `잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`; + if (_issue.format === "includes") + return `잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`; + if (_issue.format === "regex") + return `잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`; + return `잘못된 ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `잘못된 숫자: ${issue.divisor}의 배수여야 합니다`; + case "unrecognized_keys": + return `인식할 수 없는 키: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `잘못된 키: ${issue.origin}`; + case "invalid_union": + return `잘못된 입력`; + case "invalid_element": + return `잘못된 값: ${issue.origin}`; + default: + return `잘못된 입력`; + } + }; +}; +/* harmony default export */ function ko() { + return { + localeError: ko_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/lt.js + +const lt_parsedType = (data) => { + const t = typeof data; + return parsedTypeFromType(t, data); +}; +const parsedTypeFromType = (t, data = undefined) => { + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "skaičius"; + } + case "bigint": { + return "sveikasis skaičius"; + } + case "string": { + return "eilutė"; + } + case "boolean": { + return "loginė reikšmė"; + } + case "undefined": + case "void": { + return "neapibrėžta reikšmė"; + } + case "function": { + return "funkcija"; + } + case "symbol": { + return "simbolis"; + } + case "object": { + if (data === undefined) + return "nežinomas objektas"; + if (data === null) + return "nulinė reikšmė"; + if (Array.isArray(data)) + return "masyvas"; + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + return "objektas"; + } + //Zod types below + case "null": { + return "nulinė reikšmė"; + } + } + return t; +}; +const capitalizeFirstCharacter = (text) => { + return text.charAt(0).toUpperCase() + text.slice(1); +}; +function getUnitTypeFromNumber(number) { + const abs = Math.abs(number); + const last = abs % 10; + const last2 = abs % 100; + if ((last2 >= 11 && last2 <= 19) || last === 0) + return "many"; + if (last === 1) + return "one"; + return "few"; +} +const lt_error = () => { + const Sizable = { + string: { + unit: { + one: "simbolis", + few: "simboliai", + many: "simbolių", + }, + verb: { + smaller: { + inclusive: "turi būti ne ilgesnė kaip", + notInclusive: "turi būti trumpesnė kaip", + }, + bigger: { + inclusive: "turi būti ne trumpesnė kaip", + notInclusive: "turi būti ilgesnė kaip", + }, + }, + }, + file: { + unit: { + one: "baitas", + few: "baitai", + many: "baitų", + }, + verb: { + smaller: { + inclusive: "turi būti ne didesnis kaip", + notInclusive: "turi būti mažesnis kaip", + }, + bigger: { + inclusive: "turi būti ne mažesnis kaip", + notInclusive: "turi būti didesnis kaip", + }, + }, + }, + array: { + unit: { + one: "elementą", + few: "elementus", + many: "elementų", + }, + verb: { + smaller: { + inclusive: "turi turėti ne daugiau kaip", + notInclusive: "turi turėti mažiau kaip", + }, + bigger: { + inclusive: "turi turėti ne mažiau kaip", + notInclusive: "turi turėti daugiau kaip", + }, + }, + }, + set: { + unit: { + one: "elementą", + few: "elementus", + many: "elementų", + }, + verb: { + smaller: { + inclusive: "turi turėti ne daugiau kaip", + notInclusive: "turi turėti mažiau kaip", + }, + bigger: { + inclusive: "turi turėti ne mažiau kaip", + notInclusive: "turi turėti daugiau kaip", + }, + }, + }, + }; + function getSizing(origin, unitType, inclusive, targetShouldBe) { + const result = Sizable[origin] ?? null; + if (result === null) + return result; + return { + unit: result.unit[unitType], + verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"], + }; + } + const Nouns = { + regex: "įvestis", + email: "el. pašto adresas", + url: "URL", + emoji: "jaustukas", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO data ir laikas", + date: "ISO data", + time: "ISO laikas", + duration: "ISO trukmė", + ipv4: "IPv4 adresas", + ipv6: "IPv6 adresas", + cidrv4: "IPv4 tinklo prefiksas (CIDR)", + cidrv6: "IPv6 tinklo prefiksas (CIDR)", + base64: "base64 užkoduota eilutė", + base64url: "base64url užkoduota eilutė", + json_string: "JSON eilutė", + e164: "E.164 numeris", + jwt: "JWT", + template_literal: "įvestis", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Gautas tipas ${lt_parsedType(issue.input)}, o tikėtasi - ${parsedTypeFromType(issue.expected)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Privalo būti ${stringifyPrimitive(issue.values[0])}`; + return `Privalo būti vienas iš ${joinValues(issue.values, "|")} pasirinkimų`; + case "too_big": { + const origin = parsedTypeFromType(issue.origin); + const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.maximum)), issue.inclusive ?? false, "smaller"); + if (sizing?.verb) + return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} ${sizing.verb} ${issue.maximum.toString()} ${sizing.unit ?? "elementų"}`; + const adj = issue.inclusive ? "ne didesnis kaip" : "mažesnis kaip"; + return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} turi būti ${adj} ${issue.maximum.toString()} ${sizing?.unit}`; + } + case "too_small": { + const origin = parsedTypeFromType(issue.origin); + const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.minimum)), issue.inclusive ?? false, "bigger"); + if (sizing?.verb) + return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} ${sizing.verb} ${issue.minimum.toString()} ${sizing.unit ?? "elementų"}`; + const adj = issue.inclusive ? "ne mažesnis kaip" : "didesnis kaip"; + return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} turi būti ${adj} ${issue.minimum.toString()} ${sizing?.unit}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Eilutė privalo prasidėti "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Eilutė privalo pasibaigti "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Eilutė privalo įtraukti "${_issue.includes}"`; + if (_issue.format === "regex") + return `Eilutė privalo atitikti ${_issue.pattern}`; + return `Neteisingas ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Skaičius privalo būti ${issue.divisor} kartotinis.`; + case "unrecognized_keys": + return `Neatpažint${issue.keys.length > 1 ? "i" : "as"} rakt${issue.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return "Rastas klaidingas raktas"; + case "invalid_union": + return "Klaidinga įvestis"; + case "invalid_element": { + const origin = parsedTypeFromType(issue.origin); + return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} turi klaidingą įvestį`; + } + default: + return "Klaidinga įvestis"; + } + }; +}; +/* harmony default export */ function lt() { + return { + localeError: lt_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/mk.js + +const mk_error = () => { + const Sizable = { + string: { unit: "знаци", verb: "да имаат" }, + file: { unit: "бајти", verb: "да имаат" }, + array: { unit: "ставки", verb: "да имаат" }, + set: { unit: "ставки", verb: "да имаат" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "број"; + } + case "object": { + if (Array.isArray(data)) { + return "низа"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "внес", + email: "адреса на е-пошта", + url: "URL", + emoji: "емоџи", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO датум и време", + date: "ISO датум", + time: "ISO време", + duration: "ISO времетраење", + ipv4: "IPv4 адреса", + ipv6: "IPv6 адреса", + cidrv4: "IPv4 опсег", + cidrv6: "IPv6 опсег", + base64: "base64-енкодирана низа", + base64url: "base64url-енкодирана низа", + json_string: "JSON низа", + e164: "E.164 број", + jwt: "JWT", + template_literal: "внес", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Грешен внес: се очекува ${issue.expected}, примено ${parsedType(issue.input)}`; + // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; + return `Грешана опција: се очекува една ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Премногу голем: се очекува ${issue.origin ?? "вредноста"} да има ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елементи"}`; + return `Премногу голем: се очекува ${issue.origin ?? "вредноста"} да биде ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Премногу мал: се очекува ${issue.origin} да има ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Премногу мал: се очекува ${issue.origin} да биде ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Неважечка низа: мора да започнува со "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Неважечка низа: мора да завршува со "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неважечка низа: мора да вклучува "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`; + return `Invalid ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Грешен број: мора да биде делив со ${issue.divisor}`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Непрепознаени клучеви" : "Непрепознаен клуч"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Грешен клуч во ${issue.origin}`; + case "invalid_union": + return "Грешен внес"; + case "invalid_element": + return `Грешна вредност во ${issue.origin}`; + default: + return `Грешен внес`; + } + }; +}; +/* harmony default export */ function mk() { + return { + localeError: mk_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ms.js + +const ms_error = () => { + const Sizable = { + string: { unit: "aksara", verb: "mempunyai" }, + file: { unit: "bait", verb: "mempunyai" }, + array: { unit: "elemen", verb: "mempunyai" }, + set: { unit: "elemen", verb: "mempunyai" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nombor"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "input", + email: "alamat e-mel", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "tarikh masa ISO", + date: "tarikh ISO", + time: "masa ISO", + duration: "tempoh ISO", + ipv4: "alamat IPv4", + ipv6: "alamat IPv6", + cidrv4: "julat IPv4", + cidrv6: "julat IPv6", + base64: "string dikodkan base64", + base64url: "string dikodkan base64url", + json_string: "string JSON", + e164: "nombor E.164", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Input tidak sah: dijangka ${issue.expected}, diterima ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Input tidak sah: dijangka ${stringifyPrimitive(issue.values[0])}`; + return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemen"}`; + return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} adalah ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Terlalu kecil: dijangka ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Terlalu kecil: dijangka ${issue.origin} adalah ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; + if (_issue.format === "includes") + return `String tidak sah: mesti mengandungi "${_issue.includes}"`; + if (_issue.format === "regex") + return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} tidak sah`; + } + case "not_multiple_of": + return `Nombor tidak sah: perlu gandaan ${issue.divisor}`; + case "unrecognized_keys": + return `Kunci tidak dikenali: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Kunci tidak sah dalam ${issue.origin}`; + case "invalid_union": + return "Input tidak sah"; + case "invalid_element": + return `Nilai tidak sah dalam ${issue.origin}`; + default: + return `Input tidak sah`; + } + }; +}; +/* harmony default export */ function ms() { + return { + localeError: ms_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/nl.js + +const nl_error = () => { + const Sizable = { + string: { unit: "tekens", verb: "te hebben" }, + file: { unit: "bytes", verb: "te hebben" }, + array: { unit: "elementen", verb: "te hebben" }, + set: { unit: "elementen", verb: "te hebben" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "getal"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "invoer", + email: "emailadres", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum en tijd", + date: "ISO datum", + time: "ISO tijd", + duration: "ISO duur", + ipv4: "IPv4-adres", + ipv6: "IPv6-adres", + cidrv4: "IPv4-bereik", + cidrv6: "IPv6-bereik", + base64: "base64-gecodeerde tekst", + base64url: "base64 URL-gecodeerde tekst", + json_string: "JSON string", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "invoer", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ongeldige invoer: verwacht ${issue.expected}, ontving ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue.values[0])}`; + return `Ongeldige optie: verwacht één van ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Te groot: verwacht dat ${issue.origin ?? "waarde"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementen"}`; + return `Te groot: verwacht dat ${issue.origin ?? "waarde"} ${adj}${issue.maximum.toString()} is`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Te klein: verwacht dat ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Te klein: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} is`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; + } + if (_issue.format === "ends_with") + return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; + if (_issue.format === "includes") + return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; + if (_issue.format === "regex") + return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; + return `Ongeldig: ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ongeldig getal: moet een veelvoud van ${issue.divisor} zijn`; + case "unrecognized_keys": + return `Onbekende key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ongeldige key in ${issue.origin}`; + case "invalid_union": + return "Ongeldige invoer"; + case "invalid_element": + return `Ongeldige waarde in ${issue.origin}`; + default: + return `Ongeldige invoer`; + } + }; +}; +/* harmony default export */ function nl() { + return { + localeError: nl_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/no.js + +const no_error = () => { + const Sizable = { + string: { unit: "tegn", verb: "å ha" }, + file: { unit: "bytes", verb: "å ha" }, + array: { unit: "elementer", verb: "å inneholde" }, + set: { unit: "elementer", verb: "å inneholde" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "tall"; + } + case "object": { + if (Array.isArray(data)) { + return "liste"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "input", + email: "e-postadresse", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO dato- og klokkeslett", + date: "ISO-dato", + time: "ISO-klokkeslett", + duration: "ISO-varighet", + ipv4: "IPv4-område", + ipv6: "IPv6-område", + cidrv4: "IPv4-spekter", + cidrv6: "IPv6-spekter", + base64: "base64-enkodet streng", + base64url: "base64url-enkodet streng", + json_string: "JSON-streng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ugyldig input: forventet ${issue.expected}, fikk ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ugyldig verdi: forventet ${stringifyPrimitive(issue.values[0])}`; + return `Ugyldig valg: forventet en av ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementer"}`; + return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Ugyldig streng: må starte med "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ugyldig streng: må ende med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ugyldig streng: må inneholde "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ugyldig streng: må matche mønsteret ${_issue.pattern}`; + return `Ugyldig ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ugyldig tall: må være et multiplum av ${issue.divisor}`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Ukjente nøkler" : "Ukjent nøkkel"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ugyldig nøkkel i ${issue.origin}`; + case "invalid_union": + return "Ugyldig input"; + case "invalid_element": + return `Ugyldig verdi i ${issue.origin}`; + default: + return `Ugyldig input`; + } + }; +}; +/* harmony default export */ function no() { + return { + localeError: no_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ota.js + +const ota_error = () => { + const Sizable = { + string: { unit: "harf", verb: "olmalıdır" }, + file: { unit: "bayt", verb: "olmalıdır" }, + array: { unit: "unsur", verb: "olmalıdır" }, + set: { unit: "unsur", verb: "olmalıdır" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "numara"; + } + case "object": { + if (Array.isArray(data)) { + return "saf"; + } + if (data === null) { + return "gayb"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "giren", + email: "epostagâh", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO hengâmı", + date: "ISO tarihi", + time: "ISO zamanı", + duration: "ISO müddeti", + ipv4: "IPv4 nişânı", + ipv6: "IPv6 nişânı", + cidrv4: "IPv4 menzili", + cidrv6: "IPv6 menzili", + base64: "base64-şifreli metin", + base64url: "base64url-şifreli metin", + json_string: "JSON metin", + e164: "E.164 sayısı", + jwt: "JWT", + template_literal: "giren", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Fâsit giren: umulan ${issue.expected}, alınan ${parsedType(issue.input)}`; + // return `Fâsit giren: umulan ${issue.expected}, alınan ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Fâsit giren: umulan ${stringifyPrimitive(issue.values[0])}`; + return `Fâsit tercih: mûteberler ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmalıydı.`; + return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} olmalıydı.`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} ${sizing.unit} sahip olmalıydı.`; + } + return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} olmalıydı.`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Fâsit metin: "${_issue.prefix}" ile başlamalı.`; + if (_issue.format === "ends_with") + return `Fâsit metin: "${_issue.suffix}" ile bitmeli.`; + if (_issue.format === "includes") + return `Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`; + if (_issue.format === "regex") + return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`; + return `Fâsit ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Fâsit sayı: ${issue.divisor} katı olmalıydı.`; + case "unrecognized_keys": + return `Tanınmayan anahtar ${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} için tanınmayan anahtar var.`; + case "invalid_union": + return "Giren tanınamadı."; + case "invalid_element": + return `${issue.origin} için tanınmayan kıymet var.`; + default: + return `Kıymet tanınamadı.`; + } + }; +}; +/* harmony default export */ function ota() { + return { + localeError: ota_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ps.js + +const ps_error = () => { + const Sizable = { + string: { unit: "توکي", verb: "ولري" }, + file: { unit: "بایټس", verb: "ولري" }, + array: { unit: "توکي", verb: "ولري" }, + set: { unit: "توکي", verb: "ولري" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "عدد"; + } + case "object": { + if (Array.isArray(data)) { + return "ارې"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ورودي", + email: "بریښنالیک", + url: "یو آر ال", + emoji: "ایموجي", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "نیټه او وخت", + date: "نېټه", + time: "وخت", + duration: "موده", + ipv4: "د IPv4 پته", + ipv6: "د IPv6 پته", + cidrv4: "د IPv4 ساحه", + cidrv6: "د IPv6 ساحه", + base64: "base64-encoded متن", + base64url: "base64url-encoded متن", + json_string: "JSON متن", + e164: "د E.164 شمېره", + jwt: "JWT", + template_literal: "ورودي", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ناسم ورودي: باید ${issue.expected} وای, مګر ${parsedType(issue.input)} ترلاسه شو`; + case "invalid_value": + if (issue.values.length === 1) { + return `ناسم ورودي: باید ${stringifyPrimitive(issue.values[0])} وای`; + } + return `ناسم انتخاب: باید یو له ${joinValues(issue.values, "|")} څخه وای`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصرونه"} ولري`; + } + return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} وي`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} ولري`; + } + return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} وي`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `ناسم متن: باید د "${_issue.prefix}" سره پیل شي`; + } + if (_issue.format === "ends_with") { + return `ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`; + } + if (_issue.format === "includes") { + return `ناسم متن: باید "${_issue.includes}" ولري`; + } + if (_issue.format === "regex") { + return `ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`; + } + return `${Nouns[_issue.format] ?? issue.format} ناسم دی`; + } + case "not_multiple_of": + return `ناسم عدد: باید د ${issue.divisor} مضرب وي`; + case "unrecognized_keys": + return `ناسم ${issue.keys.length > 1 ? "کلیډونه" : "کلیډ"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `ناسم کلیډ په ${issue.origin} کې`; + case "invalid_union": + return `ناسمه ورودي`; + case "invalid_element": + return `ناسم عنصر په ${issue.origin} کې`; + default: + return `ناسمه ورودي`; + } + }; +}; +/* harmony default export */ function ps() { + return { + localeError: ps_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/pl.js + +const pl_error = () => { + const Sizable = { + string: { unit: "znaków", verb: "mieć" }, + file: { unit: "bajtów", verb: "mieć" }, + array: { unit: "elementów", verb: "mieć" }, + set: { unit: "elementów", verb: "mieć" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "liczba"; + } + case "object": { + if (Array.isArray(data)) { + return "tablica"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "wyrażenie", + email: "adres email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data i godzina w formacie ISO", + date: "data w formacie ISO", + time: "godzina w formacie ISO", + duration: "czas trwania ISO", + ipv4: "adres IPv4", + ipv6: "adres IPv6", + cidrv4: "zakres IPv4", + cidrv6: "zakres IPv6", + base64: "ciąg znaków zakodowany w formacie base64", + base64url: "ciąg znaków zakodowany w formacie base64url", + json_string: "ciąg znaków w formacie JSON", + e164: "liczba E.164", + jwt: "JWT", + template_literal: "wejście", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Nieprawidłowe dane wejściowe: oczekiwano ${issue.expected}, otrzymano ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive(issue.values[0])}`; + return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Za duża wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementów"}`; + } + return `Zbyt duż(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Za mała wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.minimum.toString()} ${sizing.unit ?? "elementów"}`; + } + return `Zbyt mał(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`; + if (_issue.format === "regex") + return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`; + return `Nieprawidłow(y/a/e) ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Nieprawidłowa liczba: musi być wielokrotnością ${issue.divisor}`; + case "unrecognized_keys": + return `Nierozpoznane klucze${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Nieprawidłowy klucz w ${issue.origin}`; + case "invalid_union": + return "Nieprawidłowe dane wejściowe"; + case "invalid_element": + return `Nieprawidłowa wartość w ${issue.origin}`; + default: + return `Nieprawidłowe dane wejściowe`; + } + }; +}; +/* harmony default export */ function pl() { + return { + localeError: pl_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/pt.js + +const pt_error = () => { + const Sizable = { + string: { unit: "caracteres", verb: "ter" }, + file: { unit: "bytes", verb: "ter" }, + array: { unit: "itens", verb: "ter" }, + set: { unit: "itens", verb: "ter" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "número"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "nulo"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "padrão", + email: "endereço de e-mail", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "data e hora ISO", + date: "data ISO", + time: "hora ISO", + duration: "duração ISO", + ipv4: "endereço IPv4", + ipv6: "endereço IPv6", + cidrv4: "faixa de IPv4", + cidrv6: "faixa de IPv6", + base64: "texto codificado em base64", + base64url: "URL codificada em base64", + json_string: "texto JSON", + e164: "número E.164", + jwt: "JWT", + template_literal: "entrada", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Tipo inválido: esperado ${issue.expected}, recebido ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Entrada inválida: esperado ${stringifyPrimitive(issue.values[0])}`; + return `Opção inválida: esperada uma das ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Muito grande: esperado que ${issue.origin ?? "valor"} tivesse ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`; + return `Muito grande: esperado que ${issue.origin ?? "valor"} fosse ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Muito pequeno: esperado que ${issue.origin} tivesse ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Muito pequeno: esperado que ${issue.origin} fosse ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Texto inválido: deve começar com "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Texto inválido: deve terminar com "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Texto inválido: deve incluir "${_issue.includes}"`; + if (_issue.format === "regex") + return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} inválido`; + } + case "not_multiple_of": + return `Número inválido: deve ser múltiplo de ${issue.divisor}`; + case "unrecognized_keys": + return `Chave${issue.keys.length > 1 ? "s" : ""} desconhecida${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Chave inválida em ${issue.origin}`; + case "invalid_union": + return "Entrada inválida"; + case "invalid_element": + return `Valor inválido em ${issue.origin}`; + default: + return `Campo inválido`; + } + }; +}; +/* harmony default export */ function pt() { + return { + localeError: pt_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ru.js + +function getRussianPlural(count, one, few, many) { + const absCount = Math.abs(count); + const lastDigit = absCount % 10; + const lastTwoDigits = absCount % 100; + if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { + return many; + } + if (lastDigit === 1) { + return one; + } + if (lastDigit >= 2 && lastDigit <= 4) { + return few; + } + return many; +} +const ru_error = () => { + const Sizable = { + string: { + unit: { + one: "символ", + few: "символа", + many: "символов", + }, + verb: "иметь", + }, + file: { + unit: { + one: "байт", + few: "байта", + many: "байт", + }, + verb: "иметь", + }, + array: { + unit: { + one: "элемент", + few: "элемента", + many: "элементов", + }, + verb: "иметь", + }, + set: { + unit: { + one: "элемент", + few: "элемента", + many: "элементов", + }, + verb: "иметь", + }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "число"; + } + case "object": { + if (Array.isArray(data)) { + return "массив"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ввод", + email: "email адрес", + url: "URL", + emoji: "эмодзи", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO дата и время", + date: "ISO дата", + time: "ISO время", + duration: "ISO длительность", + ipv4: "IPv4 адрес", + ipv6: "IPv6 адрес", + cidrv4: "IPv4 диапазон", + cidrv6: "IPv6 диапазон", + base64: "строка в формате base64", + base64url: "строка в формате base64url", + json_string: "JSON строка", + e164: "номер E.164", + jwt: "JWT", + template_literal: "ввод", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Неверный ввод: ожидалось ${issue.expected}, получено ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Неверный ввод: ожидалось ${stringifyPrimitive(issue.values[0])}`; + return `Неверный вариант: ожидалось одно из ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + const maxValue = Number(issue.maximum); + const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет иметь ${adj}${issue.maximum.toString()} ${unit}`; + } + return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + const minValue = Number(issue.minimum); + const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); + return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет иметь ${adj}${issue.minimum.toString()} ${unit}`; + } + return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Неверная строка: должна начинаться с "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Неверная строка: должна заканчиваться на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неверная строка: должна содержать "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неверная строка: должна соответствовать шаблону ${_issue.pattern}`; + return `Неверный ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Неверное число: должно быть кратным ${issue.divisor}`; + case "unrecognized_keys": + return `Нераспознанн${issue.keys.length > 1 ? "ые" : "ый"} ключ${issue.keys.length > 1 ? "и" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Неверный ключ в ${issue.origin}`; + case "invalid_union": + return "Неверные входные данные"; + case "invalid_element": + return `Неверное значение в ${issue.origin}`; + default: + return `Неверные входные данные`; + } + }; +}; +/* harmony default export */ function ru() { + return { + localeError: ru_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/sl.js + +const sl_error = () => { + const Sizable = { + string: { unit: "znakov", verb: "imeti" }, + file: { unit: "bajtov", verb: "imeti" }, + array: { unit: "elementov", verb: "imeti" }, + set: { unit: "elementov", verb: "imeti" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "število"; + } + case "object": { + if (Array.isArray(data)) { + return "tabela"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "vnos", + email: "e-poštni naslov", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO datum in čas", + date: "ISO datum", + time: "ISO čas", + duration: "ISO trajanje", + ipv4: "IPv4 naslov", + ipv6: "IPv6 naslov", + cidrv4: "obseg IPv4", + cidrv6: "obseg IPv6", + base64: "base64 kodiran niz", + base64url: "base64url kodiran niz", + json_string: "JSON niz", + e164: "E.164 številka", + jwt: "JWT", + template_literal: "vnos", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Neveljaven vnos: pričakovano ${issue.expected}, prejeto ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Neveljaven vnos: pričakovano ${stringifyPrimitive(issue.values[0])}`; + return `Neveljavna možnost: pričakovano eno izmed ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Preveliko: pričakovano, da bo ${issue.origin ?? "vrednost"} imelo ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementov"}`; + return `Preveliko: pričakovano, da bo ${issue.origin ?? "vrednost"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Premajhno: pričakovano, da bo ${issue.origin} imelo ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Premajhno: pričakovano, da bo ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Neveljaven niz: mora se začeti z "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Neveljaven niz: mora se končati z "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; + if (_issue.format === "regex") + return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; + return `Neveljaven ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Neveljavno število: mora biti večkratnik ${issue.divisor}`; + case "unrecognized_keys": + return `Neprepoznan${issue.keys.length > 1 ? "i ključi" : " ključ"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Neveljaven ključ v ${issue.origin}`; + case "invalid_union": + return "Neveljaven vnos"; + case "invalid_element": + return `Neveljavna vrednost v ${issue.origin}`; + default: + return "Neveljaven vnos"; + } + }; +}; +/* harmony default export */ function sl() { + return { + localeError: sl_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/sv.js + +const sv_error = () => { + const Sizable = { + string: { unit: "tecken", verb: "att ha" }, + file: { unit: "bytes", verb: "att ha" }, + array: { unit: "objekt", verb: "att innehålla" }, + set: { unit: "objekt", verb: "att innehålla" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "antal"; + } + case "object": { + if (Array.isArray(data)) { + return "lista"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "reguljärt uttryck", + email: "e-postadress", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO-datum och tid", + date: "ISO-datum", + time: "ISO-tid", + duration: "ISO-varaktighet", + ipv4: "IPv4-intervall", + ipv6: "IPv6-intervall", + cidrv4: "IPv4-spektrum", + cidrv6: "IPv6-spektrum", + base64: "base64-kodad sträng", + base64url: "base64url-kodad sträng", + json_string: "JSON-sträng", + e164: "E.164-nummer", + jwt: "JWT", + template_literal: "mall-literal", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ogiltig inmatning: förväntat ${issue.expected}, fick ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ogiltig inmatning: förväntat ${stringifyPrimitive(issue.values[0])}`; + return `Ogiltigt val: förväntade en av ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `För stor(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`; + } + return `För stor(t): förväntat ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `Ogiltig sträng: måste börja med "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `Ogiltig sträng: måste sluta med "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ogiltig sträng: måste innehålla "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`; + return `Ogiltig(t) ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Ogiltigt tal: måste vara en multipel av ${issue.divisor}`; + case "unrecognized_keys": + return `${issue.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Ogiltig nyckel i ${issue.origin ?? "värdet"}`; + case "invalid_union": + return "Ogiltig input"; + case "invalid_element": + return `Ogiltigt värde i ${issue.origin ?? "värdet"}`; + default: + return `Ogiltig input`; + } + }; +}; +/* harmony default export */ function sv() { + return { + localeError: sv_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ta.js + +const ta_error = () => { + const Sizable = { + string: { unit: "எழுத்துக்கள்", verb: "கொண்டிருக்க வேண்டும்" }, + file: { unit: "பைட்டுகள்", verb: "கொண்டிருக்க வேண்டும்" }, + array: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, + set: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "எண் அல்லாதது" : "எண்"; + } + case "object": { + if (Array.isArray(data)) { + return "அணி"; + } + if (data === null) { + return "வெறுமை"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "உள்ளீடு", + email: "மின்னஞ்சல் முகவரி", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO தேதி நேரம்", + date: "ISO தேதி", + time: "ISO நேரம்", + duration: "ISO கால அளவு", + ipv4: "IPv4 முகவரி", + ipv6: "IPv6 முகவரி", + cidrv4: "IPv4 வரம்பு", + cidrv6: "IPv6 வரம்பு", + base64: "base64-encoded சரம்", + base64url: "base64url-encoded சரம்", + json_string: "JSON சரம்", + e164: "E.164 எண்", + jwt: "JWT", + template_literal: "input", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${issue.expected}, பெறப்பட்டது ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive(issue.values[0])}`; + return `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues(issue.values, "|")} இல் ஒன்று`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "உறுப்புகள்"} ஆக இருக்க வேண்டும்`; + } + return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ஆக இருக்க வேண்டும்`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`; // + } + return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ஆக இருக்க வேண்டும்`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`; + if (_issue.format === "ends_with") + return `தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`; + if (_issue.format === "includes") + return `தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`; + if (_issue.format === "regex") + return `தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`; + return `தவறான ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `தவறான எண்: ${issue.divisor} இன் பலமாக இருக்க வேண்டும்`; + case "unrecognized_keys": + return `அடையாளம் தெரியாத விசை${issue.keys.length > 1 ? "கள்" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} இல் தவறான விசை`; + case "invalid_union": + return "தவறான உள்ளீடு"; + case "invalid_element": + return `${issue.origin} இல் தவறான மதிப்பு`; + default: + return `தவறான உள்ளீடு`; + } + }; +}; +/* harmony default export */ function ta() { + return { + localeError: ta_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/th.js + +const th_error = () => { + const Sizable = { + string: { unit: "ตัวอักษร", verb: "ควรมี" }, + file: { unit: "ไบต์", verb: "ควรมี" }, + array: { unit: "รายการ", verb: "ควรมี" }, + set: { unit: "รายการ", verb: "ควรมี" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "ไม่ใช่ตัวเลข (NaN)" : "ตัวเลข"; + } + case "object": { + if (Array.isArray(data)) { + return "อาร์เรย์ (Array)"; + } + if (data === null) { + return "ไม่มีค่า (null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ข้อมูลที่ป้อน", + email: "ที่อยู่อีเมล", + url: "URL", + emoji: "อิโมจิ", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "วันที่เวลาแบบ ISO", + date: "วันที่แบบ ISO", + time: "เวลาแบบ ISO", + duration: "ช่วงเวลาแบบ ISO", + ipv4: "ที่อยู่ IPv4", + ipv6: "ที่อยู่ IPv6", + cidrv4: "ช่วง IP แบบ IPv4", + cidrv6: "ช่วง IP แบบ IPv6", + base64: "ข้อความแบบ Base64", + base64url: "ข้อความแบบ Base64 สำหรับ URL", + json_string: "ข้อความแบบ JSON", + e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)", + jwt: "โทเคน JWT", + template_literal: "ข้อมูลที่ป้อน", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${issue.expected} แต่ได้รับ ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive(issue.values[0])}`; + return `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "ไม่เกิน" : "น้อยกว่า"; + const sizing = getSizing(issue.origin); + if (sizing) + return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()} ${sizing.unit ?? "รายการ"}`; + return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? "อย่างน้อย" : "มากกว่า"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()} ${sizing.unit}`; + } + return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`; + } + if (_issue.format === "ends_with") + return `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`; + if (_issue.format === "includes") + return `รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`; + if (_issue.format === "regex") + return `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`; + return `รูปแบบไม่ถูกต้อง: ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue.divisor} ได้ลงตัว`; + case "unrecognized_keys": + return `พบคีย์ที่ไม่รู้จัก: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `คีย์ไม่ถูกต้องใน ${issue.origin}`; + case "invalid_union": + return "ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้"; + case "invalid_element": + return `ข้อมูลไม่ถูกต้องใน ${issue.origin}`; + default: + return `ข้อมูลไม่ถูกต้อง`; + } + }; +}; +/* harmony default export */ function th() { + return { + localeError: th_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/tr.js + +const tr_parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; +}; +const tr_error = () => { + const Sizable = { + string: { unit: "karakter", verb: "olmalı" }, + file: { unit: "bayt", verb: "olmalı" }, + array: { unit: "öğe", verb: "olmalı" }, + set: { unit: "öğe", verb: "olmalı" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const Nouns = { + regex: "girdi", + email: "e-posta adresi", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO tarih ve saat", + date: "ISO tarih", + time: "ISO saat", + duration: "ISO süre", + ipv4: "IPv4 adresi", + ipv6: "IPv6 adresi", + cidrv4: "IPv4 aralığı", + cidrv6: "IPv6 aralığı", + base64: "base64 ile şifrelenmiş metin", + base64url: "base64url ile şifrelenmiş metin", + json_string: "JSON dizesi", + e164: "E.164 sayısı", + jwt: "JWT", + template_literal: "Şablon dizesi", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Geçersiz değer: beklenen ${issue.expected}, alınan ${tr_parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Geçersiz değer: beklenen ${stringifyPrimitive(issue.values[0])}`; + return `Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çok büyük: beklenen ${issue.origin ?? "değer"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "öğe"}`; + return `Çok büyük: beklenen ${issue.origin ?? "değer"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Geçersiz metin: "${_issue.prefix}" ile başlamalı`; + if (_issue.format === "ends_with") + return `Geçersiz metin: "${_issue.suffix}" ile bitmeli`; + if (_issue.format === "includes") + return `Geçersiz metin: "${_issue.includes}" içermeli`; + if (_issue.format === "regex") + return `Geçersiz metin: ${_issue.pattern} desenine uymalı`; + return `Geçersiz ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Geçersiz sayı: ${issue.divisor} ile tam bölünebilmeli`; + case "unrecognized_keys": + return `Tanınmayan anahtar${issue.keys.length > 1 ? "lar" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} içinde geçersiz anahtar`; + case "invalid_union": + return "Geçersiz değer"; + case "invalid_element": + return `${issue.origin} içinde geçersiz değer`; + default: + return `Geçersiz değer`; + } + }; +}; +/* harmony default export */ function tr() { + return { + localeError: tr_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/uk.js + +const uk_error = () => { + const Sizable = { + string: { unit: "символів", verb: "матиме" }, + file: { unit: "байтів", verb: "матиме" }, + array: { unit: "елементів", verb: "матиме" }, + set: { unit: "елементів", verb: "матиме" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "число"; + } + case "object": { + if (Array.isArray(data)) { + return "масив"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "вхідні дані", + email: "адреса електронної пошти", + url: "URL", + emoji: "емодзі", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "дата та час ISO", + date: "дата ISO", + time: "час ISO", + duration: "тривалість ISO", + ipv4: "адреса IPv4", + ipv6: "адреса IPv6", + cidrv4: "діапазон IPv4", + cidrv6: "діапазон IPv6", + base64: "рядок у кодуванні base64", + base64url: "рядок у кодуванні base64url", + json_string: "рядок JSON", + e164: "номер E.164", + jwt: "JWT", + template_literal: "вхідні дані", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${parsedType(issue.input)}`; + // return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${util.getParsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Неправильні вхідні дані: очікується ${stringifyPrimitive(issue.values[0])}`; + return `Неправильна опція: очікується одне з ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Занадто велике: очікується, що ${issue.origin ?? "значення"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елементів"}`; + return `Занадто велике: очікується, що ${issue.origin ?? "значення"} буде ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Занадто мале: очікується, що ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Занадто мале: очікується, що ${issue.origin} буде ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Неправильний рядок: повинен починатися з "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Неправильний рядок: повинен містити "${_issue.includes}"`; + if (_issue.format === "regex") + return `Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`; + return `Неправильний ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Неправильне число: повинно бути кратним ${issue.divisor}`; + case "unrecognized_keys": + return `Нерозпізнаний ключ${issue.keys.length > 1 ? "і" : ""}: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Неправильний ключ у ${issue.origin}`; + case "invalid_union": + return "Неправильні вхідні дані"; + case "invalid_element": + return `Неправильне значення у ${issue.origin}`; + default: + return `Неправильні вхідні дані`; + } + }; +}; +/* harmony default export */ function uk() { + return { + localeError: uk_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ua.js + +/** @deprecated Use `uk` instead. */ +/* harmony default export */ function ua() { + return uk(); +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ur.js + +const ur_error = () => { + const Sizable = { + string: { unit: "حروف", verb: "ہونا" }, + file: { unit: "بائٹس", verb: "ہونا" }, + array: { unit: "آئٹمز", verb: "ہونا" }, + set: { unit: "آئٹمز", verb: "ہونا" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "نمبر"; + } + case "object": { + if (Array.isArray(data)) { + return "آرے"; + } + if (data === null) { + return "نل"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ان پٹ", + email: "ای میل ایڈریس", + url: "یو آر ایل", + emoji: "ایموجی", + uuid: "یو یو آئی ڈی", + uuidv4: "یو یو آئی ڈی وی 4", + uuidv6: "یو یو آئی ڈی وی 6", + nanoid: "نینو آئی ڈی", + guid: "جی یو آئی ڈی", + cuid: "سی یو آئی ڈی", + cuid2: "سی یو آئی ڈی 2", + ulid: "یو ایل آئی ڈی", + xid: "ایکس آئی ڈی", + ksuid: "کے ایس یو آئی ڈی", + datetime: "آئی ایس او ڈیٹ ٹائم", + date: "آئی ایس او تاریخ", + time: "آئی ایس او وقت", + duration: "آئی ایس او مدت", + ipv4: "آئی پی وی 4 ایڈریس", + ipv6: "آئی پی وی 6 ایڈریس", + cidrv4: "آئی پی وی 4 رینج", + cidrv6: "آئی پی وی 6 رینج", + base64: "بیس 64 ان کوڈڈ سٹرنگ", + base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ", + json_string: "جے ایس او این سٹرنگ", + e164: "ای 164 نمبر", + jwt: "جے ڈبلیو ٹی", + template_literal: "ان پٹ", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `غلط ان پٹ: ${issue.expected} متوقع تھا، ${parsedType(issue.input)} موصول ہوا`; + case "invalid_value": + if (issue.values.length === 1) + return `غلط ان پٹ: ${stringifyPrimitive(issue.values[0])} متوقع تھا`; + return `غلط آپشن: ${joinValues(issue.values, "|")} میں سے ایک متوقع تھا`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `بہت بڑا: ${issue.origin ?? "ویلیو"} کے ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عناصر"} ہونے متوقع تھے`; + return `بہت بڑا: ${issue.origin ?? "ویلیو"} کا ${adj}${issue.maximum.toString()} ہونا متوقع تھا`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `بہت چھوٹا: ${issue.origin} کے ${adj}${issue.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`; + } + return `بہت چھوٹا: ${issue.origin} کا ${adj}${issue.minimum.toString()} ہونا متوقع تھا`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`; + } + if (_issue.format === "ends_with") + return `غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`; + if (_issue.format === "includes") + return `غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`; + if (_issue.format === "regex") + return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`; + return `غلط ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `غلط نمبر: ${issue.divisor} کا مضاعف ہونا چاہیے`; + case "unrecognized_keys": + return `غیر تسلیم شدہ کی${issue.keys.length > 1 ? "ز" : ""}: ${joinValues(issue.keys, "، ")}`; + case "invalid_key": + return `${issue.origin} میں غلط کی`; + case "invalid_union": + return "غلط ان پٹ"; + case "invalid_element": + return `${issue.origin} میں غلط ویلیو`; + default: + return `غلط ان پٹ`; + } + }; +}; +/* harmony default export */ function ur() { + return { + localeError: ur_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/vi.js + +const vi_error = () => { + const Sizable = { + string: { unit: "ký tự", verb: "có" }, + file: { unit: "byte", verb: "có" }, + array: { unit: "phần tử", verb: "có" }, + set: { unit: "phần tử", verb: "có" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "số"; + } + case "object": { + if (Array.isArray(data)) { + return "mảng"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "đầu vào", + email: "địa chỉ email", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ngày giờ ISO", + date: "ngày ISO", + time: "giờ ISO", + duration: "khoảng thời gian ISO", + ipv4: "địa chỉ IPv4", + ipv6: "địa chỉ IPv6", + cidrv4: "dải IPv4", + cidrv6: "dải IPv6", + base64: "chuỗi mã hóa base64", + base64url: "chuỗi mã hóa base64url", + json_string: "chuỗi JSON", + e164: "số E.164", + jwt: "JWT", + template_literal: "đầu vào", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Đầu vào không hợp lệ: mong đợi ${issue.expected}, nhận được ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive(issue.values[0])}`; + return `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "phần tử"}`; + return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `Quá nhỏ: mong đợi ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `Quá nhỏ: mong đợi ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`; + if (_issue.format === "regex") + return `Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`; + return `${Nouns[_issue.format] ?? issue.format} không hợp lệ`; + } + case "not_multiple_of": + return `Số không hợp lệ: phải là bội số của ${issue.divisor}`; + case "unrecognized_keys": + return `Khóa không được nhận dạng: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Khóa không hợp lệ trong ${issue.origin}`; + case "invalid_union": + return "Đầu vào không hợp lệ"; + case "invalid_element": + return `Giá trị không hợp lệ trong ${issue.origin}`; + default: + return `Đầu vào không hợp lệ`; + } + }; +}; +/* harmony default export */ function vi() { + return { + localeError: vi_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/zh-CN.js + +const zh_CN_error = () => { + const Sizable = { + string: { unit: "字符", verb: "包含" }, + file: { unit: "字节", verb: "包含" }, + array: { unit: "项", verb: "包含" }, + set: { unit: "项", verb: "包含" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "非数字(NaN)" : "数字"; + } + case "object": { + if (Array.isArray(data)) { + return "数组"; + } + if (data === null) { + return "空值(null)"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "输入", + email: "电子邮件", + url: "URL", + emoji: "表情符号", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO日期时间", + date: "ISO日期", + time: "ISO时间", + duration: "ISO时长", + ipv4: "IPv4地址", + ipv6: "IPv6地址", + cidrv4: "IPv4网段", + cidrv6: "IPv6网段", + base64: "base64编码字符串", + base64url: "base64url编码字符串", + json_string: "JSON字符串", + e164: "E.164号码", + jwt: "JWT", + template_literal: "输入", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `无效输入:期望 ${issue.expected},实际接收 ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `无效输入:期望 ${stringifyPrimitive(issue.values[0])}`; + return `无效选项:期望以下之一 ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `数值过大:期望 ${issue.origin ?? "值"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "个元素"}`; + return `数值过大:期望 ${issue.origin ?? "值"} ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `数值过小:期望 ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `数值过小:期望 ${issue.origin} ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `无效字符串:必须以 "${_issue.prefix}" 开头`; + if (_issue.format === "ends_with") + return `无效字符串:必须以 "${_issue.suffix}" 结尾`; + if (_issue.format === "includes") + return `无效字符串:必须包含 "${_issue.includes}"`; + if (_issue.format === "regex") + return `无效字符串:必须满足正则表达式 ${_issue.pattern}`; + return `无效${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `无效数字:必须是 ${issue.divisor} 的倍数`; + case "unrecognized_keys": + return `出现未知的键(key): ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `${issue.origin} 中的键(key)无效`; + case "invalid_union": + return "无效输入"; + case "invalid_element": + return `${issue.origin} 中包含无效值(value)`; + default: + return `无效输入`; + } + }; +}; +/* harmony default export */ function zh_CN() { + return { + localeError: zh_CN_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/zh-TW.js + +const zh_TW_error = () => { + const Sizable = { + string: { unit: "字元", verb: "擁有" }, + file: { unit: "位元組", verb: "擁有" }, + array: { unit: "項目", verb: "擁有" }, + set: { unit: "項目", verb: "擁有" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "number"; + } + case "object": { + if (Array.isArray(data)) { + return "array"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "輸入", + email: "郵件地址", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "ISO 日期時間", + date: "ISO 日期", + time: "ISO 時間", + duration: "ISO 期間", + ipv4: "IPv4 位址", + ipv6: "IPv6 位址", + cidrv4: "IPv4 範圍", + cidrv6: "IPv6 範圍", + base64: "base64 編碼字串", + base64url: "base64url 編碼字串", + json_string: "JSON 字串", + e164: "E.164 數值", + jwt: "JWT", + template_literal: "輸入", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `無效的輸入值:預期為 ${issue.expected},但收到 ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `無效的輸入值:預期為 ${stringifyPrimitive(issue.values[0])}`; + return `無效的選項:預期為以下其中之一 ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `數值過大:預期 ${issue.origin ?? "值"} 應為 ${adj}${issue.maximum.toString()} ${sizing.unit ?? "個元素"}`; + return `數值過大:預期 ${issue.origin ?? "值"} 應為 ${adj}${issue.maximum.toString()}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) { + return `數值過小:預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()} ${sizing.unit}`; + } + return `數值過小:預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") { + return `無效的字串:必須以 "${_issue.prefix}" 開頭`; + } + if (_issue.format === "ends_with") + return `無效的字串:必須以 "${_issue.suffix}" 結尾`; + if (_issue.format === "includes") + return `無效的字串:必須包含 "${_issue.includes}"`; + if (_issue.format === "regex") + return `無效的字串:必須符合格式 ${_issue.pattern}`; + return `無效的 ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `無效的數字:必須為 ${issue.divisor} 的倍數`; + case "unrecognized_keys": + return `無法識別的鍵值${issue.keys.length > 1 ? "們" : ""}:${joinValues(issue.keys, "、")}`; + case "invalid_key": + return `${issue.origin} 中有無效的鍵值`; + case "invalid_union": + return "無效的輸入值"; + case "invalid_element": + return `${issue.origin} 中有無效的值`; + default: + return `無效的輸入值`; + } + }; +}; +/* harmony default export */ function zh_TW() { + return { + localeError: zh_TW_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/yo.js + +const yo_error = () => { + const Sizable = { + string: { unit: "àmi", verb: "ní" }, + file: { unit: "bytes", verb: "ní" }, + array: { unit: "nkan", verb: "ní" }, + set: { unit: "nkan", verb: "ní" }, + }; + function getSizing(origin) { + return Sizable[origin] ?? null; + } + const parsedType = (data) => { + const t = typeof data; + switch (t) { + case "number": { + return Number.isNaN(data) ? "NaN" : "nọ́mbà"; + } + case "object": { + if (Array.isArray(data)) { + return "akopọ"; + } + if (data === null) { + return "null"; + } + if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { + return data.constructor.name; + } + } + } + return t; + }; + const Nouns = { + regex: "ẹ̀rọ ìbáwọlé", + email: "àdírẹ́sì ìmẹ́lì", + url: "URL", + emoji: "emoji", + uuid: "UUID", + uuidv4: "UUIDv4", + uuidv6: "UUIDv6", + nanoid: "nanoid", + guid: "GUID", + cuid: "cuid", + cuid2: "cuid2", + ulid: "ULID", + xid: "XID", + ksuid: "KSUID", + datetime: "àkókò ISO", + date: "ọjọ́ ISO", + time: "àkókò ISO", + duration: "àkókò tó pé ISO", + ipv4: "àdírẹ́sì IPv4", + ipv6: "àdírẹ́sì IPv6", + cidrv4: "àgbègbè IPv4", + cidrv6: "àgbègbè IPv6", + base64: "ọ̀rọ̀ tí a kọ́ ní base64", + base64url: "ọ̀rọ̀ base64url", + json_string: "ọ̀rọ̀ JSON", + e164: "nọ́mbà E.164", + jwt: "JWT", + template_literal: "ẹ̀rọ ìbáwọlé", + }; + return (issue) => { + switch (issue.code) { + case "invalid_type": + return `Ìbáwọlé aṣìṣe: a ní láti fi ${issue.expected}, àmọ̀ a rí ${parsedType(issue.input)}`; + case "invalid_value": + if (issue.values.length === 1) + return `Ìbáwọlé aṣìṣe: a ní láti fi ${stringifyPrimitive(issue.values[0])}`; + return `Àṣàyàn aṣìṣe: yan ọ̀kan lára ${joinValues(issue.values, "|")}`; + case "too_big": { + const adj = issue.inclusive ? "<=" : "<"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Tó pọ̀ jù: a ní láti jẹ́ pé ${issue.origin ?? "iye"} ${sizing.verb} ${adj}${issue.maximum} ${sizing.unit}`; + return `Tó pọ̀ jù: a ní láti jẹ́ ${adj}${issue.maximum}`; + } + case "too_small": { + const adj = issue.inclusive ? ">=" : ">"; + const sizing = getSizing(issue.origin); + if (sizing) + return `Kéré ju: a ní láti jẹ́ pé ${issue.origin} ${sizing.verb} ${adj}${issue.minimum} ${sizing.unit}`; + return `Kéré ju: a ní láti jẹ́ ${adj}${issue.minimum}`; + } + case "invalid_format": { + const _issue = issue; + if (_issue.format === "starts_with") + return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${_issue.prefix}"`; + if (_issue.format === "ends_with") + return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${_issue.suffix}"`; + if (_issue.format === "includes") + return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${_issue.includes}"`; + if (_issue.format === "regex") + return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${_issue.pattern}`; + return `Aṣìṣe: ${Nouns[_issue.format] ?? issue.format}`; + } + case "not_multiple_of": + return `Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${issue.divisor}`; + case "unrecognized_keys": + return `Bọtìnì àìmọ̀: ${joinValues(issue.keys, ", ")}`; + case "invalid_key": + return `Bọtìnì aṣìṣe nínú ${issue.origin}`; + case "invalid_union": + return "Ìbáwọlé aṣìṣe"; + case "invalid_element": + return `Iye aṣìṣe nínú ${issue.origin}`; + default: + return "Ìbáwọlé aṣìṣe"; + } + }; +}; +/* harmony default export */ function yo() { + return { + localeError: yo_error(), + }; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/index.js + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/registries.js +var _a; +const $output = Symbol("ZodOutput"); +const $input = Symbol("ZodInput"); +class $ZodRegistry { + constructor() { + this._map = new WeakMap(); + this._idmap = new Map(); + } + add(schema, ..._meta) { + const meta = _meta[0]; + this._map.set(schema, meta); + if (meta && typeof meta === "object" && "id" in meta) { + if (this._idmap.has(meta.id)) { + throw new Error(`ID ${meta.id} already exists in the registry`); + } + this._idmap.set(meta.id, schema); + } + return this; + } + clear() { + this._map = new WeakMap(); + this._idmap = new Map(); + return this; + } + remove(schema) { + const meta = this._map.get(schema); + if (meta && typeof meta === "object" && "id" in meta) { + this._idmap.delete(meta.id); + } + this._map.delete(schema); + return this; + } + get(schema) { + // return this._map.get(schema) as any; + // inherit metadata + const p = schema._zod.parent; + if (p) { + const pm = { ...(this.get(p) ?? {}) }; + delete pm.id; // do not inherit id + const f = { ...pm, ...this._map.get(schema) }; + return Object.keys(f).length ? f : undefined; + } + return this._map.get(schema); + } + has(schema) { + return this._map.has(schema); + } +} +// registries +function registry() { + return new $ZodRegistry(); +} +(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry()); +const globalRegistry = globalThis.__zod_globalRegistry; + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/api.js + + + + +function _string(Class, params) { + return new Class({ + type: "string", + ...normalizeParams(params), + }); +} +function _coercedString(Class, params) { + return new Class({ + type: "string", + coerce: true, + ...normalizeParams(params), + }); +} +function _email(Class, params) { + return new Class({ + type: "string", + format: "email", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _guid(Class, params) { + return new Class({ + type: "string", + format: "guid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _uuid(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _uuidv4(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v4", + ...normalizeParams(params), + }); +} +function _uuidv6(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v6", + ...normalizeParams(params), + }); +} +function _uuidv7(Class, params) { + return new Class({ + type: "string", + format: "uuid", + check: "string_format", + abort: false, + version: "v7", + ...normalizeParams(params), + }); +} +function _url(Class, params) { + return new Class({ + type: "string", + format: "url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function api_emoji(Class, params) { + return new Class({ + type: "string", + format: "emoji", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _nanoid(Class, params) { + return new Class({ + type: "string", + format: "nanoid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _cuid(Class, params) { + return new Class({ + type: "string", + format: "cuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _cuid2(Class, params) { + return new Class({ + type: "string", + format: "cuid2", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _ulid(Class, params) { + return new Class({ + type: "string", + format: "ulid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _xid(Class, params) { + return new Class({ + type: "string", + format: "xid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _ksuid(Class, params) { + return new Class({ + type: "string", + format: "ksuid", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _ipv4(Class, params) { + return new Class({ + type: "string", + format: "ipv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _ipv6(Class, params) { + return new Class({ + type: "string", + format: "ipv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _mac(Class, params) { + return new Class({ + type: "string", + format: "mac", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _cidrv4(Class, params) { + return new Class({ + type: "string", + format: "cidrv4", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _cidrv6(Class, params) { + return new Class({ + type: "string", + format: "cidrv6", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _base64(Class, params) { + return new Class({ + type: "string", + format: "base64", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _base64url(Class, params) { + return new Class({ + type: "string", + format: "base64url", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _e164(Class, params) { + return new Class({ + type: "string", + format: "e164", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +function _jwt(Class, params) { + return new Class({ + type: "string", + format: "jwt", + check: "string_format", + abort: false, + ...normalizeParams(params), + }); +} +const TimePrecision = { + Any: null, + Minute: -1, + Second: 0, + Millisecond: 3, + Microsecond: 6, +}; +function _isoDateTime(Class, params) { + return new Class({ + type: "string", + format: "datetime", + check: "string_format", + offset: false, + local: false, + precision: null, + ...normalizeParams(params), + }); +} +function _isoDate(Class, params) { + return new Class({ + type: "string", + format: "date", + check: "string_format", + ...normalizeParams(params), + }); +} +function _isoTime(Class, params) { + return new Class({ + type: "string", + format: "time", + check: "string_format", + precision: null, + ...normalizeParams(params), + }); +} +function _isoDuration(Class, params) { + return new Class({ + type: "string", + format: "duration", + check: "string_format", + ...normalizeParams(params), + }); +} +function _number(Class, params) { + return new Class({ + type: "number", + checks: [], + ...normalizeParams(params), + }); +} +function _coercedNumber(Class, params) { + return new Class({ + type: "number", + coerce: true, + checks: [], + ...normalizeParams(params), + }); +} +function _int(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "safeint", + ...normalizeParams(params), + }); +} +function _float32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float32", + ...normalizeParams(params), + }); +} +function _float64(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "float64", + ...normalizeParams(params), + }); +} +function _int32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "int32", + ...normalizeParams(params), + }); +} +function _uint32(Class, params) { + return new Class({ + type: "number", + check: "number_format", + abort: false, + format: "uint32", + ...normalizeParams(params), + }); +} +function _boolean(Class, params) { + return new Class({ + type: "boolean", + ...normalizeParams(params), + }); +} +function _coercedBoolean(Class, params) { + return new Class({ + type: "boolean", + coerce: true, + ...normalizeParams(params), + }); +} +function _bigint(Class, params) { + return new Class({ + type: "bigint", + ...normalizeParams(params), + }); +} +function _coercedBigint(Class, params) { + return new Class({ + type: "bigint", + coerce: true, + ...normalizeParams(params), + }); +} +function _int64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "int64", + ...normalizeParams(params), + }); +} +function _uint64(Class, params) { + return new Class({ + type: "bigint", + check: "bigint_format", + abort: false, + format: "uint64", + ...normalizeParams(params), + }); +} +function _symbol(Class, params) { + return new Class({ + type: "symbol", + ...normalizeParams(params), + }); +} +function api_undefined(Class, params) { + return new Class({ + type: "undefined", + ...normalizeParams(params), + }); +} +function api_null(Class, params) { + return new Class({ + type: "null", + ...normalizeParams(params), + }); +} +function _any(Class) { + return new Class({ + type: "any", + }); +} +function _unknown(Class) { + return new Class({ + type: "unknown", + }); +} +function _never(Class, params) { + return new Class({ + type: "never", + ...normalizeParams(params), + }); +} +function _void(Class, params) { + return new Class({ + type: "void", + ...normalizeParams(params), + }); +} +function _date(Class, params) { + return new Class({ + type: "date", + ...normalizeParams(params), + }); +} +function _coercedDate(Class, params) { + return new Class({ + type: "date", + coerce: true, + ...normalizeParams(params), + }); +} +function _nan(Class, params) { + return new Class({ + type: "nan", + ...normalizeParams(params), + }); +} +function _lt(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +function _lte(value, params) { + return new $ZodCheckLessThan({ + check: "less_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +function _gt(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: false, + }); +} +function _gte(value, params) { + return new $ZodCheckGreaterThan({ + check: "greater_than", + ...normalizeParams(params), + value, + inclusive: true, + }); +} + +function _positive(params) { + return _gt(0, params); +} +// negative +function _negative(params) { + return _lt(0, params); +} +// nonpositive +function _nonpositive(params) { + return _lte(0, params); +} +// nonnegative +function _nonnegative(params) { + return _gte(0, params); +} +function _multipleOf(value, params) { + return new $ZodCheckMultipleOf({ + check: "multiple_of", + ...normalizeParams(params), + value, + }); +} +function _maxSize(maximum, params) { + return new $ZodCheckMaxSize({ + check: "max_size", + ...normalizeParams(params), + maximum, + }); +} +function _minSize(minimum, params) { + return new $ZodCheckMinSize({ + check: "min_size", + ...normalizeParams(params), + minimum, + }); +} +function _size(size, params) { + return new $ZodCheckSizeEquals({ + check: "size_equals", + ...normalizeParams(params), + size, + }); +} +function _maxLength(maximum, params) { + const ch = new $ZodCheckMaxLength({ + check: "max_length", + ...normalizeParams(params), + maximum, + }); + return ch; +} +function _minLength(minimum, params) { + return new $ZodCheckMinLength({ + check: "min_length", + ...normalizeParams(params), + minimum, + }); +} +function _length(length, params) { + return new $ZodCheckLengthEquals({ + check: "length_equals", + ...normalizeParams(params), + length, + }); +} +function _regex(pattern, params) { + return new $ZodCheckRegex({ + check: "string_format", + format: "regex", + ...normalizeParams(params), + pattern, + }); +} +function _lowercase(params) { + return new $ZodCheckLowerCase({ + check: "string_format", + format: "lowercase", + ...normalizeParams(params), + }); +} +function _uppercase(params) { + return new $ZodCheckUpperCase({ + check: "string_format", + format: "uppercase", + ...normalizeParams(params), + }); +} +function _includes(includes, params) { + return new $ZodCheckIncludes({ + check: "string_format", + format: "includes", + ...normalizeParams(params), + includes, + }); +} +function _startsWith(prefix, params) { + return new $ZodCheckStartsWith({ + check: "string_format", + format: "starts_with", + ...normalizeParams(params), + prefix, + }); +} +function _endsWith(suffix, params) { + return new $ZodCheckEndsWith({ + check: "string_format", + format: "ends_with", + ...normalizeParams(params), + suffix, + }); +} +function _property(property, schema, params) { + return new $ZodCheckProperty({ + check: "property", + property, + schema, + ...normalizeParams(params), + }); +} +function _mime(types, params) { + return new $ZodCheckMimeType({ + check: "mime_type", + mime: types, + ...normalizeParams(params), + }); +} +function _overwrite(tx) { + return new $ZodCheckOverwrite({ + check: "overwrite", + tx, + }); +} +// normalize +function _normalize(form) { + return _overwrite((input) => input.normalize(form)); +} +// trim +function _trim() { + return _overwrite((input) => input.trim()); +} +// toLowerCase +function _toLowerCase() { + return _overwrite((input) => input.toLowerCase()); +} +// toUpperCase +function _toUpperCase() { + return _overwrite((input) => input.toUpperCase()); +} +// slugify +function _slugify() { + return _overwrite((input) => slugify(input)); +} +function _array(Class, element, params) { + return new Class({ + type: "array", + element, + // get element() { + // return element; + // }, + ...normalizeParams(params), + }); +} +function _union(Class, options, params) { + return new Class({ + type: "union", + options, + ...normalizeParams(params), + }); +} +function _xor(Class, options, params) { + return new Class({ + type: "union", + options, + inclusive: false, + ...normalizeParams(params), + }); +} +function _discriminatedUnion(Class, discriminator, options, params) { + return new Class({ + type: "union", + options, + discriminator, + ...normalizeParams(params), + }); +} +function _intersection(Class, left, right) { + return new Class({ + type: "intersection", + left, + right, + }); +} +// export function _tuple( +// Class: util.SchemaClass, +// items: [], +// params?: string | $ZodTupleParams +// ): schemas.$ZodTuple<[], null>; +function _tuple(Class, items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new Class({ + type: "tuple", + items, + rest, + ...normalizeParams(params), + }); +} +function _record(Class, keyType, valueType, params) { + return new Class({ + type: "record", + keyType, + valueType, + ...normalizeParams(params), + }); +} +function _map(Class, keyType, valueType, params) { + return new Class({ + type: "map", + keyType, + valueType, + ...normalizeParams(params), + }); +} +function _set(Class, valueType, params) { + return new Class({ + type: "set", + valueType, + ...normalizeParams(params), + }); +} +function _enum(Class, values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + // if (Array.isArray(values)) { + // for (const value of values) { + // entries[value] = value; + // } + // } else { + // Object.assign(entries, values); + // } + // const entries: util.EnumLike = {}; + // for (const val of values) { + // entries[val] = val; + // } + return new Class({ + type: "enum", + entries, + ...normalizeParams(params), + }); +} +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function _nativeEnum(Class, entries, params) { + return new Class({ + type: "enum", + entries, + ...normalizeParams(params), + }); +} +function _literal(Class, value, params) { + return new Class({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params), + }); +} +function _file(Class, params) { + return new Class({ + type: "file", + ...normalizeParams(params), + }); +} +function _transform(Class, fn) { + return new Class({ + type: "transform", + transform: fn, + }); +} +function _optional(Class, innerType) { + return new Class({ + type: "optional", + innerType, + }); +} +function _nullable(Class, innerType) { + return new Class({ + type: "nullable", + innerType, + }); +} +function _default(Class, innerType, defaultValue) { + return new Class({ + type: "default", + innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +function _nonoptional(Class, innerType, params) { + return new Class({ + type: "nonoptional", + innerType, + ...normalizeParams(params), + }); +} +function _success(Class, innerType) { + return new Class({ + type: "success", + innerType, + }); +} +function _catch(Class, innerType, catchValue) { + return new Class({ + type: "catch", + innerType, + catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), + }); +} +function _pipe(Class, in_, out) { + return new Class({ + type: "pipe", + in: in_, + out, + }); +} +function _readonly(Class, innerType) { + return new Class({ + type: "readonly", + innerType, + }); +} +function _templateLiteral(Class, parts, params) { + return new Class({ + type: "template_literal", + parts, + ...normalizeParams(params), + }); +} +function _lazy(Class, getter) { + return new Class({ + type: "lazy", + getter, + }); +} +function _promise(Class, innerType) { + return new Class({ + type: "promise", + innerType, + }); +} +function _custom(Class, fn, _params) { + const norm = normalizeParams(_params); + norm.abort ?? (norm.abort = true); // default to abort:false + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...norm, + }); + return schema; +} +// same as _custom but defaults to abort:false +function _refine(Class, fn, _params) { + const schema = new Class({ + type: "custom", + check: "custom", + fn: fn, + ...normalizeParams(_params), + }); + return schema; +} +function _superRefine(fn) { + const ch = _check((payload) => { + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = ch); + _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... + payload.issues.push(util_issue(_issue)); + } + }; + return fn(payload.value, payload); + }); + return ch; +} +function _check(fn, params) { + const ch = new $ZodCheck({ + check: "custom", + ...normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function describe(description) { + const ch = new $ZodCheck({ check: "describe" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, description }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +function meta(metadata) { + const ch = new $ZodCheck({ check: "meta" }); + ch._zod.onattach = [ + (inst) => { + const existing = globalRegistry.get(inst) ?? {}; + globalRegistry.add(inst, { ...existing, ...metadata }); + }, + ]; + ch._zod.check = () => { }; // no-op check + return ch; +} +function _stringbool(Classes, _params) { + const params = normalizeParams(_params); + let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; + let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; + if (params.case !== "sensitive") { + truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); + } + const truthySet = new Set(truthyArray); + const falsySet = new Set(falsyArray); + const _Codec = Classes.Codec ?? $ZodCodec; + const _Boolean = Classes.Boolean ?? $ZodBoolean; + const _String = Classes.String ?? $ZodString; + const stringSchema = new _String({ type: "string", error: params.error }); + const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); + const codec = new _Codec({ + type: "pipe", + in: stringSchema, + out: booleanSchema, + transform: ((input, payload) => { + let data = input; + if (params.case !== "sensitive") + data = data.toLowerCase(); + if (truthySet.has(data)) { + return true; + } + else if (falsySet.has(data)) { + return false; + } + else { + payload.issues.push({ + code: "invalid_value", + expected: "stringbool", + values: [...truthySet, ...falsySet], + input: payload.value, + inst: codec, + continue: false, + }); + return {}; + } + }), + reverseTransform: ((input, _payload) => { + if (input === true) { + return truthyArray[0] || "true"; + } + else { + return falsyArray[0] || "false"; + } + }), + error: params.error, + }); + return codec; +} +function _stringFormat(Class, format, fnOrRegex, _params = {}) { + const params = normalizeParams(_params); + const def = { + ...normalizeParams(_params), + check: "string_format", + type: "string", + format, + fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), + ...params, + }; + if (fnOrRegex instanceof RegExp) { + def.pattern = fnOrRegex; + } + const inst = new Class(def); + return inst; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/to-json-schema.js + +// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { +// return { +// processor: inputs.processor, +// metadataRegistry: inputs.metadata ?? globalRegistry, +// target: inputs.target ?? "draft-2020-12", +// unrepresentable: inputs.unrepresentable ?? "throw", +// }; +// } +function initializeContext(params) { + // Normalize target: convert old non-hyphenated versions to hyphenated versions + let target = params?.target ?? "draft-2020-12"; + if (target === "draft-4") + target = "draft-04"; + if (target === "draft-7") + target = "draft-07"; + return { + processors: params.processors ?? {}, + metadataRegistry: params?.metadata ?? globalRegistry, + target, + unrepresentable: params?.unrepresentable ?? "throw", + override: params?.override ?? (() => { }), + io: params?.io ?? "output", + counter: 0, + seen: new Map(), + cycles: params?.cycles ?? "ref", + reused: params?.reused ?? "inline", + external: params?.external ?? undefined, + }; +} +function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { + var _a; + const def = schema._zod.def; + // check for schema in seens + const seen = ctx.seen.get(schema); + if (seen) { + seen.count++; + // check if cycle + const isCycle = _params.schemaPath.includes(schema); + if (isCycle) { + seen.cycle = _params.path; + } + return seen.schema; + } + // initialize + const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; + ctx.seen.set(schema, result); + // custom method overrides default behavior + const overrideSchema = schema._zod.toJSONSchema?.(); + if (overrideSchema) { + result.schema = overrideSchema; + } + else { + const params = { + ..._params, + schemaPath: [..._params.schemaPath, schema], + path: _params.path, + }; + const parent = schema._zod.parent; + if (parent) { + // schema was cloned from another schema + result.ref = parent; + to_json_schema_process(parent, ctx, params); + ctx.seen.get(parent).isParent = true; + } + else if (schema._zod.processJSONSchema) { + schema._zod.processJSONSchema(ctx, result.schema, params); + } + else { + const _json = result.schema; + const processor = ctx.processors[def.type]; + if (!processor) { + throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); + } + processor(schema, ctx, _json, params); + } + } + // metadata + const meta = ctx.metadataRegistry.get(schema); + if (meta) + Object.assign(result.schema, meta); + if (ctx.io === "input" && isTransforming(schema)) { + // examples/defaults only apply to output type of pipe + delete result.schema.examples; + delete result.schema.default; + } + // set prefault as default + if (ctx.io === "input" && result.schema._prefault) + (_a = result.schema).default ?? (_a.default = result.schema._prefault); + delete result.schema._prefault; + // pulling fresh from ctx.seen in case it was overwritten + const _result = ctx.seen.get(schema); + return _result.schema; +} +function extractDefs(ctx, schema +// params: EmitParams +) { + // iterate over seen map; + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // returns a ref to the schema + // defId will be empty if the ref points to an external schema (or #) + const makeURI = (entry) => { + // comparing the seen objects because sometimes + // multiple schemas map to the same seen object. + // e.g. lazy + // external is configured + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + if (ctx.external) { + const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; + // check if schema is in the external registry + const uriGenerator = ctx.external.uri ?? ((id) => id); + if (externalId) { + return { ref: uriGenerator(externalId) }; + } + // otherwise, add to __shared + const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; + entry[1].defId = id; // set defId so it will be reused if needed + return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; + } + if (entry[1] === root) { + return { ref: "#" }; + } + // self-contained schema + const uriPrefix = `#`; + const defUriPrefix = `${uriPrefix}/${defsSegment}/`; + const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; + return { defId, ref: defUriPrefix + defId }; + }; + // stored cached version in `def` property + // remove all properties, set $ref + const extractToDef = (entry) => { + // if the schema is already a reference, do not extract it + if (entry[1].schema.$ref) { + return; + } + const seen = entry[1]; + const { ref, defId } = makeURI(entry); + seen.def = { ...seen.schema }; + // defId won't be set if the schema is a reference to an external schema + // or if the schema is the root schema + if (defId) + seen.defId = defId; + // wipe away all properties except $ref + const schema = seen.schema; + for (const key in schema) { + delete schema[key]; + } + schema.$ref = ref; + }; + // throw on cycles + // break cycles + if (ctx.cycles === "throw") { + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.cycle) { + throw new Error("Cycle detected: " + + `#/${seen.cycle?.join("/")}/` + + '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); + } + } + } + // extract schemas into $defs + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + // convert root schema to # $ref + if (schema === entry[0]) { + extractToDef(entry); // this has special handling for the root schema + continue; + } + // extract schemas that are in the external registry + if (ctx.external) { + const ext = ctx.external.registry.get(entry[0])?.id; + if (schema !== entry[0] && ext) { + extractToDef(entry); + continue; + } + } + // extract schemas with `id` meta + const id = ctx.metadataRegistry.get(entry[0])?.id; + if (id) { + extractToDef(entry); + continue; + } + // break cycles + if (seen.cycle) { + // any + extractToDef(entry); + continue; + } + // extract reused schemas + if (seen.count > 1) { + if (ctx.reused === "ref") { + extractToDef(entry); + // biome-ignore lint: + continue; + } + } + } +} +function finalize(ctx, schema) { + // + // iterate over seen map; + const root = ctx.seen.get(schema); + if (!root) + throw new Error("Unprocessed schema. This is a bug in Zod."); + // flatten _refs + const flattenRef = (zodSchema) => { + const seen = ctx.seen.get(zodSchema); + const schema = seen.def ?? seen.schema; + const _cached = { ...schema }; + // already seen + if (seen.ref === null) { + return; + } + // flatten ref if defined + const ref = seen.ref; + seen.ref = null; // prevent recursion + if (ref) { + flattenRef(ref); + // merge referenced schema into current + const refSchema = ctx.seen.get(ref).schema; + if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { + schema.allOf = schema.allOf ?? []; + schema.allOf.push(refSchema); + } + else { + Object.assign(schema, refSchema); + Object.assign(schema, _cached); // prevent overwriting any fields in the original schema + } + } + // execute overrides + if (!seen.isParent) + ctx.override({ + zodSchema: zodSchema, + jsonSchema: schema, + path: seen.path ?? [], + }); + }; + for (const entry of [...ctx.seen.entries()].reverse()) { + flattenRef(entry[0]); + } + const result = {}; + if (ctx.target === "draft-2020-12") { + result.$schema = "https://json-schema.org/draft/2020-12/schema"; + } + else if (ctx.target === "draft-07") { + result.$schema = "http://json-schema.org/draft-07/schema#"; + } + else if (ctx.target === "draft-04") { + result.$schema = "http://json-schema.org/draft-04/schema#"; + } + else if (ctx.target === "openapi-3.0") { + // OpenAPI 3.0 schema objects should not include a $schema property + } + else { + // Arbitrary string values are allowed but won't have a $schema property set + } + if (ctx.external?.uri) { + const id = ctx.external.registry.get(schema)?.id; + if (!id) + throw new Error("Schema is missing an `id` property"); + result.$id = ctx.external.uri(id); + } + Object.assign(result, root.def ?? root.schema); + // build defs object + const defs = ctx.external?.defs ?? {}; + for (const entry of ctx.seen.entries()) { + const seen = entry[1]; + if (seen.def && seen.defId) { + defs[seen.defId] = seen.def; + } + } + // set definitions in result + if (ctx.external) { + } + else { + if (Object.keys(defs).length > 0) { + if (ctx.target === "draft-2020-12") { + result.$defs = defs; + } + else { + result.definitions = defs; + } + } + } + try { + // this "finalizes" this schema and ensures all cycles are removed + // each call to finalize() is functionally independent + // though the seen map is shared + const finalized = JSON.parse(JSON.stringify(result)); + Object.defineProperty(finalized, "~standard", { + value: { + ...schema["~standard"], + jsonSchema: { + input: createStandardJSONSchemaMethod(schema, "input"), + output: createStandardJSONSchemaMethod(schema, "output"), + }, + }, + enumerable: false, + writable: false, + }); + return finalized; + } + catch (_err) { + throw new Error("Error converting schema to JSON."); + } +} +function isTransforming(_schema, _ctx) { + const ctx = _ctx ?? { seen: new Set() }; + if (ctx.seen.has(_schema)) + return false; + ctx.seen.add(_schema); + const def = _schema._zod.def; + if (def.type === "transform") + return true; + if (def.type === "array") + return isTransforming(def.element, ctx); + if (def.type === "set") + return isTransforming(def.valueType, ctx); + if (def.type === "lazy") + return isTransforming(def.getter(), ctx); + if (def.type === "promise" || + def.type === "optional" || + def.type === "nonoptional" || + def.type === "nullable" || + def.type === "readonly" || + def.type === "default" || + def.type === "prefault") { + return isTransforming(def.innerType, ctx); + } + if (def.type === "intersection") { + return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); + } + if (def.type === "record" || def.type === "map") { + return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); + } + if (def.type === "pipe") { + return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); + } + if (def.type === "object") { + for (const key in def.shape) { + if (isTransforming(def.shape[key], ctx)) + return true; + } + return false; + } + if (def.type === "union") { + for (const option of def.options) { + if (isTransforming(option, ctx)) + return true; + } + return false; + } + if (def.type === "tuple") { + for (const item of def.items) { + if (isTransforming(item, ctx)) + return true; + } + if (def.rest && isTransforming(def.rest, ctx)) + return true; + return false; + } + return false; +} +/** + * Creates a toJSONSchema method for a schema instance. + * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. + */ +const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { + const ctx = initializeContext({ ...params, processors }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; +const createStandardJSONSchemaMethod = (schema, io) => (params) => { + const { libraryOptions, target } = params ?? {}; + const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors: {} }); + to_json_schema_process(schema, ctx); + extractDefs(ctx, schema); + return finalize(ctx, schema); +}; + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/json-schema-processors.js + + +const formatMap = { + guid: "uuid", + url: "uri", + datetime: "date-time", + json_string: "json-string", + regex: "", // do not set +}; +// ==================== SIMPLE TYPE PROCESSORS ==================== +const stringProcessor = (schema, ctx, _json, _params) => { + const json = _json; + json.type = "string"; + const { minimum, maximum, format, patterns, contentEncoding } = schema._zod + .bag; + if (typeof minimum === "number") + json.minLength = minimum; + if (typeof maximum === "number") + json.maxLength = maximum; + // custom pattern overrides format + if (format) { + json.format = formatMap[format] ?? format; + if (json.format === "") + delete json.format; // empty format is not valid + } + if (contentEncoding) + json.contentEncoding = contentEncoding; + if (patterns && patterns.size > 0) { + const regexes = [...patterns]; + if (regexes.length === 1) + json.pattern = regexes[0].source; + else if (regexes.length > 1) { + json.allOf = [ + ...regexes.map((regex) => ({ + ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" + ? { type: "string" } + : {}), + pattern: regex.source, + })), + ]; + } + } +}; +const numberProcessor = (schema, ctx, _json, _params) => { + const json = _json; + const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; + if (typeof format === "string" && format.includes("int")) + json.type = "integer"; + else + json.type = "number"; + if (typeof exclusiveMinimum === "number") { + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json.minimum = exclusiveMinimum; + json.exclusiveMinimum = true; + } + else { + json.exclusiveMinimum = exclusiveMinimum; + } + } + if (typeof minimum === "number") { + json.minimum = minimum; + if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") { + if (exclusiveMinimum >= minimum) + delete json.minimum; + else + delete json.exclusiveMinimum; + } + } + if (typeof exclusiveMaximum === "number") { + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json.maximum = exclusiveMaximum; + json.exclusiveMaximum = true; + } + else { + json.exclusiveMaximum = exclusiveMaximum; + } + } + if (typeof maximum === "number") { + json.maximum = maximum; + if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") { + if (exclusiveMaximum <= maximum) + delete json.maximum; + else + delete json.exclusiveMaximum; + } + } + if (typeof multipleOf === "number") + json.multipleOf = multipleOf; +}; +const booleanProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const bigintProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt cannot be represented in JSON Schema"); + } +}; +const symbolProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Symbols cannot be represented in JSON Schema"); + } +}; +const nullProcessor = (_schema, ctx, json, _params) => { + if (ctx.target === "openapi-3.0") { + json.type = "string"; + json.nullable = true; + json.enum = [null]; + } + else { + json.type = "null"; + } +}; +const undefinedProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Undefined cannot be represented in JSON Schema"); + } +}; +const voidProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Void cannot be represented in JSON Schema"); + } +}; +const neverProcessor = (_schema, _ctx, json, _params) => { + json.not = {}; +}; +const anyProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const unknownProcessor = (_schema, _ctx, _json, _params) => { + // empty schema accepts anything +}; +const dateProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Date cannot be represented in JSON Schema"); + } +}; +const enumProcessor = (schema, _ctx, json, _params) => { + const def = schema._zod.def; + const values = getEnumValues(def.entries); + // Number enums can have both string and number values + if (values.every((v) => typeof v === "number")) + json.type = "number"; + if (values.every((v) => typeof v === "string")) + json.type = "string"; + json.enum = values; +}; +const literalProcessor = (schema, ctx, json, _params) => { + const def = schema._zod.def; + const vals = []; + for (const val of def.values) { + if (val === undefined) { + if (ctx.unrepresentable === "throw") { + throw new Error("Literal `undefined` cannot be represented in JSON Schema"); + } + else { + // do not add to vals + } + } + else if (typeof val === "bigint") { + if (ctx.unrepresentable === "throw") { + throw new Error("BigInt literals cannot be represented in JSON Schema"); + } + else { + vals.push(Number(val)); + } + } + else { + vals.push(val); + } + } + if (vals.length === 0) { + // do nothing (an undefined literal was stripped) + } + else if (vals.length === 1) { + const val = vals[0]; + json.type = val === null ? "null" : typeof val; + if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { + json.enum = [val]; + } + else { + json.const = val; + } + } + else { + if (vals.every((v) => typeof v === "number")) + json.type = "number"; + if (vals.every((v) => typeof v === "string")) + json.type = "string"; + if (vals.every((v) => typeof v === "boolean")) + json.type = "boolean"; + if (vals.every((v) => v === null)) + json.type = "null"; + json.enum = vals; + } +}; +const nanProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("NaN cannot be represented in JSON Schema"); + } +}; +const templateLiteralProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const pattern = schema._zod.pattern; + if (!pattern) + throw new Error("Pattern not found in template literal"); + _json.type = "string"; + _json.pattern = pattern.source; +}; +const fileProcessor = (schema, _ctx, json, _params) => { + const _json = json; + const file = { + type: "string", + format: "binary", + contentEncoding: "binary", + }; + const { minimum, maximum, mime } = schema._zod.bag; + if (minimum !== undefined) + file.minLength = minimum; + if (maximum !== undefined) + file.maxLength = maximum; + if (mime) { + if (mime.length === 1) { + file.contentMediaType = mime[0]; + Object.assign(_json, file); + } + else { + _json.anyOf = mime.map((m) => { + const mFile = { ...file, contentMediaType: m }; + return mFile; + }); + } + } + else { + Object.assign(_json, file); + } +}; +const successProcessor = (_schema, _ctx, json, _params) => { + json.type = "boolean"; +}; +const customProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Custom types cannot be represented in JSON Schema"); + } +}; +const functionProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Function types cannot be represented in JSON Schema"); + } +}; +const transformProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Transforms cannot be represented in JSON Schema"); + } +}; +const mapProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Map cannot be represented in JSON Schema"); + } +}; +const setProcessor = (_schema, ctx, _json, _params) => { + if (ctx.unrepresentable === "throw") { + throw new Error("Set cannot be represented in JSON Schema"); + } +}; +// ==================== COMPOSITE TYPE PROCESSORS ==================== +const arrayProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; + json.type = "array"; + json.items = to_json_schema_process(def.element, ctx, { ...params, path: [...params.path, "items"] }); +}; +const objectProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + json.properties = {}; + const shape = def.shape; + for (const key in shape) { + json.properties[key] = to_json_schema_process(shape[key], ctx, { + ...params, + path: [...params.path, "properties", key], + }); + } + // required keys + const allKeys = new Set(Object.keys(shape)); + const requiredKeys = new Set([...allKeys].filter((key) => { + const v = def.shape[key]._zod; + if (ctx.io === "input") { + return v.optin === undefined; + } + else { + return v.optout === undefined; + } + })); + if (requiredKeys.size > 0) { + json.required = Array.from(requiredKeys); + } + // catchall + if (def.catchall?._zod.def.type === "never") { + // strict + json.additionalProperties = false; + } + else if (!def.catchall) { + // regular + if (ctx.io === "output") + json.additionalProperties = false; + } + else if (def.catchall) { + json.additionalProperties = to_json_schema_process(def.catchall, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); + } +}; +const unionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches) + // This includes both z.xor() and discriminated unions + const isExclusive = def.inclusive === false; + const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], + })); + if (isExclusive) { + json.oneOf = options; + } + else { + json.anyOf = options; + } +}; +const intersectionProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const a = to_json_schema_process(def.left, ctx, { + ...params, + path: [...params.path, "allOf", 0], + }); + const b = to_json_schema_process(def.right, ctx, { + ...params, + path: [...params.path, "allOf", 1], + }); + const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; + const allOf = [ + ...(isSimpleIntersection(a) ? a.allOf : [a]), + ...(isSimpleIntersection(b) ? b.allOf : [b]), + ]; + json.allOf = allOf; +}; +const tupleProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "array"; + const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; + const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; + const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { + ...params, + path: [...params.path, prefixPath, i], + })); + const rest = def.rest + ? to_json_schema_process(def.rest, ctx, { + ...params, + path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], + }) + : null; + if (ctx.target === "draft-2020-12") { + json.prefixItems = prefixItems; + if (rest) { + json.items = rest; + } + } + else if (ctx.target === "openapi-3.0") { + json.items = { + anyOf: prefixItems, + }; + if (rest) { + json.items.anyOf.push(rest); + } + json.minItems = prefixItems.length; + if (!rest) { + json.maxItems = prefixItems.length; + } + } + else { + json.items = prefixItems; + if (rest) { + json.additionalItems = rest; + } + } + // length + const { minimum, maximum } = schema._zod.bag; + if (typeof minimum === "number") + json.minItems = minimum; + if (typeof maximum === "number") + json.maxItems = maximum; +}; +const recordProcessor = (schema, ctx, _json, params) => { + const json = _json; + const def = schema._zod.def; + json.type = "object"; + if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { + json.propertyNames = to_json_schema_process(def.keyType, ctx, { + ...params, + path: [...params.path, "propertyNames"], + }); + } + json.additionalProperties = to_json_schema_process(def.valueType, ctx, { + ...params, + path: [...params.path, "additionalProperties"], + }); +}; +const nullableProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + const inner = to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + if (ctx.target === "openapi-3.0") { + seen.ref = def.innerType; + json.nullable = true; + } + else { + json.anyOf = [inner, { type: "null" }]; + } +}; +const nonoptionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const defaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.default = JSON.parse(JSON.stringify(def.defaultValue)); +}; +const prefaultProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + if (ctx.io === "input") + json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); +}; +const catchProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + let catchValue; + try { + catchValue = def.catchValue(undefined); + } + catch { + throw new Error("Dynamic catch values are not supported in JSON Schema"); + } + json.default = catchValue; +}; +const pipeProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + const innerType = ctx.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +const readonlyProcessor = (schema, ctx, json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; + json.readOnly = true; +}; +const promiseProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const optionalProcessor = (schema, ctx, _json, params) => { + const def = schema._zod.def; + to_json_schema_process(def.innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = def.innerType; +}; +const lazyProcessor = (schema, ctx, _json, params) => { + const innerType = schema._zod.innerType; + to_json_schema_process(innerType, ctx, params); + const seen = ctx.seen.get(schema); + seen.ref = innerType; +}; +// ==================== ALL PROCESSORS ==================== +const allProcessors = { + string: stringProcessor, + number: numberProcessor, + boolean: booleanProcessor, + bigint: bigintProcessor, + symbol: symbolProcessor, + null: nullProcessor, + undefined: undefinedProcessor, + void: voidProcessor, + never: neverProcessor, + any: anyProcessor, + unknown: unknownProcessor, + date: dateProcessor, + enum: enumProcessor, + literal: literalProcessor, + nan: nanProcessor, + template_literal: templateLiteralProcessor, + file: fileProcessor, + success: successProcessor, + custom: customProcessor, + function: functionProcessor, + transform: transformProcessor, + map: mapProcessor, + set: setProcessor, + array: arrayProcessor, + object: objectProcessor, + union: unionProcessor, + intersection: intersectionProcessor, + tuple: tupleProcessor, + record: recordProcessor, + nullable: nullableProcessor, + nonoptional: nonoptionalProcessor, + default: defaultProcessor, + prefault: prefaultProcessor, + catch: catchProcessor, + pipe: pipeProcessor, + readonly: readonlyProcessor, + promise: promiseProcessor, + optional: optionalProcessor, + lazy: lazyProcessor, +}; +function toJSONSchema(input, params) { + if ("_idmap" in input) { + // Registry case + const registry = input; + const ctx = initializeContext({ ...params, processors: allProcessors }); + const defs = {}; + // First pass: process all schemas to build the seen map + for (const entry of registry._idmap.entries()) { + const [_, schema] = entry; + to_json_schema_process(schema, ctx); + } + const schemas = {}; + const external = { + registry, + uri: params?.uri, + defs, + }; + // Update the context with external configuration + ctx.external = external; + // Second pass: emit each schema + for (const entry of registry._idmap.entries()) { + const [key, schema] = entry; + extractDefs(ctx, schema); + schemas[key] = finalize(ctx, schema); + } + if (Object.keys(defs).length > 0) { + const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; + schemas.__shared = { + [defsSegment]: defs, + }; + } + return { schemas }; + } + // Single schema case + const ctx = initializeContext({ ...params, processors: allProcessors }); + to_json_schema_process(input, ctx); + extractDefs(ctx, input); + return finalize(ctx, input); +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/json-schema-generator.js + + +/** + * Legacy class-based interface for JSON Schema generation. + * This class wraps the new functional implementation to provide backward compatibility. + * + * @deprecated Use the `toJSONSchema` function instead for new code. + * + * @example + * ```typescript + * // Legacy usage (still supported) + * const gen = new JSONSchemaGenerator({ target: "draft-07" }); + * gen.process(schema); + * const result = gen.emit(schema); + * + * // Preferred modern usage + * const result = toJSONSchema(schema, { target: "draft-07" }); + * ``` + */ +class JSONSchemaGenerator { + /** @deprecated Access via ctx instead */ + get metadataRegistry() { + return this.ctx.metadataRegistry; + } + /** @deprecated Access via ctx instead */ + get target() { + return this.ctx.target; + } + /** @deprecated Access via ctx instead */ + get unrepresentable() { + return this.ctx.unrepresentable; + } + /** @deprecated Access via ctx instead */ + get override() { + return this.ctx.override; + } + /** @deprecated Access via ctx instead */ + get io() { + return this.ctx.io; + } + /** @deprecated Access via ctx instead */ + get counter() { + return this.ctx.counter; + } + set counter(value) { + this.ctx.counter = value; + } + /** @deprecated Access via ctx instead */ + get seen() { + return this.ctx.seen; + } + constructor(params) { + // Normalize target for internal context + let normalizedTarget = params?.target ?? "draft-2020-12"; + if (normalizedTarget === "draft-4") + normalizedTarget = "draft-04"; + if (normalizedTarget === "draft-7") + normalizedTarget = "draft-07"; + this.ctx = initializeContext({ + processors: allProcessors, + target: normalizedTarget, + ...(params?.metadata && { metadata: params.metadata }), + ...(params?.unrepresentable && { unrepresentable: params.unrepresentable }), + ...(params?.override && { override: params.override }), + ...(params?.io && { io: params.io }), + }); + } + /** + * Process a schema to prepare it for JSON Schema generation. + * This must be called before emit(). + */ + process(schema, _params = { path: [], schemaPath: [] }) { + return to_json_schema_process(schema, this.ctx, _params); + } + /** + * Emit the final JSON Schema after processing. + * Must call process() first. + */ + emit(schema, _params) { + // Apply emit params to the context + if (_params) { + if (_params.cycles) + this.ctx.cycles = _params.cycles; + if (_params.reused) + this.ctx.reused = _params.reused; + if (_params.external) + this.ctx.external = _params.external; + } + extractDefs(this.ctx, schema); + const result = finalize(this.ctx, schema); + // Strip ~standard property to match old implementation's return type + const { "~standard": _, ...plainResult } = result; + return plainResult; + } +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/json-schema.js + + +;// CONCATENATED MODULE: ./node_modules/zod/v4/core/index.js + + + + + + + + + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/types/zod.js + + +//#region src/utils/types/zod.ts +function isZodSchemaV4(schema) { + if (typeof schema !== "object" || schema === null) return false; + const obj = schema; + if (!("_zod" in obj)) return false; + const zod = obj._zod; + return typeof zod === "object" && zod !== null && "def" in zod; +} +function isZodSchemaV3(schema) { + if (typeof schema !== "object" || schema === null) return false; + const obj = schema; + if (!("_def" in obj) || "_zod" in obj) return false; + const def = obj._def; + return typeof def === "object" && def != null && "typeName" in def; +} +/** Backward compatible isZodSchema for Zod 3 */ +function isZodSchema(schema) { + if (isZodSchemaV4(schema)) console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."); + return isZodSchemaV3(schema); +} +/** +* Given either a Zod schema, or plain object, determine if the input is a Zod schema. +* +* @param {unknown} input +* @returns {boolean} Whether or not the provided input is a Zod schema. +*/ +function isInteropZodSchema(input) { + if (!input) return false; + if (typeof input !== "object") return false; + if (Array.isArray(input)) return false; + if (isZodSchemaV4(input) || isZodSchemaV3(input)) return true; + return false; +} +function isZodLiteralV3(obj) { + if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodLiteral") return true; + return false; +} +function isZodLiteralV4(obj) { + if (!isZodSchemaV4(obj)) return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "literal") return true; + return false; +} +/** +* Determines if the provided value is an InteropZodLiteral (Zod v3 or v4 literal schema). +* +* @param obj The value to check. +* @returns {boolean} True if the value is a Zod v3 or v4 literal schema, false otherwise. +*/ +function isInteropZodLiteral(obj) { + if (isZodLiteralV3(obj)) return true; + if (isZodLiteralV4(obj)) return true; + return false; +} +/** +* Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns a safe parse result. +* This function handles both Zod v3 and v4 schemas, returning a result object indicating success or failure. +* +* @template T - The expected output type of the schema. +* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. +* @param {unknown} input - The input value to parse. +* @returns {Promise>} A promise that resolves to a safe parse result object. +* @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. +*/ +async function interopSafeParseAsync(schema, input) { + if (isZodSchemaV4(schema)) try { + const data = await parseAsync(schema, input); + return { + success: true, + data + }; + } catch (error) { + return { + success: false, + error + }; + } + if (isZodSchemaV3(schema)) return await schema.safeParseAsync(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** +* Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. +* Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. +* +* @template T - The expected output type of the schema. +* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. +* @param {unknown} input - The input value to parse. +* @returns {Promise} A promise that resolves to the parsed value. +* @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. +*/ +async function interopParseAsync(schema, input) { + if (isZodSchemaV4(schema)) return await parseAsync(schema, input); + if (isZodSchemaV3(schema)) return await schema.parseAsync(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** +* Safely parses the input using the provided Zod schema (v3 or v4) and returns a result object +* indicating success or failure. This function is compatible with both Zod v3 and v4 schemas. +* +* @template T - The expected output type of the schema. +* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. +* @param {unknown} input - The input value to parse. +* @returns {InteropZodSafeParseResult} An object with either the parsed data (on success) +* or the error (on failure). +* @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. +*/ +function interopSafeParse(schema, input) { + if (isZodSchemaV4(schema)) try { + const data = parse_parse(schema, input); + return { + success: true, + data + }; + } catch (error) { + return { + success: false, + error + }; + } + if (isZodSchemaV3(schema)) return schema.safeParse(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** +* Parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. +* Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. +* +* @template T - The expected output type of the schema. +* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. +* @param {unknown} input - The input value to parse. +* @returns {T} The parsed value. +* @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. +*/ +function interopParse(schema, input) { + if (isZodSchemaV4(schema)) return parse_parse(schema, input); + if (isZodSchemaV3(schema)) return schema.parse(input); + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** +* Retrieves the description from a schema definition (v3, v4, or plain object), if available. +* +* @param {unknown} schema - The schema to extract the description from. +* @returns {string | undefined} The description of the schema, or undefined if not present. +*/ +function getSchemaDescription(schema) { + if (isZodSchemaV4(schema)) return globalRegistry.get(schema)?.description; + if (isZodSchemaV3(schema)) return schema.description; + if ("description" in schema && typeof schema.description === "string") return schema.description; + return void 0; +} +/** +* Determines if the provided Zod schema is "shapeless". +* A shapeless schema is one that does not define any object shape, +* such as ZodString, ZodNumber, ZodBoolean, ZodAny, etc. +* For ZodObject, it must have no shape keys to be considered shapeless. +* ZodRecord schemas are considered shapeless since they define dynamic +* key-value mappings without fixed keys. +* +* @param schema The Zod schema to check. +* @returns {boolean} True if the schema is shapeless, false otherwise. +*/ +function isShapelessZodSchema(schema) { + if (!isInteropZodSchema(schema)) return false; + if (isZodSchemaV3(schema)) { + const def = schema._def; + if (def.typeName === "ZodObject") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; + } + if (def.typeName === "ZodRecord") return true; + } + if (isZodSchemaV4(schema)) { + const def = schema._zod.def; + if (def.type === "object") { + const obj = schema; + return !obj.shape || Object.keys(obj.shape).length === 0; + } + if (def.type === "record") return true; + } + if (typeof schema === "object" && schema !== null && !("shape" in schema)) return true; + return false; +} +/** +* Determines if the provided Zod schema should be treated as a simple string schema +* that maps to DynamicTool. This aligns with the type-level constraint of +* InteropZodType which only matches basic string schemas. +* If the provided schema is just z.string(), we can make the determination that +* the tool is just a generic string tool that doesn't require any input validation. +* +* This function only returns true for basic ZodString schemas, including: +* - Basic string schemas (z.string()) +* - String schemas with validations (z.string().min(1), z.string().email(), etc.) +* +* This function returns false for everything else, including: +* - String schemas with defaults (z.string().default("value")) +* - Branded string schemas (z.string().brand<"UserId">()) +* - String schemas with catch operations (z.string().catch("default")) +* - Optional/nullable string schemas (z.string().optional()) +* - Transformed schemas (z.string().transform() or z.object().transform()) +* - Object or record schemas, even if they're empty +* - Any other schema type +* +* @param schema The Zod schema to check. +* @returns {boolean} True if the schema is a basic ZodString, false otherwise. +*/ +function isSimpleStringZodSchema(schema) { + if (!isInteropZodSchema(schema)) return false; + if (isZodSchemaV3(schema)) { + const def = schema._def; + return def.typeName === "ZodString"; + } + if (isZodSchemaV4(schema)) { + const def = schema._zod.def; + return def.type === "string"; + } + return false; +} +function isZodObjectV3(obj) { + if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodObject") return true; + return false; +} +function isZodObjectV4(obj) { + if (!isZodSchemaV4(obj)) return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "object") return true; + return false; +} +function isZodArrayV4(obj) { + if (!isZodSchemaV4(obj)) return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "array") return true; + return false; +} +function isZodOptionalV4(obj) { + if (!isZodSchemaV4(obj)) return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "optional") return true; + return false; +} +function isZodNullableV4(obj) { + if (!isZodSchemaV4(obj)) return false; + if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "nullable") return true; + return false; +} +/** +* Determines if the provided value is an InteropZodObject (Zod v3 or v4 object schema). +* +* @param obj The value to check. +* @returns {boolean} True if the value is a Zod v3 or v4 object schema, false otherwise. +*/ +function isInteropZodObject(obj) { + if (isZodObjectV3(obj)) return true; + if (isZodObjectV4(obj)) return true; + return false; +} +/** +* Retrieves the shape (fields) of a Zod object schema, supporting both Zod v3 and v4. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @returns {InteropZodObjectShape} The shape of the object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function getInteropZodObjectShape(schema) { + if (isZodSchemaV3(schema)) return schema.shape; + if (isZodSchemaV4(schema)) return schema._zod.def.shape; + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** +* Extends a Zod object schema with additional fields, supporting both Zod v3 and v4. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @param {InteropZodObjectShape} extension - The fields to add to the schema. +* @returns {InteropZodObject} The extended Zod object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function extendInteropZodObject(schema, extension) { + if (isZodSchemaV3(schema)) return schema.extend(extension); + if (isZodSchemaV4(schema)) return extend(schema, extension); + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** +* Returns a partial version of a Zod object schema, making all fields optional. +* Supports both Zod v3 and v4. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @returns {InteropZodObject} The partial Zod object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function interopZodObjectPartial(schema) { + if (isZodSchemaV3(schema)) return schema.partial(); + if (isZodSchemaV4(schema)) return partial($ZodOptional, schema, void 0); + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** +* Returns a strict version of a Zod object schema, disallowing unknown keys. +* Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies strictness +* recursively to all nested object schemas and arrays of object schemas. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @param {boolean} [recursive=false] - Whether to apply strictness recursively to nested objects/arrays. +* @returns {InteropZodObject} The strict Zod object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function interopZodObjectStrict(schema, recursive = false) { + if (isZodSchemaV3(schema)) return schema.strict(); + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + if (isZodObjectV4(keySchema)) { + const outputSchema = interopZodObjectStrict(keySchema, recursive); + outputShape[key] = outputSchema; + } else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) elementSchema = interopZodObjectStrict(elementSchema, recursive); + outputShape[key] = clone(keySchema, { + ...keySchema._zod.def, + element: elementSchema + }); + } else outputShape[key] = keySchema; + const meta$1 = globalRegistry.get(keySchema); + if (meta$1) globalRegistry.add(outputShape[key], meta$1); + } + const modifiedSchema = clone(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: _never($ZodNever) + }); + const meta = globalRegistry.get(schema); + if (meta) globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** +* Returns a passthrough version of a Zod object schema, allowing unknown keys. +* Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies passthrough +* recursively to all nested object schemas and arrays of object schemas. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @param {boolean} [recursive=false] - Whether to apply passthrough recursively to nested objects/arrays. +* @returns {InteropZodObject} The passthrough Zod object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function interopZodObjectPassthrough(schema, recursive = false) { + if (isZodObjectV3(schema)) return schema.passthrough(); + if (isZodObjectV4(schema)) { + const outputShape = schema._zod.def.shape; + if (recursive) for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { + if (isZodObjectV4(keySchema)) { + const outputSchema = interopZodObjectPassthrough(keySchema, recursive); + outputShape[key] = outputSchema; + } else if (isZodArrayV4(keySchema)) { + let elementSchema = keySchema._zod.def.element; + if (isZodObjectV4(elementSchema)) elementSchema = interopZodObjectPassthrough(elementSchema, recursive); + outputShape[key] = clone(keySchema, { + ...keySchema._zod.def, + element: elementSchema + }); + } else outputShape[key] = keySchema; + const meta$1 = globalRegistry.get(keySchema); + if (meta$1) globalRegistry.add(outputShape[key], meta$1); + } + const modifiedSchema = clone(schema, { + ...schema._zod.def, + shape: outputShape, + catchall: _unknown($ZodUnknown) + }); + const meta = globalRegistry.get(schema); + if (meta) globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +/** +* Returns a getter function for the default value of a Zod schema, if one is defined. +* Supports both Zod v3 and v4 schemas. If the schema has a default value, +* the returned function will return that value when called. If no default is defined, +* returns undefined. +* +* @template T - The type of the Zod schema. +* @param {T} schema - The Zod schema instance (either v3 or v4). +* @returns {(() => InferInteropZodOutput) | undefined} A function that returns the default value, or undefined if no default is set. +*/ +function getInteropZodDefaultGetter(schema) { + if (isZodSchemaV3(schema)) try { + const defaultValue = schema.parse(void 0); + return () => defaultValue; + } catch { + return void 0; + } + if (isZodSchemaV4(schema)) try { + const defaultValue = parse_parse(schema, void 0); + return () => defaultValue; + } catch { + return void 0; + } + return void 0; +} +function isZodTransformV3(schema) { + return isZodSchemaV3(schema) && "typeName" in schema._def && schema._def.typeName === "ZodEffects"; +} +function isZodTransformV4(schema) { + return isZodSchemaV4(schema) && schema._zod.def.type === "pipe"; +} +function interopZodTransformInputSchemaImpl(schema, recursive, cache) { + const cached = cache.get(schema); + if (cached !== void 0) return cached; + if (isZodSchemaV3(schema)) { + if (isZodTransformV3(schema)) return interopZodTransformInputSchemaImpl(schema._def.schema, recursive, cache); + return schema; + } + if (isZodSchemaV4(schema)) { + let outputSchema = schema; + if (isZodTransformV4(schema)) outputSchema = interopZodTransformInputSchemaImpl(schema._zod.def.in, recursive, cache); + if (recursive) { + if (isZodObjectV4(outputSchema)) { + const outputShape = {}; + for (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape)) outputShape[key] = interopZodTransformInputSchemaImpl(keySchema, recursive, cache); + outputSchema = clone(outputSchema, { + ...outputSchema._zod.def, + shape: outputShape + }); + } else if (isZodArrayV4(outputSchema)) { + const elementSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.element, recursive, cache); + outputSchema = clone(outputSchema, { + ...outputSchema._zod.def, + element: elementSchema + }); + } else if (isZodOptionalV4(outputSchema)) { + const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache); + outputSchema = clone(outputSchema, { + ...outputSchema._zod.def, + innerType: innerSchema + }); + } else if (isZodNullableV4(outputSchema)) { + const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache); + outputSchema = clone(outputSchema, { + ...outputSchema._zod.def, + innerType: innerSchema + }); + } + } + const meta = globalRegistry.get(schema); + if (meta) globalRegistry.add(outputSchema, meta); + cache.set(schema, outputSchema); + return outputSchema; + } + throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); +} +/** +* Returns the input type of a Zod transform schema, for both v3 and v4. +* If the schema is not a transform, returns undefined. If `recursive` is true, +* recursively processes nested object schemas and arrays of object schemas. +* +* @param schema - The Zod schema instance (v3 or v4) +* @param {boolean} [recursive=false] - Whether to recursively process nested objects/arrays. +* @returns The input Zod schema of the transform, or undefined if not a transform +*/ +function interopZodTransformInputSchema(schema, recursive = false) { + const cache = /* @__PURE__ */ new WeakMap(); + return interopZodTransformInputSchemaImpl(schema, recursive, cache); +} +/** +* Creates a modified version of a Zod object schema where fields matching a predicate are made optional. +* Supports both Zod v3 and v4 schemas and preserves the original schema version. +* +* @template T - The type of the Zod object schema. +* @param {T} schema - The Zod object schema instance (either v3 or v4). +* @param {(key: string, value: InteropZodType) => boolean} predicate - Function to determine which fields should be optional. +* @returns {InteropZodObject} The modified Zod object schema. +* @throws {Error} If the schema is not a Zod v3 or v4 object. +*/ +function interopZodObjectMakeFieldsOptional(schema, predicate) { + if (isZodSchemaV3(schema)) { + const shape = getInteropZodObjectShape(schema); + const modifiedShape = {}; + for (const [key, value] of Object.entries(shape)) if (predicate(key, value)) modifiedShape[key] = value.optional(); + else modifiedShape[key] = value; + return schema.extend(modifiedShape); + } + if (isZodSchemaV4(schema)) { + const shape = getInteropZodObjectShape(schema); + const outputShape = { ...schema._zod.def.shape }; + for (const [key, value] of Object.entries(shape)) if (predicate(key, value)) outputShape[key] = new $ZodOptional({ + type: "optional", + innerType: value + }); + const modifiedSchema = clone(schema, { + ...schema._zod.def, + shape: outputShape + }); + const meta = globalRegistry.get(schema); + if (meta) globalRegistry.add(modifiedSchema, meta); + return modifiedSchema; + } + throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); +} +function isInteropZodError(e) { + return e instanceof Error && (e.constructor.name === "ZodError" || e.constructor.name === "$ZodError"); +} + +//#endregion + +//# sourceMappingURL=zod.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/Options.js +//#region src/utils/zod-to-json-schema/Options.ts +const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); +const Options_defaultOptions = { + name: void 0, + $refStrategy: "root", + basePath: ["#"], + effectStrategy: "input", + pipeStrategy: "all", + dateStrategy: "format:date-time", + mapStrategy: "entries", + removeAdditionalStrategy: "passthrough", + allowedAdditionalProperties: true, + rejectedAdditionalProperties: false, + definitionPath: "definitions", + target: "jsonSchema7", + strictUnions: false, + definitions: {}, + errorMessages: false, + markdownDescription: false, + patternStrategy: "escape", + applyRegexFlags: false, + emailStrategy: "format:email", + base64Strategy: "contentEncoding:base64", + nameStrategy: "ref", + openAiAnyTypeName: "OpenAiAnyType" +}; +const getDefaultOptions = (options) => typeof options === "string" ? { + ...Options_defaultOptions, + name: options +} : { + ...Options_defaultOptions, + ...options +}; + +//#endregion + +//# sourceMappingURL=Options.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/Refs.js + + +//#region src/utils/zod-to-json-schema/Refs.ts +const getRefs = (options) => { + const _options = getDefaultOptions(options); + const currentPath = _options.name !== void 0 ? [ + ..._options.basePath, + _options.definitionPath, + _options.name + ] : _options.basePath; + return { + ..._options, + flags: { hasReferencedOpenAiAnyType: false }, + currentPath, + propertyPath: void 0, + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [def._def, { + def: def._def, + path: [ + ..._options.basePath, + _options.definitionPath, + name + ], + jsonSchema: void 0 + }])) + }; +}; + +//#endregion + +//# sourceMappingURL=Refs.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/getRelativePath.js +//#region src/utils/zod-to-json-schema/getRelativePath.ts +const getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break; + return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); +}; + +//#endregion + +//# sourceMappingURL=getRelativePath.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/any.js + + +//#region src/utils/zod-to-json-schema/parsers/any.ts +function parseAnyDef(refs) { + if (refs.target !== "openAi") return {}; + const anyDefinitionPath = [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ]; + refs.flags.hasReferencedOpenAiAnyType = true; + return { $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") }; +} + +//#endregion + +//# sourceMappingURL=any.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/errorMessages.js +//#region src/utils/zod-to-json-schema/errorMessages.ts +function addErrorMessage(res, key, errorMessage, refs) { + if (!refs?.errorMessages) return; + if (errorMessage) res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage + }; +} +function setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + addErrorMessage(res, key, errorMessage, refs); +} + +//#endregion + +//# sourceMappingURL=errorMessages.js.map +;// CONCATENATED MODULE: ./node_modules/zod/v3/helpers/util.js +var util; +(function (util) { + util.assertEqual = (_) => { }; + function assertIs(_arg) { } + util.assertIs = assertIs; + function assertNever(_x) { + throw new Error(); + } + util.assertNever = assertNever; + util.arrayToEnum = (items) => { + const obj = {}; + for (const item of items) { + obj[item] = item; + } + return obj; + }; + util.getValidEnumValues = (obj) => { + const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); + const filtered = {}; + for (const k of validKeys) { + filtered[k] = obj[k]; + } + return util.objectValues(filtered); + }; + util.objectValues = (obj) => { + return util.objectKeys(obj).map(function (e) { + return obj[e]; + }); + }; + util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban + ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban + : (object) => { + const keys = []; + for (const key in object) { + if (Object.prototype.hasOwnProperty.call(object, key)) { + keys.push(key); + } + } + return keys; + }; + util.find = (arr, checker) => { + for (const item of arr) { + if (checker(item)) + return item; + } + return undefined; + }; + util.isInteger = typeof Number.isInteger === "function" + ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban + : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; + function joinValues(array, separator = " | ") { + return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); + } + util.joinValues = joinValues; + util.jsonStringifyReplacer = (_, value) => { + if (typeof value === "bigint") { + return value.toString(); + } + return value; + }; +})(util || (util = {})); +var objectUtil; +(function (objectUtil) { + objectUtil.mergeShapes = (first, second) => { + return { + ...first, + ...second, // second overwrites first + }; + }; +})(objectUtil || (objectUtil = {})); +const ZodParsedType = util.arrayToEnum([ + "string", + "nan", + "number", + "integer", + "float", + "boolean", + "date", + "bigint", + "symbol", + "function", + "undefined", + "null", + "array", + "object", + "unknown", + "promise", + "void", + "never", + "map", + "set", +]); +const util_getParsedType = (data) => { + const t = typeof data; + switch (t) { + case "undefined": + return ZodParsedType.undefined; + case "string": + return ZodParsedType.string; + case "number": + return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; + case "boolean": + return ZodParsedType.boolean; + case "function": + return ZodParsedType.function; + case "bigint": + return ZodParsedType.bigint; + case "symbol": + return ZodParsedType.symbol; + case "object": + if (Array.isArray(data)) { + return ZodParsedType.array; + } + if (data === null) { + return ZodParsedType.null; + } + if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { + return ZodParsedType.promise; + } + if (typeof Map !== "undefined" && data instanceof Map) { + return ZodParsedType.map; + } + if (typeof Set !== "undefined" && data instanceof Set) { + return ZodParsedType.set; + } + if (typeof Date !== "undefined" && data instanceof Date) { + return ZodParsedType.date; + } + return ZodParsedType.object; + default: + return ZodParsedType.unknown; + } +}; + +;// CONCATENATED MODULE: ./node_modules/zod/v3/ZodError.js + +const ZodIssueCode = util.arrayToEnum([ + "invalid_type", + "invalid_literal", + "custom", + "invalid_union", + "invalid_union_discriminator", + "invalid_enum_value", + "unrecognized_keys", + "invalid_arguments", + "invalid_return_type", + "invalid_date", + "invalid_string", + "too_small", + "too_big", + "invalid_intersection_types", + "not_multiple_of", + "not_finite", +]); +const quotelessJson = (obj) => { + const json = JSON.stringify(obj, null, 2); + return json.replace(/"([^"]+)":/g, "$1:"); +}; +class ZodError extends Error { + get errors() { + return this.issues; + } + constructor(issues) { + super(); + this.issues = []; + this.addIssue = (sub) => { + this.issues = [...this.issues, sub]; + }; + this.addIssues = (subs = []) => { + this.issues = [...this.issues, ...subs]; + }; + const actualProto = new.target.prototype; + if (Object.setPrototypeOf) { + // eslint-disable-next-line ban/ban + Object.setPrototypeOf(this, actualProto); + } + else { + this.__proto__ = actualProto; + } + this.name = "ZodError"; + this.issues = issues; + } + format(_mapper) { + const mapper = _mapper || + function (issue) { + return issue.message; + }; + const fieldErrors = { _errors: [] }; + const processError = (error) => { + for (const issue of error.issues) { + if (issue.code === "invalid_union") { + issue.unionErrors.map(processError); + } + else if (issue.code === "invalid_return_type") { + processError(issue.returnTypeError); + } + else if (issue.code === "invalid_arguments") { + processError(issue.argumentsError); + } + else if (issue.path.length === 0) { + fieldErrors._errors.push(mapper(issue)); + } + else { + let curr = fieldErrors; + let i = 0; + while (i < issue.path.length) { + const el = issue.path[i]; + const terminal = i === issue.path.length - 1; + if (!terminal) { + curr[el] = curr[el] || { _errors: [] }; + // if (typeof el === "string") { + // curr[el] = curr[el] || { _errors: [] }; + // } else if (typeof el === "number") { + // const errorArray: any = []; + // errorArray._errors = []; + // curr[el] = curr[el] || errorArray; + // } + } + else { + curr[el] = curr[el] || { _errors: [] }; + curr[el]._errors.push(mapper(issue)); + } + curr = curr[el]; + i++; + } + } + } + }; + processError(this); + return fieldErrors; + } + static assert(value) { + if (!(value instanceof ZodError)) { + throw new Error(`Not a ZodError: ${value}`); + } + } + toString() { + return this.message; + } + get message() { + return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); + } + get isEmpty() { + return this.issues.length === 0; + } + flatten(mapper = (issue) => issue.message) { + const fieldErrors = Object.create(null); + const formErrors = []; + for (const sub of this.issues) { + if (sub.path.length > 0) { + const firstEl = sub.path[0]; + fieldErrors[firstEl] = fieldErrors[firstEl] || []; + fieldErrors[firstEl].push(mapper(sub)); + } + else { + formErrors.push(mapper(sub)); + } + } + return { formErrors, fieldErrors }; + } + get formErrors() { + return this.flatten(); + } +} +ZodError.create = (issues) => { + const error = new ZodError(issues); + return error; +}; + +;// CONCATENATED MODULE: ./node_modules/zod/v3/locales/en.js + + +const errorMap = (issue, _ctx) => { + let message; + switch (issue.code) { + case ZodIssueCode.invalid_type: + if (issue.received === ZodParsedType.undefined) { + message = "Required"; + } + else { + message = `Expected ${issue.expected}, received ${issue.received}`; + } + break; + case ZodIssueCode.invalid_literal: + message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; + break; + case ZodIssueCode.unrecognized_keys: + message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; + break; + case ZodIssueCode.invalid_union: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_union_discriminator: + message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; + break; + case ZodIssueCode.invalid_enum_value: + message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; + break; + case ZodIssueCode.invalid_arguments: + message = `Invalid function arguments`; + break; + case ZodIssueCode.invalid_return_type: + message = `Invalid function return type`; + break; + case ZodIssueCode.invalid_date: + message = `Invalid date`; + break; + case ZodIssueCode.invalid_string: + if (typeof issue.validation === "object") { + if ("includes" in issue.validation) { + message = `Invalid input: must include "${issue.validation.includes}"`; + if (typeof issue.validation.position === "number") { + message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; + } + } + else if ("startsWith" in issue.validation) { + message = `Invalid input: must start with "${issue.validation.startsWith}"`; + } + else if ("endsWith" in issue.validation) { + message = `Invalid input: must end with "${issue.validation.endsWith}"`; + } + else { + util.assertNever(issue.validation); + } + } + else if (issue.validation !== "regex") { + message = `Invalid ${issue.validation}`; + } + else { + message = "Invalid"; + } + break; + case ZodIssueCode.too_small: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "bigint") + message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.too_big: + if (issue.type === "array") + message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; + else if (issue.type === "string") + message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; + else if (issue.type === "number") + message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "bigint") + message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; + else if (issue.type === "date") + message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; + else + message = "Invalid input"; + break; + case ZodIssueCode.custom: + message = `Invalid input`; + break; + case ZodIssueCode.invalid_intersection_types: + message = `Intersection results could not be merged`; + break; + case ZodIssueCode.not_multiple_of: + message = `Number must be a multiple of ${issue.multipleOf}`; + break; + case ZodIssueCode.not_finite: + message = "Number must be finite"; + break; + default: + message = _ctx.defaultError; + util.assertNever(issue); + } + return { message }; +}; +/* harmony default export */ const locales_en = (errorMap); + +;// CONCATENATED MODULE: ./node_modules/zod/v3/errors.js + +let overrideErrorMap = locales_en; + +function setErrorMap(map) { + overrideErrorMap = map; +} +function getErrorMap() { + return overrideErrorMap; +} + +;// CONCATENATED MODULE: ./node_modules/zod/v3/helpers/parseUtil.js + + +const makeIssue = (params) => { + const { data, path, errorMaps, issueData } = params; + const fullPath = [...path, ...(issueData.path || [])]; + const fullIssue = { + ...issueData, + path: fullPath, + }; + if (issueData.message !== undefined) { + return { + ...issueData, + path: fullPath, + message: issueData.message, + }; + } + let errorMessage = ""; + const maps = errorMaps + .filter((m) => !!m) + .slice() + .reverse(); + for (const map of maps) { + errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; + } + return { + ...issueData, + path: fullPath, + message: errorMessage, + }; +}; +const EMPTY_PATH = []; +function addIssueToContext(ctx, issueData) { + const overrideMap = getErrorMap(); + const issue = makeIssue({ + issueData: issueData, + data: ctx.data, + path: ctx.path, + errorMaps: [ + ctx.common.contextualErrorMap, // contextual error map is first priority + ctx.schemaErrorMap, // then schema-bound map if available + overrideMap, // then global override map + overrideMap === locales_en ? undefined : locales_en, // then global default map + ].filter((x) => !!x), + }); + ctx.common.issues.push(issue); +} +class ParseStatus { + constructor() { + this.value = "valid"; + } + dirty() { + if (this.value === "valid") + this.value = "dirty"; + } + abort() { + if (this.value !== "aborted") + this.value = "aborted"; + } + static mergeArray(status, results) { + const arrayValue = []; + for (const s of results) { + if (s.status === "aborted") + return INVALID; + if (s.status === "dirty") + status.dirty(); + arrayValue.push(s.value); + } + return { status: status.value, value: arrayValue }; + } + static async mergeObjectAsync(status, pairs) { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + }); + } + return ParseStatus.mergeObjectSync(status, syncPairs); + } + static mergeObjectSync(status, pairs) { + const finalObject = {}; + for (const pair of pairs) { + const { key, value } = pair; + if (key.status === "aborted") + return INVALID; + if (value.status === "aborted") + return INVALID; + if (key.status === "dirty") + status.dirty(); + if (value.status === "dirty") + status.dirty(); + if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { + finalObject[key.value] = value.value; + } + } + return { status: status.value, value: finalObject }; + } +} +const INVALID = Object.freeze({ + status: "aborted", +}); +const DIRTY = (value) => ({ status: "dirty", value }); +const OK = (value) => ({ status: "valid", value }); +const isAborted = (x) => x.status === "aborted"; +const isDirty = (x) => x.status === "dirty"; +const isValid = (x) => x.status === "valid"; +const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; + +;// CONCATENATED MODULE: ./node_modules/zod/v3/helpers/errorUtil.js +var errorUtil; +(function (errorUtil) { + errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; + // biome-ignore lint: + errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; +})(errorUtil || (errorUtil = {})); + +;// CONCATENATED MODULE: ./node_modules/zod/v3/types.js + + + + + +class ParseInputLazyPath { + constructor(parent, value, path, key) { + this._cachedPath = []; + this.parent = parent; + this.data = value; + this._path = path; + this._key = key; + } + get path() { + if (!this._cachedPath.length) { + if (Array.isArray(this._key)) { + this._cachedPath.push(...this._path, ...this._key); + } + else { + this._cachedPath.push(...this._path, this._key); + } + } + return this._cachedPath; + } +} +const handleResult = (ctx, result) => { + if (isValid(result)) { + return { success: true, data: result.value }; + } + else { + if (!ctx.common.issues.length) { + throw new Error("Validation failed but no issues detected."); + } + return { + success: false, + get error() { + if (this._error) + return this._error; + const error = new ZodError(ctx.common.issues); + this._error = error; + return this._error; + }, + }; + } +}; +function processCreateParams(params) { + if (!params) + return {}; + const { errorMap, invalid_type_error, required_error, description } = params; + if (errorMap && (invalid_type_error || required_error)) { + throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); + } + if (errorMap) + return { errorMap: errorMap, description }; + const customMap = (iss, ctx) => { + const { message } = params; + if (iss.code === "invalid_enum_value") { + return { message: message ?? ctx.defaultError }; + } + if (typeof ctx.data === "undefined") { + return { message: message ?? required_error ?? ctx.defaultError }; + } + if (iss.code !== "invalid_type") + return { message: ctx.defaultError }; + return { message: message ?? invalid_type_error ?? ctx.defaultError }; + }; + return { errorMap: customMap, description }; +} +class ZodType { + get description() { + return this._def.description; + } + _getType(input) { + return util_getParsedType(input.data); + } + _getOrReturnCtx(input, ctx) { + return (ctx || { + common: input.parent.common, + data: input.data, + parsedType: util_getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }); + } + _processInputParams(input) { + return { + status: new ParseStatus(), + ctx: { + common: input.parent.common, + data: input.data, + parsedType: util_getParsedType(input.data), + schemaErrorMap: this._def.errorMap, + path: input.path, + parent: input.parent, + }, + }; + } + _parseSync(input) { + const result = this._parse(input); + if (isAsync(result)) { + throw new Error("Synchronous parse encountered promise."); + } + return result; + } + _parseAsync(input) { + const result = this._parse(input); + return Promise.resolve(result); + } + parse(data, params) { + const result = this.safeParse(data, params); + if (result.success) + return result.data; + throw result.error; + } + safeParse(data, params) { + const ctx = { + common: { + issues: [], + async: params?.async ?? false, + contextualErrorMap: params?.errorMap, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: util_getParsedType(data), + }; + const result = this._parseSync({ data, path: ctx.path, parent: ctx }); + return handleResult(ctx, result); + } + "~validate"(data) { + const ctx = { + common: { + issues: [], + async: !!this["~standard"].async, + }, + path: [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: util_getParsedType(data), + }; + if (!this["~standard"].async) { + try { + const result = this._parseSync({ data, path: [], parent: ctx }); + return isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }; + } + catch (err) { + if (err?.message?.toLowerCase()?.includes("encountered")) { + this["~standard"].async = true; + } + ctx.common = { + issues: [], + async: true, + }; + } + } + return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) + ? { + value: result.value, + } + : { + issues: ctx.common.issues, + }); + } + async parseAsync(data, params) { + const result = await this.safeParseAsync(data, params); + if (result.success) + return result.data; + throw result.error; + } + async safeParseAsync(data, params) { + const ctx = { + common: { + issues: [], + contextualErrorMap: params?.errorMap, + async: true, + }, + path: params?.path || [], + schemaErrorMap: this._def.errorMap, + parent: null, + data, + parsedType: util_getParsedType(data), + }; + const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); + const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); + return handleResult(ctx, result); + } + refine(check, message) { + const getIssueProperties = (val) => { + if (typeof message === "string" || typeof message === "undefined") { + return { message }; + } + else if (typeof message === "function") { + return message(val); + } + else { + return message; + } + }; + return this._refinement((val, ctx) => { + const result = check(val); + const setError = () => ctx.addIssue({ + code: ZodIssueCode.custom, + ...getIssueProperties(val), + }); + if (typeof Promise !== "undefined" && result instanceof Promise) { + return result.then((data) => { + if (!data) { + setError(); + return false; + } + else { + return true; + } + }); + } + if (!result) { + setError(); + return false; + } + else { + return true; + } + }); + } + refinement(check, refinementData) { + return this._refinement((val, ctx) => { + if (!check(val)) { + ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); + return false; + } + else { + return true; + } + }); + } + _refinement(refinement) { + return new ZodEffects({ + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "refinement", refinement }, + }); + } + superRefine(refinement) { + return this._refinement(refinement); + } + constructor(def) { + /** Alias of safeParseAsync */ + this.spa = this.safeParseAsync; + this._def = def; + this.parse = this.parse.bind(this); + this.safeParse = this.safeParse.bind(this); + this.parseAsync = this.parseAsync.bind(this); + this.safeParseAsync = this.safeParseAsync.bind(this); + this.spa = this.spa.bind(this); + this.refine = this.refine.bind(this); + this.refinement = this.refinement.bind(this); + this.superRefine = this.superRefine.bind(this); + this.optional = this.optional.bind(this); + this.nullable = this.nullable.bind(this); + this.nullish = this.nullish.bind(this); + this.array = this.array.bind(this); + this.promise = this.promise.bind(this); + this.or = this.or.bind(this); + this.and = this.and.bind(this); + this.transform = this.transform.bind(this); + this.brand = this.brand.bind(this); + this.default = this.default.bind(this); + this.catch = this.catch.bind(this); + this.describe = this.describe.bind(this); + this.pipe = this.pipe.bind(this); + this.readonly = this.readonly.bind(this); + this.isNullable = this.isNullable.bind(this); + this.isOptional = this.isOptional.bind(this); + this["~standard"] = { + version: 1, + vendor: "zod", + validate: (data) => this["~validate"](data), + }; + } + optional() { + return ZodOptional.create(this, this._def); + } + nullable() { + return ZodNullable.create(this, this._def); + } + nullish() { + return this.nullable().optional(); + } + array() { + return ZodArray.create(this); + } + promise() { + return ZodPromise.create(this, this._def); + } + or(option) { + return ZodUnion.create([this, option], this._def); + } + and(incoming) { + return ZodIntersection.create(this, incoming, this._def); + } + transform(transform) { + return new ZodEffects({ + ...processCreateParams(this._def), + schema: this, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect: { type: "transform", transform }, + }); + } + default(def) { + const defaultValueFunc = typeof def === "function" ? def : () => def; + return new ZodDefault({ + ...processCreateParams(this._def), + innerType: this, + defaultValue: defaultValueFunc, + typeName: ZodFirstPartyTypeKind.ZodDefault, + }); + } + brand() { + return new ZodBranded({ + typeName: ZodFirstPartyTypeKind.ZodBranded, + type: this, + ...processCreateParams(this._def), + }); + } + catch(def) { + const catchValueFunc = typeof def === "function" ? def : () => def; + return new ZodCatch({ + ...processCreateParams(this._def), + innerType: this, + catchValue: catchValueFunc, + typeName: ZodFirstPartyTypeKind.ZodCatch, + }); + } + describe(description) { + const This = this.constructor; + return new This({ + ...this._def, + description, + }); + } + pipe(target) { + return ZodPipeline.create(this, target); + } + readonly() { + return ZodReadonly.create(this); + } + isOptional() { + return this.safeParse(undefined).success; + } + isNullable() { + return this.safeParse(null).success; + } +} +const cuidRegex = /^c[^\s-]{8,}$/i; +const cuid2Regex = /^[0-9a-z]+$/; +const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; +// const uuidRegex = +// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; +const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; +const nanoidRegex = /^[a-z0-9_-]{21}$/i; +const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; +const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; +// from https://stackoverflow.com/a/46181/1550155 +// old version: too slow, didn't support unicode +// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; +//old email regex +// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; +// eslint-disable-next-line +// const emailRegex = +// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; +// const emailRegex = +// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; +// const emailRegex = +// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; +const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; +// const emailRegex = +// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; +// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression +const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; +let emojiRegex; +// faster, simpler, safer +const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; +const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; +// const ipv6Regex = +// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; +const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a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0-8]|1[01][0-9]|[1-9]?[0-9])$/; +// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript +const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; +// https://base64.guru/standards/base64url +const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; +// simple +// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; +// no leap year validation +// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; +// with leap year validation +const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; +const dateRegex = new RegExp(`^${dateRegexSource}$`); +function timeRegexSource(args) { + let secondsRegexSource = `[0-5]\\d`; + if (args.precision) { + secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; + } + else if (args.precision == null) { + secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; + } + const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero + return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; +} +function timeRegex(args) { + return new RegExp(`^${timeRegexSource(args)}$`); +} +// Adapted from https://stackoverflow.com/a/3143231 +function datetimeRegex(args) { + let regex = `${dateRegexSource}T${timeRegexSource(args)}`; + const opts = []; + opts.push(args.local ? `Z?` : `Z`); + if (args.offset) + opts.push(`([+-]\\d{2}:?\\d{2})`); + regex = `${regex}(${opts.join("|")})`; + return new RegExp(`^${regex}$`); +} +function isValidIP(ip, version) { + if ((version === "v4" || !version) && ipv4Regex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6Regex.test(ip)) { + return true; + } + return false; +} +function types_isValidJWT(jwt, alg) { + if (!jwtRegex.test(jwt)) + return false; + try { + const [header] = jwt.split("."); + if (!header) + return false; + // Convert base64url to base64 + const base64 = header + .replace(/-/g, "+") + .replace(/_/g, "/") + .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); + // @ts-ignore + const decoded = JSON.parse(atob(base64)); + if (typeof decoded !== "object" || decoded === null) + return false; + if ("typ" in decoded && decoded?.typ !== "JWT") + return false; + if (!decoded.alg) + return false; + if (alg && decoded.alg !== alg) + return false; + return true; + } + catch { + return false; + } +} +function isValidCidr(ip, version) { + if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { + return true; + } + if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { + return true; + } + return false; +} +class ZodString extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = String(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.string) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.string, + received: ctx.parsedType, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.length < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.length > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "length") { + const tooBig = input.data.length > check.value; + const tooSmall = input.data.length < check.value; + if (tooBig || tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + if (tooBig) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + else if (tooSmall) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "string", + inclusive: true, + exact: true, + message: check.message, + }); + } + status.dirty(); + } + } + else if (check.kind === "email") { + if (!emailRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "email", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "emoji") { + if (!emojiRegex) { + emojiRegex = new RegExp(_emojiRegex, "u"); + } + if (!emojiRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "emoji", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "uuid") { + if (!uuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "uuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "nanoid") { + if (!nanoidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "nanoid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid") { + if (!cuidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cuid2") { + if (!cuid2Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cuid2", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ulid") { + if (!ulidRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ulid", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "url") { + try { + // @ts-ignore + new URL(input.data); + } + catch { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "regex") { + check.regex.lastIndex = 0; + const testResult = check.regex.test(input.data); + if (!testResult) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "regex", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "trim") { + input.data = input.data.trim(); + } + else if (check.kind === "includes") { + if (!input.data.includes(check.value, check.position)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { includes: check.value, position: check.position }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "toLowerCase") { + input.data = input.data.toLowerCase(); + } + else if (check.kind === "toUpperCase") { + input.data = input.data.toUpperCase(); + } + else if (check.kind === "startsWith") { + if (!input.data.startsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { startsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "endsWith") { + if (!input.data.endsWith(check.value)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: { endsWith: check.value }, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "datetime") { + const regex = datetimeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "datetime", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "date") { + const regex = dateRegex; + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "date", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "time") { + const regex = timeRegex(check); + if (!regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_string, + validation: "time", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "duration") { + if (!durationRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "duration", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "ip") { + if (!isValidIP(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "ip", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "jwt") { + if (!types_isValidJWT(input.data, check.alg)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "jwt", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "cidr") { + if (!isValidCidr(input.data, check.version)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "cidr", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64") { + if (!base64Regex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "base64url") { + if (!base64urlRegex.test(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + validation: "base64url", + code: ZodIssueCode.invalid_string, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _regex(regex, validation, message) { + return this.refinement((data) => regex.test(data), { + validation, + code: ZodIssueCode.invalid_string, + ...errorUtil.errToObj(message), + }); + } + _addCheck(check) { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + email(message) { + return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); + } + url(message) { + return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); + } + emoji(message) { + return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); + } + uuid(message) { + return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); + } + nanoid(message) { + return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); + } + cuid(message) { + return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); + } + cuid2(message) { + return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); + } + ulid(message) { + return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); + } + base64(message) { + return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); + } + base64url(message) { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return this._addCheck({ + kind: "base64url", + ...errorUtil.errToObj(message), + }); + } + jwt(options) { + return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); + } + ip(options) { + return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); + } + cidr(options) { + return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); + } + datetime(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "datetime", + precision: null, + offset: false, + local: false, + message: options, + }); + } + return this._addCheck({ + kind: "datetime", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + offset: options?.offset ?? false, + local: options?.local ?? false, + ...errorUtil.errToObj(options?.message), + }); + } + date(message) { + return this._addCheck({ kind: "date", message }); + } + time(options) { + if (typeof options === "string") { + return this._addCheck({ + kind: "time", + precision: null, + message: options, + }); + } + return this._addCheck({ + kind: "time", + precision: typeof options?.precision === "undefined" ? null : options?.precision, + ...errorUtil.errToObj(options?.message), + }); + } + duration(message) { + return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); + } + regex(regex, message) { + return this._addCheck({ + kind: "regex", + regex: regex, + ...errorUtil.errToObj(message), + }); + } + includes(value, options) { + return this._addCheck({ + kind: "includes", + value: value, + position: options?.position, + ...errorUtil.errToObj(options?.message), + }); + } + startsWith(value, message) { + return this._addCheck({ + kind: "startsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + endsWith(value, message) { + return this._addCheck({ + kind: "endsWith", + value: value, + ...errorUtil.errToObj(message), + }); + } + min(minLength, message) { + return this._addCheck({ + kind: "min", + value: minLength, + ...errorUtil.errToObj(message), + }); + } + max(maxLength, message) { + return this._addCheck({ + kind: "max", + value: maxLength, + ...errorUtil.errToObj(message), + }); + } + length(len, message) { + return this._addCheck({ + kind: "length", + value: len, + ...errorUtil.errToObj(message), + }); + } + /** + * Equivalent to `.min(1)` + */ + nonempty(message) { + return this.min(1, errorUtil.errToObj(message)); + } + trim() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "trim" }], + }); + } + toLowerCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toLowerCase" }], + }); + } + toUpperCase() { + return new ZodString({ + ...this._def, + checks: [...this._def.checks, { kind: "toUpperCase" }], + }); + } + get isDatetime() { + return !!this._def.checks.find((ch) => ch.kind === "datetime"); + } + get isDate() { + return !!this._def.checks.find((ch) => ch.kind === "date"); + } + get isTime() { + return !!this._def.checks.find((ch) => ch.kind === "time"); + } + get isDuration() { + return !!this._def.checks.find((ch) => ch.kind === "duration"); + } + get isEmail() { + return !!this._def.checks.find((ch) => ch.kind === "email"); + } + get isURL() { + return !!this._def.checks.find((ch) => ch.kind === "url"); + } + get isEmoji() { + return !!this._def.checks.find((ch) => ch.kind === "emoji"); + } + get isUUID() { + return !!this._def.checks.find((ch) => ch.kind === "uuid"); + } + get isNANOID() { + return !!this._def.checks.find((ch) => ch.kind === "nanoid"); + } + get isCUID() { + return !!this._def.checks.find((ch) => ch.kind === "cuid"); + } + get isCUID2() { + return !!this._def.checks.find((ch) => ch.kind === "cuid2"); + } + get isULID() { + return !!this._def.checks.find((ch) => ch.kind === "ulid"); + } + get isIP() { + return !!this._def.checks.find((ch) => ch.kind === "ip"); + } + get isCIDR() { + return !!this._def.checks.find((ch) => ch.kind === "cidr"); + } + get isBase64() { + return !!this._def.checks.find((ch) => ch.kind === "base64"); + } + get isBase64url() { + // base64url encoding is a modification of base64 that can safely be used in URLs and filenames + return !!this._def.checks.find((ch) => ch.kind === "base64url"); + } + get minLength() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxLength() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +ZodString.create = (params) => { + return new ZodString({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodString, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); +}; +// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 +function types_floatSafeRemainder(val, step) { + const valDecCount = (val.toString().split(".")[1] || "").length; + const stepDecCount = (step.toString().split(".")[1] || "").length; + const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; + const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); + const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); + return (valInt % stepInt) / 10 ** decCount; +} +class ZodNumber extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + this.step = this.multipleOf; + } + _parse(input) { + if (this._def.coerce) { + input.data = Number(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.number) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.number, + received: ctx.parsedType, + }); + return INVALID; + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "int") { + if (!util.isInteger(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: "integer", + received: "float", + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: check.value, + type: "number", + inclusive: check.inclusive, + exact: false, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (types_floatSafeRemainder(input.data, check.value) !== 0) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "finite") { + if (!Number.isFinite(input.data)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_finite, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodNumber({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodNumber({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + int(message) { + return this._addCheck({ + kind: "int", + message: errorUtil.toString(message), + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: 0, + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value: value, + message: errorUtil.toString(message), + }); + } + finite(message) { + return this._addCheck({ + kind: "finite", + message: errorUtil.toString(message), + }); + } + safe(message) { + return this._addCheck({ + kind: "min", + inclusive: true, + value: Number.MIN_SAFE_INTEGER, + message: errorUtil.toString(message), + })._addCheck({ + kind: "max", + inclusive: true, + value: Number.MAX_SAFE_INTEGER, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } + get isInt() { + return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value))); + } + get isFinite() { + let max = null; + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { + return true; + } + else if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + else if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return Number.isFinite(min) && Number.isFinite(max); + } +} +ZodNumber.create = (params) => { + return new ZodNumber({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodNumber, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +class ZodBigInt extends ZodType { + constructor() { + super(...arguments); + this.min = this.gte; + this.max = this.lte; + } + _parse(input) { + if (this._def.coerce) { + try { + input.data = BigInt(input.data); + } + catch { + return this._getInvalidInput(input); + } + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.bigint) { + return this._getInvalidInput(input); + } + let ctx = undefined; + const status = new ParseStatus(); + for (const check of this._def.checks) { + if (check.kind === "min") { + const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; + if (tooSmall) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + type: "bigint", + minimum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "max") { + const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; + if (tooBig) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + type: "bigint", + maximum: check.value, + inclusive: check.inclusive, + message: check.message, + }); + status.dirty(); + } + } + else if (check.kind === "multipleOf") { + if (input.data % check.value !== BigInt(0)) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.not_multiple_of, + multipleOf: check.value, + message: check.message, + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { status: status.value, value: input.data }; + } + _getInvalidInput(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.bigint, + received: ctx.parsedType, + }); + return INVALID; + } + gte(value, message) { + return this.setLimit("min", value, true, errorUtil.toString(message)); + } + gt(value, message) { + return this.setLimit("min", value, false, errorUtil.toString(message)); + } + lte(value, message) { + return this.setLimit("max", value, true, errorUtil.toString(message)); + } + lt(value, message) { + return this.setLimit("max", value, false, errorUtil.toString(message)); + } + setLimit(kind, value, inclusive, message) { + return new ZodBigInt({ + ...this._def, + checks: [ + ...this._def.checks, + { + kind, + value, + inclusive, + message: errorUtil.toString(message), + }, + ], + }); + } + _addCheck(check) { + return new ZodBigInt({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + positive(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + negative(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: false, + message: errorUtil.toString(message), + }); + } + nonpositive(message) { + return this._addCheck({ + kind: "max", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + nonnegative(message) { + return this._addCheck({ + kind: "min", + value: BigInt(0), + inclusive: true, + message: errorUtil.toString(message), + }); + } + multipleOf(value, message) { + return this._addCheck({ + kind: "multipleOf", + value, + message: errorUtil.toString(message), + }); + } + get minValue() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min; + } + get maxValue() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max; + } +} +ZodBigInt.create = (params) => { + return new ZodBigInt({ + checks: [], + typeName: ZodFirstPartyTypeKind.ZodBigInt, + coerce: params?.coerce ?? false, + ...processCreateParams(params), + }); +}; +class ZodBoolean extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = Boolean(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.boolean) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.boolean, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodBoolean.create = (params) => { + return new ZodBoolean({ + typeName: ZodFirstPartyTypeKind.ZodBoolean, + coerce: params?.coerce || false, + ...processCreateParams(params), + }); +}; +class ZodDate extends ZodType { + _parse(input) { + if (this._def.coerce) { + input.data = new Date(input.data); + } + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.date) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.date, + received: ctx.parsedType, + }); + return INVALID; + } + if (Number.isNaN(input.data.getTime())) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_date, + }); + return INVALID; + } + const status = new ParseStatus(); + let ctx = undefined; + for (const check of this._def.checks) { + if (check.kind === "min") { + if (input.data.getTime() < check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + message: check.message, + inclusive: true, + exact: false, + minimum: check.value, + type: "date", + }); + status.dirty(); + } + } + else if (check.kind === "max") { + if (input.data.getTime() > check.value) { + ctx = this._getOrReturnCtx(input, ctx); + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + message: check.message, + inclusive: true, + exact: false, + maximum: check.value, + type: "date", + }); + status.dirty(); + } + } + else { + util.assertNever(check); + } + } + return { + status: status.value, + value: new Date(input.data.getTime()), + }; + } + _addCheck(check) { + return new ZodDate({ + ...this._def, + checks: [...this._def.checks, check], + }); + } + min(minDate, message) { + return this._addCheck({ + kind: "min", + value: minDate.getTime(), + message: errorUtil.toString(message), + }); + } + max(maxDate, message) { + return this._addCheck({ + kind: "max", + value: maxDate.getTime(), + message: errorUtil.toString(message), + }); + } + get minDate() { + let min = null; + for (const ch of this._def.checks) { + if (ch.kind === "min") { + if (min === null || ch.value > min) + min = ch.value; + } + } + return min != null ? new Date(min) : null; + } + get maxDate() { + let max = null; + for (const ch of this._def.checks) { + if (ch.kind === "max") { + if (max === null || ch.value < max) + max = ch.value; + } + } + return max != null ? new Date(max) : null; + } +} +ZodDate.create = (params) => { + return new ZodDate({ + checks: [], + coerce: params?.coerce || false, + typeName: ZodFirstPartyTypeKind.ZodDate, + ...processCreateParams(params), + }); +}; +class ZodSymbol extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.symbol) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.symbol, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodSymbol.create = (params) => { + return new ZodSymbol({ + typeName: ZodFirstPartyTypeKind.ZodSymbol, + ...processCreateParams(params), + }); +}; +class ZodUndefined extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.undefined, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodUndefined.create = (params) => { + return new ZodUndefined({ + typeName: ZodFirstPartyTypeKind.ZodUndefined, + ...processCreateParams(params), + }); +}; +class ZodNull extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.null) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.null, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodNull.create = (params) => { + return new ZodNull({ + typeName: ZodFirstPartyTypeKind.ZodNull, + ...processCreateParams(params), + }); +}; +class ZodAny extends ZodType { + constructor() { + super(...arguments); + // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. + this._any = true; + } + _parse(input) { + return OK(input.data); + } +} +ZodAny.create = (params) => { + return new ZodAny({ + typeName: ZodFirstPartyTypeKind.ZodAny, + ...processCreateParams(params), + }); +}; +class ZodUnknown extends ZodType { + constructor() { + super(...arguments); + // required + this._unknown = true; + } + _parse(input) { + return OK(input.data); + } +} +ZodUnknown.create = (params) => { + return new ZodUnknown({ + typeName: ZodFirstPartyTypeKind.ZodUnknown, + ...processCreateParams(params), + }); +}; +class ZodNever extends ZodType { + _parse(input) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.never, + received: ctx.parsedType, + }); + return INVALID; + } +} +ZodNever.create = (params) => { + return new ZodNever({ + typeName: ZodFirstPartyTypeKind.ZodNever, + ...processCreateParams(params), + }); +}; +class ZodVoid extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.undefined) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.void, + received: ctx.parsedType, + }); + return INVALID; + } + return OK(input.data); + } +} +ZodVoid.create = (params) => { + return new ZodVoid({ + typeName: ZodFirstPartyTypeKind.ZodVoid, + ...processCreateParams(params), + }); +}; +class ZodArray extends ZodType { + _parse(input) { + const { ctx, status } = this._processInputParams(input); + const def = this._def; + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (def.exactLength !== null) { + const tooBig = ctx.data.length > def.exactLength.value; + const tooSmall = ctx.data.length < def.exactLength.value; + if (tooBig || tooSmall) { + addIssueToContext(ctx, { + code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, + minimum: (tooSmall ? def.exactLength.value : undefined), + maximum: (tooBig ? def.exactLength.value : undefined), + type: "array", + inclusive: true, + exact: true, + message: def.exactLength.message, + }); + status.dirty(); + } + } + if (def.minLength !== null) { + if (ctx.data.length < def.minLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.minLength.message, + }); + status.dirty(); + } + } + if (def.maxLength !== null) { + if (ctx.data.length > def.maxLength.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxLength.value, + type: "array", + inclusive: true, + exact: false, + message: def.maxLength.message, + }); + status.dirty(); + } + } + if (ctx.common.async) { + return Promise.all([...ctx.data].map((item, i) => { + return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + })).then((result) => { + return ParseStatus.mergeArray(status, result); + }); + } + const result = [...ctx.data].map((item, i) => { + return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); + }); + return ParseStatus.mergeArray(status, result); + } + get element() { + return this._def.type; + } + min(minLength, message) { + return new ZodArray({ + ...this._def, + minLength: { value: minLength, message: errorUtil.toString(message) }, + }); + } + max(maxLength, message) { + return new ZodArray({ + ...this._def, + maxLength: { value: maxLength, message: errorUtil.toString(message) }, + }); + } + length(len, message) { + return new ZodArray({ + ...this._def, + exactLength: { value: len, message: errorUtil.toString(message) }, + }); + } + nonempty(message) { + return this.min(1, message); + } +} +ZodArray.create = (schema, params) => { + return new ZodArray({ + type: schema, + minLength: null, + maxLength: null, + exactLength: null, + typeName: ZodFirstPartyTypeKind.ZodArray, + ...processCreateParams(params), + }); +}; +function deepPartialify(schema) { + if (schema instanceof ZodObject) { + const newShape = {}; + for (const key in schema.shape) { + const fieldSchema = schema.shape[key]; + newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); + } + return new ZodObject({ + ...schema._def, + shape: () => newShape, + }); + } + else if (schema instanceof ZodArray) { + return new ZodArray({ + ...schema._def, + type: deepPartialify(schema.element), + }); + } + else if (schema instanceof ZodOptional) { + return ZodOptional.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodNullable) { + return ZodNullable.create(deepPartialify(schema.unwrap())); + } + else if (schema instanceof ZodTuple) { + return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); + } + else { + return schema; + } +} +class ZodObject extends ZodType { + constructor() { + super(...arguments); + this._cached = null; + /** + * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. + * If you want to pass through unknown properties, use `.passthrough()` instead. + */ + this.nonstrict = this.passthrough; + // extend< + // Augmentation extends ZodRawShape, + // NewOutput extends util.flatten<{ + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }>, + // NewInput extends util.flatten<{ + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // }> + // >( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, + // UnknownKeys, + // Catchall, + // NewOutput, + // NewInput + // > { + // return new ZodObject({ + // ...this._def, + // shape: () => ({ + // ...this._def.shape(), + // ...augmentation, + // }), + // }) as any; + // } + /** + * @deprecated Use `.extend` instead + * */ + this.augment = this.extend; + } + _getCached() { + if (this._cached !== null) + return this._cached; + const shape = this._def.shape(); + const keys = util.objectKeys(shape); + this._cached = { shape, keys }; + return this._cached; + } + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.object) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const { status, ctx } = this._processInputParams(input); + const { shape, keys: shapeKeys } = this._getCached(); + const extraKeys = []; + if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { + for (const key in ctx.data) { + if (!shapeKeys.includes(key)) { + extraKeys.push(key); + } + } + } + const pairs = []; + for (const key of shapeKeys) { + const keyValidator = shape[key]; + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (this._def.catchall instanceof ZodNever) { + const unknownKeys = this._def.unknownKeys; + if (unknownKeys === "passthrough") { + for (const key of extraKeys) { + pairs.push({ + key: { status: "valid", value: key }, + value: { status: "valid", value: ctx.data[key] }, + }); + } + } + else if (unknownKeys === "strict") { + if (extraKeys.length > 0) { + addIssueToContext(ctx, { + code: ZodIssueCode.unrecognized_keys, + keys: extraKeys, + }); + status.dirty(); + } + } + else if (unknownKeys === "strip") { + } + else { + throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); + } + } + else { + // run catchall validation + const catchall = this._def.catchall; + for (const key of extraKeys) { + const value = ctx.data[key]; + pairs.push({ + key: { status: "valid", value: key }, + value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) + ), + alwaysSet: key in ctx.data, + }); + } + } + if (ctx.common.async) { + return Promise.resolve() + .then(async () => { + const syncPairs = []; + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + syncPairs.push({ + key, + value, + alwaysSet: pair.alwaysSet, + }); + } + return syncPairs; + }) + .then((syncPairs) => { + return ParseStatus.mergeObjectSync(status, syncPairs); + }); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get shape() { + return this._def.shape(); + } + strict(message) { + errorUtil.errToObj; + return new ZodObject({ + ...this._def, + unknownKeys: "strict", + ...(message !== undefined + ? { + errorMap: (issue, ctx) => { + const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; + if (issue.code === "unrecognized_keys") + return { + message: errorUtil.errToObj(message).message ?? defaultError, + }; + return { + message: defaultError, + }; + }, + } + : {}), + }); + } + strip() { + return new ZodObject({ + ...this._def, + unknownKeys: "strip", + }); + } + passthrough() { + return new ZodObject({ + ...this._def, + unknownKeys: "passthrough", + }); + } + // const AugmentFactory = + // (def: Def) => + // ( + // augmentation: Augmentation + // ): ZodObject< + // extendShape, Augmentation>, + // Def["unknownKeys"], + // Def["catchall"] + // > => { + // return new ZodObject({ + // ...def, + // shape: () => ({ + // ...def.shape(), + // ...augmentation, + // }), + // }) as any; + // }; + extend(augmentation) { + return new ZodObject({ + ...this._def, + shape: () => ({ + ...this._def.shape(), + ...augmentation, + }), + }); + } + /** + * Prior to zod@1.0.12 there was a bug in the + * inferred type of merged objects. Please + * upgrade if you are experiencing issues. + */ + merge(merging) { + const merged = new ZodObject({ + unknownKeys: merging._def.unknownKeys, + catchall: merging._def.catchall, + shape: () => ({ + ...this._def.shape(), + ...merging._def.shape(), + }), + typeName: ZodFirstPartyTypeKind.ZodObject, + }); + return merged; + } + // merge< + // Incoming extends AnyZodObject, + // Augmentation extends Incoming["shape"], + // NewOutput extends { + // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation + // ? Augmentation[k]["_output"] + // : k extends keyof Output + // ? Output[k] + // : never; + // }, + // NewInput extends { + // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation + // ? Augmentation[k]["_input"] + // : k extends keyof Input + // ? Input[k] + // : never; + // } + // >( + // merging: Incoming + // ): ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"], + // NewOutput, + // NewInput + // > { + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + setKey(key, schema) { + return this.augment({ [key]: schema }); + } + // merge( + // merging: Incoming + // ): //ZodObject = (merging) => { + // ZodObject< + // extendShape>, + // Incoming["_def"]["unknownKeys"], + // Incoming["_def"]["catchall"] + // > { + // // const mergedShape = objectUtil.mergeShapes( + // // this._def.shape(), + // // merging._def.shape() + // // ); + // const merged: any = new ZodObject({ + // unknownKeys: merging._def.unknownKeys, + // catchall: merging._def.catchall, + // shape: () => + // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), + // typeName: ZodFirstPartyTypeKind.ZodObject, + // }) as any; + // return merged; + // } + catchall(index) { + return new ZodObject({ + ...this._def, + catchall: index, + }); + } + pick(mask) { + const shape = {}; + for (const key of util.objectKeys(mask)) { + if (mask[key] && this.shape[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + omit(mask) { + const shape = {}; + for (const key of util.objectKeys(this.shape)) { + if (!mask[key]) { + shape[key] = this.shape[key]; + } + } + return new ZodObject({ + ...this._def, + shape: () => shape, + }); + } + /** + * @deprecated + */ + deepPartial() { + return deepPartialify(this); + } + partial(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + const fieldSchema = this.shape[key]; + if (mask && !mask[key]) { + newShape[key] = fieldSchema; + } + else { + newShape[key] = fieldSchema.optional(); + } + } + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + required(mask) { + const newShape = {}; + for (const key of util.objectKeys(this.shape)) { + if (mask && !mask[key]) { + newShape[key] = this.shape[key]; + } + else { + const fieldSchema = this.shape[key]; + let newField = fieldSchema; + while (newField instanceof ZodOptional) { + newField = newField._def.innerType; + } + newShape[key] = newField; + } + } + return new ZodObject({ + ...this._def, + shape: () => newShape, + }); + } + keyof() { + return createZodEnum(util.objectKeys(this.shape)); + } +} +ZodObject.create = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.strictCreate = (shape, params) => { + return new ZodObject({ + shape: () => shape, + unknownKeys: "strict", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +ZodObject.lazycreate = (shape, params) => { + return new ZodObject({ + shape, + unknownKeys: "strip", + catchall: ZodNever.create(), + typeName: ZodFirstPartyTypeKind.ZodObject, + ...processCreateParams(params), + }); +}; +class ZodUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const options = this._def.options; + function handleResults(results) { + // return first issue-free validation if it exists + for (const result of results) { + if (result.result.status === "valid") { + return result.result; + } + } + for (const result of results) { + if (result.result.status === "dirty") { + // add issues from dirty option + ctx.common.issues.push(...result.ctx.common.issues); + return result.result; + } + } + // return invalid + const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + if (ctx.common.async) { + return Promise.all(options.map(async (option) => { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + return { + result: await option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }), + ctx: childCtx, + }; + })).then(handleResults); + } + else { + let dirty = undefined; + const issues = []; + for (const option of options) { + const childCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + parent: null, + }; + const result = option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: childCtx, + }); + if (result.status === "valid") { + return result; + } + else if (result.status === "dirty" && !dirty) { + dirty = { result, ctx: childCtx }; + } + if (childCtx.common.issues.length) { + issues.push(childCtx.common.issues); + } + } + if (dirty) { + ctx.common.issues.push(...dirty.ctx.common.issues); + return dirty.result; + } + const unionErrors = issues.map((issues) => new ZodError(issues)); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union, + unionErrors, + }); + return INVALID; + } + } + get options() { + return this._def.options; + } +} +ZodUnion.create = (types, params) => { + return new ZodUnion({ + options: types, + typeName: ZodFirstPartyTypeKind.ZodUnion, + ...processCreateParams(params), + }); +}; +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +////////// ////////// +////////// ZodDiscriminatedUnion ////////// +////////// ////////// +///////////////////////////////////////////////////// +///////////////////////////////////////////////////// +const getDiscriminator = (type) => { + if (type instanceof ZodLazy) { + return getDiscriminator(type.schema); + } + else if (type instanceof ZodEffects) { + return getDiscriminator(type.innerType()); + } + else if (type instanceof ZodLiteral) { + return [type.value]; + } + else if (type instanceof ZodEnum) { + return type.options; + } + else if (type instanceof ZodNativeEnum) { + // eslint-disable-next-line ban/ban + return util.objectValues(type.enum); + } + else if (type instanceof ZodDefault) { + return getDiscriminator(type._def.innerType); + } + else if (type instanceof ZodUndefined) { + return [undefined]; + } + else if (type instanceof ZodNull) { + return [null]; + } + else if (type instanceof ZodOptional) { + return [undefined, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodNullable) { + return [null, ...getDiscriminator(type.unwrap())]; + } + else if (type instanceof ZodBranded) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodReadonly) { + return getDiscriminator(type.unwrap()); + } + else if (type instanceof ZodCatch) { + return getDiscriminator(type._def.innerType); + } + else { + return []; + } +}; +class ZodDiscriminatedUnion extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const discriminator = this.discriminator; + const discriminatorValue = ctx.data[discriminator]; + const option = this.optionsMap.get(discriminatorValue); + if (!option) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_union_discriminator, + options: Array.from(this.optionsMap.keys()), + path: [discriminator], + }); + return INVALID; + } + if (ctx.common.async) { + return option._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + else { + return option._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + } + } + get discriminator() { + return this._def.discriminator; + } + get options() { + return this._def.options; + } + get optionsMap() { + return this._def.optionsMap; + } + /** + * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. + * However, it only allows a union of objects, all of which need to share a discriminator property. This property must + * have a different value for each object in the union. + * @param discriminator the name of the discriminator property + * @param types an array of object schemas + * @param params + */ + static create(discriminator, options, params) { + // Get all the valid discriminator values + const optionsMap = new Map(); + // try { + for (const type of options) { + const discriminatorValues = getDiscriminator(type.shape[discriminator]); + if (!discriminatorValues.length) { + throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); + } + for (const value of discriminatorValues) { + if (optionsMap.has(value)) { + throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); + } + optionsMap.set(value, type); + } + } + return new ZodDiscriminatedUnion({ + typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, + discriminator, + options, + optionsMap, + ...processCreateParams(params), + }); + } +} +function types_mergeValues(a, b) { + const aType = util_getParsedType(a); + const bType = util_getParsedType(b); + if (a === b) { + return { valid: true, data: a }; + } + else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { + const bKeys = util.objectKeys(b); + const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); + const newObj = { ...a, ...b }; + for (const key of sharedKeys) { + const sharedValue = types_mergeValues(a[key], b[key]); + if (!sharedValue.valid) { + return { valid: false }; + } + newObj[key] = sharedValue.data; + } + return { valid: true, data: newObj }; + } + else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { + if (a.length !== b.length) { + return { valid: false }; + } + const newArray = []; + for (let index = 0; index < a.length; index++) { + const itemA = a[index]; + const itemB = b[index]; + const sharedValue = types_mergeValues(itemA, itemB); + if (!sharedValue.valid) { + return { valid: false }; + } + newArray.push(sharedValue.data); + } + return { valid: true, data: newArray }; + } + else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { + return { valid: true, data: a }; + } + else { + return { valid: false }; + } +} +class ZodIntersection extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const handleParsed = (parsedLeft, parsedRight) => { + if (isAborted(parsedLeft) || isAborted(parsedRight)) { + return INVALID; + } + const merged = types_mergeValues(parsedLeft.value, parsedRight.value); + if (!merged.valid) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_intersection_types, + }); + return INVALID; + } + if (isDirty(parsedLeft) || isDirty(parsedRight)) { + status.dirty(); + } + return { status: status.value, value: merged.data }; + }; + if (ctx.common.async) { + return Promise.all([ + this._def.left._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + this._def.right._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), + ]).then(([left, right]) => handleParsed(left, right)); + } + else { + return handleParsed(this._def.left._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }), this._def.right._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + })); + } + } +} +ZodIntersection.create = (left, right, params) => { + return new ZodIntersection({ + left: left, + right: right, + typeName: ZodFirstPartyTypeKind.ZodIntersection, + ...processCreateParams(params), + }); +}; +// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; +class ZodTuple extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.array) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.array, + received: ctx.parsedType, + }); + return INVALID; + } + if (ctx.data.length < this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + return INVALID; + } + const rest = this._def.rest; + if (!rest && ctx.data.length > this._def.items.length) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: this._def.items.length, + inclusive: true, + exact: false, + type: "array", + }); + status.dirty(); + } + const items = [...ctx.data] + .map((item, itemIndex) => { + const schema = this._def.items[itemIndex] || this._def.rest; + if (!schema) + return null; + return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); + }) + .filter((x) => !!x); // filter nulls + if (ctx.common.async) { + return Promise.all(items).then((results) => { + return ParseStatus.mergeArray(status, results); + }); + } + else { + return ParseStatus.mergeArray(status, items); + } + } + get items() { + return this._def.items; + } + rest(rest) { + return new ZodTuple({ + ...this._def, + rest, + }); + } +} +ZodTuple.create = (schemas, params) => { + if (!Array.isArray(schemas)) { + throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); + } + return new ZodTuple({ + items: schemas, + typeName: ZodFirstPartyTypeKind.ZodTuple, + rest: null, + ...processCreateParams(params), + }); +}; +class ZodRecord extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.object) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.object, + received: ctx.parsedType, + }); + return INVALID; + } + const pairs = []; + const keyType = this._def.keyType; + const valueType = this._def.valueType; + for (const key in ctx.data) { + pairs.push({ + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), + value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), + alwaysSet: key in ctx.data, + }); + } + if (ctx.common.async) { + return ParseStatus.mergeObjectAsync(status, pairs); + } + else { + return ParseStatus.mergeObjectSync(status, pairs); + } + } + get element() { + return this._def.valueType; + } + static create(first, second, third) { + if (second instanceof ZodType) { + return new ZodRecord({ + keyType: first, + valueType: second, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(third), + }); + } + return new ZodRecord({ + keyType: ZodString.create(), + valueType: first, + typeName: ZodFirstPartyTypeKind.ZodRecord, + ...processCreateParams(second), + }); + } +} +class ZodMap extends ZodType { + get keySchema() { + return this._def.keyType; + } + get valueSchema() { + return this._def.valueType; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.map) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.map, + received: ctx.parsedType, + }); + return INVALID; + } + const keyType = this._def.keyType; + const valueType = this._def.valueType; + const pairs = [...ctx.data.entries()].map(([key, value], index) => { + return { + key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), + value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), + }; + }); + if (ctx.common.async) { + const finalMap = new Map(); + return Promise.resolve().then(async () => { + for (const pair of pairs) { + const key = await pair.key; + const value = await pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + }); + } + else { + const finalMap = new Map(); + for (const pair of pairs) { + const key = pair.key; + const value = pair.value; + if (key.status === "aborted" || value.status === "aborted") { + return INVALID; + } + if (key.status === "dirty" || value.status === "dirty") { + status.dirty(); + } + finalMap.set(key.value, value.value); + } + return { status: status.value, value: finalMap }; + } + } +} +ZodMap.create = (keyType, valueType, params) => { + return new ZodMap({ + valueType, + keyType, + typeName: ZodFirstPartyTypeKind.ZodMap, + ...processCreateParams(params), + }); +}; +class ZodSet extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.set) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.set, + received: ctx.parsedType, + }); + return INVALID; + } + const def = this._def; + if (def.minSize !== null) { + if (ctx.data.size < def.minSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_small, + minimum: def.minSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.minSize.message, + }); + status.dirty(); + } + } + if (def.maxSize !== null) { + if (ctx.data.size > def.maxSize.value) { + addIssueToContext(ctx, { + code: ZodIssueCode.too_big, + maximum: def.maxSize.value, + type: "set", + inclusive: true, + exact: false, + message: def.maxSize.message, + }); + status.dirty(); + } + } + const valueType = this._def.valueType; + function finalizeSet(elements) { + const parsedSet = new Set(); + for (const element of elements) { + if (element.status === "aborted") + return INVALID; + if (element.status === "dirty") + status.dirty(); + parsedSet.add(element.value); + } + return { status: status.value, value: parsedSet }; + } + const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); + if (ctx.common.async) { + return Promise.all(elements).then((elements) => finalizeSet(elements)); + } + else { + return finalizeSet(elements); + } + } + min(minSize, message) { + return new ZodSet({ + ...this._def, + minSize: { value: minSize, message: errorUtil.toString(message) }, + }); + } + max(maxSize, message) { + return new ZodSet({ + ...this._def, + maxSize: { value: maxSize, message: errorUtil.toString(message) }, + }); + } + size(size, message) { + return this.min(size, message).max(size, message); + } + nonempty(message) { + return this.min(1, message); + } +} +ZodSet.create = (valueType, params) => { + return new ZodSet({ + valueType, + minSize: null, + maxSize: null, + typeName: ZodFirstPartyTypeKind.ZodSet, + ...processCreateParams(params), + }); +}; +class ZodFunction extends ZodType { + constructor() { + super(...arguments); + this.validate = this.implement; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.function) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.function, + received: ctx.parsedType, + }); + return INVALID; + } + function makeArgsIssue(args, error) { + return makeIssue({ + data: args, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), locales_en].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_arguments, + argumentsError: error, + }, + }); + } + function makeReturnsIssue(returns, error) { + return makeIssue({ + data: returns, + path: ctx.path, + errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), locales_en].filter((x) => !!x), + issueData: { + code: ZodIssueCode.invalid_return_type, + returnTypeError: error, + }, + }); + } + const params = { errorMap: ctx.common.contextualErrorMap }; + const fn = ctx.data; + if (this._def.returns instanceof ZodPromise) { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(async function (...args) { + const error = new ZodError([]); + const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { + error.addIssue(makeArgsIssue(args, e)); + throw error; + }); + const result = await Reflect.apply(fn, this, parsedArgs); + const parsedReturns = await me._def.returns._def.type + .parseAsync(result, params) + .catch((e) => { + error.addIssue(makeReturnsIssue(result, e)); + throw error; + }); + return parsedReturns; + }); + } + else { + // Would love a way to avoid disabling this rule, but we need + // an alias (using an arrow function was what caused 2651). + // eslint-disable-next-line @typescript-eslint/no-this-alias + const me = this; + return OK(function (...args) { + const parsedArgs = me._def.args.safeParse(args, params); + if (!parsedArgs.success) { + throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); + } + const result = Reflect.apply(fn, this, parsedArgs.data); + const parsedReturns = me._def.returns.safeParse(result, params); + if (!parsedReturns.success) { + throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); + } + return parsedReturns.data; + }); + } + } + parameters() { + return this._def.args; + } + returnType() { + return this._def.returns; + } + args(...items) { + return new ZodFunction({ + ...this._def, + args: ZodTuple.create(items).rest(ZodUnknown.create()), + }); + } + returns(returnType) { + return new ZodFunction({ + ...this._def, + returns: returnType, + }); + } + implement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + strictImplement(func) { + const validatedFunc = this.parse(func); + return validatedFunc; + } + static create(args, returns, params) { + return new ZodFunction({ + args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), + returns: returns || ZodUnknown.create(), + typeName: ZodFirstPartyTypeKind.ZodFunction, + ...processCreateParams(params), + }); + } +} +class ZodLazy extends ZodType { + get schema() { + return this._def.getter(); + } + _parse(input) { + const { ctx } = this._processInputParams(input); + const lazySchema = this._def.getter(); + return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); + } +} +ZodLazy.create = (getter, params) => { + return new ZodLazy({ + getter: getter, + typeName: ZodFirstPartyTypeKind.ZodLazy, + ...processCreateParams(params), + }); +}; +class ZodLiteral extends ZodType { + _parse(input) { + if (input.data !== this._def.value) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_literal, + expected: this._def.value, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } + get value() { + return this._def.value; + } +} +ZodLiteral.create = (value, params) => { + return new ZodLiteral({ + value: value, + typeName: ZodFirstPartyTypeKind.ZodLiteral, + ...processCreateParams(params), + }); +}; +function createZodEnum(values, params) { + return new ZodEnum({ + values, + typeName: ZodFirstPartyTypeKind.ZodEnum, + ...processCreateParams(params), + }); +} +class ZodEnum extends ZodType { + _parse(input) { + if (typeof input.data !== "string") { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(this._def.values); + } + if (!this._cache.has(input.data)) { + const ctx = this._getOrReturnCtx(input); + const expectedValues = this._def.values; + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get options() { + return this._def.values; + } + get enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Values() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + get Enum() { + const enumValues = {}; + for (const val of this._def.values) { + enumValues[val] = val; + } + return enumValues; + } + extract(values, newDef = this._def) { + return ZodEnum.create(values, { + ...this._def, + ...newDef, + }); + } + exclude(values, newDef = this._def) { + return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { + ...this._def, + ...newDef, + }); + } +} +ZodEnum.create = createZodEnum; +class ZodNativeEnum extends ZodType { + _parse(input) { + const nativeEnumValues = util.getValidEnumValues(this._def.values); + const ctx = this._getOrReturnCtx(input); + if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + expected: util.joinValues(expectedValues), + received: ctx.parsedType, + code: ZodIssueCode.invalid_type, + }); + return INVALID; + } + if (!this._cache) { + this._cache = new Set(util.getValidEnumValues(this._def.values)); + } + if (!this._cache.has(input.data)) { + const expectedValues = util.objectValues(nativeEnumValues); + addIssueToContext(ctx, { + received: ctx.data, + code: ZodIssueCode.invalid_enum_value, + options: expectedValues, + }); + return INVALID; + } + return OK(input.data); + } + get enum() { + return this._def.values; + } +} +ZodNativeEnum.create = (values, params) => { + return new ZodNativeEnum({ + values: values, + typeName: ZodFirstPartyTypeKind.ZodNativeEnum, + ...processCreateParams(params), + }); +}; +class ZodPromise extends ZodType { + unwrap() { + return this._def.type; + } + _parse(input) { + const { ctx } = this._processInputParams(input); + if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.promise, + received: ctx.parsedType, + }); + return INVALID; + } + const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); + return OK(promisified.then((data) => { + return this._def.type.parseAsync(data, { + path: ctx.path, + errorMap: ctx.common.contextualErrorMap, + }); + })); + } +} +ZodPromise.create = (schema, params) => { + return new ZodPromise({ + type: schema, + typeName: ZodFirstPartyTypeKind.ZodPromise, + ...processCreateParams(params), + }); +}; +class ZodEffects extends ZodType { + innerType() { + return this._def.schema; + } + sourceType() { + return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects + ? this._def.schema.sourceType() + : this._def.schema; + } + _parse(input) { + const { status, ctx } = this._processInputParams(input); + const effect = this._def.effect || null; + const checkCtx = { + addIssue: (arg) => { + addIssueToContext(ctx, arg); + if (arg.fatal) { + status.abort(); + } + else { + status.dirty(); + } + }, + get path() { + return ctx.path; + }, + }; + checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); + if (effect.type === "preprocess") { + const processed = effect.transform(ctx.data, checkCtx); + if (ctx.common.async) { + return Promise.resolve(processed).then(async (processed) => { + if (status.value === "aborted") + return INVALID; + const result = await this._def.schema._parseAsync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + }); + } + else { + if (status.value === "aborted") + return INVALID; + const result = this._def.schema._parseSync({ + data: processed, + path: ctx.path, + parent: ctx, + }); + if (result.status === "aborted") + return INVALID; + if (result.status === "dirty") + return DIRTY(result.value); + if (status.value === "dirty") + return DIRTY(result.value); + return result; + } + } + if (effect.type === "refinement") { + const executeRefinement = (acc) => { + const result = effect.refinement(acc, checkCtx); + if (ctx.common.async) { + return Promise.resolve(result); + } + if (result instanceof Promise) { + throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); + } + return acc; + }; + if (ctx.common.async === false) { + const inner = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + // return value is ignored + executeRefinement(inner.value); + return { status: status.value, value: inner.value }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { + if (inner.status === "aborted") + return INVALID; + if (inner.status === "dirty") + status.dirty(); + return executeRefinement(inner.value).then(() => { + return { status: status.value, value: inner.value }; + }); + }); + } + } + if (effect.type === "transform") { + if (ctx.common.async === false) { + const base = this._def.schema._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (!isValid(base)) + return INVALID; + const result = effect.transform(base.value, checkCtx); + if (result instanceof Promise) { + throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); + } + return { status: status.value, value: result }; + } + else { + return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { + if (!isValid(base)) + return INVALID; + return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ + status: status.value, + value: result, + })); + }); + } + } + util.assertNever(effect); + } +} +ZodEffects.create = (schema, effect, params) => { + return new ZodEffects({ + schema, + typeName: ZodFirstPartyTypeKind.ZodEffects, + effect, + ...processCreateParams(params), + }); +}; +ZodEffects.createWithPreprocess = (preprocess, schema, params) => { + return new ZodEffects({ + schema, + effect: { type: "preprocess", transform: preprocess }, + typeName: ZodFirstPartyTypeKind.ZodEffects, + ...processCreateParams(params), + }); +}; + +class ZodOptional extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.undefined) { + return OK(undefined); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +ZodOptional.create = (type, params) => { + return new ZodOptional({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodOptional, + ...processCreateParams(params), + }); +}; +class ZodNullable extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType === ZodParsedType.null) { + return OK(null); + } + return this._def.innerType._parse(input); + } + unwrap() { + return this._def.innerType; + } +} +ZodNullable.create = (type, params) => { + return new ZodNullable({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodNullable, + ...processCreateParams(params), + }); +}; +class ZodDefault extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + let data = ctx.data; + if (ctx.parsedType === ZodParsedType.undefined) { + data = this._def.defaultValue(); + } + return this._def.innerType._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + removeDefault() { + return this._def.innerType; + } +} +ZodDefault.create = (type, params) => { + return new ZodDefault({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodDefault, + defaultValue: typeof params.default === "function" ? params.default : () => params.default, + ...processCreateParams(params), + }); +}; +class ZodCatch extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + // newCtx is used to not collect issues from inner types in ctx + const newCtx = { + ...ctx, + common: { + ...ctx.common, + issues: [], + }, + }; + const result = this._def.innerType._parse({ + data: newCtx.data, + path: newCtx.path, + parent: { + ...newCtx, + }, + }); + if (isAsync(result)) { + return result.then((result) => { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + }); + } + else { + return { + status: "valid", + value: result.status === "valid" + ? result.value + : this._def.catchValue({ + get error() { + return new ZodError(newCtx.common.issues); + }, + input: newCtx.data, + }), + }; + } + } + removeCatch() { + return this._def.innerType; + } +} +ZodCatch.create = (type, params) => { + return new ZodCatch({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodCatch, + catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, + ...processCreateParams(params), + }); +}; +class ZodNaN extends ZodType { + _parse(input) { + const parsedType = this._getType(input); + if (parsedType !== ZodParsedType.nan) { + const ctx = this._getOrReturnCtx(input); + addIssueToContext(ctx, { + code: ZodIssueCode.invalid_type, + expected: ZodParsedType.nan, + received: ctx.parsedType, + }); + return INVALID; + } + return { status: "valid", value: input.data }; + } +} +ZodNaN.create = (params) => { + return new ZodNaN({ + typeName: ZodFirstPartyTypeKind.ZodNaN, + ...processCreateParams(params), + }); +}; +const BRAND = Symbol("zod_brand"); +class ZodBranded extends ZodType { + _parse(input) { + const { ctx } = this._processInputParams(input); + const data = ctx.data; + return this._def.type._parse({ + data, + path: ctx.path, + parent: ctx, + }); + } + unwrap() { + return this._def.type; + } +} +class ZodPipeline extends ZodType { + _parse(input) { + const { status, ctx } = this._processInputParams(input); + if (ctx.common.async) { + const handleAsync = async () => { + const inResult = await this._def.in._parseAsync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return DIRTY(inResult.value); + } + else { + return this._def.out._parseAsync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + }; + return handleAsync(); + } + else { + const inResult = this._def.in._parseSync({ + data: ctx.data, + path: ctx.path, + parent: ctx, + }); + if (inResult.status === "aborted") + return INVALID; + if (inResult.status === "dirty") { + status.dirty(); + return { + status: "dirty", + value: inResult.value, + }; + } + else { + return this._def.out._parseSync({ + data: inResult.value, + path: ctx.path, + parent: ctx, + }); + } + } + } + static create(a, b) { + return new ZodPipeline({ + in: a, + out: b, + typeName: ZodFirstPartyTypeKind.ZodPipeline, + }); + } +} +class ZodReadonly extends ZodType { + _parse(input) { + const result = this._def.innerType._parse(input); + const freeze = (data) => { + if (isValid(data)) { + data.value = Object.freeze(data.value); + } + return data; + }; + return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); + } + unwrap() { + return this._def.innerType; + } +} +ZodReadonly.create = (type, params) => { + return new ZodReadonly({ + innerType: type, + typeName: ZodFirstPartyTypeKind.ZodReadonly, + ...processCreateParams(params), + }); +}; +//////////////////////////////////////// +//////////////////////////////////////// +////////// ////////// +////////// z.custom ////////// +////////// ////////// +//////////////////////////////////////// +//////////////////////////////////////// +function cleanParams(params, data) { + const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; + const p2 = typeof p === "string" ? { message: p } : p; + return p2; +} +function custom(check, _params = {}, +/** + * @deprecated + * + * Pass `fatal` into the params object instead: + * + * ```ts + * z.string().custom((val) => val.length > 5, { fatal: false }) + * ``` + * + */ +fatal) { + if (check) + return ZodAny.create().superRefine((data, ctx) => { + const r = check(data); + if (r instanceof Promise) { + return r.then((r) => { + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + }); + } + if (!r) { + const params = cleanParams(_params, data); + const _fatal = params.fatal ?? fatal ?? true; + ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); + } + return; + }); + return ZodAny.create(); +} + +const late = { + object: ZodObject.lazycreate, +}; +var ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { + ZodFirstPartyTypeKind["ZodString"] = "ZodString"; + ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; + ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; + ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; + ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; + ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; + ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; + ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; + ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; + ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; + ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; + ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; + ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; + ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; + ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; + ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; + ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; + ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; + ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; + ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; + ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; + ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; + ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; + ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; + ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; + ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; + ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; + ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; + ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; + ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; + ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; + ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; + ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; + ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; + ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; + ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; +})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); +// requires TS 4.4+ +class types_Class { + constructor(..._) { } +} +const instanceOfType = ( +// const instanceOfType = any>( +cls, params = { + message: `Input not instance of ${cls.name}`, +}) => custom((data) => data instanceof cls, params); +const stringType = ZodString.create; +const numberType = ZodNumber.create; +const nanType = ZodNaN.create; +const bigIntType = ZodBigInt.create; +const booleanType = ZodBoolean.create; +const dateType = ZodDate.create; +const symbolType = ZodSymbol.create; +const undefinedType = ZodUndefined.create; +const nullType = ZodNull.create; +const anyType = ZodAny.create; +const unknownType = ZodUnknown.create; +const neverType = ZodNever.create; +const voidType = ZodVoid.create; +const arrayType = ZodArray.create; +const objectType = ZodObject.create; +const strictObjectType = ZodObject.strictCreate; +const unionType = ZodUnion.create; +const discriminatedUnionType = ZodDiscriminatedUnion.create; +const intersectionType = ZodIntersection.create; +const tupleType = ZodTuple.create; +const recordType = ZodRecord.create; +const mapType = ZodMap.create; +const setType = ZodSet.create; +const functionType = ZodFunction.create; +const lazyType = ZodLazy.create; +const literalType = ZodLiteral.create; +const enumType = ZodEnum.create; +const nativeEnumType = ZodNativeEnum.create; +const promiseType = ZodPromise.create; +const effectsType = ZodEffects.create; +const optionalType = ZodOptional.create; +const nullableType = ZodNullable.create; +const preprocessType = ZodEffects.createWithPreprocess; +const pipelineType = ZodPipeline.create; +const ostring = () => stringType().optional(); +const onumber = () => numberType().optional(); +const oboolean = () => booleanType().optional(); +const coerce = { + string: ((arg) => ZodString.create({ ...arg, coerce: true })), + number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), + boolean: ((arg) => ZodBoolean.create({ + ...arg, + coerce: true, + })), + bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), + date: ((arg) => ZodDate.create({ ...arg, coerce: true })), +}; + +const types_NEVER = INVALID; + +;// CONCATENATED MODULE: ./node_modules/zod/v3/external.js + + + + + + + +;// CONCATENATED MODULE: ./node_modules/zod/v3/index.js + + + +/* harmony default export */ const zod_v3 = ((/* unused pure expression or super */ null && (z))); + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/array.js + + + + +//#region src/utils/zod-to-json-schema/parsers/array.ts +function parseArrayDef(def, refs) { + const res = { type: "array" }; + if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + if (def.minLength) setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); + if (def.maxLength) setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); + if (def.exactLength) { + setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); + setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); + } + return res; +} + +//#endregion + +//# sourceMappingURL=array.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/bigint.js + + +//#region src/utils/zod-to-json-schema/parsers/bigint.ts +function parseBigintDef(def, refs) { + const res = { + type: "integer", + format: "int64" + }; + if (!def.checks) return res; + for (const check of def.checks) switch (check.kind) { + case "min": + if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + else setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); + else { + if (!check.inclusive) res.exclusiveMinimum = true; + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + else setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); + else { + if (!check.inclusive) res.exclusiveMaximum = true; + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); + break; + } + return res; +} + +//#endregion + +//# sourceMappingURL=bigint.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/boolean.js +//#region src/utils/zod-to-json-schema/parsers/boolean.ts +function parseBooleanDef() { + return { type: "boolean" }; +} + +//#endregion + +//# sourceMappingURL=boolean.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/branded.js + + +//#region src/utils/zod-to-json-schema/parsers/branded.ts +function parseBrandedDef(_def, refs) { + return parseDef(_def.type._def, refs); +} + +//#endregion + +//# sourceMappingURL=branded.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/catch.js + + +//#region src/utils/zod-to-json-schema/parsers/catch.ts +const parseCatchDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; + +//#endregion + +//# sourceMappingURL=catch.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/date.js + + +//#region src/utils/zod-to-json-schema/parsers/date.ts +function parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) return { anyOf: strategy.map((item) => parseDateDef(def, refs, item)) }; + switch (strategy) { + case "string": + case "format:date-time": return { + type: "string", + format: "date-time" + }; + case "format:date": return { + type: "string", + format: "date" + }; + case "integer": return integerDateParser(def, refs); + } +} +const integerDateParser = (def, refs) => { + const res = { + type: "integer", + format: "unix-time" + }; + if (refs.target === "openApi3") return res; + for (const check of def.checks) switch (check.kind) { + case "min": + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + break; + } + return res; +}; + +//#endregion + +//# sourceMappingURL=date.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/default.js + + +//#region src/utils/zod-to-json-schema/parsers/default.ts +function parseDefaultDef(_def, refs) { + return { + ...parseDef(_def.innerType._def, refs), + default: _def.defaultValue() + }; +} + +//#endregion + +//# sourceMappingURL=default.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/effects.js + + + +//#region src/utils/zod-to-json-schema/parsers/effects.ts +function parseEffectsDef(_def, refs) { + return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); +} + +//#endregion + +//# sourceMappingURL=effects.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/enum.js +//#region src/utils/zod-to-json-schema/parsers/enum.ts +function parseEnumDef(def) { + return { + type: "string", + enum: Array.from(def.values) + }; +} + +//#endregion + +//# sourceMappingURL=enum.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/intersection.js + + +//#region src/utils/zod-to-json-schema/parsers/intersection.ts +const isJsonSchema7AllOfType = (type) => { + if ("type" in type && type.type === "string") return false; + return "allOf" in type; +}; +function parseIntersectionDef(def, refs) { + const allOf = [parseDef(def.left._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "0" + ] + }), parseDef(def.right._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "1" + ] + })].filter((x) => !!x); + let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; + const mergedAllOf = []; + allOf.forEach((schema) => { + if (isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === void 0) unevaluatedProperties = void 0; + } else { + let nestedSchema = schema; + if ("additionalProperties" in schema && schema.additionalProperties === false) { + const { additionalProperties,...rest } = schema; + nestedSchema = rest; + } else unevaluatedProperties = void 0; + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length ? { + allOf: mergedAllOf, + ...unevaluatedProperties + } : void 0; +} + +//#endregion + +//# sourceMappingURL=intersection.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/literal.js +//#region src/utils/zod-to-json-schema/parsers/literal.ts +function parseLiteralDef(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" }; + if (refs.target === "openApi3") return { + type: parsedType === "bigint" ? "integer" : parsedType, + enum: [def.value] + }; + return { + type: parsedType === "bigint" ? "integer" : parsedType, + const: def.value + }; +} + +//#endregion + +//# sourceMappingURL=literal.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/string.js + + +//#region src/utils/zod-to-json-schema/parsers/string.ts +let string_emojiRegex = void 0; +/** +* Generated from the regular expressions found here as of 2024-05-22: +* https://github.com/colinhacks/zod/blob/master/src/types.ts. +* +* Expressions with /i flag have been changed accordingly. +*/ +const zodPatterns = { + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + emoji: () => { + if (string_emojiRegex === void 0) string_emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); + return string_emojiRegex; + }, + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, + jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ +}; +function parseStringDef(def, refs) { + const res = { type: "string" }; + if (def.checks) for (const check of def.checks) switch (check.kind) { + case "min": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + break; + case "max": + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "email": + switch (refs.emailStrategy) { + case "format:email": + addFormat(res, "email", check.message, refs); + break; + case "format:idn-email": + addFormat(res, "idn-email", check.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.email, check.message, refs); + break; + } + break; + case "url": + addFormat(res, "uri", check.message, refs); + break; + case "uuid": + addFormat(res, "uuid", check.message, refs); + break; + case "regex": + addPattern(res, check.regex, check.message, refs); + break; + case "cuid": + addPattern(res, zodPatterns.cuid, check.message, refs); + break; + case "cuid2": + addPattern(res, zodPatterns.cuid2, check.message, refs); + break; + case "startsWith": + addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); + break; + case "endsWith": + addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); + break; + case "datetime": + addFormat(res, "date-time", check.message, refs); + break; + case "date": + addFormat(res, "date", check.message, refs); + break; + case "time": + addFormat(res, "time", check.message, refs); + break; + case "duration": + addFormat(res, "duration", check.message, refs); + break; + case "length": + setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case "includes": + addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); + break; + case "ip": + if (check.version !== "v6") addFormat(res, "ipv4", check.message, refs); + if (check.version !== "v4") addFormat(res, "ipv6", check.message, refs); + break; + case "base64url": + addPattern(res, zodPatterns.base64url, check.message, refs); + break; + case "jwt": + addPattern(res, zodPatterns.jwt, check.message, refs); + break; + case "cidr": + if (check.version !== "v6") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); + if (check.version !== "v4") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); + break; + case "emoji": + addPattern(res, zodPatterns.emoji(), check.message, refs); + break; + case "ulid": + addPattern(res, zodPatterns.ulid, check.message, refs); + break; + case "base64": + switch (refs.base64Strategy) { + case "format:binary": + addFormat(res, "binary", check.message, refs); + break; + case "contentEncoding:base64": + setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); + break; + case "pattern:zod": + addPattern(res, zodPatterns.base64, check.message, refs); + break; + } + break; + case "nanoid": + addPattern(res, zodPatterns.nanoid, check.message, refs); + break; + case "toLowerCase": + case "toUpperCase": + case "trim": break; + default: + /* c8 ignore next */ + ((_) => {})(check); + } + return res; +} +function escapeLiteralCheckValue(literal, refs) { + return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal; +} +const ALPHA_NUMERIC = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); +function escapeNonAlphaNumeric(source) { + let result = ""; + for (let i = 0; i < source.length; i++) { + if (!ALPHA_NUMERIC.has(source[i])) result += "\\"; + result += source[i]; + } + return result; +} +function addFormat(schema, value, message, refs) { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) schema.anyOf = []; + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } } + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage; + } + } + schema.anyOf.push({ + format: value, + ...message && refs.errorMessages && { errorMessage: { format: message } } + }); + } else setResponseValueAndErrors(schema, "format", value, message, refs); +} +function addPattern(schema, regex, message, refs) { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) schema.allOf = []; + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } } + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage; + } + } + schema.allOf.push({ + pattern: stringifyRegExpWithFlags(regex, refs), + ...message && refs.errorMessages && { errorMessage: { pattern: message } } + }); + } else setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); +} +function stringifyRegExpWithFlags(regex, refs) { + if (!refs.applyRegexFlags || !regex.flags) return regex.source; + const flags = { + i: regex.flags.includes("i"), + m: regex.flags.includes("m"), + s: regex.flags.includes("s") + }; + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ""; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i = 0; i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } else pattern += `${source[i]}${source[i].toUpperCase()}`; + continue; + } + } else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i] === "^") { + pattern += `(^|(?<=[\r\n]))`; + continue; + } else if (source[i] === "$") { + pattern += `($|(?=[\r\n]))`; + continue; + } + } + if (flags.s && source[i] === ".") { + pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; + continue; + } + pattern += source[i]; + if (source[i] === "\\") isEscaped = true; + else if (inCharGroup && source[i] === "]") inCharGroup = false; + else if (!inCharGroup && source[i] === "[") inCharGroup = true; + } + try { + new RegExp(pattern); + } catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; +} + +//#endregion + +//# sourceMappingURL=string.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/record.js + + + + + + +//#region src/utils/zod-to-json-schema/parsers/record.ts +function parseRecordDef(def, refs) { + if (refs.target === "openAi") console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); + if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return { + type: "object", + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: parseDef(def.valueType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "properties", + key + ] + }) ?? parseAnyDef(refs) + }), {}), + additionalProperties: refs.rejectedAdditionalProperties + }; + const schema = { + type: "object", + additionalProperties: parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }) ?? refs.allowedAdditionalProperties + }; + if (refs.target === "openApi3") return schema; + if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { + const { type,...keyType } = parseStringDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return { + ...schema, + propertyNames: { enum: def.keyType._def.values } + }; + else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { + const { type,...keyType } = parseBrandedDef(def.keyType._def, refs); + return { + ...schema, + propertyNames: keyType + }; + } + return schema; +} + +//#endregion + +//# sourceMappingURL=record.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/map.js + + + + +//#region src/utils/zod-to-json-schema/parsers/map.ts +function parseMapDef(def, refs) { + if (refs.mapStrategy === "record") return parseRecordDef(def, refs); + const keys = parseDef(def.keyType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + "items", + "0" + ] + }) || parseAnyDef(refs); + const values = parseDef(def.valueType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + "items", + "1" + ] + }) || parseAnyDef(refs); + return { + type: "array", + maxItems: 125, + items: { + type: "array", + items: [keys, values], + minItems: 2, + maxItems: 2 + } + }; +} + +//#endregion + +//# sourceMappingURL=map.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nativeEnum.js +//#region src/utils/zod-to-json-schema/parsers/nativeEnum.ts +function parseNativeEnumDef(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== "number"; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); + return { + type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], + enum: actualValues + }; +} + +//#endregion + +//# sourceMappingURL=nativeEnum.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/never.js + + +//#region src/utils/zod-to-json-schema/parsers/never.ts +function parseNeverDef(refs) { + return refs.target === "openAi" ? void 0 : { not: parseAnyDef({ + ...refs, + currentPath: [...refs.currentPath, "not"] + }) }; +} + +//#endregion + +//# sourceMappingURL=never.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/null.js +//#region src/utils/zod-to-json-schema/parsers/null.ts +function parseNullDef(refs) { + return refs.target === "openApi3" ? { + enum: ["null"], + nullable: true + } : { type: "null" }; +} + +//#endregion + +//# sourceMappingURL=null.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/union.js + + +//#region src/utils/zod-to-json-schema/parsers/union.ts +const primitiveMappings = { + ZodString: "string", + ZodNumber: "number", + ZodBigInt: "integer", + ZodBoolean: "boolean", + ZodNull: "null" +}; +function parseUnionDef(def, refs) { + if (refs.target === "openApi3") return asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { + const types = options.reduce((types$1, x) => { + const type = primitiveMappings[x._def.typeName]; + return type && !types$1.includes(type) ? [...types$1, type] : types$1; + }, []); + return { type: types.length > 1 ? types : types[0] }; + } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { + const types = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case "string": + case "number": + case "boolean": return [...acc, type]; + case "bigint": return [...acc, "integer"]; + case "object": + if (x._def.value === null) return [...acc, "null"]; + return acc; + case "symbol": + case "undefined": + case "function": + default: return acc; + } + }, []); + if (types.length === options.length) { + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []) + }; + } + } else if (options.every((x) => x._def.typeName === "ZodEnum")) return { + type: "string", + enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x$1) => !acc.includes(x$1))], []) + }; + return asAnyOf(def, refs); +} +const asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + `${i}` + ] + })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); + return anyOf.length ? { anyOf } : void 0; +}; + +//#endregion + +//# sourceMappingURL=union.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nullable.js + + + +//#region src/utils/zod-to-json-schema/parsers/nullable.ts +function parseNullableDef(def, refs) { + if ([ + "ZodString", + "ZodNumber", + "ZodBigInt", + "ZodBoolean", + "ZodNull" + ].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === "openApi3") return { + type: primitiveMappings[def.innerType._def.typeName], + nullable: true + }; + return { type: [primitiveMappings[def.innerType._def.typeName], "null"] }; + } + if (refs.target === "openApi3") { + const base$1 = parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath] + }); + if (base$1 && "$ref" in base$1) return { + allOf: [base$1], + nullable: true + }; + return base$1 && { + ...base$1, + nullable: true + }; + } + const base = parseDef(def.innerType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + "0" + ] + }); + return base && { anyOf: [base, { type: "null" }] }; +} + +//#endregion + +//# sourceMappingURL=nullable.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/number.js + + +//#region src/utils/zod-to-json-schema/parsers/number.ts +function parseNumberDef(def, refs) { + const res = { type: "number" }; + if (!def.checks) return res; + for (const check of def.checks) switch (check.kind) { + case "int": + res.type = "integer"; + addErrorMessage(res, "type", check.message, refs); + break; + case "min": + if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + else setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); + else { + if (!check.inclusive) res.exclusiveMinimum = true; + setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); + } + break; + case "max": + if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + else setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); + else { + if (!check.inclusive) res.exclusiveMaximum = true; + setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); + } + break; + case "multipleOf": + setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); + break; + } + return res; +} + +//#endregion + +//# sourceMappingURL=number.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/object.js + + +//#region src/utils/zod-to-json-schema/parsers/object.ts +function parseObjectDef(def, refs) { + const forceOptionalIntoNullable = refs.target === "openAi"; + const result = { + type: "object", + properties: {} + }; + const required = []; + const shape = def.shape(); + for (const propName in shape) { + let propDef = shape[propName]; + if (propDef === void 0 || propDef._def === void 0) continue; + let propOptional = safeIsOptional(propDef); + if (propOptional && forceOptionalIntoNullable) { + if (propDef._def.typeName === "ZodOptional") propDef = propDef._def.innerType; + if (!propDef.isNullable()) propDef = propDef.nullable(); + propOptional = false; + } + const parsedDef = parseDef(propDef._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "properties", + propName + ], + propertyPath: [ + ...refs.currentPath, + "properties", + propName + ] + }); + if (parsedDef === void 0) continue; + result.properties[propName] = parsedDef; + if (!propOptional) required.push(propName); + } + if (required.length) result.required = required; + const additionalProperties = decideAdditionalProperties(def, refs); + if (additionalProperties !== void 0) result.additionalProperties = additionalProperties; + return result; +} +function decideAdditionalProperties(def, refs) { + if (def.catchall._def.typeName !== "ZodNever") return parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalProperties"] + }); + switch (def.unknownKeys) { + case "passthrough": return refs.allowedAdditionalProperties; + case "strict": return refs.rejectedAdditionalProperties; + case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; + } +} +function safeIsOptional(schema) { + try { + return schema.isOptional(); + } catch { + return true; + } +} + +//#endregion + +//# sourceMappingURL=object.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/optional.js + + + +//#region src/utils/zod-to-json-schema/parsers/optional.ts +const parseOptionalDef = (def, refs) => { + if (refs.currentPath.toString() === refs.propertyPath?.toString()) return parseDef(def.innerType._def, refs); + const innerSchema = parseDef(def.innerType._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "anyOf", + "1" + ] + }); + return innerSchema ? { anyOf: [{ not: parseAnyDef(refs) }, innerSchema] } : parseAnyDef(refs); +}; + +//#endregion + +//# sourceMappingURL=optional.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/pipeline.js + + +//#region src/utils/zod-to-json-schema/parsers/pipeline.ts +const parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === "input") return parseDef(def.in._def, refs); + else if (refs.pipeStrategy === "output") return parseDef(def.out._def, refs); + const a = parseDef(def.in._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + "0" + ] + }); + const b = parseDef(def.out._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "allOf", + a ? "1" : "0" + ] + }); + return { allOf: [a, b].filter((x) => x !== void 0) }; +}; + +//#endregion + +//# sourceMappingURL=pipeline.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/promise.js + + +//#region src/utils/zod-to-json-schema/parsers/promise.ts +function parsePromiseDef(def, refs) { + return parseDef(def.type._def, refs); +} + +//#endregion + +//# sourceMappingURL=promise.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/set.js + + + +//#region src/utils/zod-to-json-schema/parsers/set.ts +function parseSetDef(def, refs) { + const items = parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, "items"] + }); + const schema = { + type: "array", + uniqueItems: true, + items + }; + if (def.minSize) setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); + if (def.maxSize) setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); + return schema; +} + +//#endregion + +//# sourceMappingURL=set.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/tuple.js + + +//#region src/utils/zod-to-json-schema/parsers/tuple.ts +function parseTupleDef(def, refs) { + if (def.rest) return { + type: "array", + minItems: def.items.length, + items: def.items.map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + `${i}` + ] + })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), + additionalItems: parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, "additionalItems"] + }) + }; + else return { + type: "array", + minItems: def.items.length, + maxItems: def.items.length, + items: def.items.map((x, i) => parseDef(x._def, { + ...refs, + currentPath: [ + ...refs.currentPath, + "items", + `${i}` + ] + })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) + }; +} + +//#endregion + +//# sourceMappingURL=tuple.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/undefined.js + + +//#region src/utils/zod-to-json-schema/parsers/undefined.ts +function parseUndefinedDef(refs) { + return { not: parseAnyDef(refs) }; +} + +//#endregion + +//# sourceMappingURL=undefined.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/unknown.js + + +//#region src/utils/zod-to-json-schema/parsers/unknown.ts +function parseUnknownDef(refs) { + return parseAnyDef(refs); +} + +//#endregion + +//# sourceMappingURL=unknown.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/readonly.js + + +//#region src/utils/zod-to-json-schema/parsers/readonly.ts +const parseReadonlyDef = (def, refs) => { + return parseDef(def.innerType._def, refs); +}; + +//#endregion + +//# sourceMappingURL=readonly.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/selectParser.js + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +//#region src/utils/zod-to-json-schema/selectParser.ts +const selectParser = (def, typeName, refs) => { + switch (typeName) { + case ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs); + case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def, refs); + case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs); + case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def, refs); + case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef(); + case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs); + case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef(refs); + case ZodFirstPartyTypeKind.ZodNull: return parseNullDef(refs); + case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs); + case ZodFirstPartyTypeKind.ZodUnion: + case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs); + case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs); + case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs); + case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs); + case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def, refs); + case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def); + case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def); + case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs); + case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs); + case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs); + case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def; + case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind.ZodNaN: + case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(refs); + case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs); + case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(refs); + case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(refs); + case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs); + case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind.ZodFunction: + case ZodFirstPartyTypeKind.ZodVoid: + case ZodFirstPartyTypeKind.ZodSymbol: return void 0; + default: + /* c8 ignore next */ + return ((_) => void 0)(typeName); + } +}; + +//#endregion + +//# sourceMappingURL=selectParser.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parseDef.js + + + + + +//#region src/utils/zod-to-json-schema/parseDef.ts +function parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== ignoreOverride) return overrideResult; + } + if (seenItem && !forceResolution) { + const seenSchema = get$ref(seenItem, refs); + if (seenSchema !== void 0) return seenSchema; + } + const newItem = { + def, + path: refs.currentPath, + jsonSchema: void 0 + }; + refs.seen.set(def, newItem); + const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); + const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; + if (jsonSchema) addMeta(def, refs, jsonSchema); + if (refs.postProcess) { + const postProcessResult = refs.postProcess(jsonSchema, def, refs); + newItem.jsonSchema = jsonSchema; + return postProcessResult; + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +const get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case "root": return { $ref: item.path.join("/") }; + case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; + case "none": + case "seen": + if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); + return parseAnyDef(refs); + } + return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0; + } +}; +const addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) jsonSchema.markdownDescription = def.description; + } + return jsonSchema; +}; + +//#endregion + +//# sourceMappingURL=parseDef.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/zodToJsonSchema.js + + + + +//#region src/utils/zod-to-json-schema/zodToJsonSchema.ts +const zodToJsonSchema_zodToJsonSchema = (schema, options) => { + const refs = getRefs(options); + let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name$1, schema$1]) => ({ + ...acc, + [name$1]: parseDef(schema$1._def, { + ...refs, + currentPath: [ + ...refs.basePath, + refs.definitionPath, + name$1 + ] + }, true) ?? parseAnyDef(refs) + }), {}) : void 0; + const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; + const main = parseDef(schema._def, name === void 0 ? refs : { + ...refs, + currentPath: [ + ...refs.basePath, + refs.definitionPath, + name + ] + }, false) ?? parseAnyDef(refs); + const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; + if (title !== void 0) main.title = title; + if (refs.flags.hasReferencedOpenAiAnyType) { + if (!definitions) definitions = {}; + if (!definitions[refs.openAiAnyTypeName]) definitions[refs.openAiAnyTypeName] = { + type: [ + "string", + "number", + "integer", + "boolean", + "array", + "null" + ], + items: { $ref: refs.$refStrategy === "relative" ? "1" : [ + ...refs.basePath, + refs.definitionPath, + refs.openAiAnyTypeName + ].join("/") } + }; + } + const combined = name === void 0 ? definitions ? { + ...main, + [refs.definitionPath]: definitions + } : main : { + $ref: [ + ...refs.$refStrategy === "relative" ? [] : refs.basePath, + refs.definitionPath, + name + ].join("/"), + [refs.definitionPath]: { + ...definitions, + [name]: main + } + }; + if (refs.target === "jsonSchema7") combined.$schema = "http://json-schema.org/draft-07/schema#"; + else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; + if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); + return combined; +}; + +//#endregion + +//# sourceMappingURL=zodToJsonSchema.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/index.js + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js +function deepCompareStrict(a, b) { + const typeofa = typeof a; + if (typeofa !== typeof b) { + return false; + } + if (Array.isArray(a)) { + if (!Array.isArray(b)) { + return false; + } + const length = a.length; + if (length !== b.length) { + return false; + } + for (let i = 0; i < length; i++) { + if (!deepCompareStrict(a[i], b[i])) { + return false; + } + } + return true; + } + if (typeofa === 'object') { + if (!a || !b) { + return a === b; + } + const aKeys = Object.keys(a); + const bKeys = Object.keys(b); + const length = aKeys.length; + if (length !== bKeys.length) { + return false; + } + for (const k of aKeys) { + if (!deepCompareStrict(a[k], b[k])) { + return false; + } + } + return true; + } + return a === b; +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/pointer.js +function encodePointer(p) { + return encodeURI(escapePointer(p)); +} +function escapePointer(p) { + return p.replace(/~/g, '~0').replace(/\//g, '~1'); +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/dereference.js + +const schemaKeyword = { + additionalItems: true, + unevaluatedItems: true, + items: true, + contains: true, + additionalProperties: true, + unevaluatedProperties: true, + propertyNames: true, + not: true, + if: true, + then: true, + else: true +}; +const schemaArrayKeyword = { + prefixItems: true, + items: true, + allOf: true, + anyOf: true, + oneOf: true +}; +const schemaMapKeyword = { + $defs: true, + definitions: true, + properties: true, + patternProperties: true, + dependentSchemas: true +}; +const ignoredKeyword = { + id: true, + $id: true, + $ref: true, + $schema: true, + $anchor: true, + $vocabulary: true, + $comment: true, + default: true, + enum: true, + const: true, + required: true, + type: true, + maximum: true, + minimum: true, + exclusiveMaximum: true, + exclusiveMinimum: true, + multipleOf: true, + maxLength: true, + minLength: true, + pattern: true, + format: true, + maxItems: true, + minItems: true, + uniqueItems: true, + maxProperties: true, + minProperties: true +}; +let initialBaseURI = typeof self !== 'undefined' && + self.location && + self.location.origin !== 'null' + ? + new URL(self.location.origin + self.location.pathname + location.search) + : new URL('https://github.com/cfworker'); +function dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = '') { + if (schema && typeof schema === 'object' && !Array.isArray(schema)) { + const id = schema.$id || schema.id; + if (id) { + const url = new URL(id, baseURI.href); + if (url.hash.length > 1) { + lookup[url.href] = schema; + } + else { + url.hash = ''; + if (basePointer === '') { + baseURI = url; + } + else { + dereference(schema, lookup, baseURI); + } + } + } + } + else if (schema !== true && schema !== false) { + return lookup; + } + const schemaURI = baseURI.href + (basePointer ? '#' + basePointer : ''); + if (lookup[schemaURI] !== undefined) { + throw new Error(`Duplicate schema URI "${schemaURI}".`); + } + lookup[schemaURI] = schema; + if (schema === true || schema === false) { + return lookup; + } + if (schema.__absolute_uri__ === undefined) { + Object.defineProperty(schema, '__absolute_uri__', { + enumerable: false, + value: schemaURI + }); + } + if (schema.$ref && schema.__absolute_ref__ === undefined) { + const url = new URL(schema.$ref, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, '__absolute_ref__', { + enumerable: false, + value: url.href + }); + } + if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) { + const url = new URL(schema.$recursiveRef, baseURI.href); + url.hash = url.hash; + Object.defineProperty(schema, '__absolute_recursive_ref__', { + enumerable: false, + value: url.href + }); + } + if (schema.$anchor) { + const url = new URL('#' + schema.$anchor, baseURI.href); + lookup[url.href] = schema; + } + for (let key in schema) { + if (ignoredKeyword[key]) { + continue; + } + const keyBase = `${basePointer}/${encodePointer(key)}`; + const subSchema = schema[key]; + if (Array.isArray(subSchema)) { + if (schemaArrayKeyword[key]) { + const length = subSchema.length; + for (let i = 0; i < length; i++) { + dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`); + } + } + } + else if (schemaMapKeyword[key]) { + for (let subKey in subSchema) { + dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`); + } + } + else { + dereference(subSchema, lookup, baseURI, keyBase); + } + } + return lookup; +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/format.js +const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; +const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; +const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; +const HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; +const URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){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%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; +const URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; +const UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; +const JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; +const JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; +const RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; +const EMAIL = (input) => { + if (input[0] === '"') + return false; + const [name, host, ...rest] = input.split('@'); + if (!name || + !host || + rest.length !== 0 || + name.length > 64 || + host.length > 253) + return false; + if (name[0] === '.' || name.endsWith('.') || name.includes('..')) + return false; + if (!/^[a-z0-9.-]+$/i.test(host) || + !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) + return false; + return host + .split('.') + .every(part => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); +}; +const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; +const IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; +const DURATION = (input) => input.length > 1 && + input.length < 80 && + (/^P\d+([.,]\d+)?W$/.test(input) || + (/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && + /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input))); +function bind(r) { + return r.test.bind(r); +} +const format = { + date: format_date, + time: format_time.bind(undefined, false), + 'date-time': date_time, + duration: DURATION, + uri, + 'uri-reference': bind(URIREF), + 'uri-template': bind(URITEMPLATE), + url: bind(URL_), + email: EMAIL, + hostname: bind(HOSTNAME), + ipv4: bind(IPV4), + ipv6: bind(IPV6), + regex: regex, + uuid: bind(UUID), + 'json-pointer': bind(JSON_POINTER), + 'json-pointer-uri-fragment': bind(JSON_POINTER_URI_FRAGMENT), + 'relative-json-pointer': bind(RELATIVE_JSON_POINTER) +}; +function isLeapYear(year) { + return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); +} +function format_date(str) { + const matches = str.match(DATE); + if (!matches) + return false; + const year = +matches[1]; + const month = +matches[2]; + const day = +matches[3]; + return (month >= 1 && + month <= 12 && + day >= 1 && + day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month])); +} +function format_time(full, str) { + const matches = str.match(TIME); + if (!matches) + return false; + const hour = +matches[1]; + const minute = +matches[2]; + const second = +matches[3]; + const timeZone = !!matches[5]; + return (((hour <= 23 && minute <= 59 && second <= 59) || + (hour == 23 && minute == 59 && second == 60)) && + (!full || timeZone)); +} +const DATE_TIME_SEPARATOR = /t|\s/i; +function date_time(str) { + const dateTime = str.split(DATE_TIME_SEPARATOR); + return dateTime.length == 2 && format_date(dateTime[0]) && format_time(true, dateTime[1]); +} +const NOT_URI_FRAGMENT = /\/|:/; +const URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/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*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; +function uri(str) { + return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); +} +const Z_ANCHOR = /[^\\]\\Z/; +function regex(str) { + if (Z_ANCHOR.test(str)) + return false; + try { + new RegExp(str, 'u'); + return true; + } + catch (e) { + return false; + } +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/types.js +var OutputFormat; +(function (OutputFormat) { + OutputFormat[OutputFormat["Flag"] = 1] = "Flag"; + OutputFormat[OutputFormat["Basic"] = 2] = "Basic"; + OutputFormat[OutputFormat["Detailed"] = 4] = "Detailed"; +})(OutputFormat || (OutputFormat = {})); + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js +function ucs2length(s) { + let result = 0; + let length = s.length; + let index = 0; + let charCode; + while (index < length) { + result++; + charCode = s.charCodeAt(index++); + if (charCode >= 0xd800 && charCode <= 0xdbff && index < length) { + charCode = s.charCodeAt(index); + if ((charCode & 0xfc00) == 0xdc00) { + index++; + } + } + } + return result; +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validate.js + + + + + +function validate_validate(instance, schema, draft = '2019-09', lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = '#', schemaLocation = '#', evaluated = Object.create(null)) { + if (schema === true) { + return { valid: true, errors: [] }; + } + if (schema === false) { + return { + valid: false, + errors: [ + { + instanceLocation, + keyword: 'false', + keywordLocation: instanceLocation, + error: 'False boolean schema.' + } + ] + }; + } + const rawInstanceType = typeof instance; + let instanceType; + switch (rawInstanceType) { + case 'boolean': + case 'number': + case 'string': + instanceType = rawInstanceType; + break; + case 'object': + if (instance === null) { + instanceType = 'null'; + } + else if (Array.isArray(instance)) { + instanceType = 'array'; + } + else { + instanceType = 'object'; + } + break; + default: + throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); + } + const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema; + const errors = []; + if ($recursiveAnchor === true && recursiveAnchor === null) { + recursiveAnchor = schema; + } + if ($recursiveRef === '#') { + const refSchema = recursiveAnchor === null + ? lookup[__absolute_recursive_ref__] + : recursiveAnchor; + const keywordLocation = `${schemaLocation}/$recursiveRef`; + const result = validate_validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: '$recursiveRef', + keywordLocation, + error: 'A subschema had errors.' + }, ...result.errors); + } + } + if ($ref !== undefined) { + const uri = __absolute_ref__ || $ref; + const refSchema = lookup[uri]; + if (refSchema === undefined) { + let message = `Unresolved $ref "${$ref}".`; + if (__absolute_ref__ && __absolute_ref__ !== $ref) { + message += ` Absolute URI "${__absolute_ref__}".`; + } + message += `\nKnown schemas:\n- ${Object.keys(lookup).join('\n- ')}`; + throw new Error(message); + } + const keywordLocation = `${schemaLocation}/$ref`; + const result = validate_validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: '$ref', + keywordLocation, + error: 'A subschema had errors.' + }, ...result.errors); + } + if (draft === '4' || draft === '7') { + return { valid: errors.length === 0, errors }; + } + } + if (Array.isArray($type)) { + let length = $type.length; + let valid = false; + for (let i = 0; i < length; i++) { + if (instanceType === $type[i] || + ($type[i] === 'integer' && + instanceType === 'number' && + instance % 1 === 0 && + instance === instance)) { + valid = true; + break; + } + } + if (!valid) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` + }); + } + } + else if ($type === 'integer') { + if (instanceType !== 'number' || instance % 1 || instance !== instance) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` + }); + } + } + else if ($type !== undefined && instanceType !== $type) { + errors.push({ + instanceLocation, + keyword: 'type', + keywordLocation: `${schemaLocation}/type`, + error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` + }); + } + if ($const !== undefined) { + if (instanceType === 'object' || instanceType === 'array') { + if (!deepCompareStrict(instance, $const)) { + errors.push({ + instanceLocation, + keyword: 'const', + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` + }); + } + } + else if (instance !== $const) { + errors.push({ + instanceLocation, + keyword: 'const', + keywordLocation: `${schemaLocation}/const`, + error: `Instance does not match ${JSON.stringify($const)}.` + }); + } + } + if ($enum !== undefined) { + if (instanceType === 'object' || instanceType === 'array') { + if (!$enum.some(value => deepCompareStrict(instance, value))) { + errors.push({ + instanceLocation, + keyword: 'enum', + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` + }); + } + } + else if (!$enum.some(value => instance === value)) { + errors.push({ + instanceLocation, + keyword: 'enum', + keywordLocation: `${schemaLocation}/enum`, + error: `Instance does not match any of ${JSON.stringify($enum)}.` + }); + } + } + if ($not !== undefined) { + const keywordLocation = `${schemaLocation}/not`; + const result = validate_validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); + if (result.valid) { + errors.push({ + instanceLocation, + keyword: 'not', + keywordLocation, + error: 'Instance matched "not" schema.' + }); + } + } + let subEvaluateds = []; + if ($anyOf !== undefined) { + const keywordLocation = `${schemaLocation}/anyOf`; + const errorsLength = errors.length; + let anyValid = false; + for (let i = 0; i < $anyOf.length; i++) { + const subSchema = $anyOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + anyValid = anyValid || result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); + } + } + if (anyValid) { + errors.length = errorsLength; + } + else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'anyOf', + keywordLocation, + error: 'Instance does not match any subschemas.' + }); + } + } + if ($allOf !== undefined) { + const keywordLocation = `${schemaLocation}/allOf`; + const errorsLength = errors.length; + let allValid = true; + for (let i = 0; i < $allOf.length; i++) { + const subSchema = $allOf[i]; + const subEvaluated = Object.create(evaluated); + const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + allValid = allValid && result.valid; + if (result.valid) { + subEvaluateds.push(subEvaluated); + } + } + if (allValid) { + errors.length = errorsLength; + } + else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'allOf', + keywordLocation, + error: `Instance does not match every subschema.` + }); + } + } + if ($oneOf !== undefined) { + const keywordLocation = `${schemaLocation}/oneOf`; + const errorsLength = errors.length; + const matches = $oneOf.filter((subSchema, i) => { + const subEvaluated = Object.create(evaluated); + const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); + errors.push(...result.errors); + if (result.valid) { + subEvaluateds.push(subEvaluated); + } + return result.valid; + }).length; + if (matches === 1) { + errors.length = errorsLength; + } + else { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'oneOf', + keywordLocation, + error: `Instance does not match exactly one subschema (${matches} matches).` + }); + } + } + if (instanceType === 'object' || instanceType === 'array') { + Object.assign(evaluated, ...subEvaluateds); + } + if ($if !== undefined) { + const keywordLocation = `${schemaLocation}/if`; + const conditionResult = validate_validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; + if (conditionResult) { + if ($then !== undefined) { + const thenResult = validate_validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); + if (!thenResult.valid) { + errors.push({ + instanceLocation, + keyword: 'if', + keywordLocation, + error: `Instance does not match "then" schema.` + }, ...thenResult.errors); + } + } + } + else if ($else !== undefined) { + const elseResult = validate_validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); + if (!elseResult.valid) { + errors.push({ + instanceLocation, + keyword: 'if', + keywordLocation, + error: `Instance does not match "else" schema.` + }, ...elseResult.errors); + } + } + } + if (instanceType === 'object') { + if ($required !== undefined) { + for (const key of $required) { + if (!(key in instance)) { + errors.push({ + instanceLocation, + keyword: 'required', + keywordLocation: `${schemaLocation}/required`, + error: `Instance does not have required property "${key}".` + }); + } + } + } + const keys = Object.keys(instance); + if ($minProperties !== undefined && keys.length < $minProperties) { + errors.push({ + instanceLocation, + keyword: 'minProperties', + keywordLocation: `${schemaLocation}/minProperties`, + error: `Instance does not have at least ${$minProperties} properties.` + }); + } + if ($maxProperties !== undefined && keys.length > $maxProperties) { + errors.push({ + instanceLocation, + keyword: 'maxProperties', + keywordLocation: `${schemaLocation}/maxProperties`, + error: `Instance does not have at least ${$maxProperties} properties.` + }); + } + if ($propertyNames !== undefined) { + const keywordLocation = `${schemaLocation}/propertyNames`; + for (const key in instance) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'propertyNames', + keywordLocation, + error: `Property name "${key}" does not match schema.` + }, ...result.errors); + } + } + } + if ($dependentRequired !== undefined) { + const keywordLocation = `${schemaLocation}/dependantRequired`; + for (const key in $dependentRequired) { + if (key in instance) { + const required = $dependentRequired[key]; + for (const dependantKey of required) { + if (!(dependantKey in instance)) { + errors.push({ + instanceLocation, + keyword: 'dependentRequired', + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } + } + } + } + if ($dependentSchemas !== undefined) { + for (const key in $dependentSchemas) { + const keywordLocation = `${schemaLocation}/dependentSchemas`; + if (key in instance) { + const result = validate_validate(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'dependentSchemas', + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } + } + } + } + if ($dependencies !== undefined) { + const keywordLocation = `${schemaLocation}/dependencies`; + for (const key in $dependencies) { + if (key in instance) { + const propsOrSchema = $dependencies[key]; + if (Array.isArray(propsOrSchema)) { + for (const dependantKey of propsOrSchema) { + if (!(dependantKey in instance)) { + errors.push({ + instanceLocation, + keyword: 'dependencies', + keywordLocation, + error: `Instance has "${key}" but does not have "${dependantKey}".` + }); + } + } + } + else { + const result = validate_validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'dependencies', + keywordLocation, + error: `Instance has "${key}" but does not match dependant schema.` + }, ...result.errors); + } + } + } + } + } + const thisEvaluated = Object.create(null); + let stop = false; + if ($properties !== undefined) { + const keywordLocation = `${schemaLocation}/properties`; + for (const key in $properties) { + if (!(key in instance)) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; + } + else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'properties', + keywordLocation, + error: `Property "${key}" does not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } + if (!stop && $patternProperties !== undefined) { + const keywordLocation = `${schemaLocation}/patternProperties`; + for (const pattern in $patternProperties) { + const regex = new RegExp(pattern, 'u'); + const subSchema = $patternProperties[pattern]; + for (const key in instance) { + if (!regex.test(key)) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); + if (result.valid) { + evaluated[key] = thisEvaluated[key] = true; + } + else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'patternProperties', + keywordLocation, + error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` + }, ...result.errors); + } + } + } + } + if (!stop && $additionalProperties !== undefined) { + const keywordLocation = `${schemaLocation}/additionalProperties`; + for (const key in instance) { + if (thisEvaluated[key]) { + continue; + } + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } + else { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'additionalProperties', + keywordLocation, + error: `Property "${key}" does not match additional properties schema.` + }, ...result.errors); + } + } + } + else if (!stop && $unevaluatedProperties !== undefined) { + const keywordLocation = `${schemaLocation}/unevaluatedProperties`; + for (const key in instance) { + if (!evaluated[key]) { + const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; + const result = validate_validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); + if (result.valid) { + evaluated[key] = true; + } + else { + errors.push({ + instanceLocation, + keyword: 'unevaluatedProperties', + keywordLocation, + error: `Property "${key}" does not match unevaluated properties schema.` + }, ...result.errors); + } + } + } + } + } + else if (instanceType === 'array') { + if ($maxItems !== undefined && instance.length > $maxItems) { + errors.push({ + instanceLocation, + keyword: 'maxItems', + keywordLocation: `${schemaLocation}/maxItems`, + error: `Array has too many items (${instance.length} > ${$maxItems}).` + }); + } + if ($minItems !== undefined && instance.length < $minItems) { + errors.push({ + instanceLocation, + keyword: 'minItems', + keywordLocation: `${schemaLocation}/minItems`, + error: `Array has too few items (${instance.length} < ${$minItems}).` + }); + } + const length = instance.length; + let i = 0; + let stop = false; + if ($prefixItems !== undefined) { + const keywordLocation = `${schemaLocation}/prefixItems`; + const length2 = Math.min($prefixItems.length, length); + for (; i < length2; i++) { + const result = validate_validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'prefixItems', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } + if ($items !== undefined) { + const keywordLocation = `${schemaLocation}/items`; + if (Array.isArray($items)) { + const length2 = Math.min($items.length, length); + for (; i < length2; i++) { + const result = validate_validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'items', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } + else { + for (; i < length; i++) { + const result = validate_validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'items', + keywordLocation, + error: `Items did not match schema.` + }, ...result.errors); + if (stop) + break; + } + } + } + if (!stop && $additionalItems !== undefined) { + const keywordLocation = `${schemaLocation}/additionalItems`; + for (; i < length; i++) { + const result = validate_validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + stop = shortCircuit; + errors.push({ + instanceLocation, + keyword: 'additionalItems', + keywordLocation, + error: `Items did not match additional items schema.` + }, ...result.errors); + } + } + } + } + if ($contains !== undefined) { + if (length === 0 && $minContains === undefined) { + errors.push({ + instanceLocation, + keyword: 'contains', + keywordLocation: `${schemaLocation}/contains`, + error: `Array is empty. It must contain at least one item matching the schema.` + }); + } + else if ($minContains !== undefined && length < $minContains) { + errors.push({ + instanceLocation, + keyword: 'minContains', + keywordLocation: `${schemaLocation}/minContains`, + error: `Array has less items (${length}) than minContains (${$minContains}).` + }); + } + else { + const keywordLocation = `${schemaLocation}/contains`; + const errorsLength = errors.length; + let contained = 0; + for (let j = 0; j < length; j++) { + const result = validate_validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); + if (result.valid) { + evaluated[j] = true; + contained++; + } + else { + errors.push(...result.errors); + } + } + if (contained >= ($minContains || 0)) { + errors.length = errorsLength; + } + if ($minContains === undefined && + $maxContains === undefined && + contained === 0) { + errors.splice(errorsLength, 0, { + instanceLocation, + keyword: 'contains', + keywordLocation, + error: `Array does not contain item matching schema.` + }); + } + else if ($minContains !== undefined && contained < $minContains) { + errors.push({ + instanceLocation, + keyword: 'minContains', + keywordLocation: `${schemaLocation}/minContains`, + error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` + }); + } + else if ($maxContains !== undefined && contained > $maxContains) { + errors.push({ + instanceLocation, + keyword: 'maxContains', + keywordLocation: `${schemaLocation}/maxContains`, + error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` + }); + } + } + } + if (!stop && $unevaluatedItems !== undefined) { + const keywordLocation = `${schemaLocation}/unevaluatedItems`; + for (i; i < length; i++) { + if (evaluated[i]) { + continue; + } + const result = validate_validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); + evaluated[i] = true; + if (!result.valid) { + errors.push({ + instanceLocation, + keyword: 'unevaluatedItems', + keywordLocation, + error: `Items did not match unevaluated items schema.` + }, ...result.errors); + } + } + } + if ($uniqueItems) { + for (let j = 0; j < length; j++) { + const a = instance[j]; + const ao = typeof a === 'object' && a !== null; + for (let k = 0; k < length; k++) { + if (j === k) { + continue; + } + const b = instance[k]; + const bo = typeof b === 'object' && b !== null; + if (a === b || (ao && bo && deepCompareStrict(a, b))) { + errors.push({ + instanceLocation, + keyword: 'uniqueItems', + keywordLocation: `${schemaLocation}/uniqueItems`, + error: `Duplicate items at indexes ${j} and ${k}.` + }); + j = Number.MAX_SAFE_INTEGER; + k = Number.MAX_SAFE_INTEGER; + } + } + } + } + } + else if (instanceType === 'number') { + if (draft === '4') { + if ($minimum !== undefined && + (($exclusiveMinimum === true && instance <= $minimum) || + instance < $minimum)) { + errors.push({ + instanceLocation, + keyword: 'minimum', + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$exclusiveMinimum ? 'or equal to ' : ''} ${$minimum}.` + }); + } + if ($maximum !== undefined && + (($exclusiveMaximum === true && instance >= $maximum) || + instance > $maximum)) { + errors.push({ + instanceLocation, + keyword: 'maximum', + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$exclusiveMaximum ? 'or equal to ' : ''} ${$maximum}.` + }); + } + } + else { + if ($minimum !== undefined && instance < $minimum) { + errors.push({ + instanceLocation, + keyword: 'minimum', + keywordLocation: `${schemaLocation}/minimum`, + error: `${instance} is less than ${$minimum}.` + }); + } + if ($maximum !== undefined && instance > $maximum) { + errors.push({ + instanceLocation, + keyword: 'maximum', + keywordLocation: `${schemaLocation}/maximum`, + error: `${instance} is greater than ${$maximum}.` + }); + } + if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) { + errors.push({ + instanceLocation, + keyword: 'exclusiveMinimum', + keywordLocation: `${schemaLocation}/exclusiveMinimum`, + error: `${instance} is less than ${$exclusiveMinimum}.` + }); + } + if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) { + errors.push({ + instanceLocation, + keyword: 'exclusiveMaximum', + keywordLocation: `${schemaLocation}/exclusiveMaximum`, + error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` + }); + } + } + if ($multipleOf !== undefined) { + const remainder = instance % $multipleOf; + if (Math.abs(0 - remainder) >= 1.1920929e-7 && + Math.abs($multipleOf - remainder) >= 1.1920929e-7) { + errors.push({ + instanceLocation, + keyword: 'multipleOf', + keywordLocation: `${schemaLocation}/multipleOf`, + error: `${instance} is not a multiple of ${$multipleOf}.` + }); + } + } + } + else if (instanceType === 'string') { + const length = $minLength === undefined && $maxLength === undefined + ? 0 + : ucs2length(instance); + if ($minLength !== undefined && length < $minLength) { + errors.push({ + instanceLocation, + keyword: 'minLength', + keywordLocation: `${schemaLocation}/minLength`, + error: `String is too short (${length} < ${$minLength}).` + }); + } + if ($maxLength !== undefined && length > $maxLength) { + errors.push({ + instanceLocation, + keyword: 'maxLength', + keywordLocation: `${schemaLocation}/maxLength`, + error: `String is too long (${length} > ${$maxLength}).` + }); + } + if ($pattern !== undefined && !new RegExp($pattern, 'u').test(instance)) { + errors.push({ + instanceLocation, + keyword: 'pattern', + keywordLocation: `${schemaLocation}/pattern`, + error: `String does not match pattern.` + }); + } + if ($format !== undefined && + format[$format] && + !format[$format](instance)) { + errors.push({ + instanceLocation, + keyword: 'format', + keywordLocation: `${schemaLocation}/format`, + error: `String does not match format "${$format}".` + }); + } + } + return { valid: errors.length === 0, errors }; +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validator.js + + +class Validator { + schema; + draft; + shortCircuit; + lookup; + constructor(schema, draft = '2019-09', shortCircuit = true) { + this.schema = schema; + this.draft = draft; + this.shortCircuit = shortCircuit; + this.lookup = dereference(schema); + } + validate(instance) { + return validate_validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit); + } + addSchema(schema, id) { + if (id) { + schema = { ...schema, $id: id }; + } + dereference(schema, this.lookup); + } +} + +;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/index.js + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json_schema.js + + + + + + + +//#region src/utils/json_schema.ts +var json_schema_exports = {}; +__export(json_schema_exports, { + Validator: () => Validator, + deepCompareStrict: () => deepCompareStrict, + toJsonSchema: () => toJsonSchema, + validatesOnlyStrings: () => validatesOnlyStrings +}); +/** +* Converts a Zod schema or JSON schema to a JSON schema. +* @param schema - The schema to convert. +* @param params - The parameters to pass to the toJSONSchema function. +* @returns The converted schema. +*/ +function toJsonSchema(schema, params) { + if (isZodSchemaV4(schema)) { + const inputSchema = interopZodTransformInputSchema(schema, true); + if (isZodObjectV4(inputSchema)) { + const strictSchema = interopZodObjectStrict(inputSchema, true); + return toJSONSchema(strictSchema, params); + } else return toJSONSchema(schema, params); + } + if (isZodSchemaV3(schema)) return zodToJsonSchema_zodToJsonSchema(schema); + return schema; +} +/** +* Validates if a JSON schema validates only strings. May return false negatives in some edge cases +* (like recursive or unresolvable refs). +* +* @param schema - The schema to validate. +* @returns `true` if the schema validates only strings, `false` otherwise. +*/ +function validatesOnlyStrings(schema) { + if (!schema || typeof schema !== "object" || Object.keys(schema).length === 0 || Array.isArray(schema)) return false; + if ("type" in schema) { + if (typeof schema.type === "string") return schema.type === "string"; + if (Array.isArray(schema.type)) return schema.type.every((t) => t === "string"); + return false; + } + if ("enum" in schema) return Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.every((val) => typeof val === "string"); + if ("const" in schema) return typeof schema.const === "string"; + if ("allOf" in schema && Array.isArray(schema.allOf)) return schema.allOf.some((subschema) => validatesOnlyStrings(subschema)); + if ("anyOf" in schema && Array.isArray(schema.anyOf) || "oneOf" in schema && Array.isArray(schema.oneOf)) { + const subschemas = "anyOf" in schema ? schema.anyOf : schema.oneOf; + return subschemas.length > 0 && subschemas.every((subschema) => validatesOnlyStrings(subschema)); + } + if ("not" in schema) return false; + if ("$ref" in schema && typeof schema.$ref === "string") { + const ref = schema.$ref; + const resolved = dereference(schema); + if (resolved[ref]) return validatesOnlyStrings(resolved[ref]); + return false; + } + return false; +} + +//#endregion + +//# sourceMappingURL=json_schema.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/utils.js +//#region src/runnables/utils.ts +function isRunnableInterface(thing) { + return thing ? thing.lc_runnable : false; +} +/** +* Utility to filter the root event in the streamEvents implementation. +* This is simply binding the arguments to the namespace to make save on +* a bit of typing in the streamEvents implementation. +* +* TODO: Refactor and remove. +*/ +var _RootEventFilter = class { + includeNames; + includeTypes; + includeTags; + excludeNames; + excludeTypes; + excludeTags; + constructor(fields) { + this.includeNames = fields.includeNames; + this.includeTypes = fields.includeTypes; + this.includeTags = fields.includeTags; + this.excludeNames = fields.excludeNames; + this.excludeTypes = fields.excludeTypes; + this.excludeTags = fields.excludeTags; + } + includeEvent(event, rootType) { + let include = this.includeNames === void 0 && this.includeTypes === void 0 && this.includeTags === void 0; + const eventTags = event.tags ?? []; + if (this.includeNames !== void 0) include = include || this.includeNames.includes(event.name); + if (this.includeTypes !== void 0) include = include || this.includeTypes.includes(rootType); + if (this.includeTags !== void 0) include = include || eventTags.some((tag) => this.includeTags?.includes(tag)); + if (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(event.name); + if (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(rootType); + if (this.excludeTags !== void 0) include = include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); + return include; + } +}; +const toBase64Url = (str) => { + const encoded = btoa(str); + return encoded.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); +}; + +//#endregion + +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph_mermaid.js + + +//#region src/runnables/graph_mermaid.ts +function _escapeNodeLabel(nodeLabel) { + return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); +} +const MARKDOWN_SPECIAL_CHARS = [ + "*", + "_", + "`" +]; +function _generateMermaidGraphStyles(nodeColors) { + let styles = ""; + for (const [className, color] of Object.entries(nodeColors)) styles += `\tclassDef ${className} ${color};\n`; + return styles; +} +/** +* Draws a Mermaid graph using the provided graph data +*/ +function drawMermaid(nodes, edges, config) { + const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9 } = config ?? {}; + let mermaidGraph = withStyles ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\ngraph TD;\n` : "graph TD;\n"; + if (withStyles) { + const defaultClassLabel = "default"; + const formatDict = { [defaultClassLabel]: "{0}({1})" }; + if (firstNode !== void 0) formatDict[firstNode] = "{0}([{1}]):::first"; + if (lastNode !== void 0) formatDict[lastNode] = "{0}([{1}]):::last"; + for (const [key, node] of Object.entries(nodes)) { + const nodeName = node.name.split(":").pop() ?? ""; + const label = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `

${nodeName}

` : nodeName; + let finalLabel = label; + if (Object.keys(node.metadata ?? {}).length) finalLabel += `
${Object.entries(node.metadata ?? {}).map(([k, v]) => `${k} = ${v}`).join("\n")}`; + const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]).replace("{0}", _escapeNodeLabel(key)).replace("{1}", finalLabel); + mermaidGraph += `\t${nodeLabel}\n`; + } + } + const edgeGroups = {}; + for (const edge of edges) { + const srcParts = edge.source.split(":"); + const tgtParts = edge.target.split(":"); + const commonPrefix = srcParts.filter((src, i) => src === tgtParts[i]).join(":"); + if (!edgeGroups[commonPrefix]) edgeGroups[commonPrefix] = []; + edgeGroups[commonPrefix].push(edge); + } + const seenSubgraphs = /* @__PURE__ */ new Set(); + function sortPrefixesByDepth(prefixes) { + return [...prefixes].sort((a, b) => { + return a.split(":").length - b.split(":").length; + }); + } + function addSubgraph(edges$1, prefix) { + const selfLoop = edges$1.length === 1 && edges$1[0].source === edges$1[0].target; + if (prefix && !selfLoop) { + const subgraph = prefix.split(":").pop(); + if (seenSubgraphs.has(prefix)) throw new Error(`Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`); + seenSubgraphs.add(prefix); + mermaidGraph += `\tsubgraph ${subgraph}\n`; + } + const nestedPrefixes = sortPrefixesByDepth(Object.keys(edgeGroups).filter((nestedPrefix) => nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix && nestedPrefix.split(":").length === prefix.split(":").length + 1)); + for (const nestedPrefix of nestedPrefixes) addSubgraph(edgeGroups[nestedPrefix], nestedPrefix); + for (const edge of edges$1) { + const { source, target, data, conditional } = edge; + let edgeLabel = ""; + if (data !== void 0) { + let edgeData = data; + const words = edgeData.split(" "); + if (words.length > wrapLabelNWords) edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words.slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords).join(" ")).join(" 
 "); + edgeLabel = conditional ? ` -.  ${edgeData}  .-> ` : ` --  ${edgeData}  --> `; + } else edgeLabel = conditional ? " -.-> " : " --> "; + mermaidGraph += `\t${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};\n`; + } + if (prefix && !selfLoop) mermaidGraph += " end\n"; + } + addSubgraph(edgeGroups[""] ?? [], ""); + for (const prefix in edgeGroups) if (!prefix.includes(":") && prefix !== "") addSubgraph(edgeGroups[prefix], prefix); + if (withStyles) mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {}); + return mermaidGraph; +} +/** +* Renders Mermaid graph using the Mermaid.INK API. +* +* @example +* ```javascript +* const image = await drawMermaidImage(mermaidSyntax, { +* backgroundColor: "white", +* imageType: "png", +* }); +* fs.writeFileSync("image.png", image); +* ``` +* +* @param mermaidSyntax - The Mermaid syntax to render. +* @param config - The configuration for the image. +* @returns The image as a Blob. +*/ +async function drawMermaidImage(mermaidSyntax, config) { + let backgroundColor = config?.backgroundColor ?? "white"; + const imageType = config?.imageType ?? "png"; + const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax); + if (backgroundColor !== void 0) { + const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/; + if (!hexColorPattern.test(backgroundColor)) backgroundColor = `!${backgroundColor}`; + } + const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`; + const res = await fetch(imageUrl); + if (!res.ok) throw new Error([ + `Failed to render the graph using the Mermaid.INK API.`, + `Status code: ${res.status}`, + `Status text: ${res.statusText}` + ].join("\n")); + const content = await res.blob(); + return content; +} + +//#endregion + +//# sourceMappingURL=graph_mermaid.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph.js + + + + + + +//#region src/runnables/graph.ts +var graph_exports = {}; +__export(graph_exports, { Graph: () => Graph }); +function nodeDataStr(id, data) { + if (id !== void 0 && !wrapper_validate(id)) return id; + else if (isRunnableInterface(data)) try { + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; + return dataStr; + } catch { + return data.getName(); + } + else return data.name ?? "UnknownSchema"; +} +function nodeDataJson(node) { + if (isRunnableInterface(node.data)) return { + type: "runnable", + data: { + id: node.data.lc_id, + name: node.data.getName() + } + }; + else return { + type: "schema", + data: { + ...toJsonSchema(node.data.schema), + title: node.data.name + } + }; +} +var Graph = class Graph { + nodes = {}; + edges = []; + constructor(params) { + this.nodes = params?.nodes ?? this.nodes; + this.edges = params?.edges ?? this.edges; + } + toJSON() { + const stableNodeIds = {}; + Object.values(this.nodes).forEach((node, i) => { + stableNodeIds[node.id] = wrapper_validate(node.id) ? i : node.id; + }); + return { + nodes: Object.values(this.nodes).map((node) => ({ + id: stableNodeIds[node.id], + ...nodeDataJson(node) + })), + edges: this.edges.map((edge) => { + const item = { + source: stableNodeIds[edge.source], + target: stableNodeIds[edge.target] + }; + if (typeof edge.data !== "undefined") item.data = edge.data; + if (typeof edge.conditional !== "undefined") item.conditional = edge.conditional; + return item; + }) + }; + } + addNode(data, id, metadata) { + if (id !== void 0 && this.nodes[id] !== void 0) throw new Error(`Node with id ${id} already exists`); + const nodeId = id ?? v4(); + const node = { + id: nodeId, + data, + name: nodeDataStr(id, data), + metadata + }; + this.nodes[nodeId] = node; + return node; + } + removeNode(node) { + delete this.nodes[node.id]; + this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); + } + addEdge(source, target, data, conditional) { + if (this.nodes[source.id] === void 0) throw new Error(`Source node ${source.id} not in graph`); + if (this.nodes[target.id] === void 0) throw new Error(`Target node ${target.id} not in graph`); + const edge = { + source: source.id, + target: target.id, + data, + conditional + }; + this.edges.push(edge); + return edge; + } + firstNode() { + return _firstNode(this); + } + lastNode() { + return _lastNode(this); + } + /** + * Add all nodes and edges from another graph. + * Note this doesn't check for duplicates, nor does it connect the graphs. + */ + extend(graph, prefix = "") { + let finalPrefix = prefix; + const nodeIds = Object.values(graph.nodes).map((node) => node.id); + if (nodeIds.every(wrapper_validate)) finalPrefix = ""; + const prefixed = (id) => { + return finalPrefix ? `${finalPrefix}:${id}` : id; + }; + Object.entries(graph.nodes).forEach(([key, value]) => { + this.nodes[prefixed(key)] = { + ...value, + id: prefixed(key) + }; + }); + const newEdges = graph.edges.map((edge) => { + return { + ...edge, + source: prefixed(edge.source), + target: prefixed(edge.target) + }; + }); + this.edges = [...this.edges, ...newEdges]; + const first = graph.firstNode(); + const last = graph.lastNode(); + return [first ? { + id: prefixed(first.id), + data: first.data + } : void 0, last ? { + id: prefixed(last.id), + data: last.data + } : void 0]; + } + trimFirstNode() { + const firstNode = this.firstNode(); + if (firstNode && _firstNode(this, [firstNode.id])) this.removeNode(firstNode); + } + trimLastNode() { + const lastNode = this.lastNode(); + if (lastNode && _lastNode(this, [lastNode.id])) this.removeNode(lastNode); + } + /** + * Return a new graph with all nodes re-identified, + * using their unique, readable names where possible. + */ + reid() { + const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); + const nodeLabelCounts = /* @__PURE__ */ new Map(); + Object.values(nodeLabels).forEach((label) => { + nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); + }); + const getNodeId = (nodeId) => { + const label = nodeLabels[nodeId]; + if (wrapper_validate(nodeId) && nodeLabelCounts.get(label) === 1) return label; + else return nodeId; + }; + return new Graph({ + nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [getNodeId(id), { + ...node, + id: getNodeId(id) + }])), + edges: this.edges.map((edge) => ({ + ...edge, + source: getNodeId(edge.source), + target: getNodeId(edge.target) + })) + }); + } + drawMermaid(params) { + const { withStyles, curveStyle, nodeColors = { + default: "fill:#f2f0ff,line-height:1.2", + first: "fill-opacity:0", + last: "fill:#bfb6fc" + }, wrapLabelNWords } = params ?? {}; + const graph = this.reid(); + const firstNode = graph.firstNode(); + const lastNode = graph.lastNode(); + return drawMermaid(graph.nodes, graph.edges, { + firstNode: firstNode?.id, + lastNode: lastNode?.id, + withStyles, + curveStyle, + nodeColors, + wrapLabelNWords + }); + } + async drawMermaidPng(params) { + const mermaidSyntax = this.drawMermaid(params); + return drawMermaidImage(mermaidSyntax, { backgroundColor: params?.backgroundColor }); + } +}; +/** +* Find the single node that is not a target of any edge. +* Exclude nodes/sources with ids in the exclude list. +* If there is no such node, or there are multiple, return undefined. +* When drawing the graph, this node would be the origin. +*/ +function _firstNode(graph, exclude = []) { + const targets = new Set(graph.edges.filter((edge) => !exclude.includes(edge.source)).map((edge) => edge.target)); + const found = []; + for (const node of Object.values(graph.nodes)) if (!exclude.includes(node.id) && !targets.has(node.id)) found.push(node); + return found.length === 1 ? found[0] : void 0; +} +/** +* Find the single node that is not a source of any edge. +* Exclude nodes/targets with ids in the exclude list. +* If there is no such node, or there are multiple, return undefined. +* When drawing the graph, this node would be the destination. +*/ +function _lastNode(graph, exclude = []) { + const sources = new Set(graph.edges.filter((edge) => !exclude.includes(edge.target)).map((edge) => edge.source)); + const found = []; + for (const node of Object.values(graph.nodes)) if (!exclude.includes(node.id) && !sources.has(node.id)) found.push(node); + return found.length === 1 ? found[0] : void 0; +} + +//#endregion + +//# sourceMappingURL=graph.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/event_stream.js + + + + + +//#region src/tracers/event_stream.ts +function assignName({ name, serialized }) { + if (name !== void 0) return name; + if (serialized?.name !== void 0) return serialized.name; + else if (serialized?.id !== void 0 && Array.isArray(serialized?.id)) return serialized.id[serialized.id.length - 1]; + return "Unnamed"; +} +const isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer"; +/** +* Class that extends the `BaseTracer` class from the +* `langchain.callbacks.tracers.base` module. It represents a callback +* handler that logs the execution of runs and emits `RunLog` instances to a +* `RunLogStream`. +*/ +var EventStreamCallbackHandler = class extends BaseTracer { + autoClose = true; + includeNames; + includeTypes; + includeTags; + excludeNames; + excludeTypes; + excludeTags; + runInfoMap = /* @__PURE__ */ new Map(); + tappedPromises = /* @__PURE__ */ new Map(); + transformStream; + writer; + receiveStream; + readableStreamClosed = false; + name = "event_stream_tracer"; + lc_prefer_streaming = true; + constructor(fields) { + super({ + _awaitHandler: true, + ...fields + }); + this.autoClose = fields?.autoClose ?? true; + this.includeNames = fields?.includeNames; + this.includeTypes = fields?.includeTypes; + this.includeTags = fields?.includeTags; + this.excludeNames = fields?.excludeNames; + this.excludeTypes = fields?.excludeTypes; + this.excludeTags = fields?.excludeTags; + this.transformStream = new TransformStream({ flush: () => { + this.readableStreamClosed = true; + } }); + this.writer = this.transformStream.writable.getWriter(); + this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); + } + [Symbol.asyncIterator]() { + return this.receiveStream; + } + async persistRun(_run) {} + _includeRun(run) { + const runTags = run.tags ?? []; + let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0; + if (this.includeNames !== void 0) include = include || this.includeNames.includes(run.name); + if (this.includeTypes !== void 0) include = include || this.includeTypes.includes(run.runType); + if (this.includeTags !== void 0) include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0; + if (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(run.name); + if (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(run.runType); + if (this.excludeTags !== void 0) include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); + return include; + } + async *tapOutputIterable(runId, outputStream) { + const firstChunk = await outputStream.next(); + if (firstChunk.done) return; + const runInfo = this.runInfoMap.get(runId); + if (runInfo === void 0) { + yield firstChunk.value; + return; + } + function _formatOutputChunk(eventType, data) { + if (eventType === "llm" && typeof data === "string") return new GenerationChunk({ text: data }); + return data; + } + let tappedPromise = this.tappedPromises.get(runId); + if (tappedPromise === void 0) { + let tappedPromiseResolver; + tappedPromise = new Promise((resolve) => { + tappedPromiseResolver = resolve; + }); + this.tappedPromises.set(runId, tappedPromise); + try { + const event = { + event: `on_${runInfo.runType}_stream`, + run_id: runId, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata, + data: {} + }; + await this.send({ + ...event, + data: { chunk: _formatOutputChunk(runInfo.runType, firstChunk.value) } + }, runInfo); + yield firstChunk.value; + for await (const chunk of outputStream) { + if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") await this.send({ + ...event, + data: { chunk: _formatOutputChunk(runInfo.runType, chunk) } + }, runInfo); + yield chunk; + } + } finally { + tappedPromiseResolver?.(); + } + } else { + yield firstChunk.value; + for await (const chunk of outputStream) yield chunk; + } + } + async send(payload, run) { + if (this.readableStreamClosed) return; + if (this._includeRun(run)) await this.writer.write(payload); + } + async sendEndEvent(payload, run) { + const tappedPromise = this.tappedPromises.get(payload.run_id); + if (tappedPromise !== void 0) tappedPromise.then(() => { + this.send(payload, run); + }); + else await this.send(payload, run); + } + async onLLMStart(run) { + const runName = assignName(run); + const runType = run.inputs.messages !== void 0 ? "chat_model" : "llm"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType, + inputs: run.inputs + }; + this.runInfoMap.set(run.id, runInfo); + const eventName = `on_${runType}_start`; + await this.send({ + event: eventName, + data: { input: run.inputs }, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onLLMNewToken(run, token, kwargs) { + const runInfo = this.runInfoMap.get(run.id); + let chunk; + let eventName; + if (runInfo === void 0) throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`); + if (this.runInfoMap.size === 1) return; + if (runInfo.runType === "chat_model") { + eventName = "on_chat_model_stream"; + if (kwargs?.chunk === void 0) chunk = new AIMessageChunk({ + content: token, + id: `run-${run.id}` + }); + else chunk = kwargs.chunk.message; + } else if (runInfo.runType === "llm") { + eventName = "on_llm_stream"; + if (kwargs?.chunk === void 0) chunk = new GenerationChunk({ text: token }); + else chunk = kwargs.chunk; + } else throw new Error(`Unexpected run type ${runInfo.runType}`); + await this.send({ + event: eventName, + data: { chunk }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onLLMEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + let eventName; + if (runInfo === void 0) throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`); + const generations = run.outputs?.generations; + let output; + if (runInfo.runType === "chat_model") { + for (const generation of generations ?? []) { + if (output !== void 0) break; + output = generation[0]?.message; + } + eventName = "on_chat_model_end"; + } else if (runInfo.runType === "llm") { + output = { + generations: generations?.map((generation) => { + return generation.map((chunk) => { + return { + text: chunk.text, + generationInfo: chunk.generationInfo + }; + }); + }), + llmOutput: run.outputs?.llmOutput ?? {} + }; + eventName = "on_llm_end"; + } else throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); + await this.sendEndEvent({ + event: eventName, + data: { + output, + input: runInfo.inputs + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onChainStart(run) { + const runName = assignName(run); + const runType = run.run_type ?? "chain"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType: run.run_type + }; + let eventData = {}; + if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) { + eventData = {}; + runInfo.inputs = {}; + } else if (run.inputs.input !== void 0) { + eventData.input = run.inputs.input; + runInfo.inputs = run.inputs.input; + } else { + eventData.input = run.inputs; + runInfo.inputs = run.inputs; + } + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: `on_${runType}_start`, + data: eventData, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onChainEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === void 0) throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`); + const eventName = `on_${run.run_type}_end`; + const inputs = run.inputs ?? runInfo.inputs ?? {}; + const outputs = run.outputs?.output ?? run.outputs; + const data = { + output: outputs, + input: inputs + }; + if (inputs.input && Object.keys(inputs).length === 1) { + data.input = inputs.input; + runInfo.inputs = inputs.input; + } + await this.sendEndEvent({ + event: eventName, + data, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata ?? {} + }, runInfo); + } + async onToolStart(run) { + const runName = assignName(run); + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType: "tool", + inputs: run.inputs ?? {} + }; + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: "on_tool_start", + data: { input: run.inputs ?? {} }, + name: runName, + run_id: run.id, + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onToolEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === void 0) throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`); + if (runInfo.inputs === void 0) throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`); + const output = run.outputs?.output === void 0 ? run.outputs : run.outputs.output; + await this.sendEndEvent({ + event: "on_tool_end", + data: { + output, + input: runInfo.inputs + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async onRetrieverStart(run) { + const runName = assignName(run); + const runType = "retriever"; + const runInfo = { + tags: run.tags ?? [], + metadata: run.extra?.metadata ?? {}, + name: runName, + runType, + inputs: { query: run.inputs.query } + }; + this.runInfoMap.set(run.id, runInfo); + await this.send({ + event: "on_retriever_start", + data: { input: { query: run.inputs.query } }, + name: runName, + tags: run.tags ?? [], + run_id: run.id, + metadata: run.extra?.metadata ?? {} + }, runInfo); + } + async onRetrieverEnd(run) { + const runInfo = this.runInfoMap.get(run.id); + this.runInfoMap.delete(run.id); + if (runInfo === void 0) throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`); + await this.sendEndEvent({ + event: "on_retriever_end", + data: { + output: run.outputs?.documents ?? run.outputs, + input: runInfo.inputs + }, + run_id: run.id, + name: runInfo.name, + tags: runInfo.tags, + metadata: runInfo.metadata + }, runInfo); + } + async handleCustomEvent(eventName, data, runId) { + const runInfo = this.runInfoMap.get(runId); + if (runInfo === void 0) throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); + await this.send({ + event: "on_custom_event", + run_id: runId, + name: eventName, + tags: runInfo.tags, + metadata: runInfo.metadata, + data + }, runInfo); + } + async finish() { + const pendingPromises = [...this.tappedPromises.values()]; + Promise.all(pendingPromises).finally(() => { + this.writer.close(); + }); + } +}; + +//#endregion + +//# sourceMappingURL=event_stream.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/root_listener.js + + +//#region src/tracers/root_listener.ts +var RootListenersTracer = class extends BaseTracer { + name = "RootListenersTracer"; + /** The Run's ID. Type UUID */ + rootId; + config; + argOnStart; + argOnEnd; + argOnError; + constructor({ config, onStart, onEnd, onError }) { + super({ _awaitHandler: true }); + this.config = config; + this.argOnStart = onStart; + this.argOnEnd = onEnd; + this.argOnError = onError; + } + /** + * This is a legacy method only called once for an entire run tree + * therefore not useful here + * @param {Run} _ Not used + */ + persistRun(_) { + return Promise.resolve(); + } + async onRunCreate(run) { + if (this.rootId) return; + this.rootId = run.id; + if (this.argOnStart) await this.argOnStart(run, this.config); + } + async onRunUpdate(run) { + if (run.id !== this.rootId) return; + if (!run.error) { + if (this.argOnEnd) await this.argOnEnd(run, this.config); + } else if (this.argOnError) await this.argOnError(run, this.config); + } +}; + +//#endregion + +//# sourceMappingURL=root_listener.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/wrappers.js + + +//#region src/runnables/wrappers.ts +function convertToHttpEventStream(stream) { + const encoder = new TextEncoder(); + const finalStream = new ReadableStream({ async start(controller) { + for await (const chunk of stream) controller.enqueue(encoder.encode(`event: data\ndata: ${JSON.stringify(chunk)}\n\n`)); + controller.enqueue(encoder.encode("event: end\n\n")); + controller.close(); + } }); + return IterableReadableStream.fromReadableStream(finalStream); +} + +//#endregion + +//# sourceMappingURL=wrappers.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/iter.js + + + + +//#region src/runnables/iter.ts +function isIterableIterator(thing) { + return typeof thing === "object" && thing !== null && typeof thing[Symbol.iterator] === "function" && typeof thing.next === "function"; +} +const isIterator = (x) => x != null && typeof x === "object" && "next" in x && typeof x.next === "function"; +function isAsyncIterable(thing) { + return typeof thing === "object" && thing !== null && typeof thing[Symbol.asyncIterator] === "function"; +} +function* consumeIteratorInContext(context, iter) { + while (true) { + const { value, done } = async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(context), iter.next.bind(iter), true); + if (done) break; + else yield value; + } +} +async function* consumeAsyncIterableInContext(context, iter) { + const iterator = iter[Symbol.asyncIterator](); + while (true) { + const { value, done } = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(context), iterator.next.bind(iter), true); + if (done) break; + else yield value; + } +} + +//#endregion + +//# sourceMappingURL=iter.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/base.js + + + + + + + + + + + + + + + + + + + + + +//#region src/runnables/base.ts +function base_coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; +} +/** +* A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or +* transformed. +*/ +var Runnable = class extends Serializable { + lc_runnable = true; + name; + getName(suffix) { + const name = this.name ?? this.constructor.lc_name() ?? this.constructor.name; + return suffix ? `${name}${suffix}` : name; + } + /** + * Add retry logic to an existing runnable. + * @param fields.stopAfterAttempt The number of attempts to retry. + * @param fields.onFailedAttempt A function that is called when a retry fails. + * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. + */ + withRetry(fields) { + return new RunnableRetry({ + bound: this, + kwargs: {}, + config: {}, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields + }); + } + /** + * Bind config to a Runnable, returning a new Runnable. + * @param config New configuration parameters to attach to the new runnable. + * @returns A new RunnableBinding with a config matching what's passed. + */ + withConfig(config) { + return new RunnableBinding({ + bound: this, + config, + kwargs: {} + }); + } + /** + * Create a new runnable from the current one that will try invoking + * other passed fallback runnables if the initial invocation fails. + * @param fields.fallbacks Other runnables to call if the runnable errors. + * @returns A new RunnableWithFallbacks. + */ + withFallbacks(fields) { + const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; + return new RunnableWithFallbacks({ + runnable: this, + fallbacks + }); + } + _getOptionsList(options, length = 0) { + if (Array.isArray(options) && options.length !== length) throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); + if (Array.isArray(options)) return options.map(ensureConfig); + if (length > 1 && !Array.isArray(options) && options.runId) { + console.warn("Provided runId will be used only for the first element of the batch."); + const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); + return Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent)); + } + return Array.from({ length }, () => ensureConfig(options)); + } + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; + const caller = new async_caller_AsyncCaller({ + maxConcurrency, + onFailedAttempt: (e) => { + throw e; + } + }); + const batchCalls = inputs.map((input, i) => caller.call(async () => { + try { + const result = await this.invoke(input, configList[i]); + return result; + } catch (e) { + if (batchOptions?.returnExceptions) return e; + throw e; + } + })); + return Promise.all(batchCalls); + } + /** + * Default streaming implementation. + * Subclasses should override this method if they support streaming output. + * @param input + * @param options + */ + async *_streamIterator(input, options) { + yield this.invoke(input, options); + } + /** + * Stream output in chunks. + * @param input + * @param options + * @returns A readable stream that is also an iterable. + */ + async stream(input, options) { + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this._streamIterator(input, config), + config + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } + _separateRunnableConfigFromCallOptions(options) { + let runnableConfig; + if (options === void 0) runnableConfig = ensureConfig(options); + else runnableConfig = ensureConfig({ + callbacks: options.callbacks, + tags: options.tags, + metadata: options.metadata, + runName: options.runName, + configurable: options.configurable, + recursionLimit: options.recursionLimit, + maxConcurrency: options.maxConcurrency, + runId: options.runId, + timeout: options.timeout, + signal: options.signal + }); + const callOptions = { ...options }; + delete callOptions.callbacks; + delete callOptions.tags; + delete callOptions.metadata; + delete callOptions.runName; + delete callOptions.configurable; + delete callOptions.recursionLimit; + delete callOptions.maxConcurrency; + delete callOptions.runId; + delete callOptions.timeout; + delete callOptions.signal; + return [runnableConfig, callOptions]; + } + async _callWithConfig(func, input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, config?.runType, void 0, void 0, config?.runName ?? this.getName()); + delete config.runId; + let output; + try { + const promise = func.call(this, input, config, runManager); + output = await raceWithSignal(promise, options?.signal); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(base_coerceToDict(output, "output")); + return output; + } + /** + * Internal method that handles batching and configuration for a runnable + * It takes a function, input values, and optional configuration, and + * returns a promise that resolves to the output values. + * @param func The function to be executed for each input value. + * @param input The input values to be processed. + * @param config Optional configuration for the function execution. + * @returns A promise that resolves to the output values. + */ + async _batchWithConfig(func, inputs, options, batchOptions) { + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, void 0, void 0, optionsList[i].runName ?? this.getName()); + delete optionsList[i].runId; + return handleStartRes; + })); + let outputs; + try { + const promise = func.call(this, inputs, optionsList, runManagers, batchOptions); + outputs = await raceWithSignal(promise, optionsList?.[0]?.signal); + } catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(outputs, "output")))); + return outputs; + } + /** @internal */ + _concatOutputChunks(first, second) { + return concat(first, second); + } + /** + * Helper method to transform an Iterator of Input values into an Iterator of + * Output values, with callbacks. + * Use this to implement `stream()` or `transform()` in Runnable subclasses. + */ + async *_transformStreamWithConfig(inputGenerator, transformer, options) { + let finalInput; + let finalInputSupported = true; + let finalOutput; + let finalOutputSupported = true; + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const outerThis = this; + async function* wrapInputForTracing() { + for await (const chunk of inputGenerator) { + if (finalInputSupported) if (finalInput === void 0) finalInput = chunk; + else try { + finalInput = outerThis._concatOutputChunks(finalInput, chunk); + } catch { + finalInput = void 0; + finalInputSupported = false; + } + yield chunk; + } + } + let runManager; + try { + const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, void 0, void 0, config.runName ?? this.getName(), void 0, { lc_defers_inputs: true }), options?.signal, config); + delete config.runId; + runManager = pipe.setup; + const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); + let iterator = pipe.output; + if (streamEventsHandler !== void 0 && runManager !== void 0) iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); + const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); + if (streamLogHandler !== void 0 && runManager !== void 0) iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); + for await (const chunk of iterator) { + yield chunk; + if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = void 0; + finalOutputSupported = false; + } + } + } catch (e) { + await runManager?.handleChainError(e, void 0, void 0, void 0, { inputs: base_coerceToDict(finalInput, "input") }); + throw e; + } + await runManager?.handleChainEnd(finalOutput ?? {}, void 0, void 0, void 0, { inputs: base_coerceToDict(finalInput, "input") }); + } + getGraph(_) { + const graph = new Graph(); + const inputNode = graph.addNode({ + name: `${this.getName()}Input`, + schema: anyType() + }); + const runnableNode = graph.addNode(this); + const outputNode = graph.addNode({ + name: `${this.getName()}Output`, + schema: anyType() + }); + graph.addEdge(inputNode, runnableNode); + graph.addEdge(runnableNode, outputNode); + return graph; + } + /** + * Create a new runnable sequence that runs each individual runnable in series, + * piping the output of one runnable into another runnable or runnable-like. + * @param coerceable A runnable, function, or object whose values are functions or runnables. + * @returns A new runnable sequence. + */ + pipe(coerceable) { + return new RunnableSequence({ + first: this, + last: _coerceToRunnable(coerceable) + }); + } + /** + * Pick keys from the dict output of this runnable. Returns a new runnable. + */ + pick(keys) { + return this.pipe(new RunnablePick(keys)); + } + /** + * Assigns new fields to the dict output of this runnable. Returns a new runnable. + */ + assign(mapping) { + return this.pipe(new RunnableAssign(new RunnableMap({ steps: mapping }))); + } + /** + * Default implementation of transform, which buffers input and then calls stream. + * Subclasses should override this method if they can start producing output while + * input is still being generated. + * @param generator + * @param options + */ + async *transform(generator, options) { + let finalChunk; + for await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk; + else finalChunk = this._concatOutputChunks(finalChunk, chunk); + yield* this._streamIterator(finalChunk, ensureConfig(options)); + } + /** + * Stream all output from a runnable, as reported to the callback system. + * This includes all inner runs of LLMs, Retrievers, Tools, etc. + * Output is streamed as Log objects, which include a list of + * jsonpatch ops that describe how the state of the run has changed in each + * step, and the final state of the run. + * The jsonpatch ops can be applied in order to construct state. + * @param input + * @param options + * @param streamOptions + */ + async *streamLog(input, options, streamOptions) { + const logStreamCallbackHandler = new LogStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + _schemaFormat: "original" + }); + const config = ensureConfig(options); + yield* this._streamLog(input, logStreamCallbackHandler, config); + } + async *_streamLog(input, logStreamCallbackHandler, config) { + const { callbacks } = config; + if (callbacks === void 0) config.callbacks = [logStreamCallbackHandler]; + else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat([logStreamCallbackHandler]); + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(logStreamCallbackHandler, true); + config.callbacks = copiedCallbacks; + } + const runnableStreamPromise = this.stream(input, config); + async function consumeRunnableStream() { + try { + const runnableStream = await runnableStreamPromise; + for await (const chunk of runnableStream) { + const patch = new RunLogPatch({ ops: [{ + op: "add", + path: "/streamed_output/-", + value: chunk + }] }); + await logStreamCallbackHandler.writer.write(patch); + } + } finally { + await logStreamCallbackHandler.writer.close(); + } + } + const runnableStreamConsumePromise = consumeRunnableStream(); + try { + for await (const log of logStreamCallbackHandler) yield log; + } finally { + await runnableStreamConsumePromise; + } + } + streamEvents(input, options, streamOptions) { + let stream; + if (options.version === "v1") stream = this._streamEventsV1(input, options, streamOptions); + else if (options.version === "v2") stream = this._streamEventsV2(input, options, streamOptions); + else throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); + if (options.encoding === "text/event-stream") return convertToHttpEventStream(stream); + else return IterableReadableStream.fromAsyncGenerator(stream); + } + async *_streamEventsV2(input, options, streamOptions) { + const eventStreamer = new EventStreamCallbackHandler({ + ...streamOptions, + autoClose: false + }); + const config = ensureConfig(options); + const runId = config.runId ?? v4(); + config.runId = runId; + const callbacks = config.callbacks; + if (callbacks === void 0) config.callbacks = [eventStreamer]; + else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(eventStreamer); + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(eventStreamer, true); + config.callbacks = copiedCallbacks; + } + const abortController = new AbortController(); + const outerThis = this; + async function consumeRunnableStream() { + let signal; + let listener = null; + try { + if (options?.signal) if ("any" in AbortSignal) signal = AbortSignal.any([abortController.signal, options.signal]); + else { + signal = options.signal; + listener = () => { + abortController.abort(); + }; + options.signal.addEventListener("abort", listener, { once: true }); + } + else signal = abortController.signal; + const runnableStream = await outerThis.stream(input, { + ...config, + signal + }); + const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); + for await (const _ of tappedStream) if (abortController.signal.aborted) break; + } finally { + await eventStreamer.finish(); + if (signal && listener) signal.removeEventListener("abort", listener); + } + } + const runnableStreamConsumePromise = consumeRunnableStream(); + let firstEventSent = false; + let firstEventRunId; + try { + for await (const event of eventStreamer) { + if (!firstEventSent) { + event.data.input = input; + firstEventSent = true; + firstEventRunId = event.run_id; + yield event; + continue; + } + if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { + if (event.data?.input) delete event.data.input; + } + yield event; + } + } finally { + abortController.abort(); + await runnableStreamConsumePromise; + } + } + async *_streamEventsV1(input, options, streamOptions) { + let runLog; + let hasEncounteredStartEvent = false; + const config = ensureConfig(options); + const rootTags = config.tags ?? []; + const rootMetadata = config.metadata ?? {}; + const rootName = config.runName ?? this.getName(); + const logStreamCallbackHandler = new LogStreamCallbackHandler({ + ...streamOptions, + autoClose: false, + _schemaFormat: "streaming_events" + }); + const rootEventFilter = new _RootEventFilter({ ...streamOptions }); + const logStream = this._streamLog(input, logStreamCallbackHandler, config); + for await (const log of logStream) { + if (!runLog) runLog = RunLog.fromRunLogPatch(log); + else runLog = runLog.concat(log); + if (runLog.state === void 0) throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); + if (!hasEncounteredStartEvent) { + hasEncounteredStartEvent = true; + const state$2 = { ...runLog.state }; + const event = { + run_id: state$2.id, + event: `on_${state$2.type}_start`, + name: rootName, + tags: rootTags, + metadata: rootMetadata, + data: { input } + }; + if (rootEventFilter.includeEvent(event, state$2.type)) yield event; + } + const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]); + const dedupedPaths = [...new Set(paths)]; + for (const path of dedupedPaths) { + let eventType; + let data = {}; + const logEntry = runLog.state.logs[path]; + if (logEntry.end_time === void 0) if (logEntry.streamed_output.length > 0) eventType = "stream"; + else eventType = "start"; + else eventType = "end"; + if (eventType === "start") { + if (logEntry.inputs !== void 0) data.input = logEntry.inputs; + } else if (eventType === "end") { + if (logEntry.inputs !== void 0) data.input = logEntry.inputs; + data.output = logEntry.final_output; + } else if (eventType === "stream") { + const chunkCount = logEntry.streamed_output.length; + if (chunkCount !== 1) throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); + data = { chunk: logEntry.streamed_output[0] }; + logEntry.streamed_output = []; + } + yield { + event: `on_${logEntry.type}_${eventType}`, + name: logEntry.name, + run_id: logEntry.id, + tags: logEntry.tags, + metadata: logEntry.metadata, + data + }; + } + const { state: state$1 } = runLog; + if (state$1.streamed_output.length > 0) { + const chunkCount = state$1.streamed_output.length; + if (chunkCount !== 1) throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state$1.name}"`); + const data = { chunk: state$1.streamed_output[0] }; + state$1.streamed_output = []; + const event = { + event: `on_${state$1.type}_stream`, + run_id: state$1.id, + tags: rootTags, + metadata: rootMetadata, + name: rootName, + data + }; + if (rootEventFilter.includeEvent(event, state$1.type)) yield event; + } + } + const state = runLog?.state; + if (state !== void 0) { + const event = { + event: `on_${state.type}_end`, + name: rootName, + run_id: state.id, + tags: rootTags, + metadata: rootMetadata, + data: { output: state.final_output } + }; + if (rootEventFilter.includeEvent(event, state.type)) yield event; + } + } + static isRunnable(thing) { + return isRunnableInterface(thing); + } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError }) { + return new RunnableBinding({ + bound: this, + config: {}, + configFactories: [(config) => ({ callbacks: [new RootListenersTracer({ + config, + onStart, + onEnd, + onError + })] })] + }); + } + /** + * Convert a runnable to a tool. Return a new instance of `RunnableToolLike` + * which contains the runnable, name, description and schema. + * + * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable. + * + * @param fields + * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. + * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. + * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. + * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. + */ + asTool(fields) { + return convertRunnableToTool(this, fields); + } +}; +/** +* Wraps a runnable and applies partial config upon invocation. +* +* @example +* ```typescript +* import { +* type RunnableConfig, +* RunnableLambda, +* } from "@langchain/core/runnables"; +* +* const enhanceProfile = ( +* profile: Record, +* config?: RunnableConfig +* ) => { +* if (config?.configurable?.role) { +* return { ...profile, role: config.configurable.role }; +* } +* return profile; +* }; +* +* const runnable = RunnableLambda.from(enhanceProfile); +* +* // Bind configuration to the runnable to set the user's role dynamically +* const adminRunnable = runnable.withConfig({ configurable: { role: "Admin" } }); +* const userRunnable = runnable.withConfig({ configurable: { role: "User" } }); +* +* const result1 = await adminRunnable.invoke({ +* name: "Alice", +* email: "alice@example.com" +* }); +* +* // { name: "Alice", email: "alice@example.com", role: "Admin" } +* +* const result2 = await userRunnable.invoke({ +* name: "Bob", +* email: "bob@example.com" +* }); +* +* // { name: "Bob", email: "bob@example.com", role: "User" } +* ``` +*/ +var RunnableBinding = class RunnableBinding extends Runnable { + static lc_name() { + return "RunnableBinding"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + bound; + config; + kwargs; + configFactories; + constructor(fields) { + super(fields); + this.bound = fields.bound; + this.kwargs = fields.kwargs; + this.config = fields.config; + this.configFactories = fields.configFactories; + } + getName(suffix) { + return this.bound.getName(suffix); + } + async _mergeConfig(...options) { + const config = mergeConfigs(this.config, ...options); + return mergeConfigs(config, ...this.configFactories ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) : []); + } + withConfig(config) { + return new this.constructor({ + bound: this.bound, + kwargs: this.kwargs, + config: { + ...this.config, + ...config + } + }); + } + withRetry(fields) { + return new RunnableRetry({ + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + maxAttemptNumber: fields?.stopAfterAttempt, + ...fields + }); + } + async invoke(input, options) { + return this.bound.invoke(input, await this._mergeConfig(options, this.kwargs)); + } + async batch(inputs, options, batchOptions) { + const mergedOptions = Array.isArray(options) ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) : await this._mergeConfig(ensureConfig(options), this.kwargs); + return this.bound.batch(inputs, mergedOptions, batchOptions); + } + /** @internal */ + _concatOutputChunks(first, second) { + return this.bound._concatOutputChunks(first, second); + } + async *_streamIterator(input, options) { + yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + async stream(input, options) { + return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + async *transform(generator, options) { + yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); + } + streamEvents(input, options, streamOptions) { + const outerThis = this; + const generator = async function* () { + yield* outerThis.bound.streamEvents(input, { + ...await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs), + version: options.version + }, streamOptions); + }; + return IterableReadableStream.fromAsyncGenerator(generator()); + } + static isRunnableBinding(thing) { + return thing.bound && Runnable.isRunnable(thing.bound); + } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError }) { + return new RunnableBinding({ + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + configFactories: [(config) => ({ callbacks: [new RootListenersTracer({ + config, + onStart, + onEnd, + onError + })] })] + }); + } +}; +/** +* A runnable that delegates calls to another runnable +* with each element of the input sequence. +* @example +* ```typescript +* import { RunnableEach, RunnableLambda } from "@langchain/core/runnables"; +* +* const toUpperCase = (input: string): string => input.toUpperCase(); +* const addGreeting = (input: string): string => `Hello, ${input}!`; +* +* const upperCaseLambda = RunnableLambda.from(toUpperCase); +* const greetingLambda = RunnableLambda.from(addGreeting); +* +* const chain = new RunnableEach({ +* bound: upperCaseLambda.pipe(greetingLambda), +* }); +* +* const result = await chain.invoke(["alice", "bob", "carol"]) +* +* // ["Hello, ALICE!", "Hello, BOB!", "Hello, CAROL!"] +* ``` +*/ +var RunnableEach = class RunnableEach extends Runnable { + static lc_name() { + return "RunnableEach"; + } + lc_serializable = true; + lc_namespace = ["langchain_core", "runnables"]; + bound; + constructor(fields) { + super(fields); + this.bound = fields.bound; + } + /** + * Invokes the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(inputs, config) { + return this._callWithConfig(this._invoke.bind(this), inputs, config); + } + /** + * A helper method that is used to invoke the runnable with the specified input and configuration. + * @param input The input to invoke the runnable with. + * @param config The configuration to invoke the runnable with. + * @returns A promise that resolves to the output of the runnable. + */ + async _invoke(inputs, config, runManager) { + return this.bound.batch(inputs, config_patchConfig(config, { callbacks: runManager?.getChild() })); + } + /** + * Bind lifecycle listeners to a Runnable, returning a new Runnable. + * The Run object contains information about the run, including its id, + * type, input, output, error, startTime, endTime, and any tags or metadata + * added to the run. + * + * @param {Object} params - The object containing the callback functions. + * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. + * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. + * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. + */ + withListeners({ onStart, onEnd, onError }) { + return new RunnableEach({ bound: this.bound.withListeners({ + onStart, + onEnd, + onError + }) }); + } +}; +/** +* Base class for runnables that can be retried a +* specified number of times. +* @example +* ```typescript +* import { +* RunnableLambda, +* RunnableRetry, +* } from "@langchain/core/runnables"; +* +* // Simulate an API call that fails +* const simulateApiCall = (input: string): string => { +* console.log(`Attempting API call with input: ${input}`); +* throw new Error("API call failed due to network issue"); +* }; +* +* const apiCallLambda = RunnableLambda.from(simulateApiCall); +* +* // Apply retry logic using the .withRetry() method +* const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 }); +* +* // Alternatively, create a RunnableRetry instance manually +* const manualRetry = new RunnableRetry({ +* bound: apiCallLambda, +* maxAttemptNumber: 3, +* config: {}, +* }); +* +* // Example invocation using the .withRetry() method +* const res = await apiCallWithRetry +* .invoke("Request 1") +* .catch((error) => { +* console.error("Failed after multiple retries:", error.message); +* }); +* +* // Example invocation using the manual retry instance +* const res2 = await manualRetry +* .invoke("Request 2") +* .catch((error) => { +* console.error("Failed after multiple retries:", error.message); +* }); +* ``` +*/ +var RunnableRetry = class extends RunnableBinding { + static lc_name() { + return "RunnableRetry"; + } + lc_namespace = ["langchain_core", "runnables"]; + maxAttemptNumber = 3; + onFailedAttempt = () => {}; + constructor(fields) { + super(fields); + this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; + this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; + } + _patchConfigForRetry(attempt, config, runManager) { + const tag = attempt > 1 ? `retry:attempt:${attempt}` : void 0; + return config_patchConfig(config, { callbacks: runManager?.getChild(tag) }); + } + async _invoke(input, config, runManager) { + return p_retry_pRetry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { + onFailedAttempt: ({ error }) => this.onFailedAttempt(error, input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true + }); + } + /** + * Method that invokes the runnable with the specified input, run manager, + * and config. It handles the retry logic by catching any errors and + * recursively invoking itself with the updated config for the next retry + * attempt. + * @param input The input for the runnable. + * @param runManager The run manager for the runnable. + * @param config The config for the runnable. + * @returns A promise that resolves to the output of the runnable. + */ + async invoke(input, config) { + return this._callWithConfig(this._invoke.bind(this), input, config); + } + async _batch(inputs, configs, runManagers, batchOptions) { + const resultsMap = {}; + try { + await p_retry_pRetry(async (attemptNumber) => { + const remainingIndexes = inputs.map((_, i) => i).filter((i) => resultsMap[i.toString()] === void 0 || resultsMap[i.toString()] instanceof Error); + const remainingInputs = remainingIndexes.map((i) => inputs[i]); + const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); + const results = await super.batch(remainingInputs, patchedConfigs, { + ...batchOptions, + returnExceptions: true + }); + let firstException; + for (let i = 0; i < results.length; i += 1) { + const result = results[i]; + const resultMapIndex = remainingIndexes[i]; + if (result instanceof Error) { + if (firstException === void 0) { + firstException = result; + firstException.input = remainingInputs[i]; + } + } + resultsMap[resultMapIndex.toString()] = result; + } + if (firstException) throw firstException; + return results; + }, { + onFailedAttempt: ({ error }) => this.onFailedAttempt(error, error.input), + retries: Math.max(this.maxAttemptNumber - 1, 0), + randomize: true + }); + } catch (e) { + if (batchOptions?.returnExceptions !== true) throw e; + } + return Object.keys(resultsMap).sort((a, b) => parseInt(a, 10) - parseInt(b, 10)).map((key) => resultsMap[parseInt(key, 10)]); + } + async batch(inputs, options, batchOptions) { + return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); + } +}; +/** +* A sequence of runnables, where the output of each is the input of the next. +* @example +* ```typescript +* const promptTemplate = PromptTemplate.fromTemplate( +* "Tell me a joke about {topic}", +* ); +* const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({ model: "gpt-4o-mini" })]); +* const result = await chain.invoke({ topic: "bears" }); +* ``` +*/ +var RunnableSequence = class RunnableSequence extends Runnable { + static lc_name() { + return "RunnableSequence"; + } + first; + middle = []; + last; + omitSequenceTags = false; + lc_serializable = true; + lc_namespace = ["langchain_core", "runnables"]; + constructor(fields) { + super(fields); + this.first = fields.first; + this.middle = fields.middle ?? this.middle; + this.last = fields.last; + this.name = fields.name; + this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; + } + get steps() { + return [ + this.first, + ...this.middle, + this.last + ]; + } + async invoke(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, void 0, void 0, void 0, config?.runName); + delete config.runId; + let nextStepInput = input; + let finalOutput; + try { + const initialSteps = [this.first, ...this.middle]; + for (let i = 0; i < initialSteps.length; i += 1) { + const step = initialSteps[i]; + const promise = step.invoke(nextStepInput, config_patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) })); + nextStepInput = await raceWithSignal(promise, options?.signal); + } + if (options?.signal?.aborted) throw getAbortSignalError(options.signal); + finalOutput = await this.last.invoke(nextStepInput, config_patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${this.steps.length}`) })); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); + return finalOutput; + } + async batch(inputs, options, batchOptions) { + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName); + delete configList[i].runId; + return handleStartRes; + })); + let nextStepInputs = inputs; + try { + for (let i = 0; i < this.steps.length; i += 1) { + const step = this.steps[i]; + const promise = step.batch(nextStepInputs, runManagers.map((runManager, j) => { + const childRunManager = runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`); + return config_patchConfig(configList[j], { callbacks: childRunManager }); + }), batchOptions); + nextStepInputs = await raceWithSignal(promise, configList[0]?.signal); + } + } catch (e) { + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); + throw e; + } + await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(nextStepInputs, "output")))); + return nextStepInputs; + } + /** @internal */ + _concatOutputChunks(first, second) { + return this.last._concatOutputChunks(first, second); + } + async *_streamIterator(input, options) { + const callbackManager_ = await getCallbackManagerForConfig(options); + const { runId,...otherOptions } = options ?? {}; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherOptions?.runName); + const steps = [ + this.first, + ...this.middle, + this.last + ]; + let concatSupported = true; + let finalOutput; + async function* inputGenerator() { + yield input; + } + try { + let finalGenerator = steps[0].transform(inputGenerator(), config_patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:1`) })); + for (let i = 1; i < steps.length; i += 1) { + const step = steps[i]; + finalGenerator = await step.transform(finalGenerator, config_patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) })); + } + for await (const chunk of finalGenerator) { + options?.signal?.throwIfAborted(); + yield chunk; + if (concatSupported) if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = void 0; + concatSupported = false; + } + } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); + } + getGraph(config) { + const graph = new Graph(); + let currentLastNode = null; + this.steps.forEach((step, index) => { + const stepGraph = step.getGraph(config); + if (index !== 0) stepGraph.trimFirstNode(); + if (index !== this.steps.length - 1) stepGraph.trimLastNode(); + graph.extend(stepGraph); + const stepFirstNode = stepGraph.firstNode(); + if (!stepFirstNode) throw new Error(`Runnable ${step} has no first node`); + if (currentLastNode) graph.addEdge(currentLastNode, stepFirstNode); + currentLastNode = stepGraph.lastNode(); + }); + return graph; + } + pipe(coerceable) { + if (RunnableSequence.isRunnableSequence(coerceable)) return new RunnableSequence({ + first: this.first, + middle: this.middle.concat([ + this.last, + coerceable.first, + ...coerceable.middle + ]), + last: coerceable.last, + name: this.name ?? coerceable.name + }); + else return new RunnableSequence({ + first: this.first, + middle: [...this.middle, this.last], + last: _coerceToRunnable(coerceable), + name: this.name + }); + } + static isRunnableSequence(thing) { + return Array.isArray(thing.middle) && Runnable.isRunnable(thing); + } + static from([first, ...runnables], nameOrFields) { + let extra = {}; + if (typeof nameOrFields === "string") extra.name = nameOrFields; + else if (nameOrFields !== void 0) extra = nameOrFields; + return new RunnableSequence({ + ...extra, + first: _coerceToRunnable(first), + middle: runnables.slice(0, -1).map(_coerceToRunnable), + last: _coerceToRunnable(runnables[runnables.length - 1]) + }); + } +}; +/** +* A runnable that runs a mapping of runnables in parallel, +* and returns a mapping of their outputs. +* @example +* ```typescript +* const mapChain = RunnableMap.from({ +* joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe( +* new ChatAnthropic({}), +* ), +* poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe( +* new ChatAnthropic({}), +* ), +* }); +* const result = await mapChain.invoke({ topic: "bear" }); +* ``` +*/ +var RunnableMap = class RunnableMap extends Runnable { + static lc_name() { + return "RunnableMap"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + steps; + getStepsKeys() { + return Object.keys(this.steps); + } + constructor(fields) { + super(fields); + this.steps = {}; + for (const [key, value] of Object.entries(fields.steps)) this.steps[key] = _coerceToRunnable(value); + } + static from(steps) { + return new RunnableMap({ steps }); + } + async invoke(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { input }, config.runId, void 0, void 0, void 0, config?.runName); + delete config.runId; + const output = {}; + try { + const promises = Object.entries(this.steps).map(async ([key, runnable]) => { + output[key] = await runnable.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`map:key:${key}`) })); + }); + await raceWithSignal(Promise.all(promises), options?.signal); + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(output); + return output; + } + async *_transform(generator, runManager, options) { + const steps = { ...this.steps }; + const inputCopies = atee(generator, Object.keys(steps).length); + const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => { + const gen = runnable.transform(inputCopies[i], config_patchConfig(options, { callbacks: runManager?.getChild(`map:key:${key}`) })); + return [key, gen.next().then((result) => ({ + key, + gen, + result + }))]; + })); + while (tasks.size) { + const promise = Promise.race(tasks.values()); + const { key, result, gen } = await raceWithSignal(promise, options?.signal); + tasks.delete(key); + if (!result.done) { + yield { [key]: result.value }; + tasks.set(key, gen.next().then((result$1) => ({ + key, + gen, + result: result$1 + }))); + } + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +}; +/** +* A runnable that wraps a traced LangSmith function. +*/ +var RunnableTraceable = class RunnableTraceable extends Runnable { + lc_serializable = false; + lc_namespace = ["langchain_core", "runnables"]; + func; + constructor(fields) { + super(fields); + if (!isTraceableFunction(fields.func)) throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); + this.func = fields.func; + } + async invoke(input, options) { + const [config] = this._getOptionsList(options ?? {}, 1); + const callbacks = await getCallbackManagerForConfig(config); + const promise = this.func(config_patchConfig(config, { callbacks }), input); + return raceWithSignal(promise, config?.signal); + } + async *_streamIterator(input, options) { + const [config] = this._getOptionsList(options ?? {}, 1); + const result = await this.invoke(input, options); + if (isAsyncIterable(result)) { + for await (const item of result) { + config?.signal?.throwIfAborted(); + yield item; + } + return; + } + if (isIterator(result)) { + while (true) { + config?.signal?.throwIfAborted(); + const state = result.next(); + if (state.done) break; + yield state.value; + } + return; + } + yield result; + } + static from(func) { + return new RunnableTraceable({ func }); + } +}; +function assertNonTraceableFunction(func) { + if (isTraceableFunction(func)) throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); +} +/** +* A runnable that wraps an arbitrary function that takes a single argument. +* @example +* ```typescript +* import { RunnableLambda } from "@langchain/core/runnables"; +* +* const add = (input: { x: number; y: number }) => input.x + input.y; +* +* const multiply = (input: { value: number; multiplier: number }) => +* input.value * input.multiplier; +* +* // Create runnables for the functions +* const addLambda = RunnableLambda.from(add); +* const multiplyLambda = RunnableLambda.from(multiply); +* +* // Chain the lambdas for a mathematical operation +* const chainedLambda = addLambda.pipe((result) => +* multiplyLambda.invoke({ value: result, multiplier: 2 }) +* ); +* +* // Example invocation of the chainedLambda +* const result = await chainedLambda.invoke({ x: 2, y: 3 }); +* +* // Will log "10" (since (2 + 3) * 2 = 10) +* ``` +*/ +var RunnableLambda = class RunnableLambda extends Runnable { + static lc_name() { + return "RunnableLambda"; + } + lc_namespace = ["langchain_core", "runnables"]; + func; + constructor(fields) { + if (isTraceableFunction(fields.func)) return RunnableTraceable.from(fields.func); + super(fields); + assertNonTraceableFunction(fields.func); + this.func = fields.func; + } + static from(func) { + return new RunnableLambda({ func }); + } + async _invoke(input, config, runManager) { + return new Promise((resolve, reject) => { + const childConfig = config_patchConfig(config, { + callbacks: runManager?.getChild(), + recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 + }); + async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { + try { + let output = await this.func(input, { ...childConfig }); + if (output && Runnable.isRunnable(output)) { + if (config?.recursionLimit === 0) throw new Error("Recursion limit reached."); + output = await output.invoke(input, { + ...childConfig, + recursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 + }); + } else if (isAsyncIterable(output)) { + let finalOutput; + for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = chunk; + } + } + output = finalOutput; + } else if (isIterableIterator(output)) { + let finalOutput; + for (const chunk of consumeIteratorInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = this._concatOutputChunks(finalOutput, chunk); + } catch { + finalOutput = chunk; + } + } + output = finalOutput; + } + resolve(output); + } catch (e) { + reject(e); + } + }); + }); + } + async invoke(input, options) { + return this._callWithConfig(this._invoke.bind(this), input, options); + } + async *_transform(generator, runManager, config) { + let finalChunk; + for await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk; + else try { + finalChunk = this._concatOutputChunks(finalChunk, chunk); + } catch { + finalChunk = chunk; + } + const childConfig = config_patchConfig(config, { + callbacks: runManager?.getChild(), + recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 + }); + const output = await new Promise((resolve, reject) => { + async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { + try { + const res = await this.func(finalChunk, { + ...childConfig, + config: childConfig + }); + resolve(res); + } catch (e) { + reject(e); + } + }); + }); + if (output && Runnable.isRunnable(output)) { + if (config?.recursionLimit === 0) throw new Error("Recursion limit reached."); + const stream = await output.stream(finalChunk, childConfig); + for await (const chunk of stream) yield chunk; + } else if (isAsyncIterable(output)) for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + yield chunk; + } + else if (isIterableIterator(output)) for (const chunk of consumeIteratorInContext(childConfig, output)) { + config?.signal?.throwIfAborted(); + yield chunk; + } + else yield output; + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +}; +/** +* A runnable that runs a mapping of runnables in parallel, +* and returns a mapping of their outputs. +* @example +* ```typescript +* import { +* RunnableLambda, +* RunnableParallel, +* } from "@langchain/core/runnables"; +* +* const addYears = (age: number): number => age + 5; +* const yearsToFifty = (age: number): number => 50 - age; +* const yearsToHundred = (age: number): number => 100 - age; +* +* const addYearsLambda = RunnableLambda.from(addYears); +* const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty); +* const milestoneHundredLambda = RunnableLambda.from(yearsToHundred); +* +* // Pipe will coerce objects into RunnableParallel by default, but we +* // explicitly instantiate one here to demonstrate +* const sequence = addYearsLambda.pipe( +* RunnableParallel.from({ +* years_to_fifty: milestoneFiftyLambda, +* years_to_hundred: milestoneHundredLambda, +* }) +* ); +* +* // Invoke the sequence with a single age input +* const res = await sequence.invoke(25); +* +* // { years_to_fifty: 20, years_to_hundred: 70 } +* ``` +*/ +var RunnableParallel = class extends RunnableMap {}; +/** +* A Runnable that can fallback to other Runnables if it fails. +* External APIs (e.g., APIs for a language model) may at times experience +* degraded performance or even downtime. +* +* In these cases, it can be useful to have a fallback Runnable that can be +* used in place of the original Runnable (e.g., fallback to another LLM provider). +* +* Fallbacks can be defined at the level of a single Runnable, or at the level +* of a chain of Runnables. Fallbacks are tried in order until one succeeds or +* all fail. +* +* While you can instantiate a `RunnableWithFallbacks` directly, it is usually +* more convenient to use the `withFallbacks` method on an existing Runnable. +* +* When streaming, fallbacks will only be called on failures during the initial +* stream creation. Errors that occur after a stream starts will not fallback +* to the next Runnable. +* +* @example +* ```typescript +* import { +* RunnableLambda, +* RunnableWithFallbacks, +* } from "@langchain/core/runnables"; +* +* const primaryOperation = (input: string): string => { +* if (input !== "safe") { +* throw new Error("Primary operation failed due to unsafe input"); +* } +* return `Processed: ${input}`; +* }; +* +* // Define a fallback operation that processes the input differently +* const fallbackOperation = (input: string): string => +* `Fallback processed: ${input}`; +* +* const primaryRunnable = RunnableLambda.from(primaryOperation); +* const fallbackRunnable = RunnableLambda.from(fallbackOperation); +* +* // Apply the fallback logic using the .withFallbacks() method +* const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]); +* +* // Alternatively, create a RunnableWithFallbacks instance manually +* const manualFallbackChain = new RunnableWithFallbacks({ +* runnable: primaryRunnable, +* fallbacks: [fallbackRunnable], +* }); +* +* // Example invocation using .withFallbacks() +* const res = await runnableWithFallback +* .invoke("unsafe input") +* .catch((error) => { +* console.error("Failed after all attempts:", error.message); +* }); +* +* // "Fallback processed: unsafe input" +* +* // Example invocation using manual instantiation +* const res = await manualFallbackChain +* .invoke("safe") +* .catch((error) => { +* console.error("Failed after all attempts:", error.message); +* }); +* +* // "Processed: safe" +* ``` +*/ +var RunnableWithFallbacks = class extends Runnable { + static lc_name() { + return "RunnableWithFallbacks"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + runnable; + fallbacks; + constructor(fields) { + super(fields); + this.runnable = fields.runnable; + this.fallbacks = fields.fallbacks; + } + *runnables() { + yield this.runnable; + for (const fallback of this.fallbacks) yield fallback; + } + async invoke(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const { runId,...otherConfigFields } = config; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); + const childConfig = config_patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); + const res = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { + let firstError; + for (const runnable of this.runnables()) { + config?.signal?.throwIfAborted(); + try { + const output = await runnable.invoke(input, childConfig); + await runManager?.handleChainEnd(base_coerceToDict(output, "output")); + return output; + } catch (e) { + if (firstError === void 0) firstError = e; + } + } + if (firstError === void 0) throw new Error("No error stored at end of fallback."); + await runManager?.handleChainError(firstError); + throw firstError; + }); + return res; + } + async *_streamIterator(input, options) { + const config = ensureConfig(options); + const callbackManager_ = await getCallbackManagerForConfig(config); + const { runId,...otherConfigFields } = config; + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); + let firstError; + let stream; + for (const runnable of this.runnables()) { + config?.signal?.throwIfAborted(); + const childConfig = config_patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); + try { + const originalStream = await runnable.stream(input, childConfig); + stream = consumeAsyncIterableInContext(childConfig, originalStream); + break; + } catch (e) { + if (firstError === void 0) firstError = e; + } + } + if (stream === void 0) { + const error = firstError ?? /* @__PURE__ */ new Error("No error stored at end of fallback."); + await runManager?.handleChainError(error); + throw error; + } + let output; + try { + for await (const chunk of stream) { + yield chunk; + try { + output = output === void 0 ? output : this._concatOutputChunks(output, chunk); + } catch { + output = void 0; + } + } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(base_coerceToDict(output, "output")); + } + async batch(inputs, options, batchOptions) { + if (batchOptions?.returnExceptions) throw new Error("Not implemented."); + const configList = this._getOptionsList(options ?? {}, inputs.length); + const callbackManagers = await Promise.all(configList.map((config) => getCallbackManagerForConfig(config))); + const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { + const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName); + delete configList[i].runId; + return handleStartRes; + })); + let firstError; + for (const runnable of this.runnables()) { + configList[0].signal?.throwIfAborted(); + try { + const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => config_patchConfig(configList[j], { callbacks: runManager?.getChild() })), batchOptions); + await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(base_coerceToDict(outputs[i], "output")))); + return outputs; + } catch (e) { + if (firstError === void 0) firstError = e; + } + } + if (!firstError) throw new Error("No error stored at end of fallbacks."); + await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); + throw firstError; + } +}; +function _coerceToRunnable(coerceable) { + if (typeof coerceable === "function") return new RunnableLambda({ func: coerceable }); + else if (Runnable.isRunnable(coerceable)) return coerceable; + else if (!Array.isArray(coerceable) && typeof coerceable === "object") { + const runnables = {}; + for (const [key, value] of Object.entries(coerceable)) runnables[key] = _coerceToRunnable(value); + return new RunnableMap({ steps: runnables }); + } else throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`); +} +/** +* A runnable that assigns key-value pairs to inputs of type `Record`. +* @example +* ```typescript +* import { +* RunnableAssign, +* RunnableLambda, +* RunnableParallel, +* } from "@langchain/core/runnables"; +* +* const calculateAge = (x: { birthYear: number }): { age: number } => { +* const currentYear = new Date().getFullYear(); +* return { age: currentYear - x.birthYear }; +* }; +* +* const createGreeting = (x: { name: string }): { greeting: string } => { +* return { greeting: `Hello, ${x.name}!` }; +* }; +* +* const mapper = RunnableParallel.from({ +* age_step: RunnableLambda.from(calculateAge), +* greeting_step: RunnableLambda.from(createGreeting), +* }); +* +* const runnableAssign = new RunnableAssign({ mapper }); +* +* const res = await runnableAssign.invoke({ name: "Alice", birthYear: 1990 }); +* +* // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } } +* ``` +*/ +var RunnableAssign = class extends Runnable { + static lc_name() { + return "RunnableAssign"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + mapper; + constructor(fields) { + if (fields instanceof RunnableMap) fields = { mapper: fields }; + super(fields); + this.mapper = fields.mapper; + } + async invoke(input, options) { + const mapperResult = await this.mapper.invoke(input, options); + return { + ...input, + ...mapperResult + }; + } + async *_transform(generator, runManager, options) { + const mapperKeys = this.mapper.getStepsKeys(); + const [forPassthrough, forMapper] = atee(generator); + const mapperOutput = this.mapper.transform(forMapper, config_patchConfig(options, { callbacks: runManager?.getChild() })); + const firstMapperChunkPromise = mapperOutput.next(); + for await (const chunk of forPassthrough) { + if (typeof chunk !== "object" || Array.isArray(chunk)) throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); + const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); + if (Object.keys(filtered).length > 0) yield filtered; + } + yield (await firstMapperChunkPromise).value; + for await (const chunk of mapperOutput) yield chunk; + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +}; +/** +* A runnable that assigns key-value pairs to inputs of type `Record`. +* Useful for streaming, can be automatically created and chained by calling `runnable.pick();`. +* @example +* ```typescript +* import { RunnablePick } from "@langchain/core/runnables"; +* +* const inputData = { +* name: "John", +* age: 30, +* city: "New York", +* country: "USA", +* email: "john.doe@example.com", +* phone: "+1234567890", +* }; +* +* const basicInfoRunnable = new RunnablePick(["name", "city"]); +* +* // Example invocation +* const res = await basicInfoRunnable.invoke(inputData); +* +* // { name: 'John', city: 'New York' } +* ``` +*/ +var RunnablePick = class extends Runnable { + static lc_name() { + return "RunnablePick"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + keys; + constructor(fields) { + if (typeof fields === "string" || Array.isArray(fields)) fields = { keys: fields }; + super(fields); + this.keys = fields.keys; + } + async _pick(input) { + if (typeof this.keys === "string") return input[this.keys]; + else { + const picked = this.keys.map((key) => [key, input[key]]).filter((v) => v[1] !== void 0); + return picked.length === 0 ? void 0 : Object.fromEntries(picked); + } + } + async invoke(input, options) { + return this._callWithConfig(this._pick.bind(this), input, options); + } + async *_transform(generator) { + for await (const chunk of generator) { + const picked = await this._pick(chunk); + if (picked !== void 0) yield picked; + } + } + transform(generator, options) { + return this._transformStreamWithConfig(generator, this._transform.bind(this), options); + } + async stream(input, options) { + async function* generator() { + yield input; + } + const config = ensureConfig(options); + const wrappedGenerator = new AsyncGeneratorWithSetup({ + generator: this.transform(generator(), config), + config + }); + await wrappedGenerator.setup; + return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); + } +}; +var RunnableToolLike = class extends RunnableBinding { + name; + description; + schema; + constructor(fields) { + const sequence = RunnableSequence.from([RunnableLambda.from(async (input) => { + let toolInput; + if (_isToolCall(input)) try { + toolInput = await interopParseAsync(this.schema, input.args); + } catch { + throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); + } + else toolInput = input; + return toolInput; + }).withConfig({ runName: `${fields.name}:parse_input` }), fields.bound]).withConfig({ runName: fields.name }); + super({ + bound: sequence, + config: fields.config ?? {} + }); + this.name = fields.name; + this.description = fields.description; + this.schema = fields.schema; + } + static lc_name() { + return "RunnableToolLike"; + } +}; +/** +* Given a runnable and a Zod schema, convert the runnable to a tool. +* +* @template RunInput The input type for the runnable. +* @template RunOutput The output type for the runnable. +* +* @param {Runnable} runnable The runnable to convert to a tool. +* @param fields +* @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. +* @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. +* @param {InteropZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. +* @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. +*/ +function convertRunnableToTool(runnable, fields) { + const name = fields.name ?? runnable.getName(); + const description = fields.description ?? getSchemaDescription(fields.schema); + if (isSimpleStringZodSchema(fields.schema)) return new RunnableToolLike({ + name, + description, + schema: objectType({ input: stringType() }).transform((input) => input.input), + bound: runnable + }); + return new RunnableToolLike({ + name, + description, + schema: fields.schema, + bound: runnable + }); +} + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/transformers.js + + + + + + + + + + + +//#region src/messages/transformers.ts +const _isMessageType = (msg, types) => { + const typesAsStrings = [...new Set(types?.map((t) => { + if (typeof t === "string") return t; + const instantiatedMsgClass = new t({}); + if (!("getType" in instantiatedMsgClass) || typeof instantiatedMsgClass.getType !== "function") throw new Error("Invalid type provided."); + return instantiatedMsgClass.getType(); + }))]; + const msgType = msg.getType(); + return typesAsStrings.some((t) => t === msgType); +}; +function filterMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) return _filterMessages(messagesOrOptions, options); + return RunnableLambda.from((input) => { + return _filterMessages(input, messagesOrOptions); + }); +} +function _filterMessages(messages, options = {}) { + const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds } = options; + const filtered = []; + for (const msg of messages) { + if (excludeNames && msg.name && excludeNames.includes(msg.name)) continue; + else if (excludeTypes && _isMessageType(msg, excludeTypes)) continue; + else if (excludeIds && msg.id && excludeIds.includes(msg.id)) continue; + if (!(includeTypes || includeIds || includeNames)) filtered.push(msg); + else if (includeNames && msg.name && includeNames.some((iName) => iName === msg.name)) filtered.push(msg); + else if (includeTypes && _isMessageType(msg, includeTypes)) filtered.push(msg); + else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) filtered.push(msg); + } + return filtered; +} +function mergeMessageRuns(messages) { + if (Array.isArray(messages)) return _mergeMessageRuns(messages); + return RunnableLambda.from(_mergeMessageRuns); +} +function _mergeMessageRuns(messages) { + if (!messages.length) return []; + const merged = []; + for (const msg of messages) { + const curr = msg; + const last = merged.pop(); + if (!last) merged.push(curr); + else if (curr.getType() === "tool" || !(curr.getType() === last.getType())) merged.push(last, curr); + else { + const lastChunk = convertToChunk(last); + const currChunk = convertToChunk(curr); + const mergedChunks = lastChunk.concat(currChunk); + if (typeof lastChunk.content === "string" && typeof currChunk.content === "string") mergedChunks.content = `${lastChunk.content}\n${currChunk.content}`; + merged.push(_chunkToMsg(mergedChunks)); + } + } + return merged; +} +function trimMessages(messagesOrOptions, options) { + if (Array.isArray(messagesOrOptions)) { + const messages = messagesOrOptions; + if (!options) throw new Error("Options parameter is required when providing messages."); + return _trimMessagesHelper(messages, options); + } else { + const trimmerOptions = messagesOrOptions; + return RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ runName: "trim_messages" }); + } +} +async function _trimMessagesHelper(messages, options) { + const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter } = options; + if (startOn && strategy === "first") throw new Error("`startOn` should only be specified if `strategy` is 'last'."); + if (includeSystem && strategy === "first") throw new Error("`includeSystem` should only be specified if `strategy` is 'last'."); + let listTokenCounter; + if ("getNumTokens" in tokenCounter) listTokenCounter = async (msgs) => { + const tokenCounts = await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content))); + return tokenCounts.reduce((sum, count) => sum + count, 0); + }; + else listTokenCounter = async (msgs) => tokenCounter(msgs); + let textSplitterFunc = defaultTextSplitter; + if (textSplitter) if ("splitText" in textSplitter) textSplitterFunc = textSplitter.splitText; + else textSplitterFunc = async (text) => textSplitter(text); + if (strategy === "first") return _firstMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + partialStrategy: allowPartial ? "first" : void 0, + endOn + }); + else if (strategy === "last") return _lastMaxTokens(messages, { + maxTokens, + tokenCounter: listTokenCounter, + textSplitter: textSplitterFunc, + allowPartial, + includeSystem, + startOn, + endOn + }); + else throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`); +} +async function _firstMaxTokens(messages, options) { + const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options; + let messagesCopy = [...messages]; + let idx = 0; + for (let i = 0; i < messagesCopy.length; i += 1) { + const remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy; + if (await tokenCounter(remainingMessages) <= maxTokens) { + idx = messagesCopy.length - i; + break; + } + } + if (idx < messagesCopy.length && partialStrategy) { + let includedPartial = false; + if (Array.isArray(messagesCopy[idx].content)) { + const excluded = messagesCopy[idx]; + if (typeof excluded.content === "string") throw new Error("Expected content to be an array."); + const numBlock = excluded.content.length; + const reversedContent = partialStrategy === "last" ? [...excluded.content].reverse() : excluded.content; + for (let i = 1; i <= numBlock; i += 1) { + const partialContent = partialStrategy === "first" ? reversedContent.slice(0, i) : reversedContent.slice(-i); + const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + const updatedMessage = _switchTypeToMessage(excluded.getType(), { + ...fields, + content: partialContent + }); + const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage]; + if (await tokenCounter(slicedMessages) <= maxTokens) { + messagesCopy = slicedMessages; + idx += 1; + includedPartial = true; + } else break; + } + if (includedPartial && partialStrategy === "last") excluded.content = [...reversedContent].reverse(); + } + if (!includedPartial) { + const excluded = messagesCopy[idx]; + let text; + if (Array.isArray(excluded.content) && excluded.content.some((block) => typeof block === "string" || block.type === "text")) { + const textBlock = excluded.content.find((block) => block.type === "text" && block.text); + text = textBlock?.text; + } else if (typeof excluded.content === "string") text = excluded.content; + if (text) { + const splitTexts = await textSplitter(text); + const numSplits = splitTexts.length; + if (partialStrategy === "last") splitTexts.reverse(); + for (let _ = 0; _ < numSplits - 1; _ += 1) { + splitTexts.pop(); + excluded.content = splitTexts.join(""); + if (await tokenCounter([...messagesCopy.slice(0, idx), excluded]) <= maxTokens) { + if (partialStrategy === "last") excluded.content = [...splitTexts].reverse().join(""); + messagesCopy = [...messagesCopy.slice(0, idx), excluded]; + idx += 1; + break; + } + } + } + } + } + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) idx -= 1; + } + return messagesCopy.slice(0, idx); +} +async function _lastMaxTokens(messages, options) { + const { allowPartial = false, includeSystem = false, endOn, startOn,...rest } = options; + let messagesCopy = messages.map((message) => { + const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); + return _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message)); + }); + if (endOn) { + const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; + while (messagesCopy.length > 0 && !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) messagesCopy = messagesCopy.slice(0, -1); + } + const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system"; + let reversed_ = swappedSystem ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) : messagesCopy.reverse(); + reversed_ = await _firstMaxTokens(reversed_, { + ...rest, + partialStrategy: allowPartial ? "last" : void 0, + endOn: startOn + }); + if (swappedSystem) return [reversed_[0], ...reversed_.slice(1).reverse()]; + else return reversed_.reverse(); +} +const _MSG_CHUNK_MAP = { + human: { + message: HumanMessage, + messageChunk: HumanMessageChunk + }, + ai: { + message: AIMessage, + messageChunk: AIMessageChunk + }, + system: { + message: SystemMessage, + messageChunk: SystemMessageChunk + }, + developer: { + message: SystemMessage, + messageChunk: SystemMessageChunk + }, + tool: { + message: ToolMessage, + messageChunk: ToolMessageChunk + }, + function: { + message: FunctionMessage, + messageChunk: FunctionMessageChunk + }, + generic: { + message: ChatMessage, + messageChunk: ChatMessageChunk + }, + remove: { + message: RemoveMessage, + messageChunk: RemoveMessage + } +}; +function _switchTypeToMessage(messageType, fields, returnChunk) { + let chunk; + let msg; + switch (messageType) { + case "human": + if (returnChunk) chunk = new HumanMessageChunk(fields); + else msg = new HumanMessage(fields); + break; + case "ai": + if (returnChunk) { + let aiChunkFields = { ...fields }; + if ("tool_calls" in aiChunkFields) aiChunkFields = { + ...aiChunkFields, + tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ + ...tc, + type: "tool_call_chunk", + index: void 0, + args: JSON.stringify(tc.args) + })) + }; + chunk = new AIMessageChunk(aiChunkFields); + } else msg = new AIMessage(fields); + break; + case "system": + if (returnChunk) chunk = new SystemMessageChunk(fields); + else msg = new SystemMessage(fields); + break; + case "developer": + if (returnChunk) chunk = new SystemMessageChunk({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer" + } + }); + else msg = new SystemMessage({ + ...fields, + additional_kwargs: { + ...fields.additional_kwargs, + __openai_role__: "developer" + } + }); + break; + case "tool": + if ("tool_call_id" in fields) if (returnChunk) chunk = new ToolMessageChunk(fields); + else msg = new ToolMessage(fields); + else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined."); + break; + case "function": + if (returnChunk) chunk = new FunctionMessageChunk(fields); + else { + if (!fields.name) throw new Error("FunctionMessage must have a 'name' field"); + msg = new FunctionMessage(fields); + } + break; + case "generic": + if ("role" in fields) if (returnChunk) chunk = new ChatMessageChunk(fields); + else msg = new ChatMessage(fields); + else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined."); + break; + default: throw new Error(`Unrecognized message type ${messageType}`); + } + if (returnChunk && chunk) return chunk; + if (msg) return msg; + throw new Error(`Unrecognized message type ${messageType}`); +} +function _chunkToMsg(chunk) { + const chunkType = chunk.getType(); + let msg; + const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_"))); + if (chunkType in _MSG_CHUNK_MAP) msg = _switchTypeToMessage(chunkType, fields); + if (!msg) throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`); + return msg; +} +/** +* The default text splitter function that splits text by newlines. +* +* @param {string} text +* @returns A promise that resolves to an array of strings split by newlines. +*/ +function defaultTextSplitter(text) { + const splits = text.split("\n"); + return Promise.resolve([...splits.slice(0, -1).map((s) => `${s}\n`), splits[splits.length - 1]]); +} + +//#endregion + +//# sourceMappingURL=transformers.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/tools.js +//#region src/messages/content/tools.ts +const KNOWN_BLOCK_TYPES = [ + "tool_call", + "tool_call_chunk", + "invalid_tool_call", + "server_tool_call", + "server_tool_call_chunk", + "server_tool_call_result" +]; + +//#endregion + +//# sourceMappingURL=tools.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/multimodal.js +//#region src/messages/content/multimodal.ts +const multimodal_KNOWN_BLOCK_TYPES = [ + "image", + "video", + "audio", + "text-plain", + "file" +]; + +//#endregion + +//# sourceMappingURL=multimodal.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/index.js + + + +//#region src/messages/content/index.ts +const KNOWN_BLOCK_TYPES$2 = [ + "text", + "reasoning", + ...KNOWN_BLOCK_TYPES, + ...multimodal_KNOWN_BLOCK_TYPES +]; + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/index.js + + + + + + + + + + + + + + + + +//#region src/messages/index.ts +var messages_exports = {}; +__export(messages_exports, { + AIMessage: () => AIMessage, + AIMessageChunk: () => AIMessageChunk, + BaseMessage: () => BaseMessage, + BaseMessageChunk: () => BaseMessageChunk, + ChatMessage: () => ChatMessage, + ChatMessageChunk: () => ChatMessageChunk, + FunctionMessage: () => FunctionMessage, + FunctionMessageChunk: () => FunctionMessageChunk, + HumanMessage: () => HumanMessage, + HumanMessageChunk: () => HumanMessageChunk, + KNOWN_BLOCK_TYPES: () => KNOWN_BLOCK_TYPES$2, + RemoveMessage: () => RemoveMessage, + SystemMessage: () => SystemMessage, + SystemMessageChunk: () => SystemMessageChunk, + ToolMessage: () => ToolMessage, + ToolMessageChunk: () => ToolMessageChunk, + _isMessageFieldWithRole: () => _isMessageFieldWithRole, + _mergeDicts: () => _mergeDicts, + _mergeLists: () => _mergeLists, + _mergeObj: () => _mergeObj, + _mergeStatus: () => _mergeStatus, + coerceMessageLikeToMessage: () => utils_coerceMessageLikeToMessage, + collapseToolCallChunks: () => collapseToolCallChunks, + convertToChunk: () => convertToChunk, + convertToOpenAIImageBlock: () => convertToOpenAIImageBlock, + convertToProviderContentBlock: () => convertToProviderContentBlock, + defaultTextSplitter: () => defaultTextSplitter, + defaultToolCallParser: () => defaultToolCallParser, + filterMessages: () => filterMessages, + getBufferString: () => getBufferString, + iife: () => utils_iife, + isAIMessage: () => isAIMessage, + isAIMessageChunk: () => isAIMessageChunk, + isBase64ContentBlock: () => isBase64ContentBlock, + isBaseMessage: () => isBaseMessage, + isBaseMessageChunk: () => isBaseMessageChunk, + isChatMessage: () => isChatMessage, + isChatMessageChunk: () => isChatMessageChunk, + isDataContentBlock: () => isDataContentBlock, + isDirectToolOutput: () => isDirectToolOutput, + isFunctionMessage: () => isFunctionMessage, + isFunctionMessageChunk: () => isFunctionMessageChunk, + isHumanMessage: () => isHumanMessage, + isHumanMessageChunk: () => isHumanMessageChunk, + isIDContentBlock: () => isIDContentBlock, + isMessage: () => isMessage, + isOpenAIToolCallArray: () => isOpenAIToolCallArray, + isPlainTextContentBlock: () => isPlainTextContentBlock, + isSystemMessage: () => isSystemMessage, + isSystemMessageChunk: () => isSystemMessageChunk, + isToolMessage: () => isToolMessage, + isToolMessageChunk: () => isToolMessageChunk, + isURLContentBlock: () => isURLContentBlock, + mapChatMessagesToStoredMessages: () => mapChatMessagesToStoredMessages, + mapStoredMessageToChatMessage: () => mapStoredMessageToChatMessage, + mapStoredMessagesToChatMessages: () => mapStoredMessagesToChatMessages, + mergeContent: () => mergeContent, + mergeMessageRuns: () => mergeMessageRuns, + mergeResponseMetadata: () => mergeResponseMetadata, + mergeUsageMetadata: () => mergeUsageMetadata, + parseBase64DataUrl: () => parseBase64DataUrl, + parseMimeType: () => parseMimeType, + trimMessages: () => trimMessages +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/chat_history.js + + + + + + +//#region src/chat_history.ts +var chat_history_exports = {}; +__export(chat_history_exports, { + BaseChatMessageHistory: () => BaseChatMessageHistory, + BaseListChatMessageHistory: () => BaseListChatMessageHistory, + InMemoryChatMessageHistory: () => InMemoryChatMessageHistory +}); +/** +* Base class for all chat message histories. All chat message histories +* should extend this class. +*/ +var BaseChatMessageHistory = class extends Serializable { + /** + * Add a list of messages. + * + * Implementations should override this method to handle bulk addition of messages + * in an efficient manner to avoid unnecessary round-trips to the underlying store. + * + * @param messages - A list of BaseMessage objects to store. + */ + async addMessages(messages) { + for (const message of messages) await this.addMessage(message); + } +}; +/** +* Base class for all list chat message histories. All list chat message +* histories should extend this class. +*/ +var BaseListChatMessageHistory = class extends Serializable { + /** + * This is a convenience method for adding a human message string to the store. + * Please note that this is a convenience method. Code should favor the + * bulk addMessages interface instead to save on round-trips to the underlying + * persistence layer. + * This method may be deprecated in a future release. + */ + addUserMessage(message) { + return this.addMessage(new HumanMessage(message)); + } + /** + * This is a convenience method for adding an AI message string to the store. + * Please note that this is a convenience method. Code should favor the bulk + * addMessages interface instead to save on round-trips to the underlying + * persistence layer. + * This method may be deprecated in a future release. + */ + addAIMessage(message) { + return this.addMessage(new AIMessage(message)); + } + /** + * Add a list of messages. + * + * Implementations should override this method to handle bulk addition of messages + * in an efficient manner to avoid unnecessary round-trips to the underlying store. + * + * @param messages - A list of BaseMessage objects to store. + */ + async addMessages(messages) { + for (const message of messages) await this.addMessage(message); + } + /** + * Remove all messages from the store. + */ + clear() { + throw new Error("Not implemented."); + } +}; +/** +* Class for storing chat message history in-memory. It extends the +* BaseListChatMessageHistory class and provides methods to get, add, and +* clear messages. +*/ +var InMemoryChatMessageHistory = class extends BaseListChatMessageHistory { + lc_namespace = [ + "langchain", + "stores", + "message", + "in_memory" + ]; + messages = []; + constructor(messages) { + super(...arguments); + this.messages = messages ?? []; + } + /** + * Method to get all the messages stored in the ChatMessageHistory + * instance. + * @returns Array of stored BaseMessage instances. + */ + async getMessages() { + return this.messages; + } + /** + * Method to add a new message to the ChatMessageHistory instance. + * @param message The BaseMessage instance to add. + * @returns A promise that resolves when the message has been added. + */ + async addMessage(message) { + this.messages.push(message); + } + /** + * Method to clear all the messages from the ChatMessageHistory instance. + * @returns A promise that resolves when all messages have been cleared. + */ + async clear() { + this.messages = []; + } +}; + +//#endregion + +//# sourceMappingURL=chat_history.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/embeddings.js + + + +//#region src/embeddings.ts +var embeddings_exports = {}; +__export(embeddings_exports, { Embeddings: () => Embeddings }); +/** +* An abstract class that provides methods for embedding documents and +* queries using LangChain. +*/ +var Embeddings = class { + /** + * The async caller should be used by subclasses to make any async calls, + * which will thus benefit from the concurrency and retry logic. + */ + caller; + constructor(params) { + this.caller = new async_caller_AsyncCaller(params ?? {}); + } +}; + +//#endregion + +//# sourceMappingURL=embeddings.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/index.js +//#region src/index.ts +var src_exports = {}; + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/memory.js + + +//#region src/memory.ts +var memory_exports = {}; +__export(memory_exports, { + BaseMemory: () => BaseMemory, + getInputValue: () => getInputValue, + getOutputValue: () => getOutputValue, + getPromptInputKey: () => getPromptInputKey +}); +/** +* Abstract base class for memory in LangChain's Chains. Memory refers to +* the state in Chains. It can be used to store information about past +* executions of a Chain and inject that information into the inputs of +* future executions of the Chain. +*/ +var BaseMemory = class {}; +const getValue = (values, key) => { + if (key !== void 0) return values[key]; + const keys = Object.keys(values); + if (keys.length === 1) return values[keys[0]]; +}; +/** +* This function is used by memory classes to select the input value +* to use for the memory. If there is only one input value, it is used. +* If there are multiple input values, the inputKey must be specified. +*/ +const getInputValue = (inputValues, inputKey) => { + const value = getValue(inputValues, inputKey); + if (!value) { + const keys = Object.keys(inputValues); + throw new Error(`input values have ${keys.length} keys, you must specify an input key or pass only 1 key as input`); + } + return value; +}; +/** +* This function is used by memory classes to select the output value +* to use for the memory. If there is only one output value, it is used. +* If there are multiple output values, the outputKey must be specified. +* If no outputKey is specified, an error is thrown. +*/ +const getOutputValue = (outputValues, outputKey) => { + const value = getValue(outputValues, outputKey); + if (!value && value !== "") { + const keys = Object.keys(outputValues); + throw new Error(`output values have ${keys.length} keys, you must specify an output key or pass only 1 key as output`); + } + return value; +}; +/** +* Function used by memory classes to get the key of the prompt input, +* excluding any keys that are memory variables or the "stop" key. If +* there is not exactly one prompt input key, an error is thrown. +*/ +function getPromptInputKey(inputs, memoryVariables) { + const promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== "stop"); + if (promptInputKeys.length !== 1) throw new Error(`One input key expected, but got ${promptInputKeys.length}`); + return promptInputKeys[0]; +} + +//#endregion + +//# sourceMappingURL=memory.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompt_values.js + + + + + +//#region src/prompt_values.ts +var prompt_values_exports = {}; +__export(prompt_values_exports, { + BasePromptValue: () => BasePromptValue, + ChatPromptValue: () => ChatPromptValue, + ImagePromptValue: () => ImagePromptValue, + StringPromptValue: () => StringPromptValue +}); +/** +* Base PromptValue class. All prompt values should extend this class. +*/ +var BasePromptValue = class extends Serializable {}; +/** +* Represents a prompt value as a string. It extends the BasePromptValue +* class and overrides the toString and toChatMessages methods. +*/ +var StringPromptValue = class extends BasePromptValue { + static lc_name() { + return "StringPromptValue"; + } + lc_namespace = ["langchain_core", "prompt_values"]; + lc_serializable = true; + value; + constructor(value) { + super({ value }); + this.value = value; + } + toString() { + return this.value; + } + toChatMessages() { + return [new HumanMessage(this.value)]; + } +}; +/** +* Class that represents a chat prompt value. It extends the +* BasePromptValue and includes an array of BaseMessage instances. +*/ +var ChatPromptValue = class extends BasePromptValue { + lc_namespace = ["langchain_core", "prompt_values"]; + lc_serializable = true; + static lc_name() { + return "ChatPromptValue"; + } + messages; + constructor(fields) { + if (Array.isArray(fields)) fields = { messages: fields }; + super(fields); + this.messages = fields.messages; + } + toString() { + return getBufferString(this.messages); + } + toChatMessages() { + return this.messages; + } +}; +/** +* Class that represents an image prompt value. It extends the +* BasePromptValue and includes an ImageURL instance. +*/ +var ImagePromptValue = class extends BasePromptValue { + lc_namespace = ["langchain_core", "prompt_values"]; + lc_serializable = true; + static lc_name() { + return "ImagePromptValue"; + } + imageUrl; + /** @ignore */ + value; + constructor(fields) { + if (!("imageUrl" in fields)) fields = { imageUrl: fields }; + super(fields); + this.imageUrl = fields.imageUrl; + } + toString() { + return this.imageUrl.url; + } + toChatMessages() { + return [new HumanMessage({ content: [{ + type: "image_url", + image_url: { + detail: this.imageUrl.detail, + url: this.imageUrl.url + } + }] })]; + } +}; + +//#endregion + +//# sourceMappingURL=prompt_values.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/stores.js + + + +//#region src/stores.ts +var stores_exports = {}; +__export(stores_exports, { + BaseStore: () => BaseStore, + InMemoryStore: () => InMemoryStore +}); +/** +* Abstract interface for a key-value store. +*/ +var BaseStore = class extends Serializable {}; +/** +* In-memory implementation of the BaseStore using a dictionary. Used for +* storing key-value pairs in memory. +* @example +* ```typescript +* const store = new InMemoryStore(); +* await store.mset( +* Array.from({ length: 5 }).map((_, index) => [ +* `message:id:${index}`, +* index % 2 === 0 +* ? new AIMessage("ai stuff...") +* : new HumanMessage("human stuff..."), +* ]), +* ); +* +* const retrievedMessages = await store.mget(["message:id:0", "message:id:1"]); +* await store.mdelete(await store.yieldKeys("message:id:").toArray()); +* ``` +*/ +var InMemoryStore = class extends BaseStore { + lc_namespace = ["langchain", "storage"]; + store = {}; + /** + * Retrieves the values associated with the given keys from the store. + * @param keys Keys to retrieve values for. + * @returns Array of values associated with the given keys. + */ + async mget(keys) { + return keys.map((key) => this.store[key]); + } + /** + * Sets the values for the given keys in the store. + * @param keyValuePairs Array of key-value pairs to set in the store. + * @returns Promise that resolves when all key-value pairs have been set. + */ + async mset(keyValuePairs) { + for (const [key, value] of keyValuePairs) this.store[key] = value; + } + /** + * Deletes the given keys and their associated values from the store. + * @param keys Keys to delete from the store. + * @returns Promise that resolves when all keys have been deleted. + */ + async mdelete(keys) { + for (const key of keys) delete this.store[key]; + } + /** + * Asynchronous generator that yields keys from the store. If a prefix is + * provided, it only yields keys that start with the prefix. + * @param prefix Optional prefix to filter keys. + * @returns AsyncGenerator that yields keys from the store. + */ + async *yieldKeys(prefix) { + const keys = Object.keys(this.store); + for (const key of keys) if (prefix === void 0 || key.startsWith(prefix)) yield key; + } +}; + +//#endregion + +//# sourceMappingURL=stores.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/retrievers/index.js + + + + + +//#region src/retrievers/index.ts +var retrievers_exports = {}; +__export(retrievers_exports, { BaseRetriever: () => BaseRetriever }); +/** +* Abstract base class for a document retrieval system, designed to +* process string queries and return the most relevant documents from a source. +* +* `BaseRetriever` provides common properties and methods for derived retrievers, +* such as callbacks, tagging, and verbose logging. Custom retrieval systems +* should extend this class and implement `_getRelevantDocuments` to define +* the specific retrieval logic. +* +* @template Metadata - The type of metadata associated with each document, +* defaulting to `Record`. +*/ +var BaseRetriever = class extends Runnable { + /** + * Optional callbacks to handle various events in the retrieval process. + */ + callbacks; + /** + * Tags to label or categorize the retrieval operation. + */ + tags; + /** + * Metadata to provide additional context or information about the retrieval + * operation. + */ + metadata; + /** + * If set to `true`, enables verbose logging for the retrieval process. + */ + verbose; + /** + * Constructs a new `BaseRetriever` instance with optional configuration fields. + * + * @param fields - Optional input configuration that can include `callbacks`, + * `tags`, `metadata`, and `verbose` settings for custom retriever behavior. + */ + constructor(fields) { + super(fields); + this.callbacks = fields?.callbacks; + this.tags = fields?.tags ?? []; + this.metadata = fields?.metadata ?? {}; + this.verbose = fields?.verbose ?? false; + } + /** + * TODO: This should be an abstract method, but we'd like to avoid breaking + * changes to people currently using subclassed custom retrievers. + * Change it on next major release. + */ + /** + * Placeholder method for retrieving relevant documents based on a query. + * + * This method is intended to be implemented by subclasses and will be + * converted to an abstract method in the next major release. Currently, it + * throws an error if not implemented, ensuring that custom retrievers define + * the specific retrieval logic. + * + * @param _query - The query string used to search for relevant documents. + * @param _callbacks - (optional) Callback manager for managing callbacks + * during retrieval. + * @returns A promise resolving to an array of `DocumentInterface` instances relevant to the query. + * @throws {Error} Throws an error indicating the method is not implemented. + */ + _getRelevantDocuments(_query, _callbacks) { + throw new Error("Not implemented!"); + } + /** + * Executes a retrieval operation. + * + * @param input - The query string used to search for relevant documents. + * @param options - (optional) Configuration options for the retrieval run, + * which may include callbacks, tags, and metadata. + * @returns A promise that resolves to an array of `DocumentInterface` instances + * representing the most relevant documents to the query. + */ + async invoke(input, options) { + const parsedConfig = ensureConfig(parseCallbackConfigArg(options)); + const callbackManager_ = await CallbackManager.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }); + const runManager = await callbackManager_?.handleRetrieverStart(this.toJSON(), input, parsedConfig.runId, void 0, void 0, void 0, parsedConfig.runName); + try { + const results = await this._getRelevantDocuments(input, runManager); + await runManager?.handleRetrieverEnd(results); + return results; + } catch (error) { + await runManager?.handleRetrieverError(error); + throw error; + } + } +}; + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/vectorstores.js + + + + +//#region src/vectorstores.ts +var vectorstores_exports = {}; +__export(vectorstores_exports, { + SaveableVectorStore: () => SaveableVectorStore, + VectorStore: () => VectorStore, + VectorStoreRetriever: () => VectorStoreRetriever +}); +/** +* Class for retrieving documents from a `VectorStore` based on vector similarity +* or maximal marginal relevance (MMR). +* +* `VectorStoreRetriever` extends `BaseRetriever`, implementing methods for +* adding documents to the underlying vector store and performing document +* retrieval with optional configurations. +* +* @class VectorStoreRetriever +* @extends BaseRetriever +* @implements VectorStoreRetrieverInterface +* @template V - Type of vector store implementing `VectorStoreInterface`. +*/ +var VectorStoreRetriever = class extends BaseRetriever { + static lc_name() { + return "VectorStoreRetriever"; + } + get lc_namespace() { + return ["langchain_core", "vectorstores"]; + } + /** + * The instance of `VectorStore` used for storing and retrieving document embeddings. + * This vector store must implement the `VectorStoreInterface` to be compatible + * with the retriever’s operations. + */ + vectorStore; + /** + * Specifies the number of documents to retrieve for each search query. + * Defaults to 4 if not specified, providing a basic result count for similarity or MMR searches. + */ + k = 4; + /** + * Determines the type of search operation to perform on the vector store. + * + * - `"similarity"` (default): Conducts a similarity search based purely on vector similarity + * to the query. + * - `"mmr"`: Executes a maximal marginal relevance (MMR) search, balancing relevance and + * diversity in the retrieved results. + */ + searchType = "similarity"; + /** + * Additional options specific to maximal marginal relevance (MMR) search, applicable + * only if `searchType` is set to `"mmr"`. + * + * Includes: + * - `fetchK`: The initial number of documents fetched before applying the MMR algorithm, + * allowing for a larger selection from which to choose the most diverse results. + * - `lambda`: A parameter between 0 and 1 to adjust the relevance-diversity balance, + * where 0 prioritizes diversity and 1 prioritizes relevance. + */ + searchKwargs; + /** + * Optional filter applied to search results, defined by the `FilterType` of the vector store. + * Allows for refined, targeted results by restricting the returned documents based + * on specified filter criteria. + */ + filter; + /** + * Returns the type of vector store, as defined by the `vectorStore` instance. + * + * @returns {string} The vector store type. + */ + _vectorstoreType() { + return this.vectorStore._vectorstoreType(); + } + /** + * Initializes a new instance of `VectorStoreRetriever` with the specified configuration. + * + * This constructor configures the retriever to interact with a given `VectorStore` + * and supports different retrieval strategies, including similarity search and maximal + * marginal relevance (MMR) search. Various options allow customization of the number + * of documents retrieved per query, filtering based on conditions, and fine-tuning + * MMR-specific parameters. + * + * @param fields - Configuration options for setting up the retriever: + * + * - `vectorStore` (required): The `VectorStore` instance implementing `VectorStoreInterface` + * that will be used to store and retrieve document embeddings. This is the core component + * of the retriever, enabling vector-based similarity and MMR searches. + * + * - `k` (optional): Specifies the number of documents to retrieve per search query. If not + * provided, defaults to 4. This count determines the number of most relevant documents returned + * for each search operation, balancing performance with comprehensiveness. + * + * - `searchType` (optional): Defines the search approach used by the retriever, allowing for + * flexibility between two methods: + * - `"similarity"` (default): A similarity-based search, retrieving documents with high vector + * similarity to the query. This type prioritizes relevance and is often used when diversity + * among results is less critical. + * - `"mmr"`: Maximal Marginal Relevance search, which combines relevance with diversity. MMR + * is useful for scenarios where varied content is essential, as it selects results that + * both match the query and introduce content diversity. + * + * - `filter` (optional): A filter of type `FilterType`, defined by the vector store, that allows + * for refined and targeted search results. This filter applies specified conditions to limit + * which documents are eligible for retrieval, offering control over the scope of results. + * + * - `searchKwargs` (optional, applicable only if `searchType` is `"mmr"`): Additional settings + * for configuring MMR-specific behavior. These parameters allow further tuning of the MMR + * search process: + * - `fetchK`: The initial number of documents fetched from the vector store before the MMR + * algorithm is applied. Fetching a larger set enables the algorithm to select a more + * diverse subset of documents. + * - `lambda`: A parameter controlling the relevance-diversity balance, where 0 emphasizes + * diversity and 1 prioritizes relevance. Intermediate values provide a blend of the two, + * allowing customization based on the importance of content variety relative to query relevance. + */ + constructor(fields) { + super(fields); + this.vectorStore = fields.vectorStore; + this.k = fields.k ?? this.k; + this.searchType = fields.searchType ?? this.searchType; + this.filter = fields.filter; + if (fields.searchType === "mmr") this.searchKwargs = fields.searchKwargs; + } + /** + * Retrieves relevant documents based on the specified query, using either + * similarity or maximal marginal relevance (MMR) search. + * + * If `searchType` is set to `"mmr"`, performs an MMR search to balance + * similarity and diversity among results. If `searchType` is `"similarity"`, + * retrieves results purely based on similarity to the query. + * + * @param query - The query string used to find relevant documents. + * @param runManager - Optional callback manager for tracking retrieval progress. + * @returns A promise that resolves to an array of `DocumentInterface` instances + * representing the most relevant documents to the query. + * @throws {Error} Throws an error if MMR search is requested but not supported + * by the vector store. + * @protected + */ + async _getRelevantDocuments(query, runManager) { + if (this.searchType === "mmr") { + if (typeof this.vectorStore.maxMarginalRelevanceSearch !== "function") throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`); + return this.vectorStore.maxMarginalRelevanceSearch(query, { + k: this.k, + filter: this.filter, + ...this.searchKwargs + }, runManager?.getChild("vectorstore")); + } + return this.vectorStore.similaritySearch(query, this.k, this.filter, runManager?.getChild("vectorstore")); + } + /** + * Adds an array of documents to the vector store, embedding them as part of + * the storage process. + * + * This method delegates document embedding and storage to the `addDocuments` + * method of the underlying vector store. + * + * @param documents - An array of documents to embed and add to the vector store. + * @param options - Optional settings to customize document addition. + * @returns A promise that resolves to an array of document IDs or `void`, + * depending on the vector store's implementation. + */ + async addDocuments(documents, options) { + return this.vectorStore.addDocuments(documents, options); + } +}; +/** +* Abstract class representing a vector storage system for performing +* similarity searches on embedded documents. +* +* `VectorStore` provides methods for adding precomputed vectors or documents, +* removing documents based on criteria, and performing similarity searches +* with optional scoring. Subclasses are responsible for implementing specific +* storage mechanisms and the exact behavior of certain abstract methods. +* +* @abstract +* @extends Serializable +* @implements VectorStoreInterface +*/ +var VectorStore = class extends Serializable { + /** + * Namespace within LangChain to uniquely identify this vector store's + * location, based on the vector store type. + * + * @internal + */ + lc_namespace = [ + "langchain", + "vectorstores", + this._vectorstoreType() + ]; + /** + * Embeddings interface for generating vector embeddings from text queries, + * enabling vector-based similarity searches. + */ + embeddings; + /** + * Initializes a new vector store with embeddings and database configuration. + * + * @param embeddings - Instance of `EmbeddingsInterface` used to embed queries. + * @param dbConfig - Configuration settings for the database or storage system. + */ + constructor(embeddings, dbConfig) { + super(dbConfig); + this.embeddings = embeddings; + } + /** + * Deletes documents from the vector store based on the specified parameters. + * + * @param _params - Flexible key-value pairs defining conditions for document deletion. + * @returns A promise that resolves once the deletion is complete. + */ + async delete(_params) { + throw new Error("Not implemented."); + } + /** + * Searches for documents similar to a text query by embedding the query and + * performing a similarity search on the resulting vector. + * + * @param query - Text query for finding similar documents. + * @param k - Number of similar results to return. Defaults to 4. + * @param filter - Optional filter based on `FilterType`. + * @param _callbacks - Optional callbacks for monitoring search progress + * @returns A promise resolving to an array of `DocumentInterface` instances representing similar documents. + */ + async similaritySearch(query, k = 4, filter = void 0, _callbacks = void 0) { + const results = await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query), k, filter); + return results.map((result) => result[0]); + } + /** + * Searches for documents similar to a text query by embedding the query, + * and returns results with similarity scores. + * + * @param query - Text query for finding similar documents. + * @param k - Number of similar results to return. Defaults to 4. + * @param filter - Optional filter based on `FilterType`. + * @param _callbacks - Optional callbacks for monitoring search progress + * @returns A promise resolving to an array of tuples, each containing a + * document and its similarity score. + */ + async similaritySearchWithScore(query, k = 4, filter = void 0, _callbacks = void 0) { + return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query), k, filter); + } + /** + * Creates a `VectorStore` instance from an array of text strings and optional + * metadata, using the specified embeddings and database configuration. + * + * Subclasses must implement this method to define how text and metadata + * are embedded and stored in the vector store. Throws an error if not overridden. + * + * @param _texts - Array of strings representing the text documents to be stored. + * @param _metadatas - Metadata for the texts, either as an array (one for each text) + * or a single object (applied to all texts). + * @param _embeddings - Instance of `EmbeddingsInterface` to embed the texts. + * @param _dbConfig - Database configuration settings. + * @returns A promise that resolves to a new `VectorStore` instance. + * @throws {Error} Throws an error if this method is not overridden by a subclass. + */ + static fromTexts(_texts, _metadatas, _embeddings, _dbConfig) { + throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); + } + /** + * Creates a `VectorStore` instance from an array of documents, using the specified + * embeddings and database configuration. + * + * Subclasses must implement this method to define how documents are embedded + * and stored. Throws an error if not overridden. + * + * @param _docs - Array of `DocumentInterface` instances representing the documents to be stored. + * @param _embeddings - Instance of `EmbeddingsInterface` to embed the documents. + * @param _dbConfig - Database configuration settings. + * @returns A promise that resolves to a new `VectorStore` instance. + * @throws {Error} Throws an error if this method is not overridden by a subclass. + */ + static fromDocuments(_docs, _embeddings, _dbConfig) { + throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); + } + /** + * Creates a `VectorStoreRetriever` instance with flexible configuration options. + * + * @param kOrFields + * - If a number is provided, it sets the `k` parameter (number of items to retrieve). + * - If an object is provided, it should contain various configuration options. + * @param filter + * - Optional filter criteria to limit the items retrieved based on the specified filter type. + * @param callbacks + * - Optional callbacks that may be triggered at specific stages of the retrieval process. + * @param tags + * - Tags to categorize or label the `VectorStoreRetriever`. Defaults to an empty array if not provided. + * @param metadata + * - Additional metadata as key-value pairs to add contextual information for the retrieval process. + * @param verbose + * - If `true`, enables detailed logging for the retrieval process. Defaults to `false`. + * + * @returns + * - A configured `VectorStoreRetriever` instance based on the provided parameters. + * + * @example + * Basic usage with a `k` value: + * ```typescript + * const retriever = myVectorStore.asRetriever(5); + * ``` + * + * Usage with a configuration object: + * ```typescript + * const retriever = myVectorStore.asRetriever({ + * k: 10, + * filter: myFilter, + * tags: ['example', 'test'], + * verbose: true, + * searchType: 'mmr', + * searchKwargs: { alpha: 0.5 }, + * }); + * ``` + */ + asRetriever(kOrFields, filter, callbacks, tags, metadata, verbose) { + if (typeof kOrFields === "number") return new VectorStoreRetriever({ + vectorStore: this, + k: kOrFields, + filter, + tags: [...tags ?? [], this._vectorstoreType()], + metadata, + verbose, + callbacks + }); + else { + const params = { + vectorStore: this, + k: kOrFields?.k, + filter: kOrFields?.filter, + tags: [...kOrFields?.tags ?? [], this._vectorstoreType()], + metadata: kOrFields?.metadata, + verbose: kOrFields?.verbose, + callbacks: kOrFields?.callbacks, + searchType: kOrFields?.searchType + }; + if (kOrFields?.searchType === "mmr") return new VectorStoreRetriever({ + ...params, + searchKwargs: kOrFields.searchKwargs + }); + return new VectorStoreRetriever({ ...params }); + } + } +}; +/** +* Abstract class extending `VectorStore` that defines a contract for saving +* and loading vector store instances. +* +* The `SaveableVectorStore` class allows vector store implementations to +* persist their data and retrieve it when needed.The format for saving and +* loading data is left to the implementing subclass. +* +* Subclasses must implement the `save` method to handle their custom +* serialization logic, while the `load` method enables reconstruction of a +* vector store from saved data, requiring compatible embeddings through the +* `EmbeddingsInterface`. +* +* @abstract +* @extends VectorStore +*/ +var SaveableVectorStore = class extends VectorStore { + /** + * Loads a vector store instance from the specified directory, using the + * provided embeddings to ensure compatibility. + * + * This static method reconstructs a `SaveableVectorStore` from previously + * saved data. Implementations should interpret the saved data format to + * recreate the vector store instance. + * + * @param _directory - The directory path from which the vector store + * data will be loaded. + * @param _embeddings - An instance of `EmbeddingsInterface` to align + * the embeddings with the loaded vector data. + * @returns A promise that resolves to a `SaveableVectorStore` instance + * constructed from the saved data. + */ + static load(_directory, _embeddings) { + throw new Error("Not implemented"); + } +}; + +//#endregion + +//# sourceMappingURL=vectorstores.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/js-sha256/hash.js + + +//#region src/utils/js-sha256/hash.ts +var HEX_CHARS = "0123456789abcdef".split(""); +var EXTRA = [ + -2147483648, + 8388608, + 32768, + 128 +]; +var SHIFT = [ + 24, + 16, + 8, + 0 +]; +var K = [ + 1116352408, + 1899447441, + 3049323471, + 3921009573, + 961987163, + 1508970993, + 2453635748, + 2870763221, + 3624381080, + 310598401, + 607225278, + 1426881987, + 1925078388, + 2162078206, + 2614888103, + 3248222580, + 3835390401, + 4022224774, + 264347078, + 604807628, + 770255983, + 1249150122, + 1555081692, + 1996064986, + 2554220882, + 2821834349, + 2952996808, + 3210313671, + 3336571891, + 3584528711, + 113926993, + 338241895, + 666307205, + 773529912, + 1294757372, + 1396182291, + 1695183700, + 1986661051, + 2177026350, + 2456956037, + 2730485921, + 2820302411, + 3259730800, + 3345764771, + 3516065817, + 3600352804, + 4094571909, + 275423344, + 430227734, + 506948616, + 659060556, + 883997877, + 958139571, + 1322822218, + 1537002063, + 1747873779, + 1955562222, + 2024104815, + 2227730452, + 2361852424, + 2428436474, + 2756734187, + 3204031479, + 3329325298 +]; +var blocks = []; +function Sha256(is224, sharedMemory) { + if (sharedMemory) { + blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; + this.blocks = blocks; + } else this.blocks = [ + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0, + 0 + ]; + if (is224) { + this.h0 = 3238371032; + this.h1 = 914150663; + this.h2 = 812702999; + this.h3 = 4144912697; + this.h4 = 4290775857; + this.h5 = 1750603025; + this.h6 = 1694076839; + this.h7 = 3204075428; + } else { + this.h0 = 1779033703; + this.h1 = 3144134277; + this.h2 = 1013904242; + this.h3 = 2773480762; + this.h4 = 1359893119; + this.h5 = 2600822924; + this.h6 = 528734635; + this.h7 = 1541459225; + } + this.block = this.start = this.bytes = this.hBytes = 0; + this.finalized = this.hashed = false; + this.first = true; + this.is224 = is224; +} +Sha256.prototype.update = function(message) { + if (this.finalized) return; + var notString, type = typeof message; + if (type !== "string") { + if (type === "object") { + if (message === null) throw new Error(ERROR); + else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) message = new Uint8Array(message); + else if (!Array.isArray(message)) { + if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) throw new Error(ERROR); + } + } else throw new Error(ERROR); + notString = true; + } + var code, index = 0, i, length = message.length, blocks$1 = this.blocks; + while (index < length) { + if (this.hashed) { + this.hashed = false; + blocks$1[0] = this.block; + this.block = blocks$1[16] = blocks$1[1] = blocks$1[2] = blocks$1[3] = blocks$1[4] = blocks$1[5] = blocks$1[6] = blocks$1[7] = blocks$1[8] = blocks$1[9] = blocks$1[10] = blocks$1[11] = blocks$1[12] = blocks$1[13] = blocks$1[14] = blocks$1[15] = 0; + } + if (notString) for (i = this.start; index < length && i < 64; ++index) blocks$1[i >>> 2] |= message[index] << SHIFT[i++ & 3]; + else for (i = this.start; index < length && i < 64; ++index) { + code = message.charCodeAt(index); + if (code < 128) blocks$1[i >>> 2] |= code << SHIFT[i++ & 3]; + else if (code < 2048) { + blocks$1[i >>> 2] |= (192 | code >>> 6) << SHIFT[i++ & 3]; + blocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } else if (code < 55296 || code >= 57344) { + blocks$1[i >>> 2] |= (224 | code >>> 12) << SHIFT[i++ & 3]; + blocks$1[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; + blocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } else { + code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023); + blocks$1[i >>> 2] |= (240 | code >>> 18) << SHIFT[i++ & 3]; + blocks$1[i >>> 2] |= (128 | code >>> 12 & 63) << SHIFT[i++ & 3]; + blocks$1[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; + blocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; + } + } + this.lastByteIndex = i; + this.bytes += i - this.start; + if (i >= 64) { + this.block = blocks$1[16]; + this.start = i - 64; + this.hash(); + this.hashed = true; + } else this.start = i; + } + if (this.bytes > 4294967295) { + this.hBytes += this.bytes / 4294967296 << 0; + this.bytes = this.bytes % 4294967296; + } + return this; +}; +Sha256.prototype.finalize = function() { + if (this.finalized) return; + this.finalized = true; + var blocks$1 = this.blocks, i = this.lastByteIndex; + blocks$1[16] = this.block; + blocks$1[i >>> 2] |= EXTRA[i & 3]; + this.block = blocks$1[16]; + if (i >= 56) { + if (!this.hashed) this.hash(); + blocks$1[0] = this.block; + blocks$1[16] = blocks$1[1] = blocks$1[2] = blocks$1[3] = blocks$1[4] = blocks$1[5] = blocks$1[6] = blocks$1[7] = blocks$1[8] = blocks$1[9] = blocks$1[10] = blocks$1[11] = blocks$1[12] = blocks$1[13] = blocks$1[14] = blocks$1[15] = 0; + } + blocks$1[14] = this.hBytes << 3 | this.bytes >>> 29; + blocks$1[15] = this.bytes << 3; + this.hash(); +}; +Sha256.prototype.hash = function() { + var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks$1 = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; + for (j = 16; j < 64; ++j) { + t1 = blocks$1[j - 15]; + s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3; + t1 = blocks$1[j - 2]; + s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; + blocks$1[j] = blocks$1[j - 16] + s0 + blocks$1[j - 7] + s1 << 0; + } + bc = b & c; + for (j = 0; j < 64; j += 4) { + if (this.first) { + if (this.is224) { + ab = 300032; + t1 = blocks$1[0] - 1413257819; + h = t1 - 150054599 << 0; + d = t1 + 24177077 << 0; + } else { + ab = 704751109; + t1 = blocks$1[0] - 210244248; + h = t1 - 1521486534 << 0; + d = t1 + 143694565 << 0; + } + this.first = false; + } else { + s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); + s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); + ab = a & b; + maj = ab ^ a & c ^ bc; + ch = e & f ^ ~e & g; + t1 = h + s1 + ch + K[j] + blocks$1[j]; + t2 = s0 + maj; + h = d + t1 << 0; + d = t1 + t2 << 0; + } + s0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10); + s1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7); + da = d & a; + maj = da ^ d & b ^ ab; + ch = g & h ^ ~g & e; + t1 = f + s1 + ch + K[j + 1] + blocks$1[j + 1]; + t2 = s0 + maj; + g = c + t1 << 0; + c = t1 + t2 << 0; + s0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10); + s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7); + cd = c & d; + maj = cd ^ c & a ^ da; + ch = f & g ^ ~f & h; + t1 = e + s1 + ch + K[j + 2] + blocks$1[j + 2]; + t2 = s0 + maj; + f = b + t1 << 0; + b = t1 + t2 << 0; + s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10); + s1 = (f >>> 6 | f << 26) ^ (f >>> 11 | f << 21) ^ (f >>> 25 | f << 7); + bc = b & c; + maj = bc ^ b & d ^ cd; + ch = f & g ^ ~f & h; + t1 = e + s1 + ch + K[j + 3] + blocks$1[j + 3]; + t2 = s0 + maj; + e = a + t1 << 0; + a = t1 + t2 << 0; + this.chromeBugWorkAround = true; + } + this.h0 = this.h0 + a << 0; + this.h1 = this.h1 + b << 0; + this.h2 = this.h2 + c << 0; + this.h3 = this.h3 + d << 0; + this.h4 = this.h4 + e << 0; + this.h5 = this.h5 + f << 0; + this.h6 = this.h6 + g << 0; + this.h7 = this.h7 + h << 0; +}; +Sha256.prototype.hex = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var hex = HEX_CHARS[h0 >>> 28 & 15] + HEX_CHARS[h0 >>> 24 & 15] + HEX_CHARS[h0 >>> 20 & 15] + HEX_CHARS[h0 >>> 16 & 15] + HEX_CHARS[h0 >>> 12 & 15] + HEX_CHARS[h0 >>> 8 & 15] + HEX_CHARS[h0 >>> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >>> 28 & 15] + HEX_CHARS[h1 >>> 24 & 15] + HEX_CHARS[h1 >>> 20 & 15] + HEX_CHARS[h1 >>> 16 & 15] + HEX_CHARS[h1 >>> 12 & 15] + HEX_CHARS[h1 >>> 8 & 15] + HEX_CHARS[h1 >>> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >>> 28 & 15] + HEX_CHARS[h2 >>> 24 & 15] + HEX_CHARS[h2 >>> 20 & 15] + HEX_CHARS[h2 >>> 16 & 15] + HEX_CHARS[h2 >>> 12 & 15] + HEX_CHARS[h2 >>> 8 & 15] + HEX_CHARS[h2 >>> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >>> 28 & 15] + HEX_CHARS[h3 >>> 24 & 15] + HEX_CHARS[h3 >>> 20 & 15] + HEX_CHARS[h3 >>> 16 & 15] + HEX_CHARS[h3 >>> 12 & 15] + HEX_CHARS[h3 >>> 8 & 15] + HEX_CHARS[h3 >>> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >>> 28 & 15] + HEX_CHARS[h4 >>> 24 & 15] + HEX_CHARS[h4 >>> 20 & 15] + HEX_CHARS[h4 >>> 16 & 15] + HEX_CHARS[h4 >>> 12 & 15] + HEX_CHARS[h4 >>> 8 & 15] + HEX_CHARS[h4 >>> 4 & 15] + HEX_CHARS[h4 & 15] + HEX_CHARS[h5 >>> 28 & 15] + HEX_CHARS[h5 >>> 24 & 15] + HEX_CHARS[h5 >>> 20 & 15] + HEX_CHARS[h5 >>> 16 & 15] + HEX_CHARS[h5 >>> 12 & 15] + HEX_CHARS[h5 >>> 8 & 15] + HEX_CHARS[h5 >>> 4 & 15] + HEX_CHARS[h5 & 15] + HEX_CHARS[h6 >>> 28 & 15] + HEX_CHARS[h6 >>> 24 & 15] + HEX_CHARS[h6 >>> 20 & 15] + HEX_CHARS[h6 >>> 16 & 15] + HEX_CHARS[h6 >>> 12 & 15] + HEX_CHARS[h6 >>> 8 & 15] + HEX_CHARS[h6 >>> 4 & 15] + HEX_CHARS[h6 & 15]; + if (!this.is224) hex += HEX_CHARS[h7 >>> 28 & 15] + HEX_CHARS[h7 >>> 24 & 15] + HEX_CHARS[h7 >>> 20 & 15] + HEX_CHARS[h7 >>> 16 & 15] + HEX_CHARS[h7 >>> 12 & 15] + HEX_CHARS[h7 >>> 8 & 15] + HEX_CHARS[h7 >>> 4 & 15] + HEX_CHARS[h7 & 15]; + return hex; +}; +Sha256.prototype.toString = Sha256.prototype.hex; +Sha256.prototype.digest = function() { + this.finalize(); + var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; + var arr = [ + h0 >>> 24 & 255, + h0 >>> 16 & 255, + h0 >>> 8 & 255, + h0 & 255, + h1 >>> 24 & 255, + h1 >>> 16 & 255, + h1 >>> 8 & 255, + h1 & 255, + h2 >>> 24 & 255, + h2 >>> 16 & 255, + h2 >>> 8 & 255, + h2 & 255, + h3 >>> 24 & 255, + h3 >>> 16 & 255, + h3 >>> 8 & 255, + h3 & 255, + h4 >>> 24 & 255, + h4 >>> 16 & 255, + h4 >>> 8 & 255, + h4 & 255, + h5 >>> 24 & 255, + h5 >>> 16 & 255, + h5 >>> 8 & 255, + h5 & 255, + h6 >>> 24 & 255, + h6 >>> 16 & 255, + h6 >>> 8 & 255, + h6 & 255 + ]; + if (!this.is224) arr.push(h7 >>> 24 & 255, h7 >>> 16 & 255, h7 >>> 8 & 255, h7 & 255); + return arr; +}; +Sha256.prototype.array = Sha256.prototype.digest; +Sha256.prototype.arrayBuffer = function() { + this.finalize(); + var buffer = /* @__PURE__ */ new ArrayBuffer(this.is224 ? 28 : 32); + var dataView = new DataView(buffer); + dataView.setUint32(0, this.h0); + dataView.setUint32(4, this.h1); + dataView.setUint32(8, this.h2); + dataView.setUint32(12, this.h3); + dataView.setUint32(16, this.h4); + dataView.setUint32(20, this.h5); + dataView.setUint32(24, this.h6); + if (!this.is224) dataView.setUint32(28, this.h7); + return buffer; +}; +const sha256 = (...strings) => { + return new Sha256(false, true).update(strings.join("")).hex(); +}; + +//#endregion + +//# sourceMappingURL=hash.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/hash.js + + + +//#region src/utils/hash.ts +var hash_exports = {}; +__export(hash_exports, { sha256: () => sha256 }); + +//#endregion + +//# sourceMappingURL=hash.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/caches/index.js + + + + + +//#region src/caches/index.ts +var caches_exports = {}; +__export(caches_exports, { + BaseCache: () => caches_BaseCache, + InMemoryCache: () => InMemoryCache, + defaultHashKeyEncoder: () => defaultHashKeyEncoder, + deserializeStoredGeneration: () => deserializeStoredGeneration, + serializeGeneration: () => serializeGeneration +}); +const defaultHashKeyEncoder = (...strings) => sha256(strings.join("_")); +function deserializeStoredGeneration(storedGeneration) { + if (storedGeneration.message !== void 0) return { + text: storedGeneration.text, + message: mapStoredMessageToChatMessage(storedGeneration.message) + }; + else return { text: storedGeneration.text }; +} +function serializeGeneration(generation) { + const serializedValue = { text: generation.text }; + if (generation.message !== void 0) serializedValue.message = generation.message.toDict(); + return serializedValue; +} +/** +* Base class for all caches. All caches should extend this class. +*/ +var caches_BaseCache = class { + keyEncoder = defaultHashKeyEncoder; + /** + * Sets a custom key encoder function for the cache. + * This function should take a prompt and an LLM key and return a string + * that will be used as the cache key. + * @param keyEncoderFn The custom key encoder function. + */ + makeDefaultKeyEncoder(keyEncoderFn) { + this.keyEncoder = keyEncoderFn; + } +}; +const GLOBAL_MAP = /* @__PURE__ */ new Map(); +/** +* A cache for storing LLM generations that stores data in memory. +*/ +var InMemoryCache = class InMemoryCache extends caches_BaseCache { + cache; + constructor(map) { + super(); + this.cache = map ?? /* @__PURE__ */ new Map(); + } + /** + * Retrieves data from the cache using a prompt and an LLM key. If the + * data is not found, it returns null. + * @param prompt The prompt used to find the data. + * @param llmKey The LLM key used to find the data. + * @returns The data corresponding to the prompt and LLM key, or null if not found. + */ + lookup(prompt, llmKey) { + return Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null); + } + /** + * Updates the cache with new data using a prompt and an LLM key. + * @param prompt The prompt used to store the data. + * @param llmKey The LLM key used to store the data. + * @param value The data to be stored. + */ + async update(prompt, llmKey, value) { + this.cache.set(this.keyEncoder(prompt, llmKey), value); + } + /** + * Returns a global instance of InMemoryCache using a predefined global + * map as the initial cache. + * @returns A global instance of InMemoryCache. + */ + static global() { + return new InMemoryCache(GLOBAL_MAP); + } +}; + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/document_loaders/base.js + + +//#region src/document_loaders/base.ts +var document_loaders_base_base_exports = {}; +__export(document_loaders_base_base_exports, { BaseDocumentLoader: () => BaseDocumentLoader }); +/** +* Abstract class that provides a default implementation for the +* loadAndSplit() method from the DocumentLoader interface. The load() +* method is left abstract and needs to be implemented by subclasses. +*/ +var BaseDocumentLoader = class {}; + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/document_loaders/langsmith.js + + + + +//#region src/document_loaders/langsmith.ts +var langsmith_exports = {}; +__export(langsmith_exports, { LangSmithLoader: () => LangSmithLoader }); +/** +* Document loader integration with LangSmith. +* +* ## [Constructor args](https://api.js.langchain.com/interfaces/_langchain_core.document_loaders_langsmith.LangSmithLoaderFields.html) +* +*
+* Load +* +* ```typescript +* import { LangSmithLoader } from '@langchain/core/document_loaders/langsmith'; +* import { Client } from 'langsmith'; +* +* const langSmithClient = new Client({ +* apiKey: process.env.LANGSMITH_API_KEY, +* }) +* +* const loader = new LangSmithLoader({ +* datasetId: "9a3b36f7-b308-40a5-9b46-6613853b6330", +* limit: 1, +* }); +* +* const docs = await loader.load(); +* ``` +* +* ```txt +* [ +* { +* pageContent: '{\n "input_key_str": "string",\n "input_key_bool": true\n}', +* metadata: { +* id: '8523d9e9-c123-4b23-9b46-21021nds289e', +* created_at: '2024-08-19T17:09:14.806441+00:00', +* modified_at: '2024-08-19T17:09:14.806441+00:00', +* name: '#8517 @ brace-test-dataset', +* dataset_id: '9a3b36f7-b308-40a5-9b46-6613853b6330', +* source_run_id: null, +* metadata: [Object], +* inputs: [Object], +* outputs: [Object] +* } +* } +* ] +* ``` +*
+*/ +var LangSmithLoader = class extends BaseDocumentLoader { + datasetId; + datasetName; + exampleIds; + asOf; + splits; + inlineS3Urls; + offset; + limit; + metadata; + filter; + contentKey; + formatContent; + client; + constructor(fields) { + super(); + if (fields.client && fields.clientConfig) throw new Error("client and clientConfig cannot both be provided."); + this.client = fields.client ?? new Client(fields?.clientConfig); + this.contentKey = fields.contentKey ? fields.contentKey.split(".") : []; + this.formatContent = fields.formatContent ?? _stringify; + this.datasetId = fields.datasetId; + this.datasetName = fields.datasetName; + this.exampleIds = fields.exampleIds; + this.asOf = fields.asOf; + this.splits = fields.splits; + this.inlineS3Urls = fields.inlineS3Urls; + this.offset = fields.offset; + this.limit = fields.limit; + this.metadata = fields.metadata; + this.filter = fields.filter; + } + async load() { + const documents = []; + for await (const example of this.client.listExamples({ + datasetId: this.datasetId, + datasetName: this.datasetName, + exampleIds: this.exampleIds, + asOf: this.asOf, + splits: this.splits, + inlineS3Urls: this.inlineS3Urls, + offset: this.offset, + limit: this.limit, + metadata: this.metadata, + filter: this.filter + })) { + let content = example.inputs; + for (const key of this.contentKey) content = content[key]; + const contentStr = this.formatContent(content); + const metadata = example; + ["created_at", "modified_at"].forEach((k) => { + if (k in metadata) { + if (typeof metadata[k] === "object") metadata[k] = metadata[k].toString(); + } + }); + documents.push({ + pageContent: contentStr, + metadata + }); + } + return documents; + } +}; +function _stringify(x) { + if (typeof x === "string") return x; + else try { + return JSON.stringify(x, null, 2); + } catch { + return String(x); + } +} + +//#endregion + +//# sourceMappingURL=langsmith.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/documents/document.js +//#region src/documents/document.ts +/** +* Interface for interacting with a document. +*/ +var Document = class { + pageContent; + metadata; + /** + * An optional identifier for the document. + * + * Ideally this should be unique across the document collection and formatted + * as a UUID, but this will not be enforced. + */ + id; + constructor(fields) { + this.pageContent = fields.pageContent !== void 0 ? fields.pageContent.toString() : ""; + this.metadata = fields.metadata ?? {}; + this.id = fields.id; + } +}; + +//#endregion + +//# sourceMappingURL=document.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/documents/transformers.js + + +//#region src/documents/transformers.ts +/** +* Abstract base class for document transformation systems. +* +* A document transformation system takes an array of Documents and returns an +* array of transformed Documents. These arrays do not necessarily have to have +* the same length. +* +* One example of this is a text splitter that splits a large document into +* many smaller documents. +*/ +var BaseDocumentTransformer = class extends Runnable { + lc_namespace = [ + "langchain_core", + "documents", + "transformers" + ]; + /** + * Method to invoke the document transformation. This method calls the + * transformDocuments method with the provided input. + * @param input The input documents to be transformed. + * @param _options Optional configuration object to customize the behavior of callbacks. + * @returns A Promise that resolves to the transformed documents. + */ + invoke(input, _options) { + return this.transformDocuments(input); + } +}; +/** +* Class for document transformers that return exactly one transformed document +* for each input document. +*/ +var MappingDocumentTransformer = class extends BaseDocumentTransformer { + async transformDocuments(documents) { + const newDocuments = []; + for (const document of documents) { + const transformedDocument = await this._transformDocument(document); + newDocuments.push(transformedDocument); + } + return newDocuments; + } +}; + +//#endregion + +//# sourceMappingURL=transformers.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/documents/index.js + + + + +//#region src/documents/index.ts +var documents_exports = {}; +__export(documents_exports, { + BaseDocumentTransformer: () => BaseDocumentTransformer, + Document: () => Document, + MappingDocumentTransformer: () => MappingDocumentTransformer +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/base.js + + +//#region src/example_selectors/base.ts +/** +* Base class for example selectors. +*/ +var BaseExampleSelector = class extends Serializable { + lc_namespace = [ + "langchain_core", + "example_selectors", + "base" + ]; +}; + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/conditional.js +//#region src/example_selectors/conditional.ts +/** +* Abstract class that defines the interface for selecting a prompt for a +* given language model. +*/ +var BasePromptSelector = class { + /** + * Asynchronous version of `getPrompt` that also accepts an options object + * for partial variables. + * @param llm The language model for which to get a prompt. + * @param options Optional object for partial variables. + * @returns A Promise that resolves to a prompt template. + */ + async getPromptAsync(llm, options) { + const prompt = this.getPrompt(llm); + return prompt.partial(options?.partialVariables ?? {}); + } +}; +/** +* Concrete implementation of `BasePromptSelector` that selects a prompt +* based on a set of conditions. It has a default prompt that it returns +* if none of the conditions are met. +*/ +var ConditionalPromptSelector = class extends BasePromptSelector { + defaultPrompt; + conditionals; + constructor(default_prompt, conditionals = []) { + super(); + this.defaultPrompt = default_prompt; + this.conditionals = conditionals; + } + /** + * Method that selects a prompt based on a set of conditions. If none of + * the conditions are met, it returns the default prompt. + * @param llm The language model for which to get a prompt. + * @returns A prompt template. + */ + getPrompt(llm) { + for (const [condition, prompt] of this.conditionals) if (condition(llm)) return prompt; + return this.defaultPrompt; + } +}; +/** +* Type guard function that checks if a given language model is of type +* `BaseLLM`. +*/ +function isLLM(llm) { + return llm._modelType() === "base_llm"; +} +/** +* Type guard function that checks if a given language model is of type +* `BaseChatModel`. +*/ +function isChatModel(llm) { + return llm._modelType() === "base_chat_model"; +} + +//#endregion + +//# sourceMappingURL=conditional.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/length_based.js + + +//#region src/example_selectors/length_based.ts +/** +* Calculates the length of a text based on the number of words and lines. +*/ +function getLengthBased(text) { + return text.split(/\n| /).length; +} +/** +* A specialized example selector that selects examples based on their +* length, ensuring that the total length of the selected examples does +* not exceed a specified maximum length. +* @example +* ```typescript +* const exampleSelector = new LengthBasedExampleSelector( +* [ +* { input: "happy", output: "sad" }, +* { input: "tall", output: "short" }, +* { input: "energetic", output: "lethargic" }, +* { input: "sunny", output: "gloomy" }, +* { input: "windy", output: "calm" }, +* ], +* { +* examplePrompt: new PromptTemplate({ +* inputVariables: ["input", "output"], +* template: "Input: {input}\nOutput: {output}", +* }), +* maxLength: 25, +* }, +* ); +* const dynamicPrompt = new FewShotPromptTemplate({ +* exampleSelector, +* examplePrompt: new PromptTemplate({ +* inputVariables: ["input", "output"], +* template: "Input: {input}\nOutput: {output}", +* }), +* prefix: "Give the antonym of every input", +* suffix: "Input: {adjective}\nOutput:", +* inputVariables: ["adjective"], +* }); +* console.log(dynamicPrompt.format({ adjective: "big" })); +* console.log( +* dynamicPrompt.format({ +* adjective: +* "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else", +* }), +* ); +* ``` +*/ +var LengthBasedExampleSelector = class LengthBasedExampleSelector extends BaseExampleSelector { + examples = []; + examplePrompt; + getTextLength = getLengthBased; + maxLength = 2048; + exampleTextLengths = []; + constructor(data) { + super(data); + this.examplePrompt = data.examplePrompt; + this.maxLength = data.maxLength ?? 2048; + this.getTextLength = data.getTextLength ?? getLengthBased; + } + /** + * Adds an example to the list of examples and calculates its length. + * @param example The example to be added. + * @returns Promise that resolves when the example has been added and its length calculated. + */ + async addExample(example) { + this.examples.push(example); + const stringExample = await this.examplePrompt.format(example); + this.exampleTextLengths.push(this.getTextLength(stringExample)); + } + /** + * Calculates the lengths of the examples. + * @param v Array of lengths of the examples. + * @param values Instance of LengthBasedExampleSelector. + * @returns Promise that resolves with an array of lengths of the examples. + */ + async calculateExampleTextLengths(v, values) { + if (v.length > 0) return v; + const { examples, examplePrompt } = values; + const stringExamples = await Promise.all(examples.map((eg) => examplePrompt.format(eg))); + return stringExamples.map((eg) => this.getTextLength(eg)); + } + /** + * Selects examples until the total length of the selected examples + * reaches the maxLength. + * @param inputVariables The input variables for the examples. + * @returns Promise that resolves with an array of selected examples. + */ + async selectExamples(inputVariables) { + const inputs = Object.values(inputVariables).join(" "); + let remainingLength = this.maxLength - this.getTextLength(inputs); + let i = 0; + const examples = []; + while (remainingLength > 0 && i < this.examples.length) { + const newLength = remainingLength - this.exampleTextLengths[i]; + if (newLength < 0) break; + else { + examples.push(this.examples[i]); + remainingLength = newLength; + } + i += 1; + } + return examples; + } + /** + * Creates a new instance of LengthBasedExampleSelector and adds a list of + * examples to it. + * @param examples Array of examples to be added. + * @param args Input parameters for the LengthBasedExampleSelector. + * @returns Promise that resolves with a new instance of LengthBasedExampleSelector with the examples added. + */ + static async fromExamples(examples, args) { + const selector = new LengthBasedExampleSelector(args); + await Promise.all(examples.map((eg) => selector.addExample(eg))); + return selector; + } +}; + +//#endregion + +//# sourceMappingURL=length_based.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/semantic_similarity.js + + + +//#region src/example_selectors/semantic_similarity.ts +function sortedValues(values) { + return Object.keys(values).sort().map((key) => values[key]); +} +/** +* Class that selects examples based on semantic similarity. It extends +* the BaseExampleSelector class. +* @example +* ```typescript +* const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples( +* [ +* { input: "happy", output: "sad" }, +* { input: "tall", output: "short" }, +* { input: "energetic", output: "lethargic" }, +* { input: "sunny", output: "gloomy" }, +* { input: "windy", output: "calm" }, +* ], +* new OpenAIEmbeddings(), +* HNSWLib, +* { k: 1 }, +* ); +* const dynamicPrompt = new FewShotPromptTemplate({ +* exampleSelector, +* examplePrompt: PromptTemplate.fromTemplate( +* "Input: {input}\nOutput: {output}", +* ), +* prefix: "Give the antonym of every input", +* suffix: "Input: {adjective}\nOutput:", +* inputVariables: ["adjective"], +* }); +* console.log(await dynamicPrompt.format({ adjective: "rainy" })); +* ``` +*/ +var SemanticSimilarityExampleSelector = class SemanticSimilarityExampleSelector extends BaseExampleSelector { + vectorStoreRetriever; + exampleKeys; + inputKeys; + constructor(data) { + super(data); + this.exampleKeys = data.exampleKeys; + this.inputKeys = data.inputKeys; + if (data.vectorStore !== void 0) this.vectorStoreRetriever = data.vectorStore.asRetriever({ + k: data.k ?? 4, + filter: data.filter + }); + else if (data.vectorStoreRetriever) this.vectorStoreRetriever = data.vectorStoreRetriever; + else throw new Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`); + } + /** + * Method that adds a new example to the vectorStore. The example is + * converted to a string and added to the vectorStore as a document. + * @param example The example to be added to the vectorStore. + * @returns Promise that resolves when the example has been added to the vectorStore. + */ + async addExample(example) { + const inputKeys = this.inputKeys ?? Object.keys(example); + const stringExample = sortedValues(inputKeys.reduce((acc, key) => ({ + ...acc, + [key]: example[key] + }), {})).join(" "); + await this.vectorStoreRetriever.addDocuments([new Document({ + pageContent: stringExample, + metadata: example + })]); + } + /** + * Method that selects which examples to use based on semantic similarity. + * It performs a similarity search in the vectorStore using the input + * variables and returns the examples with the highest similarity. + * @param inputVariables The input variables used for the similarity search. + * @returns Promise that resolves with an array of the selected examples. + */ + async selectExamples(inputVariables) { + const inputKeys = this.inputKeys ?? Object.keys(inputVariables); + const query = sortedValues(inputKeys.reduce((acc, key) => ({ + ...acc, + [key]: inputVariables[key] + }), {})).join(" "); + const exampleDocs = await this.vectorStoreRetriever.invoke(query); + const examples = exampleDocs.map((doc) => doc.metadata); + if (this.exampleKeys) return examples.map((example) => this.exampleKeys.reduce((acc, key) => ({ + ...acc, + [key]: example[key] + }), {})); + return examples; + } + /** + * Static method that creates a new instance of + * SemanticSimilarityExampleSelector. It takes a list of examples, an + * instance of Embeddings, a VectorStore class, and an options object as + * parameters. It converts the examples to strings, creates a VectorStore + * from the strings and the embeddings, and returns a new + * SemanticSimilarityExampleSelector with the created VectorStore and the + * options provided. + * @param examples The list of examples to be used. + * @param embeddings The instance of Embeddings to be used. + * @param vectorStoreCls The VectorStore class to be used. + * @param options The options object for the SemanticSimilarityExampleSelector. + * @returns Promise that resolves with a new instance of SemanticSimilarityExampleSelector. + */ + static async fromExamples(examples, embeddings, vectorStoreCls, options = {}) { + const inputKeys = options.inputKeys ?? null; + const stringExamples = examples.map((example) => sortedValues(inputKeys ? inputKeys.reduce((acc, key) => ({ + ...acc, + [key]: example[key] + }), {}) : example).join(" ")); + const vectorStore = await vectorStoreCls.fromTexts(stringExamples, examples, embeddings, options); + return new SemanticSimilarityExampleSelector({ + vectorStore, + k: options.k ?? 4, + exampleKeys: options.exampleKeys, + inputKeys: options.inputKeys + }); + } +}; + +//#endregion + +//# sourceMappingURL=semantic_similarity.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/index.js + + + + + + +//#region src/example_selectors/index.ts +var example_selectors_exports = {}; +__export(example_selectors_exports, { + BaseExampleSelector: () => BaseExampleSelector, + BasePromptSelector: () => BasePromptSelector, + ConditionalPromptSelector: () => ConditionalPromptSelector, + LengthBasedExampleSelector: () => LengthBasedExampleSelector, + SemanticSimilarityExampleSelector: () => SemanticSimilarityExampleSelector, + isChatModel: () => isChatModel, + isLLM: () => isLLM +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/indexing/record_manager.js + + +//#region src/indexing/record_manager.ts +const UUIDV5_NAMESPACE = "10f90ea3-90a4-4962-bf75-83a0f3c1c62a"; +var RecordManager = class extends Serializable { + lc_namespace = ["langchain", "recordmanagers"]; +}; + +//#endregion + +//# sourceMappingURL=record_manager.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/indexing/base.js + + + + + + +//#region src/indexing/base.ts +/** +* HashedDocument is a Document with hashes calculated. +* Hashes are calculated based on page content and metadata. +* It is used for indexing. +*/ +var _HashedDocument = class { + uid; + hash_; + contentHash; + metadataHash; + pageContent; + metadata; + keyEncoder = sha256; + constructor(fields) { + this.uid = fields.uid; + this.pageContent = fields.pageContent; + this.metadata = fields.metadata; + } + makeDefaultKeyEncoder(keyEncoderFn) { + this.keyEncoder = keyEncoderFn; + } + calculateHashes() { + const forbiddenKeys = [ + "hash_", + "content_hash", + "metadata_hash" + ]; + for (const key of forbiddenKeys) if (key in this.metadata) throw new Error(`Metadata cannot contain key ${key} as it is reserved for internal use. Restricted keys: [${forbiddenKeys.join(", ")}]`); + const contentHash = this._hashStringToUUID(this.pageContent); + try { + const metadataHash = this._hashNestedDictToUUID(this.metadata); + this.contentHash = contentHash; + this.metadataHash = metadataHash; + } catch (e) { + throw new Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`); + } + this.hash_ = this._hashStringToUUID(this.contentHash + this.metadataHash); + if (!this.uid) this.uid = this.hash_; + } + toDocument() { + return new Document({ + pageContent: this.pageContent, + metadata: this.metadata + }); + } + static fromDocument(document, uid) { + const doc = new this({ + pageContent: document.pageContent, + metadata: document.metadata, + uid: uid || document.uid + }); + doc.calculateHashes(); + return doc; + } + _hashStringToUUID(inputString) { + const hash_value = this.keyEncoder(inputString); + return v5(hash_value, UUIDV5_NAMESPACE); + } + _hashNestedDictToUUID(data) { + const serialized_data = JSON.stringify(data, Object.keys(data).sort()); + const hash_value = this.keyEncoder(serialized_data); + return v5(hash_value, UUIDV5_NAMESPACE); + } +}; +function _batch(size, iterable) { + const batches = []; + let currentBatch = []; + iterable.forEach((item) => { + currentBatch.push(item); + if (currentBatch.length >= size) { + batches.push(currentBatch); + currentBatch = []; + } + }); + if (currentBatch.length > 0) batches.push(currentBatch); + return batches; +} +function _deduplicateInOrder(hashedDocuments) { + const seen = /* @__PURE__ */ new Set(); + const deduplicated = []; + for (const hashedDoc of hashedDocuments) { + if (!hashedDoc.hash_) throw new Error("Hashed document does not have a hash"); + if (!seen.has(hashedDoc.hash_)) { + seen.add(hashedDoc.hash_); + deduplicated.push(hashedDoc); + } + } + return deduplicated; +} +function _getSourceIdAssigner(sourceIdKey) { + if (sourceIdKey === null) return (_doc) => null; + else if (typeof sourceIdKey === "string") return (doc) => doc.metadata[sourceIdKey]; + else if (typeof sourceIdKey === "function") return sourceIdKey; + else throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`); +} +const _isBaseDocumentLoader = (arg) => { + if ("load" in arg && typeof arg.load === "function" && "loadAndSplit" in arg && typeof arg.loadAndSplit === "function") return true; + return false; +}; +/** +* Index data from the doc source into the vector store. +* +* Indexing functionality uses a manager to keep track of which documents +* are in the vector store. +* +* This allows us to keep track of which documents were updated, and which +* documents were deleted, which documents should be skipped. +* +* For the time being, documents are indexed using their hashes, and users +* are not able to specify the uid of the document. +* +* @param {IndexArgs} args +* @param {BaseDocumentLoader | DocumentInterface[]} args.docsSource The source of documents to index. Can be a DocumentLoader or a list of Documents. +* @param {RecordManagerInterface} args.recordManager The record manager to use for keeping track of indexed documents. +* @param {VectorStore} args.vectorStore The vector store to use for storing the documents. +* @param {IndexOptions | undefined} args.options Options for indexing. +* @returns {Promise} +*/ +async function index(args) { + const { docsSource, recordManager, vectorStore, options } = args; + const { batchSize = 100, cleanup, sourceIdKey, cleanupBatchSize = 1e3, forceUpdate = false } = options ?? {}; + if (cleanup === "incremental" && !sourceIdKey) throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'."); + const docs = _isBaseDocumentLoader(docsSource) ? await docsSource.load() : docsSource; + const sourceIdAssigner = _getSourceIdAssigner(sourceIdKey ?? null); + const indexStartDt = await recordManager.getTime(); + let numAdded = 0; + let numDeleted = 0; + let numUpdated = 0; + let numSkipped = 0; + const batches = _batch(batchSize ?? 100, docs); + for (const batch of batches) { + const hashedDocs = _deduplicateInOrder(batch.map((doc) => _HashedDocument.fromDocument(doc))); + const sourceIds = hashedDocs.map((doc) => sourceIdAssigner(doc)); + if (cleanup === "incremental") hashedDocs.forEach((_hashedDoc, index$1) => { + const source = sourceIds[index$1]; + if (source === null) throw new Error("sourceIdKey must be provided when cleanup is incremental"); + }); + const batchExists = await recordManager.exists(hashedDocs.map((doc) => doc.uid)); + const uids = []; + const docsToIndex = []; + const docsToUpdate = []; + const seenDocs = /* @__PURE__ */ new Set(); + hashedDocs.forEach((hashedDoc, i) => { + const docExists = batchExists[i]; + if (docExists) if (forceUpdate) seenDocs.add(hashedDoc.uid); + else { + docsToUpdate.push(hashedDoc.uid); + return; + } + uids.push(hashedDoc.uid); + docsToIndex.push(hashedDoc.toDocument()); + }); + if (docsToUpdate.length > 0) { + await recordManager.update(docsToUpdate, { timeAtLeast: indexStartDt }); + numSkipped += docsToUpdate.length; + } + if (docsToIndex.length > 0) { + await vectorStore.addDocuments(docsToIndex, { ids: uids }); + numAdded += docsToIndex.length - seenDocs.size; + numUpdated += seenDocs.size; + } + await recordManager.update(hashedDocs.map((doc) => doc.uid), { + timeAtLeast: indexStartDt, + groupIds: sourceIds + }); + if (cleanup === "incremental") { + sourceIds.forEach((sourceId) => { + if (!sourceId) throw new Error("Source id cannot be null"); + }); + const uidsToDelete = await recordManager.listKeys({ + before: indexStartDt, + groupIds: sourceIds + }); + if (uidsToDelete.length > 0) { + await vectorStore.delete({ ids: uidsToDelete }); + await recordManager.deleteKeys(uidsToDelete); + numDeleted += uidsToDelete.length; + } + } + } + if (cleanup === "full") { + let uidsToDelete = await recordManager.listKeys({ + before: indexStartDt, + limit: cleanupBatchSize + }); + while (uidsToDelete.length > 0) { + await vectorStore.delete({ ids: uidsToDelete }); + await recordManager.deleteKeys(uidsToDelete); + numDeleted += uidsToDelete.length; + uidsToDelete = await recordManager.listKeys({ + before: indexStartDt, + limit: cleanupBatchSize + }); + } + } + return { + numAdded, + numDeleted, + numUpdated, + numSkipped + }; +} + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/indexing/index.js + + + + +//#region src/indexing/index.ts +var indexing_exports = {}; +__export(indexing_exports, { + RecordManager: () => RecordManager, + UUIDV5_NAMESPACE: () => UUIDV5_NAMESPACE, + _HashedDocument: () => _HashedDocument, + _batch: () => _batch, + _deduplicateInOrder: () => _deduplicateInOrder, + _getSourceIdAssigner: () => _getSourceIdAssigner, + _isBaseDocumentLoader: () => _isBaseDocumentLoader, + index: () => index +}); + +//#endregion + +//# sourceMappingURL=index.js.map +// EXTERNAL MODULE: ./node_modules/base64-js/index.js +var base64_js = __nccwpck_require__(8793); +;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/chunk-VL2OQCWN.js + + +var chunk_VL2OQCWN_defProp = Object.defineProperty; +var __defNormalProp = (obj, key, value) => key in obj ? chunk_VL2OQCWN_defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; +var __publicField = (obj, key, value) => { + __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); + return value; +}; + +// src/utils.ts +function never(_) { +} +function bytePairMerge(piece, ranks) { + let parts = Array.from( + { length: piece.length }, + (_, i) => ({ start: i, end: i + 1 }) + ); + while (parts.length > 1) { + let minRank = null; + for (let i = 0; i < parts.length - 1; i++) { + const slice = piece.slice(parts[i].start, parts[i + 1].end); + const rank = ranks.get(slice.join(",")); + if (rank == null) + continue; + if (minRank == null || rank < minRank[0]) { + minRank = [rank, i]; + } + } + if (minRank != null) { + const i = minRank[1]; + parts[i] = { start: parts[i].start, end: parts[i + 1].end }; + parts.splice(i + 1, 1); + } else { + break; + } + } + return parts; +} +function bytePairEncode(piece, ranks) { + if (piece.length === 1) + return [ranks.get(piece.join(","))]; + return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); +} +function chunk_VL2OQCWN_escapeRegex(str) { + return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); +} +var _Tiktoken = class { + /** @internal */ + specialTokens; + /** @internal */ + inverseSpecialTokens; + /** @internal */ + patStr; + /** @internal */ + textEncoder = new TextEncoder(); + /** @internal */ + textDecoder = new TextDecoder("utf-8"); + /** @internal */ + rankMap = /* @__PURE__ */ new Map(); + /** @internal */ + textMap = /* @__PURE__ */ new Map(); + constructor(ranks, extendedSpecialTokens) { + this.patStr = ranks.pat_str; + const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { + const [_, offsetStr, ...tokens] = x.split(" "); + const offset = Number.parseInt(offsetStr, 10); + tokens.forEach((token, i) => memo[token] = offset + i); + return memo; + }, {}); + for (const [token, rank] of Object.entries(uncompressed)) { + const bytes = base64_js.toByteArray(token); + this.rankMap.set(bytes.join(","), rank); + this.textMap.set(rank, bytes); + } + this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; + this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { + memo[rank] = this.textEncoder.encode(text); + return memo; + }, {}); + } + encode(text, allowedSpecial = [], disallowedSpecial = "all") { + const regexes = new RegExp(this.patStr, "ug"); + const specialRegex = _Tiktoken.specialTokenRegex( + Object.keys(this.specialTokens) + ); + const ret = []; + const allowedSpecialSet = new Set( + allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial + ); + const disallowedSpecialSet = new Set( + disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( + (x) => !allowedSpecialSet.has(x) + ) : disallowedSpecial + ); + if (disallowedSpecialSet.size > 0) { + const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ + ...disallowedSpecialSet + ]); + const specialMatch = text.match(disallowedSpecialRegex); + if (specialMatch != null) { + throw new Error( + `The text contains a special token that is not allowed: ${specialMatch[0]}` + ); + } + } + let start = 0; + while (true) { + let nextSpecial = null; + let startFind = start; + while (true) { + specialRegex.lastIndex = startFind; + nextSpecial = specialRegex.exec(text); + if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) + break; + startFind = nextSpecial.index + 1; + } + const end = nextSpecial?.index ?? text.length; + for (const match of text.substring(start, end).matchAll(regexes)) { + const piece = this.textEncoder.encode(match[0]); + const token2 = this.rankMap.get(piece.join(",")); + if (token2 != null) { + ret.push(token2); + continue; + } + ret.push(...bytePairEncode(piece, this.rankMap)); + } + if (nextSpecial == null) + break; + let token = this.specialTokens[nextSpecial[0]]; + ret.push(token); + start = nextSpecial.index + nextSpecial[0].length; + } + return ret; + } + decode(tokens) { + const res = []; + let length = 0; + for (let i2 = 0; i2 < tokens.length; ++i2) { + const token = tokens[i2]; + const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; + if (bytes != null) { + res.push(bytes); + length += bytes.length; + } + } + const mergedArray = new Uint8Array(length); + let i = 0; + for (const bytes of res) { + mergedArray.set(bytes, i); + i += bytes.length; + } + return this.textDecoder.decode(mergedArray); + } +}; +var Tiktoken = _Tiktoken; +__publicField(Tiktoken, "specialTokenRegex", (tokens) => { + return new RegExp(tokens.map((i) => chunk_VL2OQCWN_escapeRegex(i)).join("|"), "g"); +}); +function getEncodingNameForModel(model) { + switch (model) { + case "gpt2": { + return "gpt2"; + } + case "code-cushman-001": + case "code-cushman-002": + case "code-davinci-001": + case "code-davinci-002": + case "cushman-codex": + case "davinci-codex": + case "davinci-002": + case "text-davinci-002": + case "text-davinci-003": { + return "p50k_base"; + } + case "code-davinci-edit-001": + case "text-davinci-edit-001": { + return "p50k_edit"; + } + case "ada": + case "babbage": + case "babbage-002": + case "code-search-ada-code-001": + case "code-search-babbage-code-001": + case "curie": + case "davinci": + case "text-ada-001": + case "text-babbage-001": + case "text-curie-001": + case "text-davinci-001": + case "text-search-ada-doc-001": + case "text-search-babbage-doc-001": + case "text-search-curie-doc-001": + case "text-search-davinci-doc-001": + case "text-similarity-ada-001": + case "text-similarity-babbage-001": + case "text-similarity-curie-001": + case "text-similarity-davinci-001": { + return "r50k_base"; + } + case "gpt-3.5-turbo-instruct-0914": + case "gpt-3.5-turbo-instruct": + case "gpt-3.5-turbo-16k-0613": + case "gpt-3.5-turbo-16k": + case "gpt-3.5-turbo-0613": + case "gpt-3.5-turbo-0301": + case "gpt-3.5-turbo": + case "gpt-4-32k-0613": + case "gpt-4-32k-0314": + case "gpt-4-32k": + case "gpt-4-0613": + case "gpt-4-0314": + case "gpt-4": + case "gpt-3.5-turbo-1106": + case "gpt-35-turbo": + case "gpt-4-1106-preview": + case "gpt-4-vision-preview": + case "gpt-3.5-turbo-0125": + case "gpt-4-turbo": + case "gpt-4-turbo-2024-04-09": + case "gpt-4-turbo-preview": + case "gpt-4-0125-preview": + case "text-embedding-ada-002": + case "text-embedding-3-small": + case "text-embedding-3-large": { + return "cl100k_base"; + } + case "gpt-4o": + case "gpt-4o-2024-05-13": + case "gpt-4o-2024-08-06": + case "gpt-4o-2024-11-20": + case "gpt-4o-mini-2024-07-18": + case "gpt-4o-mini": + case "gpt-4o-search-preview": + case "gpt-4o-search-preview-2025-03-11": + case "gpt-4o-mini-search-preview": + case "gpt-4o-mini-search-preview-2025-03-11": + case "gpt-4o-audio-preview": + case "gpt-4o-audio-preview-2024-12-17": + case "gpt-4o-audio-preview-2024-10-01": + case "gpt-4o-mini-audio-preview": + case "gpt-4o-mini-audio-preview-2024-12-17": + case "o1": + case "o1-2024-12-17": + case "o1-mini": + case "o1-mini-2024-09-12": + case "o1-preview": + case "o1-preview-2024-09-12": + case "o1-pro": + case "o1-pro-2025-03-19": + case "o3": + case "o3-2025-04-16": + case "o3-mini": + case "o3-mini-2025-01-31": + case "o4-mini": + case "o4-mini-2025-04-16": + case "chatgpt-4o-latest": + case "gpt-4o-realtime": + case "gpt-4o-realtime-preview-2024-10-01": + case "gpt-4o-realtime-preview-2024-12-17": + case "gpt-4o-mini-realtime-preview": + case "gpt-4o-mini-realtime-preview-2024-12-17": + case "gpt-4.1": + case "gpt-4.1-2025-04-14": + case "gpt-4.1-mini": + case "gpt-4.1-mini-2025-04-14": + case "gpt-4.1-nano": + case "gpt-4.1-nano-2025-04-14": + case "gpt-4.5-preview": + case "gpt-4.5-preview-2025-02-27": + case "gpt-5": + case "gpt-5-2025-08-07": + case "gpt-5-nano": + case "gpt-5-nano-2025-08-07": + case "gpt-5-mini": + case "gpt-5-mini-2025-08-07": + case "gpt-5-chat-latest": { + return "o200k_base"; + } + default: + throw new Error("Unknown model"); + } +} + + + +;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/lite.js + + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/tiktoken.js + + + + +//#region src/utils/tiktoken.ts +var tiktoken_exports = {}; +__export(tiktoken_exports, { + encodingForModel: () => encodingForModel, + getEncoding: () => getEncoding +}); +const cache = {}; +const caller = /* @__PURE__ */ new async_caller_AsyncCaller({}); +async function getEncoding(encoding) { + if (!(encoding in cache)) cache[encoding] = caller.fetch(`https://tiktoken.pages.dev/js/${encoding}.json`).then((res) => res.json()).then((data) => new Tiktoken(data)).catch((e) => { + delete cache[encoding]; + throw e; + }); + return await cache[encoding]; +} +async function encodingForModel(model) { + return getEncoding(getEncodingNameForModel(model)); +} + +//#endregion + +//# sourceMappingURL=tiktoken.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/base.js + + + + + + + + +//#region src/language_models/base.ts +var language_models_base_base_exports = {}; +__export(language_models_base_base_exports, { + BaseLangChain: () => BaseLangChain, + BaseLanguageModel: () => BaseLanguageModel, + calculateMaxTokens: () => calculateMaxTokens, + getEmbeddingContextSize: () => getEmbeddingContextSize, + getModelContextSize: () => getModelContextSize, + getModelNameForTiktoken: () => getModelNameForTiktoken, + isOpenAITool: () => isOpenAITool +}); +const getModelNameForTiktoken = (modelName) => { + if (modelName.startsWith("gpt-5")) return "gpt-5"; + if (modelName.startsWith("gpt-3.5-turbo-16k")) return "gpt-3.5-turbo-16k"; + if (modelName.startsWith("gpt-3.5-turbo-")) return "gpt-3.5-turbo"; + if (modelName.startsWith("gpt-4-32k")) return "gpt-4-32k"; + if (modelName.startsWith("gpt-4-")) return "gpt-4"; + if (modelName.startsWith("gpt-4o")) return "gpt-4o"; + return modelName; +}; +const getEmbeddingContextSize = (modelName) => { + switch (modelName) { + case "text-embedding-ada-002": return 8191; + default: return 2046; + } +}; +/** +* Get the context window size (max input tokens) for a given model. +* +* Context window sizes are sourced from official model documentation: +* - OpenAI: https://platform.openai.com/docs/models +* - Anthropic: https://docs.anthropic.com/claude/docs/models-overview +* - Google: https://ai.google.dev/gemini/docs/models/gemini +* +* @param modelName - The name of the model +* @returns The context window size in tokens +*/ +const getModelContextSize = (modelName) => { + const normalizedName = getModelNameForTiktoken(modelName); + switch (normalizedName) { + case "gpt-5": + case "gpt-5-turbo": + case "gpt-5-turbo-preview": return 4e5; + case "gpt-4o": + case "gpt-4o-mini": + case "gpt-4o-2024-05-13": + case "gpt-4o-2024-08-06": return 128e3; + case "gpt-4-turbo": + case "gpt-4-turbo-preview": + case "gpt-4-turbo-2024-04-09": + case "gpt-4-0125-preview": + case "gpt-4-1106-preview": return 128e3; + case "gpt-4-32k": + case "gpt-4-32k-0314": + case "gpt-4-32k-0613": return 32768; + case "gpt-4": + case "gpt-4-0314": + case "gpt-4-0613": return 8192; + case "gpt-3.5-turbo-16k": + case "gpt-3.5-turbo-16k-0613": return 16384; + case "gpt-3.5-turbo": + case "gpt-3.5-turbo-0301": + case "gpt-3.5-turbo-0613": + case "gpt-3.5-turbo-1106": + case "gpt-3.5-turbo-0125": return 4096; + case "text-davinci-003": + case "text-davinci-002": return 4097; + case "text-davinci-001": return 2049; + case "text-curie-001": + case "text-babbage-001": + case "text-ada-001": return 2048; + case "code-davinci-002": + case "code-davinci-001": return 8e3; + case "code-cushman-001": return 2048; + case "claude-3-5-sonnet-20241022": + case "claude-3-5-sonnet-20240620": + case "claude-3-opus-20240229": + case "claude-3-sonnet-20240229": + case "claude-3-haiku-20240307": + case "claude-2.1": return 2e5; + case "claude-2.0": + case "claude-instant-1.2": return 1e5; + case "gemini-1.5-pro": + case "gemini-1.5-pro-latest": + case "gemini-1.5-flash": + case "gemini-1.5-flash-latest": return 1e6; + case "gemini-pro": + case "gemini-pro-vision": return 32768; + default: return 4097; + } +}; +/** +* Whether or not the input matches the OpenAI tool definition. +* @param {unknown} tool The input to check. +* @returns {boolean} Whether the input is an OpenAI tool definition. +*/ +function isOpenAITool(tool) { + if (typeof tool !== "object" || !tool) return false; + if ("type" in tool && tool.type === "function" && "function" in tool && typeof tool.function === "object" && tool.function && "name" in tool.function && "parameters" in tool.function) return true; + return false; +} +const calculateMaxTokens = async ({ prompt, modelName }) => { + let numTokens; + try { + numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; + } catch { + console.warn("Failed to calculate number of tokens, falling back to approximate count"); + numTokens = Math.ceil(prompt.length / 4); + } + const maxTokens = getModelContextSize(modelName); + return maxTokens - numTokens; +}; +const getVerbosity = () => false; +/** +* Base class for language models, chains, tools. +*/ +var BaseLangChain = class extends Runnable { + /** + * Whether to print out response text. + */ + verbose; + callbacks; + tags; + metadata; + get lc_attributes() { + return { + callbacks: void 0, + verbose: void 0 + }; + } + constructor(params) { + super(params); + this.verbose = params.verbose ?? getVerbosity(); + this.callbacks = params.callbacks; + this.tags = params.tags ?? []; + this.metadata = params.metadata ?? {}; + } +}; +/** +* Base class for language models. +*/ +var BaseLanguageModel = class extends BaseLangChain { + /** + * Keys that the language model accepts as call options. + */ + get callKeys() { + return [ + "stop", + "timeout", + "signal", + "tags", + "metadata", + "callbacks" + ]; + } + /** + * The async caller should be used by subclasses to make any async calls, + * which will thus benefit from the concurrency and retry logic. + */ + caller; + cache; + constructor({ callbacks, callbackManager,...params }) { + const { cache,...rest } = params; + super({ + callbacks: callbacks ?? callbackManager, + ...rest + }); + if (typeof cache === "object") this.cache = cache; + else if (cache) this.cache = InMemoryCache.global(); + else this.cache = void 0; + this.caller = new async_caller_AsyncCaller(params ?? {}); + } + _encoding; + /** + * Get the number of tokens in the content. + * @param content The content to get the number of tokens for. + * @returns The number of tokens in the content. + */ + async getNumTokens(content) { + let textContent; + if (typeof content === "string") textContent = content; + else + /** + * Content is an array of ContentBlock + * + * ToDo(@christian-bromann): This is a temporary fix to get the number of tokens for the content. + * We need to find a better way to do this. + * @see https://github.com/langchain-ai/langchainjs/pull/8341#pullrequestreview-2933713116 + */ + textContent = content.map((item) => { + if (typeof item === "string") return item; + if (item.type === "text" && "text" in item) return item.text; + return ""; + }).join(""); + let numTokens = Math.ceil(textContent.length / 4); + if (!this._encoding) try { + this._encoding = await encodingForModel("modelName" in this ? getModelNameForTiktoken(this.modelName) : "gpt2"); + } catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error); + } + if (this._encoding) try { + numTokens = this._encoding.encode(textContent).length; + } catch (error) { + console.warn("Failed to calculate number of tokens, falling back to approximate count", error); + } + return numTokens; + } + static _convertInputToPromptValue(input) { + if (typeof input === "string") return new StringPromptValue(input); + else if (Array.isArray(input)) return new ChatPromptValue(input.map(utils_coerceMessageLikeToMessage)); + else return input; + } + /** + * Get the identifying parameters of the LLM. + */ + _identifyingParams() { + return {}; + } + /** + * Create a unique cache key for a specific call to a specific language model. + * @param callOptions Call options for the model + * @returns A unique cache key. + */ + _getSerializedCacheKeyParametersForCall({ config,...callOptions }) { + const params = { + ...this._identifyingParams(), + ...callOptions, + _type: this._llmType(), + _model: this._modelType() + }; + const filteredEntries = Object.entries(params).filter(([_, value]) => value !== void 0); + const serializedEntries = filteredEntries.map(([key, value]) => `${key}:${JSON.stringify(value)}`).sort().join(","); + return serializedEntries; + } + /** + * @deprecated + * Return a json-like object representing this LLM. + */ + serialize() { + return { + ...this._identifyingParams(), + _type: this._llmType(), + _model: this._modelType() + }; + } + /** + * @deprecated + * Load an LLM from a json-like object describing it. + */ + static async deserialize(_data) { + throw new Error("Use .toJSON() instead"); + } + /** + * Return profiling information for the model. + * + * @returns {ModelProfile} An object describing the model's capabilities and constraints + */ + get profile() { + return {}; + } +}; + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/passthrough.js + + + + +//#region src/runnables/passthrough.ts +/** +* A runnable to passthrough inputs unchanged or with additional keys. +* +* This runnable behaves almost like the identity function, except that it +* can be configured to add additional keys to the output, if the input is +* an object. +* +* The example below demonstrates how to use `RunnablePassthrough to +* passthrough the input from the `.invoke()` +* +* @example +* ```typescript +* const chain = RunnableSequence.from([ +* { +* question: new RunnablePassthrough(), +* context: async () => loadContextFromStore(), +* }, +* prompt, +* llm, +* outputParser, +* ]); +* const response = await chain.invoke( +* "I can pass a single string instead of an object since I'm using `RunnablePassthrough`." +* ); +* ``` +*/ +var RunnablePassthrough = class extends Runnable { + static lc_name() { + return "RunnablePassthrough"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + func; + constructor(fields) { + super(fields); + if (fields) this.func = fields.func; + } + async invoke(input, options) { + const config = ensureConfig(options); + if (this.func) await this.func(input, config); + return this._callWithConfig((input$1) => Promise.resolve(input$1), input, config); + } + async *transform(generator, options) { + const config = ensureConfig(options); + let finalOutput; + let finalOutputSupported = true; + for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) { + yield chunk; + if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = concat(finalOutput, chunk); + } catch { + finalOutput = void 0; + finalOutputSupported = false; + } + } + if (this.func && finalOutput !== void 0) await this.func(finalOutput, config); + } + /** + * A runnable that assigns key-value pairs to the input. + * + * The example below shows how you could use it with an inline function. + * + * @example + * ```typescript + * const prompt = + * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema} + * Question: {question} + * SQL Query:`); + * + * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()` + * // call (in this example it's the question), along with any inputs passed to the `.assign()` method. + * // In this case, we're passing the schema. + * const sqlQueryGeneratorChain = RunnableSequence.from([ + * RunnablePassthrough.assign({ + * schema: async () => db.getTableInfo(), + * }), + * prompt, + * new ChatOpenAI({ model: "gpt-4o-mini" }).withConfig({ stop: ["\nSQLResult:"] }), + * new StringOutputParser(), + * ]); + * const result = await sqlQueryGeneratorChain.invoke({ + * question: "How many employees are there?", + * }); + * ``` + */ + static assign(mapping) { + return new RunnableAssign(new RunnableMap({ steps: mapping })); + } +}; + +//#endregion + +//# sourceMappingURL=passthrough.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/utils.js +//#region src/language_models/utils.ts +const language_models_utils_iife = (fn) => fn(); +function castStandardMessageContent(message) { + const Cls = message.constructor; + return new Cls({ + ...message, + content: message.contentBlocks, + response_metadata: { + ...message.response_metadata, + output_version: "v1" + } + }); +} + +//#endregion + +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/chat_models.js + + + + + + + + + + + + + + + + + + +//#region src/language_models/chat_models.ts +var chat_models_exports = {}; +__export(chat_models_exports, { + BaseChatModel: () => BaseChatModel, + SimpleChatModel: () => SimpleChatModel +}); +function _formatForTracing(messages) { + const messagesToTrace = []; + for (const message of messages) { + let messageToTrace = message; + if (Array.isArray(message.content)) for (let idx = 0; idx < message.content.length; idx++) { + const block = message.content[idx]; + if (isURLContentBlock(block) || isBase64ContentBlock(block)) { + if (messageToTrace === message) messageToTrace = new message.constructor({ + ...messageToTrace, + content: [ + ...message.content.slice(0, idx), + convertToOpenAIImageBlock(block), + ...message.content.slice(idx + 1) + ] + }); + } + } + messagesToTrace.push(messageToTrace); + } + return messagesToTrace; +} +/** +* Base class for chat models. It extends the BaseLanguageModel class and +* provides methods for generating chat based on input messages. +*/ +var BaseChatModel = class BaseChatModel extends BaseLanguageModel { + lc_namespace = [ + "langchain", + "chat_models", + this._llmType() + ]; + disableStreaming = false; + outputVersion; + get callKeys() { + return [...super.callKeys, "outputVersion"]; + } + constructor(fields) { + super(fields); + this.outputVersion = language_models_utils_iife(() => { + const outputVersion = fields.outputVersion ?? getEnvironmentVariable("LC_OUTPUT_VERSION"); + if (outputVersion && ["v0", "v1"].includes(outputVersion)) return outputVersion; + return "v0"; + }); + } + _separateRunnableConfigFromCallOptionsCompat(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + callOptions.signal = runnableConfig.signal; + return [runnableConfig, callOptions]; + } + /** + * Invokes the chat model with a single input. + * @param input The input for the language model. + * @param options The call options. + * @returns A Promise that resolves to a BaseMessageChunk. + */ + async invoke(input, options) { + const promptValue = BaseChatModel._convertInputToPromptValue(input); + const result = await this.generatePrompt([promptValue], options, options?.callbacks); + const chatGeneration = result.generations[0][0]; + return chatGeneration.message; + } + async *_streamResponseChunks(_messages, _options, _runManager) { + throw new Error("Not implemented."); + } + async *_streamIterator(input, options) { + if (this._streamResponseChunks === BaseChatModel.prototype._streamResponseChunks || this.disableStreaming) yield this.invoke(input, options); + else { + const prompt = BaseChatModel._convertInputToPromptValue(input); + const messages = prompt.toChatMessages(); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); + const inheritableMetadata = { + ...runnableConfig.metadata, + ...this.getLsParams(callOptions) + }; + const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: callOptions, + invocation_params: this?.invocationParams(callOptions), + batch_size: 1 + }; + const outputVersion = callOptions.outputVersion ?? this.outputVersion; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName); + let generationChunk; + let llmOutput; + try { + for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) chunk.message._updateId(`run-${runId}`); + } + chunk.message.response_metadata = { + ...chunk.generationInfo, + ...chunk.message.response_metadata + }; + if (outputVersion === "v1") yield castStandardMessageContent(chunk.message); + else yield chunk.message; + if (!generationChunk) generationChunk = chunk; + else generationChunk = generationChunk.concat(chunk); + if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) llmOutput = { tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens + } }; + } + } catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ + generations: [[generationChunk]], + llmOutput + }))); + } + } + getLsParams(options) { + const providerName = this.getName().startsWith("Chat") ? this.getName().replace("Chat", "") : this.getName(); + return { + ls_model_type: "chat", + ls_stop: options.stop, + ls_provider: providerName + }; + } + /** @ignore */ + async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) { + const baseMessages = messages.map((messageList) => messageList.map(utils_coerceMessageLikeToMessage)); + let runManagers; + if (startedRunManagers !== void 0 && startedRunManagers.length === baseMessages.length) runManagers = startedRunManagers; + else { + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParams(parsedOptions) + }; + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: 1 + }; + runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName); + } + const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; + const generations = []; + const llmOutputs = []; + const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); + if (hasStreamingHandler && !this.disableStreaming && baseMessages.length === 1 && this._streamResponseChunks !== BaseChatModel.prototype._streamResponseChunks) try { + const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]); + let aggregated; + let llmOutput; + for await (const chunk of stream) { + if (chunk.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) chunk.message._updateId(`run-${runId}`); + } + if (aggregated === void 0) aggregated = chunk; + else aggregated = concat(aggregated, chunk); + if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) llmOutput = { tokenUsage: { + promptTokens: chunk.message.usage_metadata.input_tokens, + completionTokens: chunk.message.usage_metadata.output_tokens, + totalTokens: chunk.message.usage_metadata.total_tokens + } }; + } + if (aggregated === void 0) throw new Error("Received empty response from chat model call."); + generations.push([aggregated]); + await runManagers?.[0].handleLLMEnd({ + generations, + llmOutput + }); + } catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; + } + else { + const results = await Promise.allSettled(baseMessages.map(async (messageList, i) => { + const generateResults = await this._generate(messageList, { + ...parsedOptions, + promptIndex: i + }, runManagers?.[i]); + if (outputVersion === "v1") for (const generation of generateResults.generations) generation.message = castStandardMessageContent(generation.message); + return generateResults; + })); + await Promise.all(results.map(async (pResult, i) => { + if (pResult.status === "fulfilled") { + const result = pResult.value; + for (const generation of result.generations) { + if (generation.message.id == null) { + const runId = runManagers?.at(0)?.runId; + if (runId != null) generation.message._updateId(`run-${runId}`); + } + generation.message.response_metadata = { + ...generation.generationInfo, + ...generation.message.response_metadata + }; + } + if (result.generations.length === 1) result.generations[0].message.response_metadata = { + ...result.llmOutput, + ...result.generations[0].message.response_metadata + }; + generations[i] = result.generations; + llmOutputs[i] = result.llmOutput; + return runManagers?.[i]?.handleLLMEnd({ + generations: [result.generations], + llmOutput: result.llmOutput + }); + } else { + await runManagers?.[i]?.handleLLMError(pResult.reason); + return Promise.reject(pResult.reason); + } + })); + } + const output = { + generations, + llmOutput: llmOutputs.length ? this._combineLLMOutput?.(...llmOutputs) : void 0 + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, + configurable: true + }); + return output; + } + async _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions }) { + const baseMessages = messages.map((messageList) => messageList.map(utils_coerceMessageLikeToMessage)); + const inheritableMetadata = { + ...handledOptions.metadata, + ...this.getLsParams(parsedOptions) + }; + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: 1 + }; + const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName); + const missingPromptIndices = []; + const results = await Promise.allSettled(baseMessages.map(async (baseMessage, index) => { + const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); + const result = await cache.lookup(prompt, llmStringKey); + if (result == null) missingPromptIndices.push(index); + return result; + })); + const cachedResults = results.map((result, index) => ({ + result, + runManager: runManagers?.[index] + })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); + const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; + const generations = []; + await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { + if (promiseResult.status === "fulfilled") { + const result = promiseResult.value; + generations[i] = result.map((result$1) => { + if ("message" in result$1 && isBaseMessage(result$1.message) && isAIMessage(result$1.message)) { + result$1.message.usage_metadata = { + input_tokens: 0, + output_tokens: 0, + total_tokens: 0 + }; + if (outputVersion === "v1") result$1.message = castStandardMessageContent(result$1.message); + } + result$1.generationInfo = { + ...result$1.generationInfo, + tokenUsage: {} + }; + return result$1; + }); + if (result.length) await runManager?.handleLLMNewToken(result[0].text); + return runManager?.handleLLMEnd({ generations: [result] }, void 0, void 0, void 0, { cached: true }); + } else { + await runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { cached: true }); + return Promise.reject(promiseResult.reason); + } + })); + const output = { + generations, + missingPromptIndices, + startedRunManagers: runManagers + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, + configurable: true + }); + return output; + } + /** + * Generates chat based on the input messages. + * @param messages An array of arrays of BaseMessage instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generate(messages, options, callbacks) { + let parsedOptions; + if (Array.isArray(options)) parsedOptions = { stop: options }; + else parsedOptions = options; + const baseMessages = messages.map((messageList) => messageList.map(utils_coerceMessageLikeToMessage)); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) return this._generateUncached(baseMessages, callOptions, runnableConfig); + const { cache } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ + messages: baseMessages, + cache, + llmStringKey, + parsedOptions: callOptions, + handledOptions: runnableConfig + }); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0); + await Promise.all(results.generations.map(async (generation, index) => { + const promptIndex = missingPromptIndices[index]; + generations[promptIndex] = generation; + const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); + return cache.update(prompt, llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { + generations, + llmOutput + }; + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(_options) { + return {}; + } + _modelType() { + return "base_chat_model"; + } + /** + * Generates a prompt based on the input prompt values. + * @param promptValues An array of BasePromptValue instances. + * @param options The call options or an array of stop sequences. + * @param callbacks The callbacks for the language model. + * @returns A Promise that resolves to an LLMResult. + */ + async generatePrompt(promptValues, options, callbacks) { + const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); + return this.generate(promptMessages, options, callbacks); + } + withStructuredOutput(outputSchema, config) { + if (typeof this.bindTools !== "function") throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`); + if (config?.strict) throw new Error(`"strict" mode is not supported for this model by default.`); + const schema = outputSchema; + const name = config?.name; + const description = getSchemaDescription(schema) ?? "A function available to call."; + const method = config?.method; + const includeRaw = config?.includeRaw; + if (method === "jsonMode") throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`); + let functionName = name ?? "extract"; + let tools; + if (isInteropZodSchema(schema)) tools = [{ + type: "function", + function: { + name: functionName, + description, + parameters: toJsonSchema(schema) + } + }]; + else { + if ("name" in schema) functionName = schema.name; + tools = [{ + type: "function", + function: { + name: functionName, + description, + parameters: schema + } + }]; + } + const llm = this.bindTools(tools); + const outputParser = RunnableLambda.from((input) => { + if (!AIMessageChunk.isInstance(input)) throw new Error("Input is not an AIMessageChunk."); + if (!input.tool_calls || input.tool_calls.length === 0) throw new Error("No tool calls found in the response."); + const toolCall = input.tool_calls.find((tc) => tc.name === functionName); + if (!toolCall) throw new Error(`No tool call found with name ${functionName}.`); + return toolCall.args; + }); + if (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: "StructuredOutput" }); + const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); + const parserNone = RunnablePassthrough.assign({ parsed: () => null }); + const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); + return RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" }); + } +}; +/** +* An abstract class that extends BaseChatModel and provides a simple +* implementation of _generate. +*/ +var SimpleChatModel = class extends BaseChatModel { + async _generate(messages, options, runManager) { + const text = await this._call(messages, options, runManager); + const message = new AIMessage(text); + if (typeof message.content !== "string") throw new Error("Cannot generate with a simple chat model when output is not a string."); + return { generations: [{ + text: message.content, + message + }] }; + } +}; + +//#endregion + +//# sourceMappingURL=chat_models.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/llms.js + + + + + + + +//#region src/language_models/llms.ts +var llms_exports = {}; +__export(llms_exports, { + BaseLLM: () => BaseLLM, + LLM: () => LLM +}); +/** +* LLM Wrapper. Takes in a prompt (or prompts) and returns a string. +*/ +var BaseLLM = class BaseLLM extends BaseLanguageModel { + lc_namespace = [ + "langchain", + "llms", + this._llmType() + ]; + /** + * This method takes an input and options, and returns a string. It + * converts the input to a prompt value and generates a result based on + * the prompt. + * @param input Input for the LLM. + * @param options Options for the LLM call. + * @returns A string result based on the prompt. + */ + async invoke(input, options) { + const promptValue = BaseLLM._convertInputToPromptValue(input); + const result = await this.generatePrompt([promptValue], options, options?.callbacks); + return result.generations[0][0].text; + } + async *_streamResponseChunks(_input, _options, _runManager) { + throw new Error("Not implemented."); + } + _separateRunnableConfigFromCallOptionsCompat(options) { + const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); + callOptions.signal = runnableConfig.signal; + return [runnableConfig, callOptions]; + } + async *_streamIterator(input, options) { + if (this._streamResponseChunks === BaseLLM.prototype._streamResponseChunks) yield this.invoke(input, options); + else { + const prompt = BaseLLM._convertInputToPromptValue(input); + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); + const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: callOptions, + invocation_params: this?.invocationParams(callOptions), + batch_size: 1 + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName); + let generation = new GenerationChunk({ text: "" }); + try { + for await (const chunk of this._streamResponseChunks(prompt.toString(), callOptions, runManagers?.[0])) { + if (!generation) generation = chunk; + else generation = generation.concat(chunk); + if (typeof chunk.text === "string") yield chunk.text; + } + } catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ generations: [[generation]] }))); + } + } + /** + * This method takes prompt values, options, and callbacks, and generates + * a result based on the prompts. + * @param promptValues Prompt values for the LLM. + * @param options Options for the LLM call. + * @param callbacks Callbacks for the LLM call. + * @returns An LLMResult based on the prompts. + */ + async generatePrompt(promptValues, options, callbacks) { + const prompts = promptValues.map((promptValue) => promptValue.toString()); + return this.generate(prompts, options, callbacks); + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(_options) { + return {}; + } + _flattenLLMResult(llmResult) { + const llmResults = []; + for (let i = 0; i < llmResult.generations.length; i += 1) { + const genList = llmResult.generations[i]; + if (i === 0) llmResults.push({ + generations: [genList], + llmOutput: llmResult.llmOutput + }); + else { + const llmOutput = llmResult.llmOutput ? { + ...llmResult.llmOutput, + tokenUsage: {} + } : void 0; + llmResults.push({ + generations: [genList], + llmOutput + }); + } + } + return llmResults; + } + /** @ignore */ + async _generateUncached(prompts, parsedOptions, handledOptions, startedRunManagers) { + let runManagers; + if (startedRunManagers !== void 0 && startedRunManagers.length === prompts.length) runManagers = startedRunManagers; + else { + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: prompts.length + }; + runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, handledOptions.runId, void 0, extra, void 0, void 0, handledOptions?.runName); + } + const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); + let output; + if (hasStreamingHandler && prompts.length === 1 && this._streamResponseChunks !== BaseLLM.prototype._streamResponseChunks) try { + const stream = await this._streamResponseChunks(prompts[0], parsedOptions, runManagers?.[0]); + let aggregated; + for await (const chunk of stream) if (aggregated === void 0) aggregated = chunk; + else aggregated = concat(aggregated, chunk); + if (aggregated === void 0) throw new Error("Received empty response from chat model call."); + output = { + generations: [[aggregated]], + llmOutput: {} + }; + await runManagers?.[0].handleLLMEnd(output); + } catch (e) { + await runManagers?.[0].handleLLMError(e); + throw e; + } + else { + try { + output = await this._generate(prompts, parsedOptions, runManagers?.[0]); + } catch (err) { + await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); + throw err; + } + const flattenedOutputs = this._flattenLLMResult(output); + await Promise.all((runManagers ?? []).map((runManager, i) => runManager?.handleLLMEnd(flattenedOutputs[i]))); + } + const runIds = runManagers?.map((manager) => manager.runId) || void 0; + Object.defineProperty(output, RUN_KEY, { + value: runIds ? { runIds } : void 0, + configurable: true + }); + return output; + } + async _generateCached({ prompts, cache, llmStringKey, parsedOptions, handledOptions, runId }) { + const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); + const extra = { + options: parsedOptions, + invocation_params: this?.invocationParams(parsedOptions), + batch_size: prompts.length + }; + const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, runId, void 0, extra, void 0, void 0, handledOptions?.runName); + const missingPromptIndices = []; + const results = await Promise.allSettled(prompts.map(async (prompt, index) => { + const result = await cache.lookup(prompt, llmStringKey); + if (result == null) missingPromptIndices.push(index); + return result; + })); + const cachedResults = results.map((result, index) => ({ + result, + runManager: runManagers?.[index] + })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); + const generations = []; + await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { + if (promiseResult.status === "fulfilled") { + const result = promiseResult.value; + generations[i] = result.map((result$1) => { + result$1.generationInfo = { + ...result$1.generationInfo, + tokenUsage: {} + }; + return result$1; + }); + if (result.length) await runManager?.handleLLMNewToken(result[0].text); + return runManager?.handleLLMEnd({ generations: [result] }, void 0, void 0, void 0, { cached: true }); + } else { + await runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { cached: true }); + return Promise.reject(promiseResult.reason); + } + })); + const output = { + generations, + missingPromptIndices, + startedRunManagers: runManagers + }; + Object.defineProperty(output, RUN_KEY, { + value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, + configurable: true + }); + return output; + } + /** + * Run the LLM on the given prompts and input, handling caching. + */ + async generate(prompts, options, callbacks) { + if (!Array.isArray(prompts)) throw new Error("Argument 'prompts' is expected to be a string[]"); + let parsedOptions; + if (Array.isArray(options)) parsedOptions = { stop: options }; + else parsedOptions = options; + const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); + runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; + if (!this.cache) return this._generateUncached(prompts, callOptions, runnableConfig); + const { cache } = this; + const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); + const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ + prompts, + cache, + llmStringKey, + parsedOptions: callOptions, + handledOptions: runnableConfig, + runId: runnableConfig.runId + }); + let llmOutput = {}; + if (missingPromptIndices.length > 0) { + const results = await this._generateUncached(missingPromptIndices.map((i) => prompts[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0); + await Promise.all(results.generations.map(async (generation, index) => { + const promptIndex = missingPromptIndices[index]; + generations[promptIndex] = generation; + return cache.update(prompts[promptIndex], llmStringKey, generation); + })); + llmOutput = results.llmOutput ?? {}; + } + return { + generations, + llmOutput + }; + } + /** + * Get the identifying parameters of the LLM. + */ + _identifyingParams() { + return {}; + } + _modelType() { + return "base_llm"; + } +}; +/** +* LLM class that provides a simpler interface to subclass than {@link BaseLLM}. +* +* Requires only implementing a simpler {@link _call} method instead of {@link _generate}. +* +* @augments BaseLLM +*/ +var LLM = class extends BaseLLM { + async _generate(prompts, options, runManager) { + const generations = await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, { + ...options, + promptIndex + }, runManager).then((text) => [{ text }]))); + return { generations }; + } +}; + +//#endregion + +//# sourceMappingURL=llms.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/profile.js +//#region src/language_models/profile.ts +var profile_exports = {}; + +//#endregion + +//# sourceMappingURL=profile.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/retrievers/document_compressors/index.js + + +//#region src/retrievers/document_compressors/index.ts +var document_compressors_exports = {}; +__export(document_compressors_exports, { BaseDocumentCompressor: () => BaseDocumentCompressor }); +/** +* Base Document Compression class. All compressors should extend this class. +*/ +var BaseDocumentCompressor = class { + static isBaseDocumentCompressor(x) { + return x?.compressDocuments !== void 0; + } +}; + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/base.js + + +//#region src/prompts/base.ts +/** +* Base class for prompt templates. Exposes a format method that returns a +* string prompt given a set of input values. +*/ +var BasePromptTemplate = class extends Runnable { + lc_serializable = true; + lc_namespace = [ + "langchain_core", + "prompts", + this._getPromptType() + ]; + get lc_attributes() { + return { partialVariables: void 0 }; + } + inputVariables; + outputParser; + partialVariables; + /** + * Metadata to be used for tracing. + */ + metadata; + /** Tags to be used for tracing. */ + tags; + constructor(input) { + super(input); + const { inputVariables } = input; + if (inputVariables.includes("stop")) throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename."); + Object.assign(this, input); + } + /** + * Merges partial variables and user variables. + * @param userVariables The user variables to merge with the partial variables. + * @returns A Promise that resolves to an object containing the merged variables. + */ + async mergePartialAndUserVariables(userVariables) { + const partialVariables = this.partialVariables ?? {}; + const partialValues = {}; + for (const [key, value] of Object.entries(partialVariables)) if (typeof value === "string") partialValues[key] = value; + else partialValues[key] = await value(); + const allKwargs = { + ...partialValues, + ...userVariables + }; + return allKwargs; + } + /** + * Invokes the prompt template with the given input and options. + * @param input The input to invoke the prompt template with. + * @param options Optional configuration for the callback. + * @returns A Promise that resolves to the output of the prompt template. + */ + async invoke(input, options) { + const metadata = { + ...this.metadata, + ...options?.metadata + }; + const tags = [...this.tags ?? [], ...options?.tags ?? []]; + return this._callWithConfig((input$1) => this.formatPromptValue(input$1), input, { + ...options, + tags, + metadata, + runType: "prompt" + }); + } +}; + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/string.js + + + +//#region src/prompts/string.ts +/** +* Base class for string prompt templates. It extends the +* BasePromptTemplate class and overrides the formatPromptValue method to +* return a StringPromptValue. +*/ +var BaseStringPromptTemplate = class extends BasePromptTemplate { + /** + * Formats the prompt given the input values and returns a formatted + * prompt value. + * @param values The input values to format the prompt. + * @returns A Promise that resolves to a formatted prompt value. + */ + async formatPromptValue(values) { + const formattedPrompt = await this.format(values); + return new StringPromptValue(formattedPrompt); + } +}; + +//#endregion + +//# sourceMappingURL=string.js.map +;// CONCATENATED MODULE: ./node_modules/mustache/mustache.mjs +/*! + * mustache.js - Logic-less {{mustache}} templates with JavaScript + * http://github.com/janl/mustache.js + */ + +var mustache_objectToString = Object.prototype.toString; +var mustache_isArray = Array.isArray || function isArrayPolyfill (object) { + return mustache_objectToString.call(object) === '[object Array]'; +}; + +function isFunction (object) { + return typeof object === 'function'; +} + +/** + * More correct typeof string handling array + * which normally returns typeof 'object' + */ +function typeStr (obj) { + return mustache_isArray(obj) ? 'array' : typeof obj; +} + +function escapeRegExp (string) { + return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&'); +} + +/** + * Null safe way of checking whether or not an object, + * including its prototype, has a given property + */ +function hasProperty (obj, propName) { + return obj != null && typeof obj === 'object' && (propName in obj); +} + +/** + * Safe way of detecting whether or not the given thing is a primitive and + * whether it has the given property + */ +function primitiveHasOwnProperty (primitive, propName) { + return ( + primitive != null + && typeof primitive !== 'object' + && primitive.hasOwnProperty + && primitive.hasOwnProperty(propName) + ); +} + +// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577 +// See https://github.com/janl/mustache.js/issues/189 +var regExpTest = RegExp.prototype.test; +function testRegExp (re, string) { + return regExpTest.call(re, string); +} + +var nonSpaceRe = /\S/; +function isWhitespace (string) { + return !testRegExp(nonSpaceRe, string); +} + +var entityMap = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''', + '/': '/', + '`': '`', + '=': '=' +}; + +function escapeHtml (string) { + return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) { + return entityMap[s]; + }); +} + +var whiteRe = /\s*/; +var spaceRe = /\s+/; +var equalsRe = /\s*=/; +var curlyRe = /\s*\}/; +var tagRe = /#|\^|\/|>|\{|&|=|!/; + +/** + * Breaks up the given `template` string into a tree of tokens. If the `tags` + * argument is given here it must be an array with two string values: the + * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of + * course, the default is to use mustaches (i.e. mustache.tags). + * + * A token is an array with at least 4 elements. The first element is the + * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag + * did not contain a symbol (i.e. {{myValue}}) this element is "name". For + * all text that appears outside a symbol this element is "text". + * + * The second element of a token is its "value". For mustache tags this is + * whatever else was inside the tag besides the opening symbol. For text tokens + * this is the text itself. + * + * The third and fourth elements of the token are the start and end indices, + * respectively, of the token in the original template. + * + * Tokens that are the root node of a subtree contain two more elements: 1) an + * array of tokens in the subtree and 2) the index in the original template at + * which the closing tag for that section begins. + * + * Tokens for partials also contain two more elements: 1) a string value of + * indendation prior to that tag and 2) the index of that tag on that line - + * eg a value of 2 indicates the partial is the third tag on this line. + */ +function parseTemplate (template, tags) { + if (!template) + return []; + var lineHasNonSpace = false; + var sections = []; // Stack to hold section tokens + var tokens = []; // Buffer to hold the tokens + var spaces = []; // Indices of whitespace tokens on the current line + var hasTag = false; // Is there a {{tag}} on the current line? + var nonSpace = false; // Is there a non-space char on the current line? + var indentation = ''; // Tracks indentation for tags that use it + var tagIndex = 0; // Stores a count of number of tags encountered on a line + + // Strips all whitespace tokens array for the current line + // if there was a {{#tag}} on it and otherwise only space. + function stripSpace () { + if (hasTag && !nonSpace) { + while (spaces.length) + delete tokens[spaces.pop()]; + } else { + spaces = []; + } + + hasTag = false; + nonSpace = false; + } + + var openingTagRe, closingTagRe, closingCurlyRe; + function compileTags (tagsToCompile) { + if (typeof tagsToCompile === 'string') + tagsToCompile = tagsToCompile.split(spaceRe, 2); + + if (!mustache_isArray(tagsToCompile) || tagsToCompile.length !== 2) + throw new Error('Invalid tags: ' + tagsToCompile); + + openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*'); + closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1])); + closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1])); + } + + compileTags(tags || mustache.tags); + + var scanner = new Scanner(template); + + var start, type, value, chr, token, openSection; + while (!scanner.eos()) { + start = scanner.pos; + + // Match any text between tags. + value = scanner.scanUntil(openingTagRe); + + if (value) { + for (var i = 0, valueLength = value.length; i < valueLength; ++i) { + chr = value.charAt(i); + + if (isWhitespace(chr)) { + spaces.push(tokens.length); + indentation += chr; + } else { + nonSpace = true; + lineHasNonSpace = true; + indentation += ' '; + } + + tokens.push([ 'text', chr, start, start + 1 ]); + start += 1; + + // Check for whitespace on the current line. + if (chr === '\n') { + stripSpace(); + indentation = ''; + tagIndex = 0; + lineHasNonSpace = false; + } + } + } + + // Match the opening tag. + if (!scanner.scan(openingTagRe)) + break; + + hasTag = true; + + // Get the tag type. + type = scanner.scan(tagRe) || 'name'; + scanner.scan(whiteRe); + + // Get the tag value. + if (type === '=') { + value = scanner.scanUntil(equalsRe); + scanner.scan(equalsRe); + scanner.scanUntil(closingTagRe); + } else if (type === '{') { + value = scanner.scanUntil(closingCurlyRe); + scanner.scan(curlyRe); + scanner.scanUntil(closingTagRe); + type = '&'; + } else { + value = scanner.scanUntil(closingTagRe); + } + + // Match the closing tag. + if (!scanner.scan(closingTagRe)) + throw new Error('Unclosed tag at ' + scanner.pos); + + if (type == '>') { + token = [ type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace ]; + } else { + token = [ type, value, start, scanner.pos ]; + } + tagIndex++; + tokens.push(token); + + if (type === '#' || type === '^') { + sections.push(token); + } else if (type === '/') { + // Check section nesting. + openSection = sections.pop(); + + if (!openSection) + throw new Error('Unopened section "' + value + '" at ' + start); + + if (openSection[1] !== value) + throw new Error('Unclosed section "' + openSection[1] + '" at ' + start); + } else if (type === 'name' || type === '{' || type === '&') { + nonSpace = true; + } else if (type === '=') { + // Set the tags for the next time around. + compileTags(value); + } + } + + stripSpace(); + + // Make sure there are no open sections when we're done. + openSection = sections.pop(); + + if (openSection) + throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); + + return nestTokens(squashTokens(tokens)); +} + +/** + * Combines the values of consecutive text tokens in the given `tokens` array + * to a single token. + */ +function squashTokens (tokens) { + var squashedTokens = []; + + var token, lastToken; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + token = tokens[i]; + + if (token) { + if (token[0] === 'text' && lastToken && lastToken[0] === 'text') { + lastToken[1] += token[1]; + lastToken[3] = token[3]; + } else { + squashedTokens.push(token); + lastToken = token; + } + } + } + + return squashedTokens; +} + +/** + * Forms the given array of `tokens` into a nested tree structure where + * tokens that represent a section have two additional items: 1) an array of + * all tokens that appear in that section and 2) the index in the original + * template that represents the end of that section. + */ +function nestTokens (tokens) { + var nestedTokens = []; + var collector = nestedTokens; + var sections = []; + + var token, section; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + token = tokens[i]; + + switch (token[0]) { + case '#': + case '^': + collector.push(token); + sections.push(token); + collector = token[4] = []; + break; + case '/': + section = sections.pop(); + section[5] = token[2]; + collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; + break; + default: + collector.push(token); + } + } + + return nestedTokens; +} + +/** + * A simple string scanner that is used by the template parser to find + * tokens in template strings. + */ +function Scanner (string) { + this.string = string; + this.tail = string; + this.pos = 0; +} + +/** + * Returns `true` if the tail is empty (end of string). + */ +Scanner.prototype.eos = function eos () { + return this.tail === ''; +}; + +/** + * Tries to match the given regular expression at the current position. + * Returns the matched text if it can match, the empty string otherwise. + */ +Scanner.prototype.scan = function scan (re) { + var match = this.tail.match(re); + + if (!match || match.index !== 0) + return ''; + + var string = match[0]; + + this.tail = this.tail.substring(string.length); + this.pos += string.length; + + return string; +}; + +/** + * Skips all text until the given regular expression can be matched. Returns + * the skipped string, which is the entire tail if no match can be made. + */ +Scanner.prototype.scanUntil = function scanUntil (re) { + var index = this.tail.search(re), match; + + switch (index) { + case -1: + match = this.tail; + this.tail = ''; + break; + case 0: + match = ''; + break; + default: + match = this.tail.substring(0, index); + this.tail = this.tail.substring(index); + } + + this.pos += match.length; + + return match; +}; + +/** + * Represents a rendering context by wrapping a view object and + * maintaining a reference to the parent context. + */ +function Context (view, parentContext) { + this.view = view; + this.cache = { '.': this.view }; + this.parent = parentContext; +} + +/** + * Creates a new context using the given view with this context + * as the parent. + */ +Context.prototype.push = function push (view) { + return new Context(view, this); +}; + +/** + * Returns the value of the given name in this context, traversing + * up the context hierarchy if the value is absent in this context's view. + */ +Context.prototype.lookup = function lookup (name) { + var cache = this.cache; + + var value; + if (cache.hasOwnProperty(name)) { + value = cache[name]; + } else { + var context = this, intermediateValue, names, index, lookupHit = false; + + while (context) { + if (name.indexOf('.') > 0) { + intermediateValue = context.view; + names = name.split('.'); + index = 0; + + /** + * Using the dot notion path in `name`, we descend through the + * nested objects. + * + * To be certain that the lookup has been successful, we have to + * check if the last object in the path actually has the property + * we are looking for. We store the result in `lookupHit`. + * + * This is specially necessary for when the value has been set to + * `undefined` and we want to avoid looking up parent contexts. + * + * In the case where dot notation is used, we consider the lookup + * to be successful even if the last "object" in the path is + * not actually an object but a primitive (e.g., a string, or an + * integer), because it is sometimes useful to access a property + * of an autoboxed primitive, such as the length of a string. + **/ + while (intermediateValue != null && index < names.length) { + if (index === names.length - 1) + lookupHit = ( + hasProperty(intermediateValue, names[index]) + || primitiveHasOwnProperty(intermediateValue, names[index]) + ); + + intermediateValue = intermediateValue[names[index++]]; + } + } else { + intermediateValue = context.view[name]; + + /** + * Only checking against `hasProperty`, which always returns `false` if + * `context.view` is not an object. Deliberately omitting the check + * against `primitiveHasOwnProperty` if dot notation is not used. + * + * Consider this example: + * ``` + * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"}) + * ``` + * + * If we were to check also against `primitiveHasOwnProperty`, as we do + * in the dot notation case, then render call would return: + * + * "The length of a football field is 9." + * + * rather than the expected: + * + * "The length of a football field is 100 yards." + **/ + lookupHit = hasProperty(context.view, name); + } + + if (lookupHit) { + value = intermediateValue; + break; + } + + context = context.parent; + } + + cache[name] = value; + } + + if (isFunction(value)) + value = value.call(this.view); + + return value; +}; + +/** + * A Writer knows how to take a stream of tokens and render them to a + * string, given a context. It also maintains a cache of templates to + * avoid the need to parse the same template twice. + */ +function Writer () { + this.templateCache = { + _cache: {}, + set: function set (key, value) { + this._cache[key] = value; + }, + get: function get (key) { + return this._cache[key]; + }, + clear: function clear () { + this._cache = {}; + } + }; +} + +/** + * Clears all cached templates in this writer. + */ +Writer.prototype.clearCache = function clearCache () { + if (typeof this.templateCache !== 'undefined') { + this.templateCache.clear(); + } +}; + +/** + * Parses and caches the given `template` according to the given `tags` or + * `mustache.tags` if `tags` is omitted, and returns the array of tokens + * that is generated from the parse. + */ +Writer.prototype.parse = function parse (template, tags) { + var cache = this.templateCache; + var cacheKey = template + ':' + (tags || mustache.tags).join(':'); + var isCacheEnabled = typeof cache !== 'undefined'; + var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined; + + if (tokens == undefined) { + tokens = parseTemplate(template, tags); + isCacheEnabled && cache.set(cacheKey, tokens); + } + return tokens; +}; + +/** + * High-level method that is used to render the given `template` with + * the given `view`. + * + * The optional `partials` argument may be an object that contains the + * names and templates of partials that are used in the template. It may + * also be a function that is used to load partial templates on the fly + * that takes a single argument: the name of the partial. + * + * If the optional `config` argument is given here, then it should be an + * object with a `tags` attribute or an `escape` attribute or both. + * If an array is passed, then it will be interpreted the same way as + * a `tags` attribute on a `config` object. + * + * The `tags` attribute of a `config` object must be an array with two + * string values: the opening and closing tags used in the template (e.g. + * [ "<%", "%>" ]). The default is to mustache.tags. + * + * The `escape` attribute of a `config` object must be a function which + * accepts a string as input and outputs a safely escaped string. + * If an `escape` function is not provided, then an HTML-safe string + * escaping function is used as the default. + */ +Writer.prototype.render = function render (template, view, partials, config) { + var tags = this.getConfigTags(config); + var tokens = this.parse(template, tags); + var context = (view instanceof Context) ? view : new Context(view, undefined); + return this.renderTokens(tokens, context, partials, template, config); +}; + +/** + * Low-level method that renders the given array of `tokens` using + * the given `context` and `partials`. + * + * Note: The `originalTemplate` is only ever used to extract the portion + * of the original template that was contained in a higher-order section. + * If the template doesn't use higher-order sections, this argument may + * be omitted. + */ +Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, config) { + var buffer = ''; + + var token, symbol, value; + for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { + value = undefined; + token = tokens[i]; + symbol = token[0]; + + if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate, config); + else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate, config); + else if (symbol === '>') value = this.renderPartial(token, context, partials, config); + else if (symbol === '&') value = this.unescapedValue(token, context); + else if (symbol === 'name') value = this.escapedValue(token, context, config); + else if (symbol === 'text') value = this.rawValue(token); + + if (value !== undefined) + buffer += value; + } + + return buffer; +}; + +Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate, config) { + var self = this; + var buffer = ''; + var value = context.lookup(token[1]); + + // This function is used to render an arbitrary template + // in the current context by higher-order sections. + function subRender (template) { + return self.render(template, context, partials, config); + } + + if (!value) return; + + if (mustache_isArray(value)) { + for (var j = 0, valueLength = value.length; j < valueLength; ++j) { + buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config); + } + } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') { + buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config); + } else if (isFunction(value)) { + if (typeof originalTemplate !== 'string') + throw new Error('Cannot use higher-order sections without the original template'); + + // Extract the portion of the original template that the section contains. + value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender); + + if (value != null) + buffer += value; + } else { + buffer += this.renderTokens(token[4], context, partials, originalTemplate, config); + } + return buffer; +}; + +Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate, config) { + var value = context.lookup(token[1]); + + // Use JavaScript's definition of falsy. Include empty arrays. + // See https://github.com/janl/mustache.js/issues/186 + if (!value || (mustache_isArray(value) && value.length === 0)) + return this.renderTokens(token[4], context, partials, originalTemplate, config); +}; + +Writer.prototype.indentPartial = function indentPartial (partial, indentation, lineHasNonSpace) { + var filteredIndentation = indentation.replace(/[^ \t]/g, ''); + var partialByNl = partial.split('\n'); + for (var i = 0; i < partialByNl.length; i++) { + if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) { + partialByNl[i] = filteredIndentation + partialByNl[i]; + } + } + return partialByNl.join('\n'); +}; + +Writer.prototype.renderPartial = function renderPartial (token, context, partials, config) { + if (!partials) return; + var tags = this.getConfigTags(config); + + var value = isFunction(partials) ? partials(token[1]) : partials[token[1]]; + if (value != null) { + var lineHasNonSpace = token[6]; + var tagIndex = token[5]; + var indentation = token[4]; + var indentedValue = value; + if (tagIndex == 0 && indentation) { + indentedValue = this.indentPartial(value, indentation, lineHasNonSpace); + } + var tokens = this.parse(indentedValue, tags); + return this.renderTokens(tokens, context, partials, indentedValue, config); + } +}; + +Writer.prototype.unescapedValue = function unescapedValue (token, context) { + var value = context.lookup(token[1]); + if (value != null) + return value; +}; + +Writer.prototype.escapedValue = function escapedValue (token, context, config) { + var escape = this.getConfigEscape(config) || mustache.escape; + var value = context.lookup(token[1]); + if (value != null) + return (typeof value === 'number' && escape === mustache.escape) ? String(value) : escape(value); +}; + +Writer.prototype.rawValue = function rawValue (token) { + return token[1]; +}; + +Writer.prototype.getConfigTags = function getConfigTags (config) { + if (mustache_isArray(config)) { + return config; + } + else if (config && typeof config === 'object') { + return config.tags; + } + else { + return undefined; + } +}; + +Writer.prototype.getConfigEscape = function getConfigEscape (config) { + if (config && typeof config === 'object' && !mustache_isArray(config)) { + return config.escape; + } + else { + return undefined; + } +}; + +var mustache = { + name: 'mustache.js', + version: '4.2.0', + tags: [ '{{', '}}' ], + clearCache: undefined, + escape: undefined, + parse: undefined, + render: undefined, + Scanner: undefined, + Context: undefined, + Writer: undefined, + /** + * Allows a user to override the default caching strategy, by providing an + * object with set, get and clear methods. This can also be used to disable + * the cache by setting it to the literal `undefined`. + */ + set templateCache (cache) { + defaultWriter.templateCache = cache; + }, + /** + * Gets the default or overridden caching object from the default writer. + */ + get templateCache () { + return defaultWriter.templateCache; + } +}; + +// All high-level mustache.* functions use this writer. +var defaultWriter = new Writer(); + +/** + * Clears all cached templates in the default writer. + */ +mustache.clearCache = function clearCache () { + return defaultWriter.clearCache(); +}; + +/** + * Parses and caches the given template in the default writer and returns the + * array of tokens it contains. Doing this ahead of time avoids the need to + * parse templates on the fly as they are rendered. + */ +mustache.parse = function parse (template, tags) { + return defaultWriter.parse(template, tags); +}; + +/** + * Renders the `template` with the given `view`, `partials`, and `config` + * using the default writer. + */ +mustache.render = function render (template, view, partials, config) { + if (typeof template !== 'string') { + throw new TypeError('Invalid template! Template should be a "string" ' + + 'but "' + typeStr(template) + '" was given as the first ' + + 'argument for mustache#render(template, view, partials)'); + } + + return defaultWriter.render(template, view, partials, config); +}; + +// Export the escaping function so that the user may override it. +// See https://github.com/janl/mustache.js/issues/244 +mustache.escape = escapeHtml; + +// Export these mainly for testing, but also for advanced usage. +mustache.Scanner = Scanner; +mustache.Context = Context; +mustache.Writer = Writer; + +/* harmony default export */ const mustache_mustache = (mustache); + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/template.js + + + +//#region src/prompts/template.ts +function configureMustache() { + mustache_mustache.escape = (text) => text; +} +const parseFString = (template) => { + const chars = template.split(""); + const nodes = []; + const nextBracket = (bracket, start) => { + for (let i$1 = start; i$1 < chars.length; i$1 += 1) if (bracket.includes(chars[i$1])) return i$1; + return -1; + }; + let i = 0; + while (i < chars.length) if (chars[i] === "{" && i + 1 < chars.length && chars[i + 1] === "{") { + nodes.push({ + type: "literal", + text: "{" + }); + i += 2; + } else if (chars[i] === "}" && i + 1 < chars.length && chars[i + 1] === "}") { + nodes.push({ + type: "literal", + text: "}" + }); + i += 2; + } else if (chars[i] === "{") { + const j = nextBracket("}", i); + if (j < 0) throw new Error("Unclosed '{' in template."); + nodes.push({ + type: "variable", + name: chars.slice(i + 1, j).join("") + }); + i = j + 1; + } else if (chars[i] === "}") throw new Error("Single '}' in template."); + else { + const next = nextBracket("{}", i); + const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(""); + nodes.push({ + type: "literal", + text + }); + i = next < 0 ? chars.length : next; + } + return nodes; +}; +/** +* Convert the result of mustache.parse into an array of ParsedTemplateNode, +* to make it compatible with other LangChain string parsing template formats. +* +* @param {mustache.TemplateSpans} template The result of parsing a mustache template with the mustache.js library. +* @param {string[]} context Array of section variable names for nested context +* @returns {ParsedTemplateNode[]} +*/ +const mustacheTemplateToNodes = (template, context = []) => { + const nodes = []; + for (const temp of template) if (temp[0] === "name") { + const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1]; + nodes.push({ + type: "variable", + name + }); + } else if ([ + "#", + "&", + "^", + ">" + ].includes(temp[0])) { + nodes.push({ + type: "variable", + name: temp[1] + }); + if (temp[0] === "#" && temp.length > 4 && Array.isArray(temp[4])) { + const newContext = [...context, temp[1]]; + const nestedNodes = mustacheTemplateToNodes(temp[4], newContext); + nodes.push(...nestedNodes); + } + } else nodes.push({ + type: "literal", + text: temp[1] + }); + return nodes; +}; +const parseMustache = (template) => { + configureMustache(); + const parsed = mustache_mustache.parse(template); + return mustacheTemplateToNodes(parsed); +}; +const interpolateFString = (template, values) => { + return parseFString(template).reduce((res, node) => { + if (node.type === "variable") { + if (node.name in values) { + const stringValue = typeof values[node.name] === "string" ? values[node.name] : JSON.stringify(values[node.name]); + return res + stringValue; + } + throw new Error(`(f-string) Missing value for input ${node.name}`); + } + return res + node.text; + }, ""); +}; +const interpolateMustache = (template, values) => { + configureMustache(); + return mustache_mustache.render(template, values); +}; +const DEFAULT_FORMATTER_MAPPING = { + "f-string": interpolateFString, + mustache: interpolateMustache +}; +const DEFAULT_PARSER_MAPPING = { + "f-string": parseFString, + mustache: parseMustache +}; +const renderTemplate = (template, templateFormat, inputValues) => { + try { + return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues); + } catch (e) { + const error = addLangChainErrorFields(e, "INVALID_PROMPT_INPUT"); + throw error; + } +}; +const template_parseTemplate = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template); +const checkValidTemplate = (template, templateFormat, inputVariables) => { + if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) { + const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING); + throw new Error(`Invalid template format. Got \`${templateFormat}\`; + should be one of ${validFormats}`); + } + try { + const dummyInputs = inputVariables.reduce((acc, v) => { + acc[v] = "foo"; + return acc; + }, {}); + if (Array.isArray(template)) template.forEach((message) => { + if (message.type === "text" && "text" in message && typeof message.text === "string") renderTemplate(message.text, templateFormat, dummyInputs); + else if (message.type === "image_url") { + if (typeof message.image_url === "string") renderTemplate(message.image_url, templateFormat, dummyInputs); + else if (typeof message.image_url === "object" && message.image_url !== null && "url" in message.image_url && typeof message.image_url.url === "string") { + const imageUrl = message.image_url.url; + renderTemplate(imageUrl, templateFormat, dummyInputs); + } + } else throw new Error(`Invalid message template received. ${JSON.stringify(message, null, 2)}`); + }); + else renderTemplate(template, templateFormat, dummyInputs); + } catch (e) { + throw new Error(`Invalid prompt schema: ${e.message}`); + } +}; + +//#endregion + +//# sourceMappingURL=template.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/prompt.js + + + +//#region src/prompts/prompt.ts +/** +* Schema to represent a basic prompt for an LLM. +* @augments BasePromptTemplate +* @augments PromptTemplateInput +* +* @example +* ```ts +* import { PromptTemplate } from "langchain/prompts"; +* +* const prompt = new PromptTemplate({ +* inputVariables: ["foo"], +* template: "Say {foo}", +* }); +* ``` +*/ +var PromptTemplate = class PromptTemplate extends BaseStringPromptTemplate { + static lc_name() { + return "PromptTemplate"; + } + template; + templateFormat = "f-string"; + validateTemplate = true; + /** + * Additional fields which should be included inside + * the message content array if using a complex message + * content. + */ + additionalContentFields; + constructor(input) { + super(input); + if (input.templateFormat === "mustache" && input.validateTemplate === void 0) this.validateTemplate = false; + Object.assign(this, input); + if (this.validateTemplate) { + if (this.templateFormat === "mustache") throw new Error("Mustache templates cannot be validated."); + let totalInputVariables = this.inputVariables; + if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + checkValidTemplate(this.template, this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "prompt"; + } + /** + * Formats the prompt template with the provided values. + * @param values The values to be used to format the prompt template. + * @returns A promise that resolves to a string which is the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + return renderTemplate(this.template, this.templateFormat, allValues); + } + /** + * Take examples in list format with prefix and suffix to create a prompt. + * + * Intended to be used a a way to dynamically create a prompt from examples. + * + * @param examples - List of examples to use in the prompt. + * @param suffix - String to go after the list of examples. Should generally set up the user's input. + * @param inputVariables - A list of variable names the final prompt template will expect + * @param exampleSeparator - The separator to use in between examples + * @param prefix - String that should go before any examples. Generally includes examples. + * + * @returns The final prompt template generated. + */ + static fromExamples(examples, suffix, inputVariables, exampleSeparator = "\n\n", prefix = "") { + const template = [ + prefix, + ...examples, + suffix + ].join(exampleSeparator); + return new PromptTemplate({ + inputVariables, + template + }); + } + static fromTemplate(template, options) { + const { templateFormat = "f-string",...rest } = options ?? {}; + const names = /* @__PURE__ */ new Set(); + template_parseTemplate(template, templateFormat).forEach((node) => { + if (node.type === "variable") names.add(node.name); + }); + return new PromptTemplate({ + inputVariables: [...names], + templateFormat, + template, + ...rest + }); + } + /** + * Partially applies values to the prompt template. + * @param values The values to be partially applied to the prompt template. + * @returns A new instance of PromptTemplate with the partially applied values. + */ + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }; + return new PromptTemplate(promptDict); + } + serialize() { + if (this.outputParser !== void 0) throw new Error("Cannot serialize a prompt template with an output parser"); + return { + _type: this._getPromptType(), + input_variables: this.inputVariables, + template: this.template, + template_format: this.templateFormat + }; + } + static async deserialize(data) { + if (!data.template) throw new Error("Prompt template must have a template"); + const res = new PromptTemplate({ + inputVariables: data.input_variables, + template: data.template, + templateFormat: data.template_format + }); + return res; + } +}; + +//#endregion + +//# sourceMappingURL=prompt.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/image.js + + + + +//#region src/prompts/image.ts +/** +* An image prompt template for a multimodal model. +*/ +var ImagePromptTemplate = class ImagePromptTemplate extends BasePromptTemplate { + static lc_name() { + return "ImagePromptTemplate"; + } + lc_namespace = [ + "langchain_core", + "prompts", + "image" + ]; + template; + templateFormat = "f-string"; + validateTemplate = true; + /** + * Additional fields which should be included inside + * the message content array if using a complex message + * content. + */ + additionalContentFields; + constructor(input) { + super(input); + this.template = input.template; + this.templateFormat = input.templateFormat ?? this.templateFormat; + this.validateTemplate = input.validateTemplate ?? this.validateTemplate; + this.additionalContentFields = input.additionalContentFields; + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + checkValidTemplate([{ + type: "image_url", + image_url: this.template + }], this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "prompt"; + } + /** + * Partially applies values to the prompt template. + * @param values The values to be partially applied to the prompt template. + * @returns A new instance of ImagePromptTemplate with the partially applied values. + */ + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }; + return new ImagePromptTemplate(promptDict); + } + /** + * Formats the prompt template with the provided values. + * @param values The values to be used to format the prompt template. + * @returns A promise that resolves to a string which is the formatted prompt. + */ + async format(values) { + const formatted = {}; + for (const [key, value] of Object.entries(this.template)) if (typeof value === "string") formatted[key] = renderTemplate(value, this.templateFormat, values); + else formatted[key] = value; + const url = values.url || formatted.url; + const detail = values.detail || formatted.detail; + if (!url) throw new Error("Must provide either an image URL."); + if (typeof url !== "string") throw new Error("url must be a string."); + const output = { url }; + if (detail) output.detail = detail; + return output; + } + /** + * Formats the prompt given the input values and returns a formatted + * prompt value. + * @param values The input values to format the prompt. + * @returns A Promise that resolves to a formatted prompt value. + */ + async formatPromptValue(values) { + const formattedPrompt = await this.format(values); + return new ImagePromptValue(formattedPrompt); + } +}; + +//#endregion + +//# sourceMappingURL=image.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/dict.js + + + +//#region src/prompts/dict.ts +var DictPromptTemplate = class extends Runnable { + lc_namespace = [ + "langchain_core", + "prompts", + "dict" + ]; + lc_serializable = true; + template; + templateFormat; + inputVariables; + static lc_name() { + return "DictPromptTemplate"; + } + constructor(fields) { + const templateFormat = fields.templateFormat ?? "f-string"; + const inputVariables = _getInputVariables(fields.template, templateFormat); + super({ + inputVariables, + ...fields + }); + this.template = fields.template; + this.templateFormat = templateFormat; + this.inputVariables = inputVariables; + } + async format(values) { + return _insertInputVariables(this.template, values, this.templateFormat); + } + async invoke(values) { + return await this._callWithConfig(this.format.bind(this), values, { runType: "prompt" }); + } +}; +function _getInputVariables(template, templateFormat) { + const inputVariables = []; + for (const v of Object.values(template)) if (typeof v === "string") template_parseTemplate(v, templateFormat).forEach((t) => { + if (t.type === "variable") inputVariables.push(t.name); + }); + else if (Array.isArray(v)) { + for (const x of v) if (typeof x === "string") template_parseTemplate(x, templateFormat).forEach((t) => { + if (t.type === "variable") inputVariables.push(t.name); + }); + else if (typeof x === "object") inputVariables.push(..._getInputVariables(x, templateFormat)); + } else if (typeof v === "object" && v !== null) inputVariables.push(..._getInputVariables(v, templateFormat)); + return Array.from(new Set(inputVariables)); +} +function _insertInputVariables(template, inputs, templateFormat) { + const formatted = {}; + for (const [k, v] of Object.entries(template)) if (typeof v === "string") formatted[k] = renderTemplate(v, templateFormat, inputs); + else if (Array.isArray(v)) { + const formattedV = []; + for (const x of v) if (typeof x === "string") formattedV.push(renderTemplate(x, templateFormat, inputs)); + else if (typeof x === "object") formattedV.push(_insertInputVariables(x, inputs, templateFormat)); + formatted[k] = formattedV; + } else if (typeof v === "object" && v !== null) formatted[k] = _insertInputVariables(v, inputs, templateFormat); + else formatted[k] = v; + return formatted; +} + +//#endregion + +//# sourceMappingURL=dict.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/chat.js + + + + + + + + + + + + + + + + + +//#region src/prompts/chat.ts +/** +* Abstract class that serves as a base for creating message prompt +* templates. It defines how to format messages for different roles in a +* conversation. +*/ +var BaseMessagePromptTemplate = class extends Runnable { + lc_namespace = [ + "langchain_core", + "prompts", + "chat" + ]; + lc_serializable = true; + /** + * Calls the formatMessages method with the provided input and options. + * @param input Input for the formatMessages method + * @param options Optional BaseCallbackConfig + * @returns Formatted output messages + */ + async invoke(input, options) { + return this._callWithConfig((input$1) => this.formatMessages(input$1), input, { + ...options, + runType: "prompt" + }); + } +}; +/** +* Class that represents a placeholder for messages in a chat prompt. It +* extends the BaseMessagePromptTemplate. +*/ +var MessagesPlaceholder = class extends BaseMessagePromptTemplate { + static lc_name() { + return "MessagesPlaceholder"; + } + variableName; + optional; + constructor(fields) { + if (typeof fields === "string") fields = { variableName: fields }; + super(fields); + this.variableName = fields.variableName; + this.optional = fields.optional ?? false; + } + get inputVariables() { + return [this.variableName]; + } + async formatMessages(values) { + const input = values[this.variableName]; + if (this.optional && !input) return []; + else if (!input) { + const error = /* @__PURE__ */ new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`); + error.name = "InputFormatError"; + throw error; + } + let formattedMessages; + try { + if (Array.isArray(input)) formattedMessages = input.map(utils_coerceMessageLikeToMessage); + else formattedMessages = [utils_coerceMessageLikeToMessage(input)]; + } catch (e) { + const readableInput = typeof input === "string" ? input : JSON.stringify(input, null, 2); + const error = new Error([ + `Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`, + `Received value: ${readableInput}`, + `Additional message: ${e.message}` + ].join("\n\n")); + error.name = "InputFormatError"; + error.lc_error_code = e.lc_error_code; + throw error; + } + return formattedMessages; + } +}; +/** +* Abstract class that serves as a base for creating message string prompt +* templates. It extends the BaseMessagePromptTemplate. +*/ +var BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate { + prompt; + constructor(fields) { + if (!("prompt" in fields)) fields = { prompt: fields }; + super(fields); + this.prompt = fields.prompt; + } + get inputVariables() { + return this.prompt.inputVariables; + } + async formatMessages(values) { + return [await this.format(values)]; + } +}; +/** +* Abstract class that serves as a base for creating chat prompt +* templates. It extends the BasePromptTemplate. +*/ +var BaseChatPromptTemplate = class extends BasePromptTemplate { + constructor(input) { + super(input); + } + async format(values) { + return (await this.formatPromptValue(values)).toString(); + } + async formatPromptValue(values) { + const resultMessages = await this.formatMessages(values); + return new ChatPromptValue(resultMessages); + } +}; +/** +* Class that represents a chat message prompt template. It extends the +* BaseMessageStringPromptTemplate. +*/ +var ChatMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { + static lc_name() { + return "ChatMessagePromptTemplate"; + } + role; + constructor(fields, role) { + if (!("prompt" in fields)) fields = { + prompt: fields, + role + }; + super(fields); + this.role = fields.role; + } + async format(values) { + return new ChatMessage(await this.prompt.format(values), this.role); + } + static fromTemplate(template, role, options) { + return new this(PromptTemplate.fromTemplate(template, { templateFormat: options?.templateFormat }), role); + } +}; +function isTextTemplateParam(param) { + if (param === null || typeof param !== "object" || Array.isArray(param)) return false; + return Object.keys(param).length === 1 && "text" in param && typeof param.text === "string"; +} +function isImageTemplateParam(param) { + if (param === null || typeof param !== "object" || Array.isArray(param)) return false; + return "image_url" in param && (typeof param.image_url === "string" || typeof param.image_url === "object" && param.image_url !== null && "url" in param.image_url && typeof param.image_url.url === "string"); +} +var _StringImageMessagePromptTemplate = class extends BaseMessagePromptTemplate { + lc_namespace = [ + "langchain_core", + "prompts", + "chat" + ]; + lc_serializable = true; + inputVariables = []; + additionalOptions = {}; + prompt; + messageClass; + static _messageClass() { + throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate"); + } + chatMessageClass; + constructor(fields, additionalOptions) { + if (!("prompt" in fields)) fields = { prompt: fields }; + super(fields); + this.prompt = fields.prompt; + if (Array.isArray(this.prompt)) { + let inputVariables = []; + this.prompt.forEach((prompt) => { + if ("inputVariables" in prompt) inputVariables = inputVariables.concat(prompt.inputVariables); + }); + this.inputVariables = inputVariables; + } else this.inputVariables = this.prompt.inputVariables; + this.additionalOptions = additionalOptions ?? this.additionalOptions; + } + createMessage(content) { + const constructor = this.constructor; + if (constructor._messageClass()) { + const MsgClass = constructor._messageClass(); + return new MsgClass({ content }); + } else if (constructor.chatMessageClass) { + const MsgClass = constructor.chatMessageClass(); + return new MsgClass({ + content, + role: this.getRoleFromMessageClass(MsgClass.lc_name()) + }); + } else throw new Error("No message class defined"); + } + getRoleFromMessageClass(name) { + switch (name) { + case "HumanMessage": return "human"; + case "AIMessage": return "ai"; + case "SystemMessage": return "system"; + case "ChatMessage": return "chat"; + default: throw new Error("Invalid message class name"); + } + } + static fromTemplate(template, additionalOptions) { + if (typeof template === "string") return new this(PromptTemplate.fromTemplate(template, additionalOptions)); + const prompt = []; + for (const item of template) if (typeof item === "string") prompt.push(PromptTemplate.fromTemplate(item, additionalOptions)); + else if (item === null) {} else if (isTextTemplateParam(item)) { + let text = ""; + if (typeof item.text === "string") text = item.text ?? ""; + const options = { + ...additionalOptions, + additionalContentFields: item + }; + prompt.push(PromptTemplate.fromTemplate(text, options)); + } else if (isImageTemplateParam(item)) { + let imgTemplate = item.image_url ?? ""; + let imgTemplateObject; + let inputVariables = []; + if (typeof imgTemplate === "string") { + let parsedTemplate; + if (additionalOptions?.templateFormat === "mustache") parsedTemplate = parseMustache(imgTemplate); + else parsedTemplate = parseFString(imgTemplate); + const variables = parsedTemplate.flatMap((item$1) => item$1.type === "variable" ? [item$1.name] : []); + if ((variables?.length ?? 0) > 0) { + if (variables.length > 1) throw new Error(`Only one format variable allowed per image template.\nGot: ${variables}\nFrom: ${imgTemplate}`); + inputVariables = [variables[0]]; + } else inputVariables = []; + imgTemplate = { url: imgTemplate }; + imgTemplateObject = new ImagePromptTemplate({ + template: imgTemplate, + inputVariables, + templateFormat: additionalOptions?.templateFormat, + additionalContentFields: item + }); + } else if (typeof imgTemplate === "object") { + if ("url" in imgTemplate) { + let parsedTemplate; + if (additionalOptions?.templateFormat === "mustache") parsedTemplate = parseMustache(imgTemplate.url); + else parsedTemplate = parseFString(imgTemplate.url); + inputVariables = parsedTemplate.flatMap((item$1) => item$1.type === "variable" ? [item$1.name] : []); + } else inputVariables = []; + imgTemplateObject = new ImagePromptTemplate({ + template: imgTemplate, + inputVariables, + templateFormat: additionalOptions?.templateFormat, + additionalContentFields: item + }); + } else throw new Error("Invalid image template"); + prompt.push(imgTemplateObject); + } else if (typeof item === "object") prompt.push(new DictPromptTemplate({ + template: item, + templateFormat: additionalOptions?.templateFormat + })); + return new this({ + prompt, + additionalOptions + }); + } + async format(input) { + if (this.prompt instanceof BaseStringPromptTemplate) { + const text = await this.prompt.format(input); + return this.createMessage(text); + } else { + const content = []; + for (const prompt of this.prompt) { + let inputs = {}; + if (!("inputVariables" in prompt)) throw new Error(`Prompt ${prompt} does not have inputVariables defined.`); + for (const item of prompt.inputVariables) { + if (!inputs) inputs = { [item]: input[item] }; + inputs = { + ...inputs, + [item]: input[item] + }; + } + if (prompt instanceof BaseStringPromptTemplate) { + const formatted = await prompt.format(inputs); + let additionalContentFields; + if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; + if (formatted !== "") content.push({ + ...additionalContentFields, + type: "text", + text: formatted + }); + } else if (prompt instanceof ImagePromptTemplate) { + const formatted = await prompt.format(inputs); + let additionalContentFields; + if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; + content.push({ + ...additionalContentFields, + type: "image_url", + image_url: formatted + }); + } else if (prompt instanceof DictPromptTemplate) { + const formatted = await prompt.format(inputs); + let additionalContentFields; + if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; + content.push({ + ...additionalContentFields, + ...formatted + }); + } + } + return this.createMessage(content); + } + } + async formatMessages(values) { + return [await this.format(values)]; + } +}; +/** +* Class that represents a human message prompt template. It extends the +* BaseMessageStringPromptTemplate. +* @example +* ```typescript +* const message = HumanMessagePromptTemplate.fromTemplate("{text}"); +* const formatted = await message.format({ text: "Hello world!" }); +* +* const chatPrompt = ChatPromptTemplate.fromMessages([message]); +* const formattedChatPrompt = await chatPrompt.invoke({ +* text: "Hello world!", +* }); +* ``` +*/ +var HumanMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return HumanMessage; + } + static lc_name() { + return "HumanMessagePromptTemplate"; + } +}; +/** +* Class that represents an AI message prompt template. It extends the +* BaseMessageStringPromptTemplate. +*/ +var AIMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return AIMessage; + } + static lc_name() { + return "AIMessagePromptTemplate"; + } +}; +/** +* Class that represents a system message prompt template. It extends the +* BaseMessageStringPromptTemplate. +* @example +* ```typescript +* const message = SystemMessagePromptTemplate.fromTemplate("{text}"); +* const formatted = await message.format({ text: "Hello world!" }); +* +* const chatPrompt = ChatPromptTemplate.fromMessages([message]); +* const formattedChatPrompt = await chatPrompt.invoke({ +* text: "Hello world!", +* }); +* ``` +*/ +var SystemMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { + static _messageClass() { + return SystemMessage; + } + static lc_name() { + return "SystemMessagePromptTemplate"; + } +}; +function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) { + return typeof baseMessagePromptTemplateLike.formatMessages === "function"; +} +function _coerceMessagePromptTemplateLike(messagePromptTemplateLike, extra) { + if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || isBaseMessage(messagePromptTemplateLike)) return messagePromptTemplateLike; + if (Array.isArray(messagePromptTemplateLike) && messagePromptTemplateLike[0] === "placeholder") { + const messageContent = messagePromptTemplateLike[1]; + if (extra?.templateFormat === "mustache" && typeof messageContent === "string" && messageContent.slice(0, 2) === "{{" && messageContent.slice(-2) === "}}") { + const variableName = messageContent.slice(2, -2); + return new MessagesPlaceholder({ + variableName, + optional: true + }); + } else if (typeof messageContent === "string" && messageContent[0] === "{" && messageContent[messageContent.length - 1] === "}") { + const variableName = messageContent.slice(1, -1); + return new MessagesPlaceholder({ + variableName, + optional: true + }); + } + throw new Error(`Invalid placeholder template for format ${extra?.templateFormat ?? `"f-string"`}: "${messagePromptTemplateLike[1]}". Expected a variable name surrounded by ${extra?.templateFormat === "mustache" ? "double" : "single"} curly braces.`); + } + const message = utils_coerceMessageLikeToMessage(messagePromptTemplateLike); + let templateData; + if (typeof message.content === "string") templateData = message.content; + else templateData = message.content.map((item) => { + if ("text" in item) return { + ...item, + text: item.text + }; + else if ("image_url" in item) return { + ...item, + image_url: item.image_url + }; + else return item; + }); + if (message._getType() === "human") return HumanMessagePromptTemplate.fromTemplate(templateData, extra); + else if (message._getType() === "ai") return AIMessagePromptTemplate.fromTemplate(templateData, extra); + else if (message._getType() === "system") return SystemMessagePromptTemplate.fromTemplate(templateData, extra); + else if (ChatMessage.isInstance(message)) return ChatMessagePromptTemplate.fromTemplate(message.content, message.role, extra); + else throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`); +} +function isMessagesPlaceholder(x) { + return x.constructor.lc_name() === "MessagesPlaceholder"; +} +/** +* Class that represents a chat prompt. It extends the +* BaseChatPromptTemplate and uses an array of BaseMessagePromptTemplate +* instances to format a series of messages for a conversation. +* @example +* ```typescript +* const message = SystemMessagePromptTemplate.fromTemplate("{text}"); +* const chatPrompt = ChatPromptTemplate.fromMessages([ +* ["ai", "You are a helpful assistant."], +* message, +* ]); +* const formattedChatPrompt = await chatPrompt.invoke({ +* text: "Hello world!", +* }); +* ``` +*/ +var ChatPromptTemplate = class ChatPromptTemplate extends BaseChatPromptTemplate { + static lc_name() { + return "ChatPromptTemplate"; + } + get lc_aliases() { + return { promptMessages: "messages" }; + } + promptMessages; + validateTemplate = true; + templateFormat = "f-string"; + constructor(input) { + super(input); + if (input.templateFormat === "mustache" && input.validateTemplate === void 0) this.validateTemplate = false; + Object.assign(this, input); + if (this.validateTemplate) { + const inputVariablesMessages = /* @__PURE__ */ new Set(); + for (const promptMessage of this.promptMessages) { + if (promptMessage instanceof BaseMessage) continue; + for (const inputVariable of promptMessage.inputVariables) inputVariablesMessages.add(inputVariable); + } + const totalInputVariables = this.inputVariables; + const inputVariablesInstance = new Set(this.partialVariables ? totalInputVariables.concat(Object.keys(this.partialVariables)) : totalInputVariables); + const difference = new Set([...inputVariablesInstance].filter((x) => !inputVariablesMessages.has(x))); + if (difference.size > 0) throw new Error(`Input variables \`${[...difference]}\` are not used in any of the prompt messages.`); + const otherDifference = new Set([...inputVariablesMessages].filter((x) => !inputVariablesInstance.has(x))); + if (otherDifference.size > 0) throw new Error(`Input variables \`${[...otherDifference]}\` are used in prompt messages but not in the prompt template.`); + } + } + _getPromptType() { + return "chat"; + } + async _parseImagePrompts(message, inputValues) { + if (typeof message.content === "string") return message; + const formattedMessageContent = await Promise.all(message.content.map(async (item) => { + if (item.type !== "image_url") return item; + let imageUrl = ""; + if (typeof item.image_url === "string") imageUrl = item.image_url; + else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url && typeof item.image_url.url === "string") imageUrl = item.image_url.url; + const promptTemplatePlaceholder = PromptTemplate.fromTemplate(imageUrl, { templateFormat: this.templateFormat }); + const formattedUrl = await promptTemplatePlaceholder.format(inputValues); + if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) item.image_url.url = formattedUrl; + else item.image_url = formattedUrl; + return item; + })); + message.content = formattedMessageContent; + return message; + } + async formatMessages(values) { + const allValues = await this.mergePartialAndUserVariables(values); + let resultMessages = []; + for (const promptMessage of this.promptMessages) if (promptMessage instanceof BaseMessage) resultMessages.push(await this._parseImagePrompts(promptMessage, allValues)); + else { + let inputValues; + if (this.templateFormat === "mustache") inputValues = { ...allValues }; + else inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { + if (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) { + const error = addLangChainErrorFields(/* @__PURE__ */ new Error(`Missing value for input variable \`${inputVariable.toString()}\``), "INVALID_PROMPT_INPUT"); + throw error; + } + acc[inputVariable] = allValues[inputVariable]; + return acc; + }, {}); + const message = await promptMessage.formatMessages(inputValues); + resultMessages = resultMessages.concat(message); + } + return resultMessages; + } + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }; + return new ChatPromptTemplate(promptDict); + } + static fromTemplate(template, options) { + const prompt = PromptTemplate.fromTemplate(template, options); + const humanTemplate = new HumanMessagePromptTemplate({ prompt }); + return this.fromMessages([humanTemplate]); + } + /** + * Create a chat model-specific prompt from individual chat messages + * or message-like tuples. + * @param promptMessages Messages to be passed to the chat model + * @returns A new ChatPromptTemplate + */ + static fromMessages(promptMessages, extra) { + const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat(promptMessage instanceof ChatPromptTemplate ? promptMessage.promptMessages : [_coerceMessagePromptTemplateLike(promptMessage, extra)]), []); + const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => promptMessage instanceof ChatPromptTemplate ? Object.assign(acc, promptMessage.partialVariables) : acc, Object.create(null)); + const inputVariables = /* @__PURE__ */ new Set(); + for (const promptMessage of flattenedMessages) { + if (promptMessage instanceof BaseMessage) continue; + for (const inputVariable of promptMessage.inputVariables) { + if (inputVariable in flattenedPartialVariables) continue; + inputVariables.add(inputVariable); + } + } + return new this({ + ...extra, + inputVariables: [...inputVariables], + promptMessages: flattenedMessages, + partialVariables: flattenedPartialVariables, + templateFormat: extra?.templateFormat + }); + } +}; + +//#endregion + +//# sourceMappingURL=chat.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/few_shot.js + + + + + +//#region src/prompts/few_shot.ts +/** +* Prompt template that contains few-shot examples. +* @augments BasePromptTemplate +* @augments FewShotPromptTemplateInput +* @example +* ```typescript +* const examplePrompt = PromptTemplate.fromTemplate( +* "Input: {input}\nOutput: {output}", +* ); +* +* const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples( +* [ +* { input: "happy", output: "sad" }, +* { input: "tall", output: "short" }, +* { input: "energetic", output: "lethargic" }, +* { input: "sunny", output: "gloomy" }, +* { input: "windy", output: "calm" }, +* ], +* new OpenAIEmbeddings(), +* HNSWLib, +* { k: 1 }, +* ); +* +* const dynamicPrompt = new FewShotPromptTemplate({ +* exampleSelector, +* examplePrompt, +* prefix: "Give the antonym of every input", +* suffix: "Input: {adjective}\nOutput:", +* inputVariables: ["adjective"], +* }); +* +* // Format the dynamic prompt with the input 'rainy' +* console.log(await dynamicPrompt.format({ adjective: "rainy" })); +* +* ``` +*/ +var FewShotPromptTemplate = class FewShotPromptTemplate extends BaseStringPromptTemplate { + lc_serializable = false; + examples; + exampleSelector; + examplePrompt; + suffix = ""; + exampleSeparator = "\n\n"; + prefix = ""; + templateFormat = "f-string"; + validateTemplate = true; + constructor(input) { + super(input); + Object.assign(this, input); + if (this.examples !== void 0 && this.exampleSelector !== void 0) throw new Error("Only one of 'examples' and 'example_selector' should be provided"); + if (this.examples === void 0 && this.exampleSelector === void 0) throw new Error("One of 'examples' and 'example_selector' should be provided"); + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); + } + } + _getPromptType() { + return "few_shot"; + } + static lc_name() { + return "FewShotPromptTemplate"; + } + async getExamples(inputVariables) { + if (this.examples !== void 0) return this.examples; + if (this.exampleSelector !== void 0) return this.exampleSelector.selectExamples(inputVariables); + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + async partial(values) { + const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }; + return new FewShotPromptTemplate(promptDict); + } + /** + * Formats the prompt with the given values. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); + const template = [ + this.prefix, + ...exampleStrings, + this.suffix + ].join(this.exampleSeparator); + return renderTemplate(template, this.templateFormat, allValues); + } + serialize() { + if (this.exampleSelector || !this.examples) throw new Error("Serializing an example selector is not currently supported"); + if (this.outputParser !== void 0) throw new Error("Serializing an output parser is not currently supported"); + return { + _type: this._getPromptType(), + input_variables: this.inputVariables, + example_prompt: this.examplePrompt.serialize(), + example_separator: this.exampleSeparator, + suffix: this.suffix, + prefix: this.prefix, + template_format: this.templateFormat, + examples: this.examples + }; + } + static async deserialize(data) { + const { example_prompt } = data; + if (!example_prompt) throw new Error("Missing example prompt"); + const examplePrompt = await PromptTemplate.deserialize(example_prompt); + let examples; + if (Array.isArray(data.examples)) examples = data.examples; + else throw new Error("Invalid examples format. Only list or string are supported."); + return new FewShotPromptTemplate({ + inputVariables: data.input_variables, + examplePrompt, + examples, + exampleSeparator: data.example_separator, + prefix: data.prefix, + suffix: data.suffix, + templateFormat: data.template_format + }); + } +}; +/** +* Chat prompt template that contains few-shot examples. +* @augments BasePromptTemplateInput +* @augments FewShotChatMessagePromptTemplateInput +*/ +var FewShotChatMessagePromptTemplate = class FewShotChatMessagePromptTemplate extends BaseChatPromptTemplate { + lc_serializable = true; + examples; + exampleSelector; + examplePrompt; + suffix = ""; + exampleSeparator = "\n\n"; + prefix = ""; + templateFormat = "f-string"; + validateTemplate = true; + _getPromptType() { + return "few_shot_chat"; + } + static lc_name() { + return "FewShotChatMessagePromptTemplate"; + } + constructor(fields) { + super(fields); + this.examples = fields.examples; + this.examplePrompt = fields.examplePrompt; + this.exampleSeparator = fields.exampleSeparator ?? "\n\n"; + this.exampleSelector = fields.exampleSelector; + this.prefix = fields.prefix ?? ""; + this.suffix = fields.suffix ?? ""; + this.templateFormat = fields.templateFormat ?? "f-string"; + this.validateTemplate = fields.validateTemplate ?? true; + if (this.examples !== void 0 && this.exampleSelector !== void 0) throw new Error("Only one of 'examples' and 'example_selector' should be provided"); + if (this.examples === void 0 && this.exampleSelector === void 0) throw new Error("One of 'examples' and 'example_selector' should be provided"); + if (this.validateTemplate) { + let totalInputVariables = this.inputVariables; + if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); + checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); + } + } + async getExamples(inputVariables) { + if (this.examples !== void 0) return this.examples; + if (this.exampleSelector !== void 0) return this.exampleSelector.selectExamples(inputVariables); + throw new Error("One of 'examples' and 'example_selector' should be provided"); + } + /** + * Formats the list of values and returns a list of formatted messages. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async formatMessages(values) { + const allValues = await this.mergePartialAndUserVariables(values); + let examples = await this.getExamples(allValues); + examples = examples.map((example) => { + const result = {}; + this.examplePrompt.inputVariables.forEach((inputVariable) => { + result[inputVariable] = example[inputVariable]; + }); + return result; + }); + const messages = []; + for (const example of examples) { + const exampleMessages = await this.examplePrompt.formatMessages(example); + messages.push(...exampleMessages); + } + return messages; + } + /** + * Formats the prompt with the given values. + * @param values The values to format the prompt with. + * @returns A promise that resolves to a string representing the formatted prompt. + */ + async format(values) { + const allValues = await this.mergePartialAndUserVariables(values); + const examples = await this.getExamples(allValues); + const exampleMessages = await Promise.all(examples.map((example) => this.examplePrompt.formatMessages(example))); + const exampleStrings = exampleMessages.flat().map((message) => message.content); + const template = [ + this.prefix, + ...exampleStrings, + this.suffix + ].join(this.exampleSeparator); + return renderTemplate(template, this.templateFormat, allValues); + } + /** + * Partially formats the prompt with the given values. + * @param values The values to partially format the prompt with. + * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted. + */ + async partial(values) { + const newInputVariables = this.inputVariables.filter((variable) => !(variable in values)); + const newPartialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + const promptDict = { + ...this, + inputVariables: newInputVariables, + partialVariables: newPartialVariables + }; + return new FewShotChatMessagePromptTemplate(promptDict); + } +}; + +//#endregion + +//# sourceMappingURL=few_shot.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/pipeline.js + + + +//#region src/prompts/pipeline.ts +/** +* Class that handles a sequence of prompts, each of which may require +* different input variables. Includes methods for formatting these +* prompts, extracting required input values, and handling partial +* prompts. +* @example +* ```typescript +* const composedPrompt = new PipelinePromptTemplate({ +* pipelinePrompts: [ +* { +* name: "introduction", +* prompt: PromptTemplate.fromTemplate(`You are impersonating {person}.`), +* }, +* { +* name: "example", +* prompt: PromptTemplate.fromTemplate( +* `Here's an example of an interaction: +* Q: {example_q} +* A: {example_a}`, +* ), +* }, +* { +* name: "start", +* prompt: PromptTemplate.fromTemplate( +* `Now, do this for real! +* Q: {input} +* A:`, +* ), +* }, +* ], +* finalPrompt: PromptTemplate.fromTemplate( +* `{introduction} +* {example} +* {start}`, +* ), +* }); +* +* const formattedPrompt = await composedPrompt.format({ +* person: "Elon Musk", +* example_q: `What's your favorite car?`, +* example_a: "Tesla", +* input: `What's your favorite social media site?`, +* }); +* ``` +*/ +var PipelinePromptTemplate = class PipelinePromptTemplate extends BasePromptTemplate { + static lc_name() { + return "PipelinePromptTemplate"; + } + pipelinePrompts; + finalPrompt; + constructor(input) { + super({ + ...input, + inputVariables: [] + }); + this.pipelinePrompts = input.pipelinePrompts; + this.finalPrompt = input.finalPrompt; + this.inputVariables = this.computeInputValues(); + } + /** + * Computes the input values required by the pipeline prompts. + * @returns Array of input values required by the pipeline prompts. + */ + computeInputValues() { + const intermediateValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.name); + const inputValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.prompt.inputVariables.filter((inputValue) => !intermediateValues.includes(inputValue))).flat(); + return [...new Set(inputValues)]; + } + static extractRequiredInputValues(allValues, requiredValueNames) { + return requiredValueNames.reduce((requiredValues, valueName) => { + requiredValues[valueName] = allValues[valueName]; + return requiredValues; + }, {}); + } + /** + * Formats the pipeline prompts based on the provided input values. + * @param values Input values to format the pipeline prompts. + * @returns Promise that resolves with the formatted input values. + */ + async formatPipelinePrompts(values) { + const allValues = await this.mergePartialAndUserVariables(values); + for (const { name: pipelinePromptName, prompt: pipelinePrompt } of this.pipelinePrompts) { + const pipelinePromptInputValues = PipelinePromptTemplate.extractRequiredInputValues(allValues, pipelinePrompt.inputVariables); + if (pipelinePrompt instanceof ChatPromptTemplate) allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(pipelinePromptInputValues); + else allValues[pipelinePromptName] = await pipelinePrompt.format(pipelinePromptInputValues); + } + return PipelinePromptTemplate.extractRequiredInputValues(allValues, this.finalPrompt.inputVariables); + } + /** + * Formats the final prompt value based on the provided input values. + * @param values Input values to format the final prompt value. + * @returns Promise that resolves with the formatted final prompt value. + */ + async formatPromptValue(values) { + return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(values)); + } + async format(values) { + return this.finalPrompt.format(await this.formatPipelinePrompts(values)); + } + /** + * Handles partial prompts, which are prompts that have been partially + * filled with input values. + * @param values Partial input values. + * @returns Promise that resolves with a new PipelinePromptTemplate instance with updated input variables. + */ + async partial(values) { + const promptDict = { ...this }; + promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); + promptDict.partialVariables = { + ...this.partialVariables ?? {}, + ...values + }; + return new PipelinePromptTemplate(promptDict); + } + serialize() { + throw new Error("Not implemented."); + } + _getPromptType() { + return "pipeline"; + } +}; + +//#endregion + +//# sourceMappingURL=pipeline.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/structured.js + + + +//#region src/prompts/structured.ts +function isWithStructuredOutput(x) { + return typeof x === "object" && x != null && "withStructuredOutput" in x && typeof x.withStructuredOutput === "function"; +} +function isRunnableBinding(x) { + return typeof x === "object" && x != null && "lc_id" in x && Array.isArray(x.lc_id) && x.lc_id.join("/") === "langchain_core/runnables/RunnableBinding"; +} +var StructuredPrompt = class StructuredPrompt extends ChatPromptTemplate { + schema; + method; + lc_namespace = [ + "langchain_core", + "prompts", + "structured" + ]; + get lc_aliases() { + return { + ...super.lc_aliases, + schema: "schema_" + }; + } + constructor(input) { + super(input); + this.schema = input.schema; + this.method = input.method; + } + pipe(coerceable) { + if (isWithStructuredOutput(coerceable)) return super.pipe(coerceable.withStructuredOutput(this.schema)); + if (isRunnableBinding(coerceable) && isWithStructuredOutput(coerceable.bound)) return super.pipe(new RunnableBinding({ + bound: coerceable.bound.withStructuredOutput(this.schema, ...this.method ? [{ method: this.method }] : []), + kwargs: coerceable.kwargs ?? {}, + config: coerceable.config, + configFactories: coerceable.configFactories + })); + throw new Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`); + } + static fromMessagesAndSchema(promptMessages, schema, method) { + return StructuredPrompt.fromMessages(promptMessages, { + schema, + method + }); + } +}; + +//#endregion + +//# sourceMappingURL=structured.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/index.js + + + + + + + + + + + + +//#region src/prompts/index.ts +var prompts_exports = {}; +__export(prompts_exports, { + AIMessagePromptTemplate: () => AIMessagePromptTemplate, + BaseChatPromptTemplate: () => BaseChatPromptTemplate, + BaseMessagePromptTemplate: () => BaseMessagePromptTemplate, + BaseMessageStringPromptTemplate: () => BaseMessageStringPromptTemplate, + BasePromptTemplate: () => BasePromptTemplate, + BaseStringPromptTemplate: () => BaseStringPromptTemplate, + ChatMessagePromptTemplate: () => ChatMessagePromptTemplate, + ChatPromptTemplate: () => ChatPromptTemplate, + DEFAULT_FORMATTER_MAPPING: () => DEFAULT_FORMATTER_MAPPING, + DEFAULT_PARSER_MAPPING: () => DEFAULT_PARSER_MAPPING, + DictPromptTemplate: () => DictPromptTemplate, + FewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate, + FewShotPromptTemplate: () => FewShotPromptTemplate, + HumanMessagePromptTemplate: () => HumanMessagePromptTemplate, + ImagePromptTemplate: () => ImagePromptTemplate, + MessagesPlaceholder: () => MessagesPlaceholder, + PipelinePromptTemplate: () => PipelinePromptTemplate, + PromptTemplate: () => PromptTemplate, + StructuredPrompt: () => StructuredPrompt, + SystemMessagePromptTemplate: () => SystemMessagePromptTemplate, + checkValidTemplate: () => checkValidTemplate, + interpolateFString: () => interpolateFString, + interpolateMustache: () => interpolateMustache, + parseFString: () => parseFString, + parseMustache: () => parseMustache, + parseTemplate: () => template_parseTemplate, + renderTemplate: () => renderTemplate +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/router.js + + + +//#region src/runnables/router.ts +/** +* A runnable that routes to a set of runnables based on Input['key']. +* Returns the output of the selected runnable. +* @example +* ```typescript +* import { RouterRunnable, RunnableLambda } from "@langchain/core/runnables"; +* +* const router = new RouterRunnable({ +* runnables: { +* toUpperCase: RunnableLambda.from((text: string) => text.toUpperCase()), +* reverseText: RunnableLambda.from((text: string) => +* text.split("").reverse().join("") +* ), +* }, +* }); +* +* // Invoke the 'reverseText' runnable +* const result1 = router.invoke({ key: "reverseText", input: "Hello World" }); +* +* // "dlroW olleH" +* +* // Invoke the 'toUpperCase' runnable +* const result2 = router.invoke({ key: "toUpperCase", input: "Hello World" }); +* +* // "HELLO WORLD" +* ``` +*/ +var RouterRunnable = class extends Runnable { + static lc_name() { + return "RouterRunnable"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + runnables; + constructor(fields) { + super(fields); + this.runnables = fields.runnables; + } + async invoke(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === void 0) throw new Error(`No runnable associated with key "${key}".`); + return runnable.invoke(actualInput, ensureConfig(options)); + } + async batch(inputs, options, batchOptions) { + const keys = inputs.map((input) => input.key); + const actualInputs = inputs.map((input) => input.input); + const missingKey = keys.find((key) => this.runnables[key] === void 0); + if (missingKey !== void 0) throw new Error(`One or more keys do not have a corresponding runnable.`); + const runnables = keys.map((key) => this.runnables[key]); + const optionsList = this._getOptionsList(options ?? {}, inputs.length); + const maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; + const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; + const batchResults = []; + for (let i = 0; i < actualInputs.length; i += batchSize) { + const batchPromises = actualInputs.slice(i, i + batchSize).map((actualInput, i$1) => runnables[i$1].invoke(actualInput, optionsList[i$1])); + const batchResult = await Promise.all(batchPromises); + batchResults.push(batchResult); + } + return batchResults.flat(); + } + async stream(input, options) { + const { key, input: actualInput } = input; + const runnable = this.runnables[key]; + if (runnable === void 0) throw new Error(`No runnable associated with key "${key}".`); + return runnable.stream(actualInput, options); + } +}; + +//#endregion + +//# sourceMappingURL=router.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/branch.js + + + + +//#region src/runnables/branch.ts +/** +* Class that represents a runnable branch. The RunnableBranch is +* initialized with an array of branches and a default branch. When invoked, +* it evaluates the condition of each branch in order and executes the +* corresponding branch if the condition is true. If none of the conditions +* are true, it executes the default branch. +* @example +* ```typescript +* const branch = RunnableBranch.from([ +* [ +* (x: { topic: string; question: string }) => +* x.topic.toLowerCase().includes("anthropic"), +* anthropicChain, +* ], +* [ +* (x: { topic: string; question: string }) => +* x.topic.toLowerCase().includes("langchain"), +* langChainChain, +* ], +* generalChain, +* ]); +* +* const fullChain = RunnableSequence.from([ +* { +* topic: classificationChain, +* question: (input: { question: string }) => input.question, +* }, +* branch, +* ]); +* +* const result = await fullChain.invoke({ +* question: "how do I use LangChain?", +* }); +* ``` +*/ +var RunnableBranch = class extends Runnable { + static lc_name() { + return "RunnableBranch"; + } + lc_namespace = ["langchain_core", "runnables"]; + lc_serializable = true; + default; + branches; + constructor(fields) { + super(fields); + this.branches = fields.branches; + this.default = fields.default; + } + /** + * Convenience method for instantiating a RunnableBranch from + * RunnableLikes (objects, functions, or Runnables). + * + * Each item in the input except for the last one should be a + * tuple with two items. The first is a "condition" RunnableLike that + * returns "true" if the second RunnableLike in the tuple should run. + * + * The final item in the input should be a RunnableLike that acts as a + * default branch if no other branches match. + * + * @example + * ```ts + * import { RunnableBranch } from "@langchain/core/runnables"; + * + * const branch = RunnableBranch.from([ + * [(x: number) => x > 0, (x: number) => x + 1], + * [(x: number) => x < 0, (x: number) => x - 1], + * (x: number) => x + * ]); + * ``` + * @param branches An array where the every item except the last is a tuple of [condition, runnable] + * pairs. The last item is a default runnable which is invoked if no other condition matches. + * @returns A new RunnableBranch. + */ + static from(branches) { + if (branches.length < 1) throw new Error("RunnableBranch requires at least one branch"); + const branchLikes = branches.slice(0, -1); + const coercedBranches = branchLikes.map(([condition, runnable]) => [_coerceToRunnable(condition), _coerceToRunnable(runnable)]); + const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); + return new this({ + branches: coercedBranches, + default: defaultBranch + }); + } + async _invoke(input, config, runManager) { + let result; + for (let i = 0; i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + const conditionValue = await condition.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`condition:${i + 1}`) })); + if (conditionValue) { + result = await branchRunnable.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`branch:${i + 1}`) })); + break; + } + } + if (!result) result = await this.default.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild("branch:default") })); + return result; + } + async invoke(input, config = {}) { + return this._callWithConfig(this._invoke, input, config); + } + async *_streamIterator(input, config) { + const callbackManager_ = await getCallbackManagerForConfig(config); + const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config?.runId, void 0, void 0, void 0, config?.runName); + let finalOutput; + let finalOutputSupported = true; + let stream; + try { + for (let i = 0; i < this.branches.length; i += 1) { + const [condition, branchRunnable] = this.branches[i]; + const conditionValue = await condition.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`condition:${i + 1}`) })); + if (conditionValue) { + stream = await branchRunnable.stream(input, config_patchConfig(config, { callbacks: runManager?.getChild(`branch:${i + 1}`) })); + for await (const chunk of stream) { + yield chunk; + if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = concat(finalOutput, chunk); + } catch { + finalOutput = void 0; + finalOutputSupported = false; + } + } + break; + } + } + if (stream === void 0) { + stream = await this.default.stream(input, config_patchConfig(config, { callbacks: runManager?.getChild("branch:default") })); + for await (const chunk of stream) { + yield chunk; + if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; + else try { + finalOutput = concat(finalOutput, chunk); + } catch { + finalOutput = void 0; + finalOutputSupported = false; + } + } + } + } catch (e) { + await runManager?.handleChainError(e); + throw e; + } + await runManager?.handleChainEnd(finalOutput ?? {}); + } +}; + +//#endregion + +//# sourceMappingURL=branch.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/history.js + + + + + + + +//#region src/runnables/history.ts +/** +* Wraps a LCEL chain and manages history. It appends input messages +* and chain outputs as history, and adds the current history messages to +* the chain input. +* @example +* ```typescript +* // pnpm install @langchain/anthropic @langchain/community @upstash/redis +* +* import { +* ChatPromptTemplate, +* MessagesPlaceholder, +* } from "@langchain/core/prompts"; +* import { ChatAnthropic } from "@langchain/anthropic"; +* import { UpstashRedisChatMessageHistory } from "@langchain/community/stores/message/upstash_redis"; +* // For demos, you can also use an in-memory store: +* // import { ChatMessageHistory } from "@langchain/classic/stores/message/in_memory"; +* +* const prompt = ChatPromptTemplate.fromMessages([ +* ["system", "You're an assistant who's good at {ability}"], +* new MessagesPlaceholder("history"), +* ["human", "{question}"], +* ]); +* +* const chain = prompt.pipe(new ChatAnthropic({})); +* +* const chainWithHistory = new RunnableWithMessageHistory({ +* runnable: chain, +* getMessageHistory: (sessionId) => +* new UpstashRedisChatMessageHistory({ +* sessionId, +* config: { +* url: process.env.UPSTASH_REDIS_REST_URL!, +* token: process.env.UPSTASH_REDIS_REST_TOKEN!, +* }, +* }), +* inputMessagesKey: "question", +* historyMessagesKey: "history", +* }); +* +* const result = await chainWithHistory.invoke( +* { +* ability: "math", +* question: "What does cosine mean?", +* }, +* { +* configurable: { +* sessionId: "some_string_identifying_a_user", +* }, +* } +* ); +* +* const result2 = await chainWithHistory.invoke( +* { +* ability: "math", +* question: "What's its inverse?", +* }, +* { +* configurable: { +* sessionId: "some_string_identifying_a_user", +* }, +* } +* ); +* ``` +*/ +var RunnableWithMessageHistory = class extends RunnableBinding { + runnable; + inputMessagesKey; + outputMessagesKey; + historyMessagesKey; + getMessageHistory; + constructor(fields) { + let historyChain = RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: "loadHistory" }); + const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey; + if (messagesKey) historyChain = RunnablePassthrough.assign({ [messagesKey]: historyChain }).withConfig({ runName: "insertHistory" }); + const bound = historyChain.pipe(fields.runnable.withListeners({ onEnd: (run, config$1) => this._exitHistory(run, config$1 ?? {}) })).withConfig({ runName: "RunnableWithMessageHistory" }); + const config = fields.config ?? {}; + super({ + ...fields, + config, + bound + }); + this.runnable = fields.runnable; + this.getMessageHistory = fields.getMessageHistory; + this.inputMessagesKey = fields.inputMessagesKey; + this.outputMessagesKey = fields.outputMessagesKey; + this.historyMessagesKey = fields.historyMessagesKey; + } + _getInputMessages(inputValue) { + let parsedInputValue; + if (typeof inputValue === "object" && !Array.isArray(inputValue) && !isBaseMessage(inputValue)) { + let key; + if (this.inputMessagesKey) key = this.inputMessagesKey; + else if (Object.keys(inputValue).length === 1) key = Object.keys(inputValue)[0]; + else key = "input"; + if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) parsedInputValue = inputValue[key][0]; + else parsedInputValue = inputValue[key]; + } else parsedInputValue = inputValue; + if (typeof parsedInputValue === "string") return [new HumanMessage(parsedInputValue)]; + else if (Array.isArray(parsedInputValue)) return parsedInputValue; + else if (isBaseMessage(parsedInputValue)) return [parsedInputValue]; + else throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(parsedInputValue, null, 2)}`); + } + _getOutputMessages(outputValue) { + let parsedOutputValue; + if (!Array.isArray(outputValue) && !isBaseMessage(outputValue) && typeof outputValue !== "string") { + let key; + if (this.outputMessagesKey !== void 0) key = this.outputMessagesKey; + else if (Object.keys(outputValue).length === 1) key = Object.keys(outputValue)[0]; + else key = "output"; + if (outputValue.generations !== void 0) parsedOutputValue = outputValue.generations[0][0].message; + else parsedOutputValue = outputValue[key]; + } else parsedOutputValue = outputValue; + if (typeof parsedOutputValue === "string") return [new AIMessage(parsedOutputValue)]; + else if (Array.isArray(parsedOutputValue)) return parsedOutputValue; + else if (isBaseMessage(parsedOutputValue)) return [parsedOutputValue]; + else throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`); + } + async _enterHistory(input, kwargs) { + const history = kwargs?.configurable?.messageHistory; + const messages = await history.getMessages(); + if (this.historyMessagesKey === void 0) return messages.concat(this._getInputMessages(input)); + return messages; + } + async _exitHistory(run, config) { + const history = config.configurable?.messageHistory; + let inputs; + if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) inputs = run.inputs[0]; + else inputs = run.inputs; + let inputMessages = this._getInputMessages(inputs); + if (this.historyMessagesKey === void 0) { + const existingMessages = await history.getMessages(); + inputMessages = inputMessages.slice(existingMessages.length); + } + const outputValue = run.outputs; + if (!outputValue) throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run, null, 2)}`); + const outputMessages = this._getOutputMessages(outputValue); + await history.addMessages([...inputMessages, ...outputMessages]); + } + async _mergeConfig(...configs) { + const config = await super._mergeConfig(...configs); + if (!config.configurable || !config.configurable.sessionId) { + const exampleInput = { [this.inputMessagesKey ?? "input"]: "foo" }; + const exampleConfig = { configurable: { sessionId: "123" } }; + throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(exampleConfig)})`); + } + const { sessionId } = config.configurable; + config.configurable.messageHistory = await this.getMessageHistory(sessionId); + return config; + } +}; + +//#endregion + +//# sourceMappingURL=history.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/index.js + + + + + + + + + +//#region src/runnables/index.ts +var runnables_exports = {}; +__export(runnables_exports, { + RouterRunnable: () => RouterRunnable, + Runnable: () => Runnable, + RunnableAssign: () => RunnableAssign, + RunnableBinding: () => RunnableBinding, + RunnableBranch: () => RunnableBranch, + RunnableEach: () => RunnableEach, + RunnableLambda: () => RunnableLambda, + RunnableMap: () => RunnableMap, + RunnableParallel: () => RunnableParallel, + RunnablePassthrough: () => RunnablePassthrough, + RunnablePick: () => RunnablePick, + RunnableRetry: () => RunnableRetry, + RunnableSequence: () => RunnableSequence, + RunnableToolLike: () => RunnableToolLike, + RunnableWithFallbacks: () => RunnableWithFallbacks, + RunnableWithMessageHistory: () => RunnableWithMessageHistory, + _coerceToRunnable: () => _coerceToRunnable, + ensureConfig: () => ensureConfig, + getCallbackManagerForConfig: () => getCallbackManagerForConfig, + mergeConfigs: () => mergeConfigs, + patchConfig: () => config_patchConfig, + pickRunnableConfigKeys: () => config_pickRunnableConfigKeys, + raceWithSignal: () => raceWithSignal +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json_patch.js + + + + + +//#region src/utils/json_patch.ts +var json_patch_exports = {}; +__export(json_patch_exports, { + applyPatch: () => applyPatch, + compare: () => compare +}); + +//#endregion + +//# sourceMappingURL=json_patch.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/base.js + + + + +//#region src/output_parsers/base.ts +/** +* Abstract base class for parsing the output of a Large Language Model +* (LLM) call. It provides methods for parsing the result of an LLM call +* and invoking the parser with a given input. +*/ +var BaseLLMOutputParser = class extends Runnable { + /** + * Parses the result of an LLM call with a given prompt. By default, it + * simply calls `parseResult`. + * @param generations The generations from an LLM call. + * @param _prompt The prompt used in the LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parseResultWithPrompt(generations, _prompt, callbacks) { + return this.parseResult(generations, callbacks); + } + _baseMessageToString(message) { + return typeof message.content === "string" ? message.content : this._baseMessageContentToString(message.content); + } + _baseMessageContentToString(content) { + return JSON.stringify(content); + } + /** + * Calls the parser with a given input and optional configuration options. + * If the input is a string, it creates a generation with the input as + * text and calls `parseResult`. If the input is a `BaseMessage`, it + * creates a generation with the input as a message and the content of the + * input as text, and then calls `parseResult`. + * @param input The input to the parser, which can be a string or a `BaseMessage`. + * @param options Optional configuration options. + * @returns A promise of the parsed output. + */ + async invoke(input, options) { + if (typeof input === "string") return this._callWithConfig(async (input$1, options$1) => this.parseResult([{ text: input$1 }], options$1?.callbacks), input, { + ...options, + runType: "parser" + }); + else return this._callWithConfig(async (input$1, options$1) => this.parseResult([{ + message: input$1, + text: this._baseMessageToString(input$1) + }], options$1?.callbacks), input, { + ...options, + runType: "parser" + }); + } +}; +/** +* Class to parse the output of an LLM call. +*/ +var BaseOutputParser = class extends BaseLLMOutputParser { + parseResult(generations, callbacks) { + return this.parse(generations[0].text, callbacks); + } + async parseWithPrompt(text, _prompt, callbacks) { + return this.parse(text, callbacks); + } + /** + * Return the string type key uniquely identifying this class of parser + */ + _type() { + throw new Error("_type not implemented"); + } +}; +/** +* Exception that output parsers should raise to signify a parsing error. +* +* This exists to differentiate parsing errors from other code or execution errors +* that also may arise inside the output parser. OutputParserExceptions will be +* available to catch and handle in ways to fix the parsing error, while other +* errors will be raised. +* +* @param message - The error that's being re-raised or an error message. +* @param llmOutput - String model output which is error-ing. +* @param observation - String explanation of error which can be passed to a +* model to try and remediate the issue. +* @param sendToLLM - Whether to send the observation and llm_output back to an Agent +* after an OutputParserException has been raised. This gives the underlying +* model driving the agent the context that the previous output was improperly +* structured, in the hopes that it will update the output to the correct +* format. +*/ +var OutputParserException = class extends Error { + llmOutput; + observation; + sendToLLM; + constructor(message, llmOutput, observation, sendToLLM = false) { + super(message); + this.llmOutput = llmOutput; + this.observation = observation; + this.sendToLLM = sendToLLM; + if (sendToLLM) { + if (observation === void 0 || llmOutput === void 0) throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); + } + addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE"); + } +}; + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/transform.js + + + + + + +//#region src/output_parsers/transform.ts +/** +* Class to parse the output of an LLM call that also allows streaming inputs. +*/ +var BaseTransformOutputParser = class extends BaseOutputParser { + async *_transform(inputGenerator) { + for await (const chunk of inputGenerator) if (typeof chunk === "string") yield this.parseResult([{ text: chunk }]); + else yield this.parseResult([{ + message: chunk, + text: this._baseMessageToString(chunk) + }]); + } + /** + * Transforms an asynchronous generator of input into an asynchronous + * generator of parsed output. + * @param inputGenerator An asynchronous generator of input. + * @param options A configuration object. + * @returns An asynchronous generator of parsed output. + */ + async *transform(inputGenerator, options) { + yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { + ...options, + runType: "parser" + }); + } +}; +/** +* A base class for output parsers that can handle streaming input. It +* extends the `BaseTransformOutputParser` class and provides a method for +* converting parsed outputs into a diff format. +*/ +var BaseCumulativeTransformOutputParser = class extends BaseTransformOutputParser { + diff = false; + constructor(fields) { + super(fields); + this.diff = fields?.diff ?? this.diff; + } + async *_transform(inputGenerator) { + let prevParsed; + let accGen; + for await (const chunk of inputGenerator) { + if (typeof chunk !== "string" && typeof chunk.content !== "string") throw new Error("Cannot handle non-string output."); + let chunkGen; + if (isBaseMessageChunk(chunk)) { + if (typeof chunk.content !== "string") throw new Error("Cannot handle non-string message output."); + chunkGen = new ChatGenerationChunk({ + message: chunk, + text: chunk.content + }); + } else if (isBaseMessage(chunk)) { + if (typeof chunk.content !== "string") throw new Error("Cannot handle non-string message output."); + chunkGen = new ChatGenerationChunk({ + message: convertToChunk(chunk), + text: chunk.content + }); + } else chunkGen = new GenerationChunk({ text: chunk }); + if (accGen === void 0) accGen = chunkGen; + else accGen = accGen.concat(chunkGen); + const parsed = await this.parsePartialResult([accGen]); + if (parsed !== void 0 && parsed !== null && !deepCompareStrict(parsed, prevParsed)) { + if (this.diff) yield this._diff(prevParsed, parsed); + else yield parsed; + prevParsed = parsed; + } + } + } + getFormatInstructions() { + return ""; + } +}; + +//#endregion + +//# sourceMappingURL=transform.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/json.js + + + + + +//#region src/output_parsers/json.ts +/** +* Class for parsing the output of an LLM into a JSON object. +*/ +var JsonOutputParser = class extends BaseCumulativeTransformOutputParser { + static lc_name() { + return "JsonOutputParser"; + } + lc_namespace = ["langchain_core", "output_parsers"]; + lc_serializable = true; + /** @internal */ + _concatOutputChunks(first, second) { + if (this.diff) return super._concatOutputChunks(first, second); + return second; + } + _diff(prev, next) { + if (!next) return void 0; + if (!prev) return [{ + op: "replace", + path: "", + value: next + }]; + return compare(prev, next); + } + async parsePartialResult(generations) { + return parseJsonMarkdown(generations[0].text); + } + async parse(text) { + return parseJsonMarkdown(text, JSON.parse); + } + getFormatInstructions() { + return ""; + } +}; + +//#endregion + +//# sourceMappingURL=json.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_tools/json_output_tools_parsers.js + + + + + + + +//#region src/output_parsers/openai_tools/json_output_tools_parsers.ts +function parseToolCall(rawToolCall, options) { + if (rawToolCall.function === void 0) return void 0; + let functionArgs; + if (options?.partial) try { + functionArgs = parsePartialJson(rawToolCall.function.arguments ?? "{}"); + } catch { + return void 0; + } + else try { + functionArgs = JSON.parse(rawToolCall.function.arguments); + } catch (e) { + throw new OutputParserException([ + `Function "${rawToolCall.function.name}" arguments:`, + ``, + rawToolCall.function.arguments, + ``, + `are not valid JSON.`, + `Error: ${e.message}` + ].join("\n")); + } + const parsedToolCall = { + name: rawToolCall.function.name, + args: functionArgs, + type: "tool_call" + }; + if (options?.returnId) parsedToolCall.id = rawToolCall.id; + return parsedToolCall; +} +function convertLangChainToolCallToOpenAI(toolCall) { + if (toolCall.id === void 0) throw new Error(`All OpenAI tool calls must have an "id" field.`); + return { + id: toolCall.id, + type: "function", + function: { + name: toolCall.name, + arguments: JSON.stringify(toolCall.args) + } + }; +} +function makeInvalidToolCall(rawToolCall, errorMsg) { + return { + name: rawToolCall.function?.name, + args: rawToolCall.function?.arguments, + id: rawToolCall.id, + error: errorMsg, + type: "invalid_tool_call" + }; +} +/** +* Class for parsing the output of a tool-calling LLM into a JSON object. +*/ +var JsonOutputToolsParser = class extends BaseCumulativeTransformOutputParser { + static lc_name() { + return "JsonOutputToolsParser"; + } + returnId = false; + lc_namespace = [ + "langchain", + "output_parsers", + "openai_tools" + ]; + lc_serializable = true; + constructor(fields) { + super(fields); + this.returnId = fields?.returnId ?? this.returnId; + } + _diff() { + throw new Error("Not supported."); + } + async parse() { + throw new Error("Not implemented."); + } + async parseResult(generations) { + const result = await this.parsePartialResult(generations, false); + return result; + } + /** + * Parses the output and returns a JSON object. If `argsOnly` is true, + * only the arguments of the function call are returned. + * @param generations The output of the LLM to parse. + * @returns A JSON object representation of the function call or its arguments. + */ + async parsePartialResult(generations, partial = true) { + const message = generations[0].message; + let toolCalls; + if (isAIMessage(message) && message.tool_calls?.length) toolCalls = message.tool_calls.map((toolCall) => { + const { id,...rest } = toolCall; + if (!this.returnId) return rest; + return { + id, + ...rest + }; + }); + else if (message.additional_kwargs.tool_calls !== void 0) { + const rawToolCalls = JSON.parse(JSON.stringify(message.additional_kwargs.tool_calls)); + toolCalls = rawToolCalls.map((rawToolCall) => { + return parseToolCall(rawToolCall, { + returnId: this.returnId, + partial + }); + }); + } + if (!toolCalls) return []; + const parsedToolCalls = []; + for (const toolCall of toolCalls) if (toolCall !== void 0) { + const backwardsCompatibleToolCall = { + type: toolCall.name, + args: toolCall.args, + id: toolCall.id + }; + parsedToolCalls.push(backwardsCompatibleToolCall); + } + return parsedToolCalls; + } +}; +/** +* Class for parsing the output of a tool-calling LLM into a JSON object if you are +* expecting only a single tool to be called. +*/ +var JsonOutputKeyToolsParser = class extends JsonOutputToolsParser { + static lc_name() { + return "JsonOutputKeyToolsParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "openai_tools" + ]; + lc_serializable = true; + returnId = false; + /** The type of tool calls to return. */ + keyName; + /** Whether to return only the first tool call. */ + returnSingle = false; + zodSchema; + constructor(params) { + super(params); + this.keyName = params.keyName; + this.returnSingle = params.returnSingle ?? this.returnSingle; + this.zodSchema = params.zodSchema; + } + async _validateResult(result) { + if (this.zodSchema === void 0) return result; + const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result); + if (zodParsedResult.success) return zodParsedResult.data; + else throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error?.issues)}`, JSON.stringify(result, null, 2)); + } + async parsePartialResult(generations) { + const results = await super.parsePartialResult(generations); + const matchingResults = results.filter((result) => result.type === this.keyName); + let returnedValues = matchingResults; + if (!matchingResults.length) return void 0; + if (!this.returnId) returnedValues = matchingResults.map((result) => result.args); + if (this.returnSingle) return returnedValues[0]; + return returnedValues; + } + async parseResult(generations) { + const results = await super.parsePartialResult(generations, false); + const matchingResults = results.filter((result) => result.type === this.keyName); + let returnedValues = matchingResults; + if (!matchingResults.length) return void 0; + if (!this.returnId) returnedValues = matchingResults.map((result) => result.args); + if (this.returnSingle) return this._validateResult(returnedValues[0]); + const toolCallResults = await Promise.all(returnedValues.map((value) => this._validateResult(value))); + return toolCallResults; + } +}; + +//#endregion + +//# sourceMappingURL=json_output_tools_parsers.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_tools/index.js + + + +//#region src/output_parsers/openai_tools/index.ts +var openai_tools_exports = {}; +__export(openai_tools_exports, { + JsonOutputKeyToolsParser: () => JsonOutputKeyToolsParser, + JsonOutputToolsParser: () => JsonOutputToolsParser, + convertLangChainToolCallToOpenAI: () => convertLangChainToolCallToOpenAI, + makeInvalidToolCall: () => makeInvalidToolCall, + parseToolCall: () => parseToolCall +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/types/stream.js +//#region src/types/stream.ts +var stream_stream_exports = {}; + +//#endregion + +//# sourceMappingURL=stream.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/run_collector.js + + + +//#region src/tracers/run_collector.ts +var run_collector_exports = {}; +__export(run_collector_exports, { RunCollectorCallbackHandler: () => RunCollectorCallbackHandler }); +/** +* A callback handler that collects traced runs and makes it easy to fetch the traced run object from calls through any langchain object. +* For instance, it makes it easy to fetch the run ID and then do things with that, such as log feedback. +*/ +var RunCollectorCallbackHandler = class extends BaseTracer { + /** The name of the callback handler. */ + name = "run_collector"; + /** The ID of the example. */ + exampleId; + /** An array of traced runs. */ + tracedRuns; + /** + * Creates a new instance of the RunCollectorCallbackHandler class. + * @param exampleId The ID of the example. + */ + constructor({ exampleId } = {}) { + super({ _awaitHandler: true }); + this.exampleId = exampleId; + this.tracedRuns = []; + } + /** + * Persists the given run object. + * @param run The run object to persist. + */ + async persistRun(run) { + const run_ = { ...run }; + run_.reference_example_id = this.exampleId; + this.tracedRuns.push(run_); + } +}; + +//#endregion + +//# sourceMappingURL=run_collector.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/context.js + + +//#region src/utils/context.ts +var context_exports = {}; +__export(context_exports, { context: () => context }); +/** +* A tagged template function for creating formatted strings. +* +* This utility provides a clean, template literal-based API for string formatting +* that can be used for prompts, descriptions, and other text formatting needs. +* +* It automatically handles whitespace normalization and indentation, making it +* ideal for multi-line strings in code. +* +* When using this utility, it will: +* - Strip common leading indentation from all lines +* - Trim leading/trailing whitespace +* - Align multi-line interpolated values to match indentation +* - Support escape sequences: `\\n` (newline), `\\`` (backtick), `\\$` (dollar), `\\{` (brace) +* +* @example +* ```typescript +* import { context } from "@langchain/core/utils/context"; +* +* const role = "agent"; +* const prompt = context` +* You are an ${role}. +* Your task is to help users. +* `; +* // Returns: "You are an agent.\nYour task is to help users." +* ``` +* +* @example +* ```typescript +* // Multi-line interpolated values are aligned +* const items = "- Item 1\n- Item 2\n- Item 3"; +* const message = context` +* Shopping list: +* ${items} +* End of list. +* `; +* // The items will be indented to match " " (4 spaces) +* ``` +*/ +function context(strings, ...values) { + const raw = strings.raw; + let result = ""; + for (let i = 0; i < raw.length; i++) { + const next = raw[i].replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\\{/g, "{"); + result += next; + if (i < values.length) { + const value = alignValue(values[i], result); + result += typeof value === "string" ? value : JSON.stringify(value); + } + } + result = stripIndent(result); + result = result.trim(); + result = result.replace(/\\n/g, "\n"); + return result; +} +/** +* Adjusts the indentation of a multi-line interpolated value to match the current line. +* +* @param value - The interpolated value +* @param precedingText - The text that comes before this value +* @returns The value with adjusted indentation +*/ +function alignValue(value, precedingText) { + if (typeof value !== "string" || !value.includes("\n")) return value; + const currentLine = precedingText.slice(precedingText.lastIndexOf("\n") + 1); + const indentMatch = currentLine.match(/^(\s+)/); + if (indentMatch) { + const indent = indentMatch[1]; + return value.replace(/\n/g, `\n${indent}`); + } + return value; +} +/** +* Strips common leading indentation from all lines. +* +* @param text - The text to process +* @returns The text with common indentation removed +*/ +function stripIndent(text) { + const lines = text.split("\n"); + let minIndent = null; + for (const line of lines) { + const match = line.match(/^(\s+)\S+/); + if (match) { + const indent = match[1].length; + if (minIndent === null) minIndent = indent; + else minIndent = Math.min(minIndent, indent); + } + } + if (minIndent === null) return text; + return lines.map((line) => line[0] === " " || line[0] === " " ? line.slice(minIndent) : line).join("\n"); +} + +//#endregion + +//# sourceMappingURL=context.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_functions/json_output_functions_parsers.js + + + + + + + +//#region src/output_parsers/openai_functions/json_output_functions_parsers.ts +/** +* Class for parsing the output of an LLM. Can be configured to return +* only the arguments of the function call in the output. +*/ +var OutputFunctionsParser = class extends BaseLLMOutputParser { + static lc_name() { + return "OutputFunctionsParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "openai_functions" + ]; + lc_serializable = true; + argsOnly = true; + constructor(config) { + super(); + this.argsOnly = config?.argsOnly ?? this.argsOnly; + } + /** + * Parses the output and returns a string representation of the function + * call or its arguments. + * @param generations The output of the LLM to parse. + * @returns A string representation of the function call or its arguments. + */ + async parseResult(generations) { + if ("message" in generations[0]) { + const gen = generations[0]; + const functionCall = gen.message.additional_kwargs.function_call; + if (!functionCall) throw new Error(`No function_call in message ${JSON.stringify(generations)}`); + if (!functionCall.arguments) throw new Error(`No arguments in function_call ${JSON.stringify(generations)}`); + if (this.argsOnly) return functionCall.arguments; + return JSON.stringify(functionCall); + } else throw new Error(`No message in generations ${JSON.stringify(generations)}`); + } +}; +/** +* Class for parsing the output of an LLM into a JSON object. Uses an +* instance of `OutputFunctionsParser` to parse the output. +*/ +var JsonOutputFunctionsParser = class extends BaseCumulativeTransformOutputParser { + static lc_name() { + return "JsonOutputFunctionsParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "openai_functions" + ]; + lc_serializable = true; + outputParser; + argsOnly = true; + constructor(config) { + super(config); + this.argsOnly = config?.argsOnly ?? this.argsOnly; + this.outputParser = new OutputFunctionsParser(config); + } + _diff(prev, next) { + if (!next) return void 0; + const ops = compare(prev ?? {}, next); + return ops; + } + async parsePartialResult(generations) { + const generation = generations[0]; + if (!generation.message) return void 0; + const { message } = generation; + const functionCall = message.additional_kwargs.function_call; + if (!functionCall) return void 0; + if (this.argsOnly) return parsePartialJson(functionCall.arguments); + return { + ...functionCall, + arguments: parsePartialJson(functionCall.arguments) + }; + } + /** + * Parses the output and returns a JSON object. If `argsOnly` is true, + * only the arguments of the function call are returned. + * @param generations The output of the LLM to parse. + * @returns A JSON object representation of the function call or its arguments. + */ + async parseResult(generations) { + const result = await this.outputParser.parseResult(generations); + if (!result) throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(generations)}`); + return this.parse(result); + } + async parse(text) { + const parsedResult = JSON.parse(text); + if (this.argsOnly) return parsedResult; + parsedResult.arguments = JSON.parse(parsedResult.arguments); + return parsedResult; + } + getFormatInstructions() { + return ""; + } +}; +/** +* Class for parsing the output of an LLM into a JSON object and returning +* a specific attribute. Uses an instance of `JsonOutputFunctionsParser` +* to parse the output. +*/ +var JsonKeyOutputFunctionsParser = class extends BaseLLMOutputParser { + static lc_name() { + return "JsonKeyOutputFunctionsParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "openai_functions" + ]; + lc_serializable = true; + outputParser = new JsonOutputFunctionsParser(); + attrName; + get lc_aliases() { + return { attrName: "key_name" }; + } + constructor(fields) { + super(fields); + this.attrName = fields.attrName; + } + /** + * Parses the output and returns a specific attribute of the parsed JSON + * object. + * @param generations The output of the LLM to parse. + * @returns The value of a specific attribute of the parsed JSON object. + */ + async parseResult(generations) { + const result = await this.outputParser.parseResult(generations); + return result[this.attrName]; + } +}; + +//#endregion + +//# sourceMappingURL=json_output_functions_parsers.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_functions/index.js + + + +//#region src/output_parsers/openai_functions/index.ts +var openai_functions_exports = {}; +__export(openai_functions_exports, { + JsonKeyOutputFunctionsParser: () => JsonKeyOutputFunctionsParser, + JsonOutputFunctionsParser: () => JsonOutputFunctionsParser, + OutputFunctionsParser: () => OutputFunctionsParser +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/chunk_array.js + + +//#region src/utils/chunk_array.ts +var chunk_array_exports = {}; +__export(chunk_array_exports, { chunkArray: () => chunkArray }); +const chunkArray = (arr, chunkSize) => arr.reduce((chunks, elem, index) => { + const chunkIndex = Math.floor(index / chunkSize); + const chunk = chunks[chunkIndex] || []; + chunks[chunkIndex] = chunk.concat([elem]); + return chunks; +}, []); + +//#endregion + +//# sourceMappingURL=chunk_array.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/types.js + + + +//#region src/tools/types.ts +/** +* Confirm whether the inputted tool is an instance of `StructuredToolInterface`. +* +* @param {StructuredToolInterface | JSONSchema | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`. +* @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`. +*/ +function isStructuredTool(tool) { + return tool !== void 0 && Array.isArray(tool.lc_namespace); +} +/** +* Confirm whether the inputted tool is an instance of `RunnableToolLike`. +* +* @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`. +* @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`. +*/ +function isRunnableToolLike(tool) { + return tool !== void 0 && Runnable.isRunnable(tool) && "lc_name" in tool.constructor && typeof tool.constructor.lc_name === "function" && tool.constructor.lc_name() === "RunnableToolLike"; +} +/** +* Confirm whether or not the tool contains the necessary properties to be considered a `StructuredToolParams`. +* +* @param {unknown | undefined} tool The object to check if it is a `StructuredToolParams`. +* @returns {tool is StructuredToolParams} Whether the inputted object is a `StructuredToolParams`. +*/ +function isStructuredToolParams(tool) { + return !!tool && typeof tool === "object" && "name" in tool && "schema" in tool && (isInteropZodSchema(tool.schema) || tool.schema != null && typeof tool.schema === "object" && "type" in tool.schema && typeof tool.schema.type === "string" && [ + "null", + "boolean", + "object", + "array", + "number", + "string" + ].includes(tool.schema.type)); +} +/** +* Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams. +* It returns `is StructuredToolParams` since that is the most minimal interface of the three, +* while still containing the necessary properties to be passed to a LLM for tool calling. +* +* @param {unknown | undefined} tool The tool to check if it is a LangChain tool. +* @returns {tool is StructuredToolParams} Whether the inputted tool is a LangChain tool. +*/ +function isLangChainTool(tool) { + return isStructuredToolParams(tool) || isRunnableToolLike(tool) || isStructuredTool(tool); +} + +//#endregion + +//# sourceMappingURL=types.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/function_calling.js + + + + +//#region src/utils/function_calling.ts +var function_calling_exports = {}; +__export(function_calling_exports, { + convertToOpenAIFunction: () => convertToOpenAIFunction, + convertToOpenAITool: () => convertToOpenAITool, + isLangChainTool: () => isLangChainTool, + isRunnableToolLike: () => isRunnableToolLike, + isStructuredTool: () => isStructuredTool, + isStructuredToolParams: () => isStructuredToolParams +}); +/** +* Formats a `StructuredTool` or `RunnableToolLike` instance into a format +* that is compatible with OpenAI function calling. If `StructuredTool` or +* `RunnableToolLike` has a zod schema, the output will be converted into a +* JSON schema, which is then used as the parameters for the OpenAI tool. +* +* @param {StructuredToolInterface | RunnableToolLike} tool The tool to convert to an OpenAI function. +* @returns {FunctionDefinition} The inputted tool in OpenAI function format. +*/ +function convertToOpenAIFunction(tool, fields) { + const fieldsCopy = typeof fields === "number" ? void 0 : fields; + return { + name: tool.name, + description: tool.description, + parameters: toJsonSchema(tool.schema), + ...fieldsCopy?.strict !== void 0 ? { strict: fieldsCopy.strict } : {} + }; +} +/** +* Formats a `StructuredTool` or `RunnableToolLike` instance into a +* format that is compatible with OpenAI tool calling. If `StructuredTool` or +* `RunnableToolLike` has a zod schema, the output will be converted into a +* JSON schema, which is then used as the parameters for the OpenAI tool. +* +* @param {StructuredToolInterface | Record | RunnableToolLike} tool The tool to convert to an OpenAI tool. +* @returns {ToolDefinition} The inputted tool in OpenAI tool format. +*/ +function convertToOpenAITool(tool, fields) { + const fieldsCopy = typeof fields === "number" ? void 0 : fields; + let toolDef; + if (isLangChainTool(tool)) toolDef = { + type: "function", + function: convertToOpenAIFunction(tool) + }; + else toolDef = tool; + if (fieldsCopy?.strict !== void 0) toolDef.function.strict = fieldsCopy.strict; + return toolDef; +} + +//#endregion + +//# sourceMappingURL=function_calling.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/ir.js +//#region src/structured_query/ir.ts +const Operators = { + and: "and", + or: "or", + not: "not" +}; +const Comparators = { + eq: "eq", + ne: "ne", + lt: "lt", + gt: "gt", + lte: "lte", + gte: "gte" +}; +/** +* Abstract class for visiting expressions. Subclasses must implement +* visitOperation, visitComparison, and visitStructuredQuery methods. +*/ +var Visitor = class {}; +/** +* Abstract class representing an expression. Subclasses must implement +* the exprName property and the accept method. +*/ +var Expression = class { + accept(visitor) { + if (this.exprName === "Operation") return visitor.visitOperation(this); + else if (this.exprName === "Comparison") return visitor.visitComparison(this); + else if (this.exprName === "StructuredQuery") return visitor.visitStructuredQuery(this); + else throw new Error("Unknown Expression type"); + } +}; +/** +* Abstract class representing a filter directive. It extends the +* Expression class. +*/ +var FilterDirective = class extends Expression {}; +/** +* Class representing a comparison filter directive. It extends the +* FilterDirective class. +*/ +var Comparison = class extends FilterDirective { + exprName = "Comparison"; + constructor(comparator, attribute, value) { + super(); + this.comparator = comparator; + this.attribute = attribute; + this.value = value; + } +}; +/** +* Class representing an operation filter directive. It extends the +* FilterDirective class. +*/ +var Operation = class extends FilterDirective { + exprName = "Operation"; + constructor(operator, args) { + super(); + this.operator = operator; + this.args = args; + } +}; +/** +* Class representing a structured query expression. It extends the +* Expression class. +*/ +var StructuredQuery = class extends Expression { + exprName = "StructuredQuery"; + constructor(query, filter) { + super(); + this.query = query; + this.filter = filter; + } +}; + +//#endregion + +//# sourceMappingURL=ir.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/utils.js +//#region src/structured_query/utils.ts +/** +* Checks if the provided argument is an object and not an array. +*/ +function isObject(obj) { + return obj && typeof obj === "object" && !Array.isArray(obj); +} +/** +* Checks if a provided filter is empty. The filter can be a function, an +* object, a string, or undefined. +*/ +function isFilterEmpty(filter) { + if (!filter) return true; + if (typeof filter === "string" && filter.length > 0) return false; + if (typeof filter === "function") return false; + return isObject(filter) && Object.keys(filter).length === 0; +} +/** +* Checks if the provided value is an integer. +*/ +function isInt(value) { + if (typeof value === "number") return value % 1 === 0; + else if (typeof value === "string") { + const numberValue = parseInt(value, 10); + return !Number.isNaN(numberValue) && numberValue % 1 === 0 && numberValue.toString() === value; + } + return false; +} +/** +* Checks if the provided value is a floating-point number. +*/ +function isFloat(value) { + if (typeof value === "number") return value % 1 !== 0; + else if (typeof value === "string") { + const numberValue = parseFloat(value); + return !Number.isNaN(numberValue) && numberValue % 1 !== 0 && numberValue.toString() === value; + } + return false; +} +/** +* Checks if the provided value is a string that cannot be parsed into a +* number. +*/ +function isString(value) { + return typeof value === "string" && (Number.isNaN(parseFloat(value)) || parseFloat(value).toString() !== value); +} +/** +* Checks if the provided value is a boolean. +*/ +function isBoolean(value) { + return typeof value === "boolean"; +} +/** +* Casts a value that might be string or number to actual string or number. +* Since LLM might return back an integer/float as a string, we need to cast +* it back to a number, as many vector databases can't handle number as string +* values as a comparator. +*/ +function castValue(input) { + let value; + if (isString(input)) value = input; + else if (isInt(input)) value = parseInt(input, 10); + else if (isFloat(input)) value = parseFloat(input); + else if (isBoolean(input)) value = Boolean(input); + else throw new Error("Unsupported value type"); + return value; +} + +//#endregion + +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/base.js + + + +//#region src/structured_query/base.ts +/** +* Abstract class that provides a blueprint for creating specific +* translator classes. Defines two abstract methods: formatFunction and +* mergeFilters. +*/ +var BaseTranslator = class extends Visitor {}; +/** +* Class that extends the BaseTranslator class and provides concrete +* implementations for the abstract methods. Also declares three types: +* VisitOperationOutput, VisitComparisonOutput, and +* VisitStructuredQueryOutput, which are used as the return types for the +* visitOperation, visitComparison, and visitStructuredQuery methods +* respectively. +*/ +var BasicTranslator = class extends BaseTranslator { + allowedOperators; + allowedComparators; + constructor(opts) { + super(); + this.allowedOperators = opts?.allowedOperators ?? [Operators.and, Operators.or]; + this.allowedComparators = opts?.allowedComparators ?? [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; + } + formatFunction(func) { + if (func in Comparators) { + if (this.allowedComparators.length > 0 && this.allowedComparators.indexOf(func) === -1) throw new Error(`Comparator ${func} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`); + } else if (func in Operators) { + if (this.allowedOperators.length > 0 && this.allowedOperators.indexOf(func) === -1) throw new Error(`Operator ${func} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`); + } else throw new Error("Unknown comparator or operator"); + return `$${func}`; + } + /** + * Visits an operation and returns a result. + * @param operation The operation to visit. + * @returns The result of visiting the operation. + */ + visitOperation(operation) { + const args = operation.args?.map((arg) => arg.accept(this)); + return { [this.formatFunction(operation.operator)]: args }; + } + /** + * Visits a comparison and returns a result. + * @param comparison The comparison to visit. + * @returns The result of visiting the comparison. + */ + visitComparison(comparison) { + return { [comparison.attribute]: { [this.formatFunction(comparison.comparator)]: castValue(comparison.value) } }; + } + /** + * Visits a structured query and returns a result. + * @param query The structured query to visit. + * @returns The result of visiting the structured query. + */ + visitStructuredQuery(query) { + let nextArg = {}; + if (query.filter) nextArg = { filter: query.filter.accept(this) }; + return nextArg; + } + mergeFilters(defaultFilter, generatedFilter, mergeType = "and", forceDefaultFilter = false) { + if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) return void 0; + if (isFilterEmpty(defaultFilter) || mergeType === "replace") { + if (isFilterEmpty(generatedFilter)) return void 0; + return generatedFilter; + } + if (isFilterEmpty(generatedFilter)) { + if (forceDefaultFilter) return defaultFilter; + if (mergeType === "and") return void 0; + return defaultFilter; + } + if (mergeType === "and") return { $and: [defaultFilter, generatedFilter] }; + else if (mergeType === "or") return { $or: [defaultFilter, generatedFilter] }; + else throw new Error("Unknown merge type"); + } +}; + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/functional.js + + + + +//#region src/structured_query/functional.ts +/** +* A class that extends `BaseTranslator` to translate structured queries +* into functional filters. +* @example +* ```typescript +* const functionalTranslator = new FunctionalTranslator(); +* const relevantDocuments = await functionalTranslator.getRelevantDocuments( +* "Which movies are rated higher than 8.5?", +* ); +* ``` +*/ +var FunctionalTranslator = class extends BaseTranslator { + allowedOperators = [Operators.and, Operators.or]; + allowedComparators = [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; + formatFunction() { + throw new Error("Not implemented"); + } + /** + * Returns the allowed comparators for a given data type. + * @param input The input value to get the allowed comparators for. + * @returns An array of allowed comparators for the input data type. + */ + getAllowedComparatorsForType(inputType) { + switch (inputType) { + case "string": return [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; + case "number": return [ + Comparators.eq, + Comparators.ne, + Comparators.gt, + Comparators.gte, + Comparators.lt, + Comparators.lte + ]; + case "boolean": return [Comparators.eq, Comparators.ne]; + default: throw new Error(`Unsupported data type: ${inputType}`); + } + } + /** + * Returns a function that performs a comparison based on the provided + * comparator. + * @param comparator The comparator to base the comparison function on. + * @returns A function that takes two arguments and returns a boolean based on the comparison. + */ + getComparatorFunction(comparator) { + switch (comparator) { + case Comparators.eq: return (a, b) => a === b; + case Comparators.ne: return (a, b) => a !== b; + case Comparators.gt: return (a, b) => a > b; + case Comparators.gte: return (a, b) => a >= b; + case Comparators.lt: return (a, b) => a < b; + case Comparators.lte: return (a, b) => a <= b; + default: throw new Error("Unknown comparator"); + } + } + /** + * Returns a function that performs an operation based on the provided + * operator. + * @param operator The operator to base the operation function on. + * @returns A function that takes two boolean arguments and returns a boolean based on the operation. + */ + getOperatorFunction(operator) { + switch (operator) { + case Operators.and: return (a, b) => a && b; + case Operators.or: return (a, b) => a || b; + default: throw new Error("Unknown operator"); + } + } + /** + * Visits the operation part of a structured query and translates it into + * a functional filter. + * @param operation The operation part of a structured query. + * @returns A function that takes a `Document` as an argument and returns a boolean based on the operation. + */ + visitOperation(operation) { + const { operator, args } = operation; + if (this.allowedOperators.includes(operator)) { + const operatorFunction = this.getOperatorFunction(operator); + return (document) => { + if (!args) return true; + return args.reduce((acc, arg) => { + const result = arg.accept(this); + if (typeof result === "function") return operatorFunction(acc, result(document)); + else throw new Error("Filter is not a function"); + }, true); + }; + } else throw new Error("Operator not allowed"); + } + /** + * Visits the comparison part of a structured query and translates it into + * a functional filter. + * @param comparison The comparison part of a structured query. + * @returns A function that takes a `Document` as an argument and returns a boolean based on the comparison. + */ + visitComparison(comparison) { + const { comparator, attribute, value } = comparison; + const undefinedTrue = [Comparators.ne]; + if (this.allowedComparators.includes(comparator)) { + if (!this.getAllowedComparatorsForType(typeof value).includes(comparator)) throw new Error(`'${comparator}' comparator not allowed to be used with ${typeof value}`); + const comparatorFunction = this.getComparatorFunction(comparator); + return (document) => { + const documentValue = document.metadata[attribute]; + if (documentValue === void 0) { + if (undefinedTrue.includes(comparator)) return true; + return false; + } + return comparatorFunction(documentValue, castValue(value)); + }; + } else throw new Error("Comparator not allowed"); + } + /** + * Visits a structured query and translates it into a functional filter. + * @param query The structured query to translate. + * @returns An object containing a `filter` property, which is a function that takes a `Document` as an argument and returns a boolean based on the structured query. + */ + visitStructuredQuery(query) { + if (!query.filter) return {}; + const filterFunction = query.filter?.accept(this); + if (typeof filterFunction !== "function") throw new Error("Structured query filter is not a function"); + return { filter: filterFunction }; + } + /** + * Merges two filters into one, based on the specified merge type. + * @param defaultFilter The default filter function. + * @param generatedFilter The generated filter function. + * @param mergeType The type of merge to perform. Can be 'and', 'or', or 'replace'. Default is 'and'. + * @returns A function that takes a `Document` as an argument and returns a boolean based on the merged filters, or `undefined` if both filters are empty. + */ + mergeFilters(defaultFilter, generatedFilter, mergeType = "and") { + if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) return void 0; + if (isFilterEmpty(defaultFilter) || mergeType === "replace") { + if (isFilterEmpty(generatedFilter)) return void 0; + return generatedFilter; + } + if (isFilterEmpty(generatedFilter)) { + if (mergeType === "and") return void 0; + return defaultFilter; + } + if (mergeType === "and") return (document) => defaultFilter(document) && generatedFilter(document); + else if (mergeType === "or") return (document) => defaultFilter(document) || generatedFilter(document); + else throw new Error("Unknown merge type"); + } +}; + +//#endregion + +//# sourceMappingURL=functional.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/index.js + + + + + + +//#region src/structured_query/index.ts +var structured_query_exports = {}; +__export(structured_query_exports, { + BaseTranslator: () => BaseTranslator, + BasicTranslator: () => BasicTranslator, + Comparators: () => Comparators, + Comparison: () => Comparison, + Expression: () => Expression, + FilterDirective: () => FilterDirective, + FunctionalTranslator: () => FunctionalTranslator, + Operation: () => Operation, + Operators: () => Operators, + StructuredQuery: () => StructuredQuery, + Visitor: () => Visitor, + castValue: () => castValue, + isBoolean: () => isBoolean, + isFilterEmpty: () => isFilterEmpty, + isFloat: () => isFloat, + isInt: () => isInt, + isObject: () => isObject, + isString: () => isString +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/checks.js + + +;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/iso.js + + +const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { + $ZodISODateTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iso_datetime(params) { + return _isoDateTime(ZodISODateTime, params); +} +const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { + $ZodISODate.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iso_date(params) { + return _isoDate(ZodISODate, params); +} +const ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { + $ZodISOTime.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iso_time(params) { + return _isoTime(ZodISOTime, params); +} +const ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { + $ZodISODuration.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function iso_duration(params) { + return _isoDuration(ZodISODuration, params); +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/errors.js + + + +const errors_initializer = (inst, issues) => { + $ZodError.init(inst, issues); + inst.name = "ZodError"; + Object.defineProperties(inst, { + format: { + value: (mapper) => formatError(inst, mapper), + // enumerable: false, + }, + flatten: { + value: (mapper) => flattenError(inst, mapper), + // enumerable: false, + }, + addIssue: { + value: (issue) => { + inst.issues.push(issue); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + }, + // enumerable: false, + }, + addIssues: { + value: (issues) => { + inst.issues.push(...issues); + inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); + }, + // enumerable: false, + }, + isEmpty: { + get() { + return inst.issues.length === 0; + }, + // enumerable: false, + }, + }); + // Object.defineProperty(inst, "isEmpty", { + // get() { + // return inst.issues.length === 0; + // }, + // }); +}; +const errors_ZodError = $constructor("ZodError", errors_initializer); +const ZodRealError = $constructor("ZodError", errors_initializer, { + Parent: Error, +}); +// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ +// export type ErrorMapCtx = core.$ZodErrorMapCtx; + +;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/parse.js + + +const classic_parse_parse = /* @__PURE__ */ _parse(ZodRealError); +const parse_parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError); +const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); +const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); +// Codec functions +const parse_encode = /* @__PURE__ */ _encode(ZodRealError); +const parse_decode = /* @__PURE__ */ _decode(ZodRealError); +const parse_encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError); +const parse_decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError); +const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); +const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); +const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); +const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); + +;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/schemas.js + + + + + + + +const schemas_ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { + $ZodType.init(inst, def); + Object.assign(inst["~standard"], { + jsonSchema: { + input: createStandardJSONSchemaMethod(inst, "input"), + output: createStandardJSONSchemaMethod(inst, "output"), + }, + }); + inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); + inst.def = def; + inst.type = def.type; + Object.defineProperty(inst, "_def", { value: def }); + // base methods + inst.check = (...checks) => { + return inst.clone(mergeDefs(def, { + checks: [ + ...(def.checks ?? []), + ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), + ], + })); + }; + inst.clone = (def, params) => clone(inst, def, params); + inst.brand = () => inst; + inst.register = ((reg, meta) => { + reg.add(inst, meta); + return inst; + }); + // parsing + inst.parse = (data, params) => classic_parse_parse(inst, data, params, { callee: inst.parse }); + inst.safeParse = (data, params) => parse_safeParse(inst, data, params); + inst.parseAsync = async (data, params) => parse_parseAsync(inst, data, params, { callee: inst.parseAsync }); + inst.safeParseAsync = async (data, params) => parse_safeParseAsync(inst, data, params); + inst.spa = inst.safeParseAsync; + // encoding/decoding + inst.encode = (data, params) => parse_encode(inst, data, params); + inst.decode = (data, params) => parse_decode(inst, data, params); + inst.encodeAsync = async (data, params) => parse_encodeAsync(inst, data, params); + inst.decodeAsync = async (data, params) => parse_decodeAsync(inst, data, params); + inst.safeEncode = (data, params) => parse_safeEncode(inst, data, params); + inst.safeDecode = (data, params) => parse_safeDecode(inst, data, params); + inst.safeEncodeAsync = async (data, params) => parse_safeEncodeAsync(inst, data, params); + inst.safeDecodeAsync = async (data, params) => parse_safeDecodeAsync(inst, data, params); + // refinements + inst.refine = (check, params) => inst.check(refine(check, params)); + inst.superRefine = (refinement) => inst.check(superRefine(refinement)); + inst.overwrite = (fn) => inst.check(_overwrite(fn)); + // wrappers + inst.optional = () => optional(inst); + inst.nullable = () => nullable(inst); + inst.nullish = () => optional(nullable(inst)); + inst.nonoptional = (params) => nonoptional(inst, params); + inst.array = () => array(inst); + inst.or = (arg) => union([inst, arg]); + inst.and = (arg) => intersection(inst, arg); + inst.transform = (tx) => pipe(inst, transform(tx)); + inst.default = (def) => schemas_default(inst, def); + inst.prefault = (def) => prefault(inst, def); + // inst.coalesce = (def, params) => coalesce(inst, def, params); + inst.catch = (params) => schemas_catch(inst, params); + inst.pipe = (target) => pipe(inst, target); + inst.readonly = () => readonly(inst); + // meta + inst.describe = (description) => { + const cl = inst.clone(); + globalRegistry.add(cl, { description }); + return cl; + }; + Object.defineProperty(inst, "description", { + get() { + return globalRegistry.get(inst)?.description; + }, + configurable: true, + }); + inst.meta = (...args) => { + if (args.length === 0) { + return globalRegistry.get(inst); + } + const cl = inst.clone(); + globalRegistry.add(cl, args[0]); + return cl; + }; + // helpers + inst.isOptional = () => inst.safeParse(undefined).success; + inst.isNullable = () => inst.safeParse(null).success; + return inst; +}); +/** @internal */ +const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { + $ZodString.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); + const bag = inst._zod.bag; + inst.format = bag.format ?? null; + inst.minLength = bag.minimum ?? null; + inst.maxLength = bag.maximum ?? null; + // validations + inst.regex = (...args) => inst.check(_regex(...args)); + inst.includes = (...args) => inst.check(_includes(...args)); + inst.startsWith = (...args) => inst.check(_startsWith(...args)); + inst.endsWith = (...args) => inst.check(_endsWith(...args)); + inst.min = (...args) => inst.check(_minLength(...args)); + inst.max = (...args) => inst.check(_maxLength(...args)); + inst.length = (...args) => inst.check(_length(...args)); + inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); + inst.lowercase = (params) => inst.check(_lowercase(params)); + inst.uppercase = (params) => inst.check(_uppercase(params)); + // transforms + inst.trim = () => inst.check(_trim()); + inst.normalize = (...args) => inst.check(_normalize(...args)); + inst.toLowerCase = () => inst.check(_toLowerCase()); + inst.toUpperCase = () => inst.check(_toUpperCase()); + inst.slugify = () => inst.check(_slugify()); +}); +const schemas_ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { + $ZodString.init(inst, def); + _ZodString.init(inst, def); + inst.email = (params) => inst.check(_email(ZodEmail, params)); + inst.url = (params) => inst.check(_url(ZodURL, params)); + inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); + inst.emoji = (params) => inst.check(api_emoji(ZodEmoji, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); + inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); + inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); + inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); + inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); + inst.guid = (params) => inst.check(_guid(ZodGUID, params)); + inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); + inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); + inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); + inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); + inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); + inst.xid = (params) => inst.check(_xid(ZodXID, params)); + inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); + inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); + inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); + inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); + inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); + inst.e164 = (params) => inst.check(_e164(ZodE164, params)); + // iso + inst.datetime = (params) => inst.check(iso_datetime(params)); + inst.date = (params) => inst.check(iso_date(params)); + inst.time = (params) => inst.check(iso_time(params)); + inst.duration = (params) => inst.check(iso_duration(params)); +}); +function schemas_string(params) { + return _string(schemas_ZodString, params); +} +const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { + $ZodStringFormat.init(inst, def); + _ZodString.init(inst, def); +}); +const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmail.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_email(params) { + return _email(ZodEmail, params); +} +const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodGUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_guid(params) { + return _guid(ZodGUID, params); +} +const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodUUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_uuid(params) { + return _uuid(ZodUUID, params); +} +function uuidv4(params) { + return _uuidv4(ZodUUID, params); +} +// ZodUUIDv6 +function uuidv6(params) { + return _uuidv6(ZodUUID, params); +} +// ZodUUIDv7 +function schemas_uuidv7(params) { + return _uuidv7(ZodUUID, params); +} +const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodURL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function url(params) { + return _url(ZodURL, params); +} +function httpUrl(params) { + return _url(ZodURL, { + protocol: /^https?$/, + hostname: domain, + ...normalizeParams(params), + }); +} +const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodEmoji.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_emoji(params) { + return api_emoji(ZodEmoji, params); +} +const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodNanoID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_nanoid(params) { + return _nanoid(ZodNanoID, params); +} +const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cuid(params) { + return _cuid(ZodCUID, params); +} +const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCUID2.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cuid2(params) { + return _cuid2(ZodCUID2, params); +} +const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodULID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ulid(params) { + return _ulid(ZodULID, params); +} +const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodXID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_xid(params) { + return _xid(ZodXID, params); +} +const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodKSUID.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ksuid(params) { + return _ksuid(ZodKSUID, params); +} +const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv4(params) { + return _ipv4(ZodIPv4, params); +} +const ZodMAC = /*@__PURE__*/ $constructor("ZodMAC", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodMAC.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_mac(params) { + return _mac(ZodMAC, params); +} +const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodIPv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_ipv6(params) { + return _ipv6(ZodIPv6, params); +} +const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { + $ZodCIDRv4.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv4(params) { + return _cidrv4(ZodCIDRv4, params); +} +const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { + $ZodCIDRv6.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_cidrv6(params) { + return _cidrv6(ZodCIDRv6, params); +} +const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64(params) { + return _base64(ZodBase64, params); +} +const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodBase64URL.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_base64url(params) { + return _base64url(ZodBase64URL, params); +} +const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodE164.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function schemas_e164(params) { + return _e164(ZodE164, params); +} +const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodJWT.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function jwt(params) { + return _jwt(ZodJWT, params); +} +const ZodCustomStringFormat = /*@__PURE__*/ $constructor("ZodCustomStringFormat", (inst, def) => { + // ZodStringFormat.init(inst, def); + $ZodCustomStringFormat.init(inst, def); + ZodStringFormat.init(inst, def); +}); +function stringFormat(format, fnOrRegex, _params = {}) { + return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); +} +function schemas_hostname(_params) { + return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); +} +function schemas_hex(_params) { + return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); +} +function hash(alg, params) { + const enc = params?.enc ?? "hex"; + const format = `${alg}_${enc}`; + const regex = regexes_namespaceObject[format]; + if (!regex) + throw new Error(`Unrecognized hash format: ${format}`); + return _stringFormat(ZodCustomStringFormat, format, regex, params); +} +const schemas_ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { + $ZodNumber.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.int = (params) => inst.check(schemas_int(params)); + inst.safe = (params) => inst.check(schemas_int(params)); + inst.positive = (params) => inst.check(_gt(0, params)); + inst.nonnegative = (params) => inst.check(_gte(0, params)); + inst.negative = (params) => inst.check(_lt(0, params)); + inst.nonpositive = (params) => inst.check(_lte(0, params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + inst.step = (value, params) => inst.check(_multipleOf(value, params)); + // inst.finite = (params) => inst.check(core.finite(params)); + inst.finite = () => inst; + const bag = inst._zod.bag; + inst.minValue = + Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; + inst.maxValue = + Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; + inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); + inst.isFinite = true; + inst.format = bag.format ?? null; +}); +function schemas_number(params) { + return _number(schemas_ZodNumber, params); +} +const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { + $ZodNumberFormat.init(inst, def); + schemas_ZodNumber.init(inst, def); +}); +function schemas_int(params) { + return _int(ZodNumberFormat, params); +} +function float32(params) { + return _float32(ZodNumberFormat, params); +} +function float64(params) { + return _float64(ZodNumberFormat, params); +} +function int32(params) { + return _int32(ZodNumberFormat, params); +} +function uint32(params) { + return _uint32(ZodNumberFormat, params); +} +const schemas_ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { + $ZodBoolean.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); +}); +function schemas_boolean(params) { + return _boolean(schemas_ZodBoolean, params); +} +const schemas_ZodBigInt = /*@__PURE__*/ $constructor("ZodBigInt", (inst, def) => { + $ZodBigInt.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => bigintProcessor(inst, ctx, json, params); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.gt = (value, params) => inst.check(_gt(value, params)); + inst.gte = (value, params) => inst.check(_gte(value, params)); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.lt = (value, params) => inst.check(_lt(value, params)); + inst.lte = (value, params) => inst.check(_lte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + inst.positive = (params) => inst.check(_gt(BigInt(0), params)); + inst.negative = (params) => inst.check(_lt(BigInt(0), params)); + inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); + inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); + inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); + const bag = inst._zod.bag; + inst.minValue = bag.minimum ?? null; + inst.maxValue = bag.maximum ?? null; + inst.format = bag.format ?? null; +}); +function schemas_bigint(params) { + return _bigint(schemas_ZodBigInt, params); +} +const ZodBigIntFormat = /*@__PURE__*/ $constructor("ZodBigIntFormat", (inst, def) => { + $ZodBigIntFormat.init(inst, def); + schemas_ZodBigInt.init(inst, def); +}); +// int64 +function int64(params) { + return _int64(ZodBigIntFormat, params); +} +// uint64 +function uint64(params) { + return _uint64(ZodBigIntFormat, params); +} +const schemas_ZodSymbol = /*@__PURE__*/ $constructor("ZodSymbol", (inst, def) => { + $ZodSymbol.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => symbolProcessor(inst, ctx, json, params); +}); +function symbol(params) { + return _symbol(schemas_ZodSymbol, params); +} +const schemas_ZodUndefined = /*@__PURE__*/ $constructor("ZodUndefined", (inst, def) => { + $ZodUndefined.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => undefinedProcessor(inst, ctx, json, params); +}); +function schemas_undefined(params) { + return api_undefined(schemas_ZodUndefined, params); +} + +const schemas_ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { + $ZodNull.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); +}); +function schemas_null(params) { + return api_null(schemas_ZodNull, params); +} + +const schemas_ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { + $ZodAny.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); +}); +function any() { + return _any(schemas_ZodAny); +} +const schemas_ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { + $ZodUnknown.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); +}); +function unknown() { + return _unknown(schemas_ZodUnknown); +} +const schemas_ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { + $ZodNever.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); +}); +function schemas_never(params) { + return _never(schemas_ZodNever, params); +} +const schemas_ZodVoid = /*@__PURE__*/ $constructor("ZodVoid", (inst, def) => { + $ZodVoid.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => voidProcessor(inst, ctx, json, params); +}); +function schemas_void(params) { + return _void(schemas_ZodVoid, params); +} + +const schemas_ZodDate = /*@__PURE__*/ $constructor("ZodDate", (inst, def) => { + $ZodDate.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => dateProcessor(inst, ctx, json, params); + inst.min = (value, params) => inst.check(_gte(value, params)); + inst.max = (value, params) => inst.check(_lte(value, params)); + const c = inst._zod.bag; + inst.minDate = c.minimum ? new Date(c.minimum) : null; + inst.maxDate = c.maximum ? new Date(c.maximum) : null; +}); +function schemas_date(params) { + return _date(schemas_ZodDate, params); +} +const schemas_ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { + $ZodArray.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); + inst.element = def.element; + inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); + inst.nonempty = (params) => inst.check(_minLength(1, params)); + inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); + inst.length = (len, params) => inst.check(_length(len, params)); + inst.unwrap = () => inst.element; +}); +function array(element, params) { + return _array(schemas_ZodArray, element, params); +} +// .keyof +function keyof(schema) { + const shape = schema._zod.def.shape; + return schemas_enum(Object.keys(shape)); +} +const schemas_ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { + $ZodObjectJIT.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); + defineLazy(inst, "shape", () => { + return def.shape; + }); + inst.keyof = () => schemas_enum(Object.keys(inst._zod.def.shape)); + inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall }); + inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); + inst.strict = () => inst.clone({ ...inst._zod.def, catchall: schemas_never() }); + inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined }); + inst.extend = (incoming) => { + return extend(inst, incoming); + }; + inst.safeExtend = (incoming) => { + return safeExtend(inst, incoming); + }; + inst.merge = (other) => merge(inst, other); + inst.pick = (mask) => pick(inst, mask); + inst.omit = (mask) => omit(inst, mask); + inst.partial = (...args) => partial(schemas_ZodOptional, inst, args[0]); + inst.required = (...args) => required(ZodNonOptional, inst, args[0]); +}); +function object(shape, params) { + const def = { + type: "object", + shape: shape ?? {}, + ...normalizeParams(params), + }; + return new schemas_ZodObject(def); +} +// strictObject +function strictObject(shape, params) { + return new schemas_ZodObject({ + type: "object", + shape, + catchall: schemas_never(), + ...normalizeParams(params), + }); +} +// looseObject +function looseObject(shape, params) { + return new schemas_ZodObject({ + type: "object", + shape, + catchall: unknown(), + ...normalizeParams(params), + }); +} +const schemas_ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { + $ZodUnion.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}); +function union(options, params) { + return new schemas_ZodUnion({ + type: "union", + options: options, + ...normalizeParams(params), + }); +} +const ZodXor = /*@__PURE__*/ $constructor("ZodXor", (inst, def) => { + schemas_ZodUnion.init(inst, def); + $ZodXor.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); + inst.options = def.options; +}); +/** Creates an exclusive union (XOR) where exactly one option must match. + * Unlike regular unions that succeed when any option matches, xor fails if + * zero or more than one option matches the input. */ +function xor(options, params) { + return new ZodXor({ + type: "union", + options: options, + inclusive: false, + ...normalizeParams(params), + }); +} +const schemas_ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { + schemas_ZodUnion.init(inst, def); + $ZodDiscriminatedUnion.init(inst, def); +}); +function discriminatedUnion(discriminator, options, params) { + // const [options, params] = args; + return new schemas_ZodDiscriminatedUnion({ + type: "union", + options, + discriminator, + ...normalizeParams(params), + }); +} +const schemas_ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { + $ZodIntersection.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); +}); +function intersection(left, right) { + return new schemas_ZodIntersection({ + type: "intersection", + left: left, + right: right, + }); +} +const schemas_ZodTuple = /*@__PURE__*/ $constructor("ZodTuple", (inst, def) => { + $ZodTuple.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => tupleProcessor(inst, ctx, json, params); + inst.rest = (rest) => inst.clone({ + ...inst._zod.def, + rest: rest, + }); +}); +function tuple(items, _paramsOrRest, _params) { + const hasRest = _paramsOrRest instanceof $ZodType; + const params = hasRest ? _params : _paramsOrRest; + const rest = hasRest ? _paramsOrRest : null; + return new schemas_ZodTuple({ + type: "tuple", + items: items, + rest, + ...normalizeParams(params), + }); +} +const schemas_ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { + $ZodRecord.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function record(keyType, valueType, params) { + return new schemas_ZodRecord({ + type: "record", + keyType, + valueType: valueType, + ...normalizeParams(params), + }); +} +// type alksjf = core.output; +function partialRecord(keyType, valueType, params) { + const k = clone(keyType); + k._zod.values = undefined; + return new schemas_ZodRecord({ + type: "record", + keyType: k, + valueType: valueType, + ...normalizeParams(params), + }); +} +function looseRecord(keyType, valueType, params) { + return new schemas_ZodRecord({ + type: "record", + keyType, + valueType: valueType, + mode: "loose", + ...normalizeParams(params), + }); +} +const schemas_ZodMap = /*@__PURE__*/ $constructor("ZodMap", (inst, def) => { + $ZodMap.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => mapProcessor(inst, ctx, json, params); + inst.keyType = def.keyType; + inst.valueType = def.valueType; +}); +function map(keyType, valueType, params) { + return new schemas_ZodMap({ + type: "map", + keyType: keyType, + valueType: valueType, + ...normalizeParams(params), + }); +} +const schemas_ZodSet = /*@__PURE__*/ $constructor("ZodSet", (inst, def) => { + $ZodSet.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => setProcessor(inst, ctx, json, params); + inst.min = (...args) => inst.check(_minSize(...args)); + inst.nonempty = (params) => inst.check(_minSize(1, params)); + inst.max = (...args) => inst.check(_maxSize(...args)); + inst.size = (...args) => inst.check(_size(...args)); +}); +function set(valueType, params) { + return new schemas_ZodSet({ + type: "set", + valueType: valueType, + ...normalizeParams(params), + }); +} +const schemas_ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { + $ZodEnum.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); + inst.enum = def.entries; + inst.options = Object.values(def.entries); + const keys = new Set(Object.keys(def.entries)); + inst.extract = (values, params) => { + const newEntries = {}; + for (const value of values) { + if (keys.has(value)) { + newEntries[value] = def.entries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new schemas_ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; + inst.exclude = (values, params) => { + const newEntries = { ...def.entries }; + for (const value of values) { + if (keys.has(value)) { + delete newEntries[value]; + } + else + throw new Error(`Key ${value} not found in enum`); + } + return new schemas_ZodEnum({ + ...def, + checks: [], + ...normalizeParams(params), + entries: newEntries, + }); + }; +}); +function schemas_enum(values, params) { + const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; + return new schemas_ZodEnum({ + type: "enum", + entries, + ...normalizeParams(params), + }); +} + +/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. + * + * ```ts + * enum Colors { red, green, blue } + * z.enum(Colors); + * ``` + */ +function nativeEnum(entries, params) { + return new schemas_ZodEnum({ + type: "enum", + entries, + ...normalizeParams(params), + }); +} +const schemas_ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { + $ZodLiteral.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); + inst.values = new Set(def.values); + Object.defineProperty(inst, "value", { + get() { + if (def.values.length > 1) { + throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); + } + return def.values[0]; + }, + }); +}); +function literal(value, params) { + return new schemas_ZodLiteral({ + type: "literal", + values: Array.isArray(value) ? value : [value], + ...normalizeParams(params), + }); +} +const ZodFile = /*@__PURE__*/ $constructor("ZodFile", (inst, def) => { + $ZodFile.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => fileProcessor(inst, ctx, json, params); + inst.min = (size, params) => inst.check(_minSize(size, params)); + inst.max = (size, params) => inst.check(_maxSize(size, params)); + inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); +}); +function file(params) { + return _file(ZodFile, params); +} +const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { + $ZodTransform.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); + inst._zod.parse = (payload, _ctx) => { + if (_ctx.direction === "backward") { + throw new $ZodEncodeError(inst.constructor.name); + } + payload.addIssue = (issue) => { + if (typeof issue === "string") { + payload.issues.push(util_issue(issue, payload.value, def)); + } + else { + // for Zod 3 backwards compatibility + const _issue = issue; + if (_issue.fatal) + _issue.continue = false; + _issue.code ?? (_issue.code = "custom"); + _issue.input ?? (_issue.input = payload.value); + _issue.inst ?? (_issue.inst = inst); + // _issue.continue ??= true; + payload.issues.push(util_issue(_issue)); + } + }; + const output = def.transform(payload.value, payload); + if (output instanceof Promise) { + return output.then((output) => { + payload.value = output; + return payload; + }); + } + payload.value = output; + return payload; + }; +}); +function transform(fn) { + return new ZodTransform({ + type: "transform", + transform: fn, + }); +} +const schemas_ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { + $ZodOptional.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function optional(innerType) { + return new schemas_ZodOptional({ + type: "optional", + innerType: innerType, + }); +} +const schemas_ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { + $ZodNullable.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nullable(innerType) { + return new schemas_ZodNullable({ + type: "nullable", + innerType: innerType, + }); +} +// nullish +function schemas_nullish(innerType) { + return optional(nullable(innerType)); +} +const schemas_ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { + $ZodDefault.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeDefault = inst.unwrap; +}); +function schemas_default(innerType, defaultValue) { + return new schemas_ZodDefault({ + type: "default", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { + $ZodPrefault.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function prefault(innerType, defaultValue) { + return new ZodPrefault({ + type: "prefault", + innerType: innerType, + get defaultValue() { + return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); + }, + }); +} +const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { + $ZodNonOptional.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function nonoptional(innerType, params) { + return new ZodNonOptional({ + type: "nonoptional", + innerType: innerType, + ...normalizeParams(params), + }); +} +const ZodSuccess = /*@__PURE__*/ $constructor("ZodSuccess", (inst, def) => { + $ZodSuccess.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => successProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function success(innerType) { + return new ZodSuccess({ + type: "success", + innerType: innerType, + }); +} +const schemas_ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { + $ZodCatch.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; + inst.removeCatch = inst.unwrap; +}); +function schemas_catch(innerType, catchValue) { + return new schemas_ZodCatch({ + type: "catch", + innerType: innerType, + catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), + }); +} + +const schemas_ZodNaN = /*@__PURE__*/ $constructor("ZodNaN", (inst, def) => { + $ZodNaN.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => nanProcessor(inst, ctx, json, params); +}); +function nan(params) { + return _nan(schemas_ZodNaN, params); +} +const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { + $ZodPipe.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); + inst.in = def.in; + inst.out = def.out; +}); +function pipe(in_, out) { + return new ZodPipe({ + type: "pipe", + in: in_, + out: out, + // ...util.normalizeParams(params), + }); +} +const ZodCodec = /*@__PURE__*/ $constructor("ZodCodec", (inst, def) => { + ZodPipe.init(inst, def); + $ZodCodec.init(inst, def); +}); +function codec(in_, out, params) { + return new ZodCodec({ + type: "pipe", + in: in_, + out: out, + transform: params.decode, + reverseTransform: params.encode, + }); +} +const schemas_ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { + $ZodReadonly.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function readonly(innerType) { + return new schemas_ZodReadonly({ + type: "readonly", + innerType: innerType, + }); +} +const ZodTemplateLiteral = /*@__PURE__*/ $constructor("ZodTemplateLiteral", (inst, def) => { + $ZodTemplateLiteral.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => templateLiteralProcessor(inst, ctx, json, params); +}); +function templateLiteral(parts, params) { + return new ZodTemplateLiteral({ + type: "template_literal", + parts, + ...normalizeParams(params), + }); +} +const schemas_ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { + $ZodLazy.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.getter(); +}); +function lazy(getter) { + return new schemas_ZodLazy({ + type: "lazy", + getter: getter, + }); +} +const schemas_ZodPromise = /*@__PURE__*/ $constructor("ZodPromise", (inst, def) => { + $ZodPromise.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => promiseProcessor(inst, ctx, json, params); + inst.unwrap = () => inst._zod.def.innerType; +}); +function promise(innerType) { + return new schemas_ZodPromise({ + type: "promise", + innerType: innerType, + }); +} +const schemas_ZodFunction = /*@__PURE__*/ $constructor("ZodFunction", (inst, def) => { + $ZodFunction.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => functionProcessor(inst, ctx, json, params); +}); +function _function(params) { + return new schemas_ZodFunction({ + type: "function", + input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())), + output: params?.output ?? unknown(), + }); +} + +const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { + $ZodCustom.init(inst, def); + schemas_ZodType.init(inst, def); + inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); +}); +// custom checks +function check(fn) { + const ch = new $ZodCheck({ + check: "custom", + // ...util.normalizeParams(params), + }); + ch._zod.check = fn; + return ch; +} +function schemas_custom(fn, _params) { + return _custom(ZodCustom, fn ?? (() => true), _params); +} +function refine(fn, _params = {}) { + return _refine(ZodCustom, fn, _params); +} +// superRefine +function superRefine(fn) { + return _superRefine(fn); +} +// Re-export describe and meta from core +const schemas_describe = describe; +const schemas_meta = meta; +function _instanceof(cls, params = { + error: `Input not instance of ${cls.name}`, +}) { + const inst = new ZodCustom({ + type: "custom", + check: "custom", + fn: (data) => data instanceof cls, + abort: true, + ...normalizeParams(params), + }); + inst._zod.bag.Class = cls; + return inst; +} + +// stringbool +const stringbool = (...args) => _stringbool({ + Codec: ZodCodec, + Boolean: schemas_ZodBoolean, + String: schemas_ZodString, +}, ...args); +function json(params) { + const jsonSchema = lazy(() => { + return union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), array(jsonSchema), record(schemas_string(), jsonSchema)]); + }); + return jsonSchema; +} +// preprocess +// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */ +function preprocess(fn, schema) { + return pipe(transform(fn), schema); +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/compat.js +// Zod 3 compat layer + +/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ +const compat_ZodIssueCode = { + invalid_type: "invalid_type", + too_big: "too_big", + too_small: "too_small", + invalid_format: "invalid_format", + not_multiple_of: "not_multiple_of", + unrecognized_keys: "unrecognized_keys", + invalid_union: "invalid_union", + invalid_key: "invalid_key", + invalid_element: "invalid_element", + invalid_value: "invalid_value", + custom: "custom", +}; + +/** @deprecated Use `z.config(params)` instead. */ +function compat_setErrorMap(map) { + config({ + customError: map, + }); +} +/** @deprecated Use `z.config()` instead. */ +function compat_getErrorMap() { + return config().customError; +} +/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ +var compat_ZodFirstPartyTypeKind; +(function (ZodFirstPartyTypeKind) { +})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); + +;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/from-json-schema.js + + + +// Local z object to avoid circular dependency with ../index.js +const from_json_schema_z = { + ...classic_schemas_namespaceObject, + ...classic_checks_namespaceObject, + iso: iso_namespaceObject, +}; +function detectVersion(schema, defaultTarget) { + const $schema = schema.$schema; + if ($schema === "https://json-schema.org/draft/2020-12/schema") { + return "draft-2020-12"; + } + if ($schema === "http://json-schema.org/draft-07/schema#") { + return "draft-7"; + } + if ($schema === "http://json-schema.org/draft-04/schema#") { + return "draft-4"; + } + // Use defaultTarget if provided, otherwise default to draft-2020-12 + return defaultTarget ?? "draft-2020-12"; +} +function resolveRef(ref, ctx) { + if (!ref.startsWith("#")) { + throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); + } + const path = ref.slice(1).split("/").filter(Boolean); + // Handle root reference "#" + if (path.length === 0) { + return ctx.rootSchema; + } + const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; + if (path[0] === defsKey) { + const key = path[1]; + if (!key || !ctx.defs[key]) { + throw new Error(`Reference not found: ${ref}`); + } + return ctx.defs[key]; + } + throw new Error(`Reference not found: ${ref}`); +} +function convertBaseSchema(schema, ctx) { + // Handle unsupported features + if (schema.not !== undefined) { + // Special case: { not: {} } represents never + if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { + return from_json_schema_z.never(); + } + throw new Error("not is not supported in Zod (except { not: {} } for never)"); + } + if (schema.unevaluatedItems !== undefined) { + throw new Error("unevaluatedItems is not supported"); + } + if (schema.unevaluatedProperties !== undefined) { + throw new Error("unevaluatedProperties is not supported"); + } + if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) { + throw new Error("Conditional schemas (if/then/else) are not supported"); + } + if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) { + throw new Error("dependentSchemas and dependentRequired are not supported"); + } + // Handle $ref + if (schema.$ref) { + const refPath = schema.$ref; + if (ctx.refs.has(refPath)) { + return ctx.refs.get(refPath); + } + if (ctx.processing.has(refPath)) { + // Circular reference - use lazy + return from_json_schema_z.lazy(() => { + if (!ctx.refs.has(refPath)) { + throw new Error(`Circular reference not resolved: ${refPath}`); + } + return ctx.refs.get(refPath); + }); + } + ctx.processing.add(refPath); + const resolved = resolveRef(refPath, ctx); + const zodSchema = convertSchema(resolved, ctx); + ctx.refs.set(refPath, zodSchema); + ctx.processing.delete(refPath); + return zodSchema; + } + // Handle enum + if (schema.enum !== undefined) { + const enumValues = schema.enum; + // Special case: OpenAPI 3.0 null representation { type: "string", nullable: true, enum: [null] } + if (ctx.version === "openapi-3.0" && + schema.nullable === true && + enumValues.length === 1 && + enumValues[0] === null) { + return from_json_schema_z.null(); + } + if (enumValues.length === 0) { + return from_json_schema_z.never(); + } + if (enumValues.length === 1) { + return from_json_schema_z.literal(enumValues[0]); + } + // Check if all values are strings + if (enumValues.every((v) => typeof v === "string")) { + return from_json_schema_z.enum(enumValues); + } + // Mixed types - use union of literals + const literalSchemas = enumValues.map((v) => from_json_schema_z.literal(v)); + if (literalSchemas.length < 2) { + return literalSchemas[0]; + } + return from_json_schema_z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); + } + // Handle const + if (schema.const !== undefined) { + return from_json_schema_z.literal(schema.const); + } + // Handle type + const type = schema.type; + if (Array.isArray(type)) { + // Expand type array into anyOf union + const typeSchemas = type.map((t) => { + const typeSchema = { ...schema, type: t }; + return convertBaseSchema(typeSchema, ctx); + }); + if (typeSchemas.length === 0) { + return from_json_schema_z.never(); + } + if (typeSchemas.length === 1) { + return typeSchemas[0]; + } + return from_json_schema_z.union(typeSchemas); + } + if (!type) { + // No type specified - empty schema (any) + return from_json_schema_z.any(); + } + let zodSchema; + switch (type) { + case "string": { + let stringSchema = from_json_schema_z.string(); + // Apply format using .check() with Zod format functions + if (schema.format) { + const format = schema.format; + // Map common formats to Zod check functions + if (format === "email") { + stringSchema = stringSchema.check(from_json_schema_z.email()); + } + else if (format === "uri" || format === "uri-reference") { + stringSchema = stringSchema.check(from_json_schema_z.url()); + } + else if (format === "uuid" || format === "guid") { + stringSchema = stringSchema.check(from_json_schema_z.uuid()); + } + else if (format === "date-time") { + stringSchema = stringSchema.check(from_json_schema_z.iso.datetime()); + } + else if (format === "date") { + stringSchema = stringSchema.check(from_json_schema_z.iso.date()); + } + else if (format === "time") { + stringSchema = stringSchema.check(from_json_schema_z.iso.time()); + } + else if (format === "duration") { + stringSchema = stringSchema.check(from_json_schema_z.iso.duration()); + } + else if (format === "ipv4") { + stringSchema = stringSchema.check(from_json_schema_z.ipv4()); + } + else if (format === "ipv6") { + stringSchema = stringSchema.check(from_json_schema_z.ipv6()); + } + else if (format === "mac") { + stringSchema = stringSchema.check(from_json_schema_z.mac()); + } + else if (format === "cidr") { + stringSchema = stringSchema.check(from_json_schema_z.cidrv4()); + } + else if (format === "cidr-v6") { + stringSchema = stringSchema.check(from_json_schema_z.cidrv6()); + } + else if (format === "base64") { + stringSchema = stringSchema.check(from_json_schema_z.base64()); + } + else if (format === "base64url") { + stringSchema = stringSchema.check(from_json_schema_z.base64url()); + } + else if (format === "e164") { + stringSchema = stringSchema.check(from_json_schema_z.e164()); + } + else if (format === "jwt") { + stringSchema = stringSchema.check(from_json_schema_z.jwt()); + } + else if (format === "emoji") { + stringSchema = stringSchema.check(from_json_schema_z.emoji()); + } + else if (format === "nanoid") { + stringSchema = stringSchema.check(from_json_schema_z.nanoid()); + } + else if (format === "cuid") { + stringSchema = stringSchema.check(from_json_schema_z.cuid()); + } + else if (format === "cuid2") { + stringSchema = stringSchema.check(from_json_schema_z.cuid2()); + } + else if (format === "ulid") { + stringSchema = stringSchema.check(from_json_schema_z.ulid()); + } + else if (format === "xid") { + stringSchema = stringSchema.check(from_json_schema_z.xid()); + } + else if (format === "ksuid") { + stringSchema = stringSchema.check(from_json_schema_z.ksuid()); + } + // Note: json-string format is not currently supported by Zod + // Custom formats are ignored - keep as plain string + } + // Apply constraints + if (typeof schema.minLength === "number") { + stringSchema = stringSchema.min(schema.minLength); + } + if (typeof schema.maxLength === "number") { + stringSchema = stringSchema.max(schema.maxLength); + } + if (schema.pattern) { + // JSON Schema patterns are not implicitly anchored (match anywhere in string) + stringSchema = stringSchema.regex(new RegExp(schema.pattern)); + } + zodSchema = stringSchema; + break; + } + case "number": + case "integer": { + let numberSchema = type === "integer" ? from_json_schema_z.number().int() : from_json_schema_z.number(); + // Apply constraints + if (typeof schema.minimum === "number") { + numberSchema = numberSchema.min(schema.minimum); + } + if (typeof schema.maximum === "number") { + numberSchema = numberSchema.max(schema.maximum); + } + if (typeof schema.exclusiveMinimum === "number") { + numberSchema = numberSchema.gt(schema.exclusiveMinimum); + } + else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") { + numberSchema = numberSchema.gt(schema.minimum); + } + if (typeof schema.exclusiveMaximum === "number") { + numberSchema = numberSchema.lt(schema.exclusiveMaximum); + } + else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") { + numberSchema = numberSchema.lt(schema.maximum); + } + if (typeof schema.multipleOf === "number") { + numberSchema = numberSchema.multipleOf(schema.multipleOf); + } + zodSchema = numberSchema; + break; + } + case "boolean": { + zodSchema = from_json_schema_z.boolean(); + break; + } + case "null": { + zodSchema = from_json_schema_z.null(); + break; + } + case "object": { + const shape = {}; + const properties = schema.properties || {}; + const requiredSet = new Set(schema.required || []); + // Convert properties - mark optional ones + for (const [key, propSchema] of Object.entries(properties)) { + const propZodSchema = convertSchema(propSchema, ctx); + // If not in required array, make it optional + shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); + } + // Handle propertyNames + if (schema.propertyNames) { + const keySchema = convertSchema(schema.propertyNames, ctx); + const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" + ? convertSchema(schema.additionalProperties, ctx) + : from_json_schema_z.any(); + // Case A: No properties (pure record) + if (Object.keys(shape).length === 0) { + zodSchema = from_json_schema_z.record(keySchema, valueSchema); + break; + } + // Case B: With properties (intersection of object and looseRecord) + const objectSchema = from_json_schema_z.object(shape).passthrough(); + const recordSchema = from_json_schema_z.looseRecord(keySchema, valueSchema); + zodSchema = from_json_schema_z.intersection(objectSchema, recordSchema); + break; + } + // Handle patternProperties + if (schema.patternProperties) { + // patternProperties: keys matching pattern must satisfy corresponding schema + // Use loose records so non-matching keys pass through + const patternProps = schema.patternProperties; + const patternKeys = Object.keys(patternProps); + const looseRecords = []; + for (const pattern of patternKeys) { + const patternValue = convertSchema(patternProps[pattern], ctx); + const keySchema = from_json_schema_z.string().regex(new RegExp(pattern)); + looseRecords.push(from_json_schema_z.looseRecord(keySchema, patternValue)); + } + // Build intersection: object schema + all pattern property records + const schemasToIntersect = []; + if (Object.keys(shape).length > 0) { + // Use passthrough so patternProperties can validate additional keys + schemasToIntersect.push(from_json_schema_z.object(shape).passthrough()); + } + schemasToIntersect.push(...looseRecords); + if (schemasToIntersect.length === 0) { + zodSchema = from_json_schema_z.object({}).passthrough(); + } + else if (schemasToIntersect.length === 1) { + zodSchema = schemasToIntersect[0]; + } + else { + // Chain intersections: (A & B) & C & D ... + let result = from_json_schema_z.intersection(schemasToIntersect[0], schemasToIntersect[1]); + for (let i = 2; i < schemasToIntersect.length; i++) { + result = from_json_schema_z.intersection(result, schemasToIntersect[i]); + } + zodSchema = result; + } + break; + } + // Handle additionalProperties + // In JSON Schema, additionalProperties defaults to true (allow any extra properties) + // In Zod, objects strip unknown keys by default, so we need to handle this explicitly + const objectSchema = from_json_schema_z.object(shape); + if (schema.additionalProperties === false) { + // Strict mode - no extra properties allowed + zodSchema = objectSchema.strict(); + } + else if (typeof schema.additionalProperties === "object") { + // Extra properties must match the specified schema + zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); + } + else { + // additionalProperties is true or undefined - allow any extra properties (passthrough) + zodSchema = objectSchema.passthrough(); + } + break; + } + case "array": { + // TODO: uniqueItems is not supported + // TODO: contains/minContains/maxContains are not supported + // Check if this is a tuple (prefixItems or items as array) + const prefixItems = schema.prefixItems; + const items = schema.items; + if (prefixItems && Array.isArray(prefixItems)) { + // Tuple with prefixItems (draft-2020-12) + const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); + const rest = items && typeof items === "object" && !Array.isArray(items) + ? convertSchema(items, ctx) + : undefined; + if (rest) { + zodSchema = from_json_schema_z.tuple(tupleItems).rest(rest); + } + else { + zodSchema = from_json_schema_z.tuple(tupleItems); + } + // Apply minItems/maxItems constraints to tuples + if (typeof schema.minItems === "number") { + zodSchema = zodSchema.check(from_json_schema_z.minLength(schema.minItems)); + } + if (typeof schema.maxItems === "number") { + zodSchema = zodSchema.check(from_json_schema_z.maxLength(schema.maxItems)); + } + } + else if (Array.isArray(items)) { + // Tuple with items array (draft-7) + const tupleItems = items.map((item) => convertSchema(item, ctx)); + const rest = schema.additionalItems && typeof schema.additionalItems === "object" + ? convertSchema(schema.additionalItems, ctx) + : undefined; // additionalItems: false means no rest, handled by default tuple behavior + if (rest) { + zodSchema = from_json_schema_z.tuple(tupleItems).rest(rest); + } + else { + zodSchema = from_json_schema_z.tuple(tupleItems); + } + // Apply minItems/maxItems constraints to tuples + if (typeof schema.minItems === "number") { + zodSchema = zodSchema.check(from_json_schema_z.minLength(schema.minItems)); + } + if (typeof schema.maxItems === "number") { + zodSchema = zodSchema.check(from_json_schema_z.maxLength(schema.maxItems)); + } + } + else if (items !== undefined) { + // Regular array + const element = convertSchema(items, ctx); + let arraySchema = from_json_schema_z.array(element); + // Apply constraints + if (typeof schema.minItems === "number") { + arraySchema = arraySchema.min(schema.minItems); + } + if (typeof schema.maxItems === "number") { + arraySchema = arraySchema.max(schema.maxItems); + } + zodSchema = arraySchema; + } + else { + // No items specified - array of any + zodSchema = from_json_schema_z.array(from_json_schema_z.any()); + } + break; + } + default: + throw new Error(`Unsupported type: ${type}`); + } + // Apply metadata + if (schema.description) { + zodSchema = zodSchema.describe(schema.description); + } + if (schema.default !== undefined) { + zodSchema = zodSchema.default(schema.default); + } + return zodSchema; +} +function convertSchema(schema, ctx) { + if (typeof schema === "boolean") { + return schema ? from_json_schema_z.any() : from_json_schema_z.never(); + } + // Convert base schema first (ignoring composition keywords) + let baseSchema = convertBaseSchema(schema, ctx); + const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined; + // Process composition keywords LAST (they can appear together) + // Handle anyOf - wrap base schema with union + if (schema.anyOf && Array.isArray(schema.anyOf)) { + const options = schema.anyOf.map((s) => convertSchema(s, ctx)); + const anyOfUnion = from_json_schema_z.union(options); + baseSchema = hasExplicitType ? from_json_schema_z.intersection(baseSchema, anyOfUnion) : anyOfUnion; + } + // Handle oneOf - exclusive union (exactly one must match) + if (schema.oneOf && Array.isArray(schema.oneOf)) { + const options = schema.oneOf.map((s) => convertSchema(s, ctx)); + const oneOfUnion = from_json_schema_z.xor(options); + baseSchema = hasExplicitType ? from_json_schema_z.intersection(baseSchema, oneOfUnion) : oneOfUnion; + } + // Handle allOf - wrap base schema with intersection + if (schema.allOf && Array.isArray(schema.allOf)) { + if (schema.allOf.length === 0) { + baseSchema = hasExplicitType ? baseSchema : from_json_schema_z.any(); + } + else { + let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx); + const startIdx = hasExplicitType ? 0 : 1; + for (let i = startIdx; i < schema.allOf.length; i++) { + result = from_json_schema_z.intersection(result, convertSchema(schema.allOf[i], ctx)); + } + baseSchema = result; + } + } + // Handle nullable (OpenAPI 3.0) + if (schema.nullable === true && ctx.version === "openapi-3.0") { + baseSchema = from_json_schema_z.nullable(baseSchema); + } + // Handle readOnly + if (schema.readOnly === true) { + baseSchema = from_json_schema_z.readonly(baseSchema); + } + return baseSchema; +} +/** + * Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */ +function fromJSONSchema(schema, params) { + // Handle boolean schemas + if (typeof schema === "boolean") { + return schema ? from_json_schema_z.any() : from_json_schema_z.never(); + } + const version = detectVersion(schema, params?.defaultTarget); + const defs = (schema.$defs || schema.definitions || {}); + const ctx = { + version, + defs, + refs: new Map(), + processing: new Set(), + rootSchema: schema, + }; + return convertSchema(schema, ctx); +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/coerce.js + + +function coerce_string(params) { + return _coercedString(schemas_ZodString, params); +} +function coerce_number(params) { + return _coercedNumber(schemas_ZodNumber, params); +} +function coerce_boolean(params) { + return _coercedBoolean(schemas_ZodBoolean, params); +} +function coerce_bigint(params) { + return _coercedBigint(schemas_ZodBigInt, params); +} +function coerce_date(params) { + return _coercedDate(schemas_ZodDate, params); +} + +;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/external.js + + + + + + +// zod-specified + + +config(en()); + + + + +// iso +// must be exported from top-level +// https://github.com/colinhacks/zod/issues/4491 + + + + +;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/index.js + + + +/* harmony default export */ const classic = ((/* unused pure expression or super */ null && (z))); + +;// CONCATENATED MODULE: ./node_modules/zod/v4/index.js + + +/* harmony default export */ const zod_v4 = ((/* unused pure expression or super */ null && (z4))); + +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/index.js + + + + + + + + + + + + + + + + +//#region src/tools/index.ts +var tools_exports = {}; +__export(tools_exports, { + BaseToolkit: () => BaseToolkit, + DynamicStructuredTool: () => tools_DynamicStructuredTool, + DynamicTool: () => tools_DynamicTool, + StructuredTool: () => StructuredTool, + Tool: () => Tool, + ToolInputParsingException: () => ToolInputParsingException, + isLangChainTool: () => isLangChainTool, + isRunnableToolLike: () => isRunnableToolLike, + isStructuredTool: () => isStructuredTool, + isStructuredToolParams: () => isStructuredToolParams, + tool: () => tool +}); +/** +* Base class for Tools that accept input of any shape defined by a Zod schema. +*/ +var StructuredTool = class extends BaseLangChain { + /** + * Optional provider-specific extra fields for the tool. + * + * This is used to pass provider-specific configuration that doesn't fit into + * standard tool fields. + */ + extras; + /** + * Whether to return the tool's output directly. + * + * Setting this to true means that after the tool is called, + * an agent should stop looping. + */ + returnDirect = false; + verboseParsingErrors = false; + get lc_namespace() { + return ["langchain", "tools"]; + } + /** + * The tool response format. + * + * If "content" then the output of the tool is interpreted as the contents of a + * ToolMessage. If "content_and_artifact" then the output is expected to be a + * two-tuple corresponding to the (content, artifact) of a ToolMessage. + * + * @default "content" + */ + responseFormat = "content"; + /** + * Default config object for the tool runnable. + */ + defaultConfig; + constructor(fields) { + super(fields ?? {}); + this.verboseParsingErrors = fields?.verboseParsingErrors ?? this.verboseParsingErrors; + this.responseFormat = fields?.responseFormat ?? this.responseFormat; + this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig; + this.metadata = fields?.metadata ?? this.metadata; + this.extras = fields?.extras ?? this.extras; + } + /** + * Invokes the tool with the provided input and configuration. + * @param input The input for the tool. + * @param config Optional configuration for the tool. + * @returns A Promise that resolves with the tool's output. + */ + async invoke(input, config) { + let toolInput; + let enrichedConfig = ensureConfig(mergeConfigs(this.defaultConfig, config)); + if (_isToolCall(input)) { + toolInput = input.args; + enrichedConfig = { + ...enrichedConfig, + toolCall: input + }; + } else toolInput = input; + return this.call(toolInput, enrichedConfig); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.3.0. + * + * Calls the tool with the provided argument, configuration, and tags. It + * parses the input according to the schema, handles any errors, and + * manages callbacks. + * @param arg The input argument for the tool. + * @param configArg Optional configuration or callbacks for the tool. + * @param tags Optional tags for the tool. + * @returns A Promise that resolves with a string. + */ + async call(arg, configArg, tags) { + const inputForValidation = _isToolCall(arg) ? arg.args : arg; + let parsed; + if (isInteropZodSchema(this.schema)) try { + parsed = await interopParseAsync(this.schema, inputForValidation); + } catch (e) { + let message = `Received tool input did not match expected schema`; + if (this.verboseParsingErrors) message = `${message}\nDetails: ${e.message}`; + if (isInteropZodError(e)) message = `${message}\n\n${prettifyError(e)}`; + throw new ToolInputParsingException(message, JSON.stringify(arg)); + } + else { + const result$1 = validate_validate(inputForValidation, this.schema); + if (!result$1.valid) { + let message = `Received tool input did not match expected schema`; + if (this.verboseParsingErrors) message = `${message}\nDetails: ${result$1.errors.map((e) => `${e.keywordLocation}: ${e.error}`).join("\n")}`; + throw new ToolInputParsingException(message, JSON.stringify(arg)); + } + parsed = inputForValidation; + } + const config = parseCallbackConfigArg(configArg); + const callbackManager_ = CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose }); + const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof arg === "string" ? arg : JSON.stringify(arg), config.runId, void 0, void 0, void 0, config.runName); + delete config.runId; + let result; + try { + result = await this._call(parsed, runManager, config); + } catch (e) { + await runManager?.handleToolError(e); + throw e; + } + let content; + let artifact; + if (this.responseFormat === "content_and_artifact") if (Array.isArray(result) && result.length === 2) [content, artifact] = result; + else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(result)}`); + else content = result; + let toolCallId; + if (_isToolCall(arg)) toolCallId = arg.id; + if (!toolCallId && _configHasToolCallId(config)) toolCallId = config.toolCall.id; + const formattedOutput = _formatToolOutput({ + content, + artifact, + toolCallId, + name: this.name, + metadata: this.metadata + }); + await runManager?.handleToolEnd(formattedOutput); + return formattedOutput; + } +}; +/** +* Base class for Tools that accept input as a string. +*/ +var Tool = class extends StructuredTool { + schema = objectType({ input: stringType().optional() }).transform((obj) => obj.input); + constructor(fields) { + super(fields); + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.3.0. + * + * Calls the tool with the provided argument and callbacks. It handles + * string inputs specifically. + * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema. + * @param callbacks Optional callbacks for the tool. + * @returns A Promise that resolves with a string. + */ + call(arg, callbacks) { + const structuredArg = typeof arg === "string" || arg == null ? { input: arg } : arg; + return super.call(structuredArg, callbacks); + } +}; +/** +* A tool that can be created dynamically from a function, name, and description. +*/ +var tools_DynamicTool = class extends Tool { + static lc_name() { + return "DynamicTool"; + } + name; + description; + func; + constructor(fields) { + super(fields); + this.name = fields.name; + this.description = fields.description; + this.func = fields.func; + this.returnDirect = fields.returnDirect ?? this.returnDirect; + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.3.0. + */ + async call(arg, configArg) { + const config = parseCallbackConfigArg(configArg); + if (config.runName === void 0) config.runName = this.name; + return super.call(arg, config); + } + /** @ignore */ + async _call(input, runManager, parentConfig) { + return this.func(input, runManager, parentConfig); + } +}; +/** +* A tool that can be created dynamically from a function, name, and +* description, designed to work with structured data. It extends the +* StructuredTool class and overrides the _call method to execute the +* provided function when the tool is called. +* +* Schema can be passed as Zod or JSON schema. The tool will not validate +* input if JSON schema is passed. +*/ +var tools_DynamicStructuredTool = class extends StructuredTool { + static lc_name() { + return "DynamicStructuredTool"; + } + name; + description; + func; + schema; + constructor(fields) { + super(fields); + this.name = fields.name; + this.description = fields.description; + this.func = fields.func; + this.returnDirect = fields.returnDirect ?? this.returnDirect; + this.schema = fields.schema; + } + /** + * @deprecated Use .invoke() instead. Will be removed in 0.3.0. + */ + async call(arg, configArg, tags) { + const config = parseCallbackConfigArg(configArg); + if (config.runName === void 0) config.runName = this.name; + return super.call(arg, config, tags); + } + _call(arg, runManager, parentConfig) { + return this.func(arg, runManager, parentConfig); + } +}; +/** +* Abstract base class for toolkits in LangChain. Toolkits are collections +* of tools that agents can use. Subclasses must implement the `tools` +* property to provide the specific tools for the toolkit. +*/ +var BaseToolkit = class { + getTools() { + return this.tools; + } +}; +function tool(func, fields) { + const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema); + const isStringJSONSchema = validatesOnlyStrings(fields.schema); + if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) return new tools_DynamicTool({ + ...fields, + description: fields.description ?? fields.schema?.description ?? `${fields.name} tool`, + func: async (input, runManager, config) => { + return new Promise((resolve, reject) => { + const childConfig = config_patchConfig(config, { callbacks: runManager?.getChild() }); + async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { + try { + resolve(func(input, childConfig)); + } catch (e) { + reject(e); + } + }); + }); + } + }); + const schema = fields.schema; + const description = fields.description ?? fields.schema.description ?? `${fields.name} tool`; + return new tools_DynamicStructuredTool({ + ...fields, + description, + schema, + func: async (input, runManager, config) => { + return new Promise((resolve, reject) => { + let listener; + const cleanup = () => { + if (config?.signal && listener) config.signal.removeEventListener("abort", listener); + }; + if (config?.signal) { + listener = () => { + cleanup(); + reject(getAbortSignalError(config.signal)); + }; + config.signal.addEventListener("abort", listener); + } + const childConfig = config_patchConfig(config, { callbacks: runManager?.getChild() }); + async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { + try { + const result = await func(input, childConfig); + /** + * If the signal is aborted, we don't want to resolve the promise + * as the promise is already rejected. + */ + if (config?.signal?.aborted) { + cleanup(); + return; + } + cleanup(); + resolve(result); + } catch (e) { + cleanup(); + reject(e); + } + }); + }); + } + }); +} +function _formatToolOutput(params) { + const { content, artifact, toolCallId, metadata } = params; + if (toolCallId && !isDirectToolOutput(content)) if (typeof content === "string" || Array.isArray(content) && content.every((item) => typeof item === "object")) return new ToolMessage({ + status: "success", + content, + artifact, + tool_call_id: toolCallId, + name: params.name, + metadata + }); + else return new ToolMessage({ + status: "success", + content: tools_stringify(content), + artifact, + tool_call_id: toolCallId, + name: params.name, + metadata + }); + else return content; +} +function tools_stringify(content) { + try { + return JSON.stringify(content, null, 2) ?? ""; + } catch (_noOp) { + return `${content}`; + } +} + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/chat_models.js + + + + + + + +//#region src/utils/testing/chat_models.ts +var FakeChatModel = class extends BaseChatModel { + _combineLLMOutput() { + return []; + } + _llmType() { + return "fake"; + } + async _generate(messages, options, runManager) { + if (options?.stop?.length) return { generations: [{ + message: new AIMessage(options.stop[0]), + text: options.stop[0] + }] }; + const text = messages.map((m) => { + if (typeof m.content === "string") return m.content; + return JSON.stringify(m.content, null, 2); + }).join("\n"); + await runManager?.handleLLMNewToken(text); + return { + generations: [{ + message: new AIMessage(text), + text + }], + llmOutput: {} + }; + } +}; +var FakeStreamingChatModel = class FakeStreamingChatModel extends BaseChatModel { + sleep = 50; + responses = []; + chunks = []; + toolStyle = "openai"; + thrownErrorString; + tools = []; + constructor({ sleep = 50, responses = [], chunks = [], toolStyle = "openai", thrownErrorString,...rest }) { + super(rest); + this.sleep = sleep; + this.responses = responses; + this.chunks = chunks; + this.toolStyle = toolStyle; + this.thrownErrorString = thrownErrorString; + } + _llmType() { + return "fake"; + } + bindTools(tools) { + const merged = [...this.tools, ...tools]; + const toolDicts = merged.map((t) => { + switch (this.toolStyle) { + case "openai": return { + type: "function", + function: { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + } + }; + case "anthropic": return { + name: t.name, + description: t.description, + input_schema: toJsonSchema(t.schema) + }; + case "bedrock": return { toolSpec: { + name: t.name, + description: t.description, + inputSchema: toJsonSchema(t.schema) + } }; + case "google": return { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + }; + default: throw new Error(`Unsupported tool style: ${this.toolStyle}`); + } + }); + const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts; + const next = new FakeStreamingChatModel({ + sleep: this.sleep, + responses: this.responses, + chunks: this.chunks, + toolStyle: this.toolStyle, + thrownErrorString: this.thrownErrorString + }); + next.tools = merged; + return next.withConfig({ tools: wrapped }); + } + async _generate(messages, _options, _runManager) { + if (this.thrownErrorString) throw new Error(this.thrownErrorString); + const content = this.responses?.[0]?.content ?? messages[0].content ?? ""; + const generation = { generations: [{ + text: "", + message: new AIMessage({ + content, + tool_calls: this.chunks?.[0]?.tool_calls + }) + }] }; + return generation; + } + async *_streamResponseChunks(_messages, options, runManager) { + if (this.thrownErrorString) throw new Error(this.thrownErrorString); + if (this.chunks?.length) { + for (const msgChunk of this.chunks) { + const cg = new ChatGenerationChunk({ + message: new AIMessageChunk({ + content: msgChunk.content, + tool_calls: msgChunk.tool_calls, + additional_kwargs: msgChunk.additional_kwargs ?? {} + }), + text: msgChunk.content?.toString() ?? "" + }); + if (options.signal?.aborted) break; + yield cg; + await runManager?.handleLLMNewToken(msgChunk.content, void 0, void 0, void 0, void 0, { chunk: cg }); + } + return; + } + const fallback = this.responses?.[0] ?? new AIMessage(typeof _messages[0].content === "string" ? _messages[0].content : ""); + const text = typeof fallback.content === "string" ? fallback.content : ""; + for (const ch of text) { + await new Promise((r) => setTimeout(r, this.sleep)); + const cg = new ChatGenerationChunk({ + message: new AIMessageChunk({ content: ch }), + text: ch + }); + if (options.signal?.aborted) break; + yield cg; + await runManager?.handleLLMNewToken(ch, void 0, void 0, void 0, void 0, { chunk: cg }); + } + } +}; +/** +* A fake Chat Model that returns a predefined list of responses. It can be used +* for testing purposes. +* @example +* ```typescript +* const chat = new FakeListChatModel({ +* responses: ["I'll callback later.", "You 'console' them!"] +* }); +* +* const firstMessage = new HumanMessage("You want to hear a JavaScript joke?"); +* const secondMessage = new HumanMessage("How do you cheer up a JavaScript developer?"); +* +* // Call the chat model with a message and log the response +* const firstResponse = await chat.call([firstMessage]); +* console.log({ firstResponse }); +* +* const secondResponse = await chat.call([secondMessage]); +* console.log({ secondResponse }); +* ``` +*/ +var FakeListChatModel = class FakeListChatModel extends BaseChatModel { + static lc_name() { + return "FakeListChatModel"; + } + lc_serializable = true; + responses; + i = 0; + sleep; + emitCustomEvent = false; + generationInfo; + tools = []; + toolStyle = "openai"; + constructor(params) { + super(params); + const { responses, sleep, emitCustomEvent, generationInfo } = params; + this.responses = responses; + this.sleep = sleep; + this.emitCustomEvent = emitCustomEvent ?? this.emitCustomEvent; + this.generationInfo = generationInfo; + } + _combineLLMOutput() { + return []; + } + _llmType() { + return "fake-list"; + } + async _generate(_messages, options, runManager) { + await this._sleepIfRequested(); + if (options?.thrownErrorString) throw new Error(options.thrownErrorString); + if (this.emitCustomEvent) await runManager?.handleCustomEvent("some_test_event", { someval: true }); + if (options?.stop?.length) return { generations: [this._formatGeneration(options.stop[0])] }; + else { + const response = this._currentResponse(); + this._incrementResponse(); + return { + generations: [this._formatGeneration(response)], + llmOutput: {} + }; + } + } + _formatGeneration(text) { + return { + message: new AIMessage(text), + text + }; + } + async *_streamResponseChunks(_messages, options, runManager) { + const response = this._currentResponse(); + this._incrementResponse(); + if (this.emitCustomEvent) await runManager?.handleCustomEvent("some_test_event", { someval: true }); + const responseChars = [...response]; + for (let i = 0; i < responseChars.length; i++) { + const text = responseChars[i]; + const isLastChunk = i === responseChars.length - 1; + await this._sleepIfRequested(); + if (options?.thrownErrorString) throw new Error(options.thrownErrorString); + const chunk = this._createResponseChunk(text, isLastChunk ? this.generationInfo : void 0); + if (options.signal?.aborted) break; + yield chunk; + runManager?.handleLLMNewToken(text); + } + } + async _sleepIfRequested() { + if (this.sleep !== void 0) await this._sleep(); + } + async _sleep() { + return new Promise((resolve) => { + setTimeout(() => resolve(), this.sleep); + }); + } + _createResponseChunk(text, generationInfo) { + return new ChatGenerationChunk({ + message: new AIMessageChunk({ content: text }), + text, + generationInfo + }); + } + _currentResponse() { + return this.responses[this.i]; + } + _incrementResponse() { + if (this.i < this.responses.length - 1) this.i += 1; + else this.i = 0; + } + bindTools(tools) { + const merged = [...this.tools, ...tools]; + const toolDicts = merged.map((t) => { + switch (this.toolStyle) { + case "openai": return { + type: "function", + function: { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + } + }; + case "anthropic": return { + name: t.name, + description: t.description, + input_schema: toJsonSchema(t.schema) + }; + case "bedrock": return { toolSpec: { + name: t.name, + description: t.description, + inputSchema: toJsonSchema(t.schema) + } }; + case "google": return { + name: t.name, + description: t.description, + parameters: toJsonSchema(t.schema) + }; + default: throw new Error(`Unsupported tool style: ${this.toolStyle}`); + } + }); + const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts; + const next = new FakeListChatModel({ + responses: this.responses, + sleep: this.sleep, + emitCustomEvent: this.emitCustomEvent, + generationInfo: this.generationInfo + }); + next.tools = merged; + next.toolStyle = this.toolStyle; + next.i = this.i; + return next.withConfig({ tools: wrapped }); + } + withStructuredOutput(_params, _config) { + return RunnableLambda.from(async (input) => { + const message = await this.invoke(input); + if (message.tool_calls?.[0]?.args) return message.tool_calls[0].args; + if (typeof message.content === "string") return JSON.parse(message.content); + throw new Error("No structured output found"); + }); + } +}; + +//#endregion + +//# sourceMappingURL=chat_models.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/embeddings.js + + +//#region src/utils/testing/embeddings.ts +/** +* A class that provides synthetic embeddings by overriding the +* embedDocuments and embedQuery methods to generate embeddings based on +* the input documents. The embeddings are generated by converting each +* document into chunks, calculating a numerical value for each chunk, and +* returning an array of these values as the embedding. +*/ +var SyntheticEmbeddings = class extends Embeddings { + vectorSize; + constructor(params) { + super(params ?? {}); + this.vectorSize = params?.vectorSize ?? 4; + } + /** + * Generates synthetic embeddings for a list of documents. + * @param documents List of documents to generate embeddings for. + * @returns A promise that resolves with a list of synthetic embeddings for each document. + */ + async embedDocuments(documents) { + return Promise.all(documents.map((doc) => this.embedQuery(doc))); + } + /** + * Generates a synthetic embedding for a document. The document is + * converted into chunks, a numerical value is calculated for each chunk, + * and an array of these values is returned as the embedding. + * @param document The document to generate an embedding for. + * @returns A promise that resolves with a synthetic embedding for the document. + */ + async embedQuery(document) { + let doc = document; + doc = doc.toLowerCase().replaceAll(/[^a-z ]/g, ""); + const padMod = doc.length % this.vectorSize; + const padGapSize = padMod === 0 ? 0 : this.vectorSize - padMod; + const padSize = doc.length + padGapSize; + doc = doc.padEnd(padSize, " "); + const chunkSize = doc.length / this.vectorSize; + const docChunk = []; + for (let co = 0; co < doc.length; co += chunkSize) docChunk.push(doc.slice(co, co + chunkSize)); + const ret = docChunk.map((s) => { + let sum = 0; + for (let co = 0; co < s.length; co += 1) sum += s === " " ? 0 : s.charCodeAt(co); + const ret$1 = sum % 26 / 26; + return ret$1; + }); + return ret; + } +}; +/** +* A class that provides fake embeddings by overriding the embedDocuments +* and embedQuery methods to return fixed values. +*/ +var FakeEmbeddings = class extends Embeddings { + constructor(params) { + super(params ?? {}); + } + /** + * Generates fixed embeddings for a list of documents. + * @param documents List of documents to generate embeddings for. + * @returns A promise that resolves with a list of fixed embeddings for each document. + */ + embedDocuments(documents) { + return Promise.resolve(documents.map(() => [ + .1, + .2, + .3, + .4 + ])); + } + /** + * Generates a fixed embedding for a query. + * @param _ The query to generate an embedding for. + * @returns A promise that resolves with a fixed embedding for the query. + */ + embedQuery(_) { + return Promise.resolve([ + .1, + .2, + .3, + .4 + ]); + } +}; + +//#endregion + +//# sourceMappingURL=embeddings.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/llms.js + + +//#region src/utils/testing/llms.ts +var FakeLLM = class extends LLM { + response; + thrownErrorString; + constructor(fields) { + super(fields); + this.response = fields.response; + this.thrownErrorString = fields.thrownErrorString; + } + _llmType() { + return "fake"; + } + async _call(prompt, _options, runManager) { + if (this.thrownErrorString) throw new Error(this.thrownErrorString); + const response = this.response ?? prompt; + await runManager?.handleLLMNewToken(response); + return response; + } +}; +var FakeStreamingLLM = class extends LLM { + sleep = 50; + responses; + thrownErrorString; + constructor(fields) { + super(fields); + this.sleep = fields.sleep ?? this.sleep; + this.responses = fields.responses; + this.thrownErrorString = fields.thrownErrorString; + } + _llmType() { + return "fake"; + } + async _call(prompt) { + if (this.thrownErrorString) throw new Error(this.thrownErrorString); + const response = this.responses?.[0]; + this.responses = this.responses?.slice(1); + return response ?? prompt; + } + async *_streamResponseChunks(input, _options, runManager) { + if (this.thrownErrorString) throw new Error(this.thrownErrorString); + const response = this.responses?.[0]; + this.responses = this.responses?.slice(1); + for (const c of response ?? input) { + await new Promise((resolve) => setTimeout(resolve, this.sleep)); + yield { + text: c, + generationInfo: {} + }; + await runManager?.handleLLMNewToken(c); + } + } +}; + +//#endregion + +//# sourceMappingURL=llms.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/message_history.js + + + + + + +//#region src/utils/testing/message_history.ts +var FakeChatMessageHistory = class extends BaseChatMessageHistory { + lc_namespace = [ + "langchain_core", + "message", + "fake" + ]; + messages = []; + constructor() { + super(); + } + async getMessages() { + return this.messages; + } + async addMessage(message) { + this.messages.push(message); + } + async addUserMessage(message) { + this.messages.push(new HumanMessage(message)); + } + async addAIMessage(message) { + this.messages.push(new AIMessage(message)); + } + async clear() { + this.messages = []; + } +}; +var FakeListChatMessageHistory = class extends BaseListChatMessageHistory { + lc_namespace = [ + "langchain_core", + "message", + "fake" + ]; + messages = []; + constructor() { + super(); + } + async addMessage(message) { + this.messages.push(message); + } + async getMessages() { + return this.messages; + } +}; +var FakeTracer = class extends BaseTracer { + name = "fake_tracer"; + runs = []; + constructor() { + super(); + } + persistRun(run) { + this.runs.push(run); + return Promise.resolve(); + } +}; + +//#endregion + +//# sourceMappingURL=message_history.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/output_parsers.js + + +//#region src/utils/testing/output_parsers.ts +/** +* Parser for comma-separated values. It splits the input text by commas +* and trims the resulting values. +*/ +var FakeSplitIntoListParser = class extends BaseOutputParser { + lc_namespace = ["tests", "fake"]; + getFormatInstructions() { + return ""; + } + async parse(text) { + return text.split(",").map((value) => value.trim()); + } +}; + +//#endregion + +//# sourceMappingURL=output_parsers.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/retrievers.js + + + +//#region src/utils/testing/retrievers.ts +var FakeRetriever = class extends BaseRetriever { + lc_namespace = ["test", "fake"]; + output = [new Document({ pageContent: "foo" }), new Document({ pageContent: "bar" })]; + constructor(fields) { + super(); + this.output = fields?.output ?? this.output; + } + async _getRelevantDocuments(_query) { + return this.output; + } +}; + +//#endregion + +//# sourceMappingURL=retrievers.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/runnables.js + + +//#region src/utils/testing/runnables.ts +var FakeRunnable = class extends Runnable { + lc_namespace = ["tests", "fake"]; + returnOptions; + constructor(fields) { + super(fields); + this.returnOptions = fields.returnOptions; + } + async invoke(input, options) { + if (this.returnOptions) return options ?? {}; + return { input }; + } +}; + +//#endregion + +//# sourceMappingURL=runnables.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/tools.js + + +//#region src/utils/testing/tools.ts +var FakeTool = class extends StructuredTool { + name; + description; + schema; + constructor(fields) { + super(fields); + this.name = fields.name; + this.description = fields.description; + this.schema = fields.schema; + } + async _call(arg, _runManager) { + return JSON.stringify(arg); + } +}; + +//#endregion + +//# sourceMappingURL=tools.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/tracers.js + + +//#region src/utils/testing/tracers.ts +var SingleRunExtractor = class extends BaseTracer { + runPromiseResolver; + runPromise; + /** The name of the callback handler. */ + name = "single_run_extractor"; + constructor() { + super(); + this.runPromise = new Promise((extract) => { + this.runPromiseResolver = extract; + }); + } + async persistRun(run) { + this.runPromiseResolver(run); + } + async extract() { + return this.runPromise; + } +}; + +//#endregion + +//# sourceMappingURL=tracers.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/ml-distance/similarities.js +//#region src/utils/ml-distance/similarities.ts +/** +* Returns the average of cosine distances between vectors a and b +* @param a - first vector +* @param b - second vector +* +*/ +function cosine(a, b) { + let p = 0; + let p2 = 0; + let q2 = 0; + for (let i = 0; i < a.length; i++) { + p += a[i] * b[i]; + p2 += a[i] * a[i]; + q2 += b[i] * b[i]; + } + return p / (Math.sqrt(p2) * Math.sqrt(q2)); +} + +//#endregion + +//# sourceMappingURL=similarities.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/vectorstores.js + + + + +//#region src/utils/testing/vectorstores.ts +/** +* Class that extends `VectorStore` to store vectors in memory. Provides +* methods for adding documents, performing similarity searches, and +* creating instances from texts, documents, or an existing index. +*/ +var FakeVectorStore = class FakeVectorStore extends VectorStore { + memoryVectors = []; + similarity; + _vectorstoreType() { + return "memory"; + } + constructor(embeddings, { similarity,...rest } = {}) { + super(embeddings, rest); + this.similarity = similarity ?? cosine; + } + /** + * Method to add documents to the memory vector store. It extracts the + * text from each document, generates embeddings for them, and adds the + * resulting vectors to the store. + * @param documents Array of `Document` instances to be added to the store. + * @returns Promise that resolves when all documents have been added. + */ + async addDocuments(documents) { + const texts = documents.map(({ pageContent }) => pageContent); + return this.addVectors(await this.embeddings.embedDocuments(texts), documents); + } + /** + * Method to add vectors to the memory vector store. It creates + * `MemoryVector` instances for each vector and document pair and adds + * them to the store. + * @param vectors Array of vectors to be added to the store. + * @param documents Array of `Document` instances corresponding to the vectors. + * @returns Promise that resolves when all vectors have been added. + */ + async addVectors(vectors, documents) { + const memoryVectors = vectors.map((embedding, idx) => ({ + content: documents[idx].pageContent, + embedding, + metadata: documents[idx].metadata + })); + this.memoryVectors = this.memoryVectors.concat(memoryVectors); + } + /** + * Method to perform a similarity search in the memory vector store. It + * calculates the similarity between the query vector and each vector in + * the store, sorts the results by similarity, and returns the top `k` + * results along with their scores. + * @param query Query vector to compare against the vectors in the store. + * @param k Number of top results to return. + * @param filter Optional filter function to apply to the vectors before performing the search. + * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score. + */ + async similaritySearchVectorWithScore(query, k, filter) { + const filterFunction = (memoryVector) => { + if (!filter) return true; + const doc = new Document({ + metadata: memoryVector.metadata, + pageContent: memoryVector.content + }); + return filter(doc); + }; + const filteredMemoryVectors = this.memoryVectors.filter(filterFunction); + const searches = filteredMemoryVectors.map((vector, index) => ({ + similarity: this.similarity(query, vector.embedding), + index + })).sort((a, b) => a.similarity > b.similarity ? -1 : 0).slice(0, k); + const result = searches.map((search) => [new Document({ + metadata: filteredMemoryVectors[search.index].metadata, + pageContent: filteredMemoryVectors[search.index].content + }), search.similarity]); + return result; + } + /** + * Static method to create a `FakeVectorStore` instance from an array of + * texts. It creates a `Document` for each text and metadata pair, and + * adds them to the store. + * @param texts Array of texts to be added to the store. + * @param metadatas Array or single object of metadata corresponding to the texts. + * @param embeddings `Embeddings` instance used to generate embeddings for the texts. + * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. + * @returns Promise that resolves with a new `FakeVectorStore` instance. + */ + static async fromTexts(texts, metadatas, embeddings, dbConfig) { + const docs = []; + for (let i = 0; i < texts.length; i += 1) { + const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas; + const newDoc = new Document({ + pageContent: texts[i], + metadata + }); + docs.push(newDoc); + } + return FakeVectorStore.fromDocuments(docs, embeddings, dbConfig); + } + /** + * Static method to create a `FakeVectorStore` instance from an array of + * `Document` instances. It adds the documents to the store. + * @param docs Array of `Document` instances to be added to the store. + * @param embeddings `Embeddings` instance used to generate embeddings for the documents. + * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. + * @returns Promise that resolves with a new `FakeVectorStore` instance. + */ + static async fromDocuments(docs, embeddings, dbConfig) { + const instance = new this(embeddings, dbConfig); + await instance.addDocuments(docs); + return instance; + } + /** + * Static method to create a `FakeVectorStore` instance from an existing + * index. It creates a new `FakeVectorStore` instance without adding any + * documents or vectors. + * @param embeddings `Embeddings` instance used to generate embeddings for the documents. + * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. + * @returns Promise that resolves with a new `FakeVectorStore` instance. + */ + static async fromExistingIndex(embeddings, dbConfig) { + const instance = new this(embeddings, dbConfig); + return instance; + } +}; + +//#endregion + +//# sourceMappingURL=vectorstores.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/index.js + + + + + + + + + + + + +//#region src/utils/testing/index.ts +var testing_exports = {}; +__export(testing_exports, { + FakeChatMessageHistory: () => FakeChatMessageHistory, + FakeChatModel: () => FakeChatModel, + FakeEmbeddings: () => FakeEmbeddings, + FakeLLM: () => FakeLLM, + FakeListChatMessageHistory: () => FakeListChatMessageHistory, + FakeListChatModel: () => FakeListChatModel, + FakeRetriever: () => FakeRetriever, + FakeRunnable: () => FakeRunnable, + FakeSplitIntoListParser: () => FakeSplitIntoListParser, + FakeStreamingChatModel: () => FakeStreamingChatModel, + FakeStreamingLLM: () => FakeStreamingLLM, + FakeTool: () => FakeTool, + FakeTracer: () => FakeTracer, + FakeVectorStore: () => FakeVectorStore, + SingleRunExtractor: () => SingleRunExtractor, + SyntheticEmbeddings: () => SyntheticEmbeddings +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/types/index.js + + + +//#region src/utils/types/index.ts +var types_exports = {}; +__export(types_exports, { + extendInteropZodObject: () => extendInteropZodObject, + getInteropZodDefaultGetter: () => getInteropZodDefaultGetter, + getInteropZodObjectShape: () => getInteropZodObjectShape, + getSchemaDescription: () => getSchemaDescription, + interopParse: () => interopParse, + interopParseAsync: () => interopParseAsync, + interopSafeParse: () => interopSafeParse, + interopSafeParseAsync: () => interopSafeParseAsync, + interopZodObjectMakeFieldsOptional: () => interopZodObjectMakeFieldsOptional, + interopZodObjectPartial: () => interopZodObjectPartial, + interopZodObjectPassthrough: () => interopZodObjectPassthrough, + interopZodObjectStrict: () => interopZodObjectStrict, + interopZodTransformInputSchema: () => interopZodTransformInputSchema, + isInteropZodError: () => isInteropZodError, + isInteropZodLiteral: () => isInteropZodLiteral, + isInteropZodObject: () => isInteropZodObject, + isInteropZodSchema: () => isInteropZodSchema, + isShapelessZodSchema: () => isShapelessZodSchema, + isSimpleStringZodSchema: () => isSimpleStringZodSchema, + isZodArrayV4: () => isZodArrayV4, + isZodLiteralV3: () => isZodLiteralV3, + isZodLiteralV4: () => isZodLiteralV4, + isZodNullableV4: () => isZodNullableV4, + isZodObjectV3: () => isZodObjectV3, + isZodObjectV4: () => isZodObjectV4, + isZodOptionalV4: () => isZodOptionalV4, + isZodSchema: () => isZodSchema, + isZodSchemaV3: () => isZodSchemaV3, + isZodSchemaV4: () => isZodSchemaV4 +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/event_source_parse.js + + + +//#region src/utils/event_source_parse.ts +var event_source_parse_exports = {}; +__export(event_source_parse_exports, { + EventStreamContentType: () => EventStreamContentType, + convertEventStreamToIterableReadableDataStream: () => convertEventStreamToIterableReadableDataStream, + getBytes: () => getBytes, + getLines: () => getLines, + getMessages: () => getMessages +}); +const EventStreamContentType = "text/event-stream"; +/** +* Converts a ReadableStream into a callback pattern. +* @param stream The input ReadableStream. +* @param onChunk A function that will be called on each new byte chunk in the stream. +* @returns {Promise} A promise that will be resolved when the stream closes. +*/ +async function getBytes(stream, onChunk) { + if (stream instanceof ReadableStream) { + const reader = stream.getReader(); + while (true) { + const result = await reader.read(); + if (result.done) { + onChunk(new Uint8Array(), true); + break; + } + onChunk(result.value); + } + } else try { + for await (const chunk of stream) onChunk(new Uint8Array(chunk)); + onChunk(new Uint8Array(), true); + } catch (e) { + throw new Error([ + "Parsing event source stream failed.", + "Ensure your implementation of fetch returns a web or Node readable stream.", + `Error: ${e.message}` + ].join("\n")); + } +} +var ControlChars = /* @__PURE__ */ function(ControlChars$1) { + ControlChars$1[ControlChars$1["NewLine"] = 10] = "NewLine"; + ControlChars$1[ControlChars$1["CarriageReturn"] = 13] = "CarriageReturn"; + ControlChars$1[ControlChars$1["Space"] = 32] = "Space"; + ControlChars$1[ControlChars$1["Colon"] = 58] = "Colon"; + return ControlChars$1; +}(ControlChars || {}); +/** +* Parses arbitary byte chunks into EventSource line buffers. +* Each line should be of the format "field: value" and ends with \r, \n, or \r\n. +* @param onLine A function that will be called on each new EventSource line. +* @returns A function that should be called for each incoming byte chunk. +*/ +function getLines(onLine) { + let buffer; + let position; + let fieldLength; + let discardTrailingNewline = false; + return function onChunk(arr, flush) { + if (flush) { + onLine(arr, 0, true); + return; + } + if (buffer === void 0) { + buffer = arr; + position = 0; + fieldLength = -1; + } else buffer = event_source_parse_concat(buffer, arr); + const bufLength = buffer.length; + let lineStart = 0; + while (position < bufLength) { + if (discardTrailingNewline) { + if (buffer[position] === ControlChars.NewLine) lineStart = ++position; + discardTrailingNewline = false; + } + let lineEnd = -1; + for (; position < bufLength && lineEnd === -1; ++position) switch (buffer[position]) { + case ControlChars.Colon: + if (fieldLength === -1) fieldLength = position - lineStart; + break; + case ControlChars.CarriageReturn: discardTrailingNewline = true; + case ControlChars.NewLine: + lineEnd = position; + break; + } + if (lineEnd === -1) break; + onLine(buffer.subarray(lineStart, lineEnd), fieldLength); + lineStart = position; + fieldLength = -1; + } + if (lineStart === bufLength) buffer = void 0; + else if (lineStart !== 0) { + buffer = buffer.subarray(lineStart); + position -= lineStart; + } + }; +} +/** +* Parses line buffers into EventSourceMessages. +* @param onId A function that will be called on each `id` field. +* @param onRetry A function that will be called on each `retry` field. +* @param onMessage A function that will be called on each message. +* @returns A function that should be called for each incoming line buffer. +*/ +function getMessages(onMessage, onId, onRetry) { + let message = newMessage(); + const decoder = new TextDecoder(); + return function onLine(line, fieldLength, flush) { + if (flush) { + if (!isEmpty(message)) { + onMessage?.(message); + message = newMessage(); + } + return; + } + if (line.length === 0) { + onMessage?.(message); + message = newMessage(); + } else if (fieldLength > 0) { + const field = decoder.decode(line.subarray(0, fieldLength)); + const valueOffset = fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1); + const value = decoder.decode(line.subarray(valueOffset)); + switch (field) { + case "data": + message.data = message.data ? message.data + "\n" + value : value; + break; + case "event": + message.event = value; + break; + case "id": + onId?.(message.id = value); + break; + case "retry": { + const retry = parseInt(value, 10); + if (!Number.isNaN(retry)) onRetry?.(message.retry = retry); + break; + } + } + } + }; +} +function event_source_parse_concat(a, b) { + const res = new Uint8Array(a.length + b.length); + res.set(a); + res.set(b, a.length); + return res; +} +function newMessage() { + return { + data: "", + event: "", + id: "", + retry: void 0 + }; +} +function convertEventStreamToIterableReadableDataStream(stream, onMetadataEvent) { + const dataStream = new ReadableStream({ async start(controller) { + const enqueueLine = getMessages((msg) => { + if (msg.event === "error") throw new Error(msg.data ?? "Unspecified event streaming error."); + else if (msg.event === "metadata") onMetadataEvent?.(msg); + else if (msg.data) controller.enqueue(msg.data); + }); + const onLine = (line, fieldLength, flush) => { + enqueueLine(line, fieldLength, flush); + if (flush) controller.close(); + }; + await getBytes(stream, getLines(onLine)); + } }); + return IterableReadableStream.fromReadableStream(dataStream); +} +function isEmpty(message) { + return message.data === "" && message.event === "" && message.id === "" && message.retry === void 0; +} + +//#endregion + +//# sourceMappingURL=event_source_parse.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/bytes.js + + +//#region src/output_parsers/bytes.ts +/** +* OutputParser that parses LLMResult into the top likely string and +* encodes it into bytes. +*/ +var BytesOutputParser = class extends BaseTransformOutputParser { + static lc_name() { + return "BytesOutputParser"; + } + lc_namespace = [ + "langchain_core", + "output_parsers", + "bytes" + ]; + lc_serializable = true; + textEncoder = new TextEncoder(); + parse(text) { + return Promise.resolve(this.textEncoder.encode(text)); + } + getFormatInstructions() { + return ""; + } +}; + +//#endregion + +//# sourceMappingURL=bytes.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/list.js + + + +//#region src/output_parsers/list.ts +/** +* Class to parse the output of an LLM call to a list. +* @augments BaseOutputParser +*/ +var ListOutputParser = class extends BaseTransformOutputParser { + re; + async *_transform(inputGenerator) { + let buffer = ""; + for await (const input of inputGenerator) { + if (typeof input === "string") buffer += input; + else buffer += input.content; + if (!this.re) { + const parts = await this.parse(buffer); + if (parts.length > 1) { + for (const part of parts.slice(0, -1)) yield [part]; + buffer = parts[parts.length - 1]; + } + } else { + const matches = [...buffer.matchAll(this.re)]; + if (matches.length > 1) { + let doneIdx = 0; + for (const match of matches.slice(0, -1)) { + yield [match[1]]; + doneIdx += (match.index ?? 0) + match[0].length; + } + buffer = buffer.slice(doneIdx); + } + } + } + for (const part of await this.parse(buffer)) yield [part]; + } +}; +/** +* Class to parse the output of an LLM call as a comma-separated list. +* @augments ListOutputParser +*/ +var CommaSeparatedListOutputParser = class extends ListOutputParser { + static lc_name() { + return "CommaSeparatedListOutputParser"; + } + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + lc_serializable = true; + /** + * Parses the given text into an array of strings, using a comma as the + * separator. If the parsing fails, throws an OutputParserException. + * @param text The text to parse. + * @returns An array of strings obtained by splitting the input text at each comma. + */ + async parse(text) { + try { + return text.trim().split(",").map((s) => s.trim()); + } catch { + throw new OutputParserException(`Could not parse output: ${text}`, text); + } + } + /** + * Provides instructions on the expected format of the response for the + * CommaSeparatedListOutputParser. + * @returns A string containing instructions on the expected format of the response. + */ + getFormatInstructions() { + return `Your response should be a list of comma separated values, eg: \`foo, bar, baz\``; + } +}; +/** +* Class to parse the output of an LLM call to a list with a specific length and separator. +* @augments ListOutputParser +*/ +var CustomListOutputParser = class extends ListOutputParser { + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + length; + separator; + constructor({ length, separator }) { + super(...arguments); + this.length = length; + this.separator = separator || ","; + } + /** + * Parses the given text into an array of strings, using the specified + * separator. If the parsing fails or the number of items in the list + * doesn't match the expected length, throws an OutputParserException. + * @param text The text to parse. + * @returns An array of strings obtained by splitting the input text at each occurrence of the specified separator. + */ + async parse(text) { + try { + const items = text.trim().split(this.separator).map((s) => s.trim()); + if (this.length !== void 0 && items.length !== this.length) throw new OutputParserException(`Incorrect number of items. Expected ${this.length}, got ${items.length}.`); + return items; + } catch (e) { + if (Object.getPrototypeOf(e) === OutputParserException.prototype) throw e; + throw new OutputParserException(`Could not parse output: ${text}`); + } + } + /** + * Provides instructions on the expected format of the response for the + * CustomListOutputParser, including the number of items and the + * separator. + * @returns A string containing instructions on the expected format of the response. + */ + getFormatInstructions() { + return `Your response should be a list of ${this.length === void 0 ? "" : `${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`; + } +}; +var NumberedListOutputParser = class extends ListOutputParser { + static lc_name() { + return "NumberedListOutputParser"; + } + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + lc_serializable = true; + getFormatInstructions() { + return `Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz`; + } + re = /\d+\.\s([^\n]+)/g; + async parse(text) { + return [...text.matchAll(this.re) ?? []].map((m) => m[1]); + } +}; +var MarkdownListOutputParser = class extends ListOutputParser { + static lc_name() { + return "NumberedListOutputParser"; + } + lc_namespace = [ + "langchain_core", + "output_parsers", + "list" + ]; + lc_serializable = true; + getFormatInstructions() { + return `Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz`; + } + re = /^\s*[-*]\s([^\n]+)$/gm; + async parse(text) { + return [...text.matchAll(this.re) ?? []].map((m) => m[1]); + } +}; + +//#endregion + +//# sourceMappingURL=list.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/string.js + + +//#region src/output_parsers/string.ts +/** +* OutputParser that parses LLMResult into the top likely string. +* @example +* ```typescript +* const promptTemplate = PromptTemplate.fromTemplate( +* "Tell me a joke about {topic}", +* ); +* +* const chain = RunnableSequence.from([ +* promptTemplate, +* new ChatOpenAI({ model: "gpt-4o-mini" }), +* new StringOutputParser(), +* ]); +* +* const result = await chain.invoke({ topic: "bears" }); +* console.log("What do you call a bear with no teeth? A gummy bear!"); +* ``` +*/ +var StringOutputParser = class extends BaseTransformOutputParser { + static lc_name() { + return "StrOutputParser"; + } + lc_namespace = [ + "langchain_core", + "output_parsers", + "string" + ]; + lc_serializable = true; + /** + * Parses a string output from an LLM call. This method is meant to be + * implemented by subclasses to define how a string output from an LLM + * should be parsed. + * @param text The string output from an LLM call. + * @param callbacks Optional callbacks. + * @returns A promise of the parsed output. + */ + parse(text) { + return Promise.resolve(text); + } + getFormatInstructions() { + return ""; + } + _textContentToString(content) { + return content.text; + } + _imageUrlContentToString(_content) { + throw new Error(`Cannot coerce a multimodal "image_url" message part into a string.`); + } + _messageContentToString(content) { + switch (content.type) { + case "text": + case "text_delta": + if ("text" in content) return this._textContentToString(content); + break; + case "image_url": + if ("image_url" in content) return this._imageUrlContentToString(content); + break; + default: throw new Error(`Cannot coerce "${content.type}" message part into a string.`); + } + throw new Error(`Invalid content type: ${content.type}`); + } + _baseMessageContentToString(content) { + return content.reduce((acc, item) => acc + this._messageContentToString(item), ""); + } +}; + +//#endregion + +//# sourceMappingURL=string.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/structured.js + + + + + +//#region src/output_parsers/structured.ts +var StructuredOutputParser = class extends BaseOutputParser { + static lc_name() { + return "StructuredOutputParser"; + } + lc_namespace = [ + "langchain", + "output_parsers", + "structured" + ]; + toJSON() { + return this.toJSONNotImplemented(); + } + constructor(schema) { + super(schema); + this.schema = schema; + } + /** + * Creates a new StructuredOutputParser from a Zod schema. + * @param schema The Zod schema which the output should match + * @returns A new instance of StructuredOutputParser. + */ + static fromZodSchema(schema) { + return new this(schema); + } + /** + * Creates a new StructuredOutputParser from a set of names and + * descriptions. + * @param schemas An object where each key is a name and each value is a description + * @returns A new instance of StructuredOutputParser. + */ + static fromNamesAndDescriptions(schemas) { + const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); + return new this(zodSchema); + } + /** + * Returns a markdown code snippet with a JSON object formatted according + * to the schema. + * @param options Optional. The options for formatting the instructions + * @returns A markdown code snippet with a JSON object formatted according to the schema. + */ + getFormatInstructions() { + return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance. + +"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents. + +For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}} +would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings. +Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted. + +Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas! + +Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: +\`\`\`json +${JSON.stringify(toJsonSchema(this.schema))} +\`\`\` +`; + } + /** + * Parses the given text according to the schema. + * @param text The text to parse + * @returns The parsed output. + */ + async parse(text) { + try { + const trimmedText = text.trim(); + const json = trimmedText.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1] || trimmedText.match(/```json\s*([\s\S]*?)```/)?.[1] || trimmedText; + const escapedJson = json.replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, (_match, capturedGroup) => { + const escapedInsideQuotes = capturedGroup.replace(/\n/g, "\\n"); + return `"${escapedInsideQuotes}"`; + }).replace(/\n/g, ""); + return await interopParseAsync(this.schema, JSON.parse(escapedJson)); + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); + } + } +}; +/** +* A specific type of `StructuredOutputParser` that parses JSON data +* formatted as a markdown code snippet. +*/ +var JsonMarkdownStructuredOutputParser = class extends StructuredOutputParser { + static lc_name() { + return "JsonMarkdownStructuredOutputParser"; + } + getFormatInstructions(options) { + const interpolationDepth = options?.interpolationDepth ?? 1; + if (interpolationDepth < 1) throw new Error("f string interpolation depth must be at least 1"); + return `Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(toJsonSchema(this.schema)).replaceAll("{", "{".repeat(interpolationDepth)).replaceAll("}", "}".repeat(interpolationDepth))}\n\`\`\``; + } + _schemaToInstruction(schemaInput, indent = 2) { + const schema = schemaInput; + if ("type" in schema) { + let nullable = false; + let type; + if (Array.isArray(schema.type)) { + const nullIdx = schema.type.findIndex((type$1) => type$1 === "null"); + if (nullIdx !== -1) { + nullable = true; + schema.type.splice(nullIdx, 1); + } + type = schema.type.join(" | "); + } else type = schema.type; + if (schema.type === "object" && schema.properties) { + const description$1 = schema.description ? ` // ${schema.description}` : ""; + const properties = Object.entries(schema.properties).map(([key, value]) => { + const isOptional = schema.required?.includes(key) ? "" : " (optional)"; + return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(value, indent + 2)}${isOptional}`; + }).join("\n"); + return `{\n${properties}\n${" ".repeat(indent - 2)}}${description$1}`; + } + if (schema.type === "array" && schema.items) { + const description$1 = schema.description ? ` // ${schema.description}` : ""; + return `array[\n${" ".repeat(indent)}${this._schemaToInstruction(schema.items, indent + 2)}\n${" ".repeat(indent - 2)}] ${description$1}`; + } + const isNullable = nullable ? " (nullable)" : ""; + const description = schema.description ? ` // ${schema.description}` : ""; + return `${type}${description}${isNullable}`; + } + if ("anyOf" in schema) return schema.anyOf.map((s) => this._schemaToInstruction(s, indent)).join(`\n${" ".repeat(indent - 2)}`); + throw new Error("unsupported schema type"); + } + static fromZodSchema(schema) { + return new this(schema); + } + static fromNamesAndDescriptions(schemas) { + const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); + return new this(zodSchema); + } +}; +/** +* A type of `StructuredOutputParser` that handles asymmetric input and +* output schemas. +*/ +var AsymmetricStructuredOutputParser = class extends BaseOutputParser { + structuredInputParser; + constructor({ inputSchema }) { + super(...arguments); + this.structuredInputParser = new JsonMarkdownStructuredOutputParser(inputSchema); + } + async parse(text) { + let parsedInput; + try { + parsedInput = await this.structuredInputParser.parse(text); + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); + } + return this.outputProcessor(parsedInput); + } + getFormatInstructions() { + return this.structuredInputParser.getFormatInstructions(); + } +}; + +//#endregion + +//# sourceMappingURL=structured.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/sax-js/sax.js +//#region src/utils/sax-js/sax.ts +const initializeSax = function() { + const sax$1 = {}; + sax$1.parser = function(strict, opt) { + return new SAXParser(strict, opt); + }; + sax$1.SAXParser = SAXParser; + sax$1.SAXStream = SAXStream; + sax$1.createStream = createStream; + sax$1.MAX_BUFFER_LENGTH = 64 * 1024; + const buffers = [ + "comment", + "sgmlDecl", + "textNode", + "tagName", + "doctype", + "procInstName", + "procInstBody", + "entity", + "attribName", + "attribValue", + "cdata", + "script" + ]; + sax$1.EVENTS = [ + "text", + "processinginstruction", + "sgmldeclaration", + "doctype", + "comment", + "opentagstart", + "attribute", + "opentag", + "closetag", + "opencdata", + "cdata", + "closecdata", + "error", + "end", + "ready", + "script", + "opennamespace", + "closenamespace" + ]; + function SAXParser(strict, opt) { + if (!(this instanceof SAXParser)) return new SAXParser(strict, opt); + var parser = this; + clearBuffers(parser); + parser.q = parser.c = ""; + parser.bufferCheckPosition = sax$1.MAX_BUFFER_LENGTH; + parser.opt = opt || {}; + parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags; + parser.looseCase = parser.opt.lowercase ? "toLowerCase" : "toUpperCase"; + parser.tags = []; + parser.closed = parser.closedRoot = parser.sawRoot = false; + parser.tag = parser.error = null; + parser.strict = !!strict; + parser.noscript = !!(strict || parser.opt.noscript); + parser.state = S.BEGIN; + parser.strictEntities = parser.opt.strictEntities; + parser.ENTITIES = parser.strictEntities ? Object.create(sax$1.XML_ENTITIES) : Object.create(sax$1.ENTITIES); + parser.attribList = []; + if (parser.opt.xmlns) parser.ns = Object.create(rootNS); + parser.trackPosition = parser.opt.position !== false; + if (parser.trackPosition) parser.position = parser.line = parser.column = 0; + emit(parser, "onready"); + } + if (!Object.create) Object.create = function(o) { + function F() {} + F.prototype = o; + var newf = new F(); + return newf; + }; + if (!Object.keys) Object.keys = function(o) { + var a = []; + for (var i in o) if (o.hasOwnProperty(i)) a.push(i); + return a; + }; + function checkBufferLength(parser) { + var maxAllowed = Math.max(sax$1.MAX_BUFFER_LENGTH, 10); + var maxActual = 0; + for (var i = 0, l = buffers.length; i < l; i++) { + var len = parser[buffers[i]].length; + if (len > maxAllowed) switch (buffers[i]) { + case "textNode": + closeText(parser); + break; + case "cdata": + emitNode(parser, "oncdata", parser.cdata); + parser.cdata = ""; + break; + case "script": + emitNode(parser, "onscript", parser.script); + parser.script = ""; + break; + default: error(parser, "Max buffer length exceeded: " + buffers[i]); + } + maxActual = Math.max(maxActual, len); + } + var m = sax$1.MAX_BUFFER_LENGTH - maxActual; + parser.bufferCheckPosition = m + parser.position; + } + function clearBuffers(parser) { + for (var i = 0, l = buffers.length; i < l; i++) parser[buffers[i]] = ""; + } + function flushBuffers(parser) { + closeText(parser); + if (parser.cdata !== "") { + emitNode(parser, "oncdata", parser.cdata); + parser.cdata = ""; + } + if (parser.script !== "") { + emitNode(parser, "onscript", parser.script); + parser.script = ""; + } + } + SAXParser.prototype = { + end: function() { + end(this); + }, + write, + resume: function() { + this.error = null; + return this; + }, + close: function() { + return this.write(null); + }, + flush: function() { + flushBuffers(this); + } + }; + var Stream = ReadableStream; + if (!Stream) Stream = function() {}; + var streamWraps = sax$1.EVENTS.filter(function(ev) { + return ev !== "error" && ev !== "end"; + }); + function createStream(strict, opt) { + return new SAXStream(strict, opt); + } + function SAXStream(strict, opt) { + if (!(this instanceof SAXStream)) return new SAXStream(strict, opt); + Stream.apply(this); + this._parser = new SAXParser(strict, opt); + this.writable = true; + this.readable = true; + var me = this; + this._parser.onend = function() { + me.emit("end"); + }; + this._parser.onerror = function(er) { + me.emit("error", er); + me._parser.error = null; + }; + this._decoder = null; + streamWraps.forEach(function(ev) { + Object.defineProperty(me, "on" + ev, { + get: function() { + return me._parser["on" + ev]; + }, + set: function(h) { + if (!h) { + me.removeAllListeners(ev); + me._parser["on" + ev] = h; + return h; + } + me.on(ev, h); + }, + enumerable: true, + configurable: false + }); + }); + } + SAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } }); + SAXStream.prototype.write = function(data) { + this._parser.write(data.toString()); + this.emit("data", data); + return true; + }; + SAXStream.prototype.end = function(chunk) { + if (chunk && chunk.length) this.write(chunk); + this._parser.end(); + return true; + }; + SAXStream.prototype.on = function(ev, handler) { + var me = this; + if (!me._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) me._parser["on" + ev] = function() { + var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments); + args.splice(0, 0, ev); + me.emit.apply(me, args); + }; + return Stream.prototype.on.call(me, ev, handler); + }; + var CDATA = "[CDATA["; + var DOCTYPE = "DOCTYPE"; + var XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"; + var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/"; + var rootNS = { + xml: XML_NAMESPACE, + xmlns: XMLNS_NAMESPACE + }; + var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; + var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; + var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; + var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; + function isWhitespace(c) { + return c === " " || c === "\n" || c === "\r" || c === " "; + } + function isQuote(c) { + return c === "\"" || c === "'"; + } + function isAttribEnd(c) { + return c === ">" || isWhitespace(c); + } + function isMatch(regex, c) { + return regex.test(c); + } + function notMatch(regex, c) { + return !isMatch(regex, c); + } + var S = 0; + sax$1.STATE = { + BEGIN: S++, + BEGIN_WHITESPACE: S++, + TEXT: S++, + TEXT_ENTITY: S++, + OPEN_WAKA: S++, + SGML_DECL: S++, + SGML_DECL_QUOTED: S++, + DOCTYPE: S++, + DOCTYPE_QUOTED: S++, + DOCTYPE_DTD: S++, + DOCTYPE_DTD_QUOTED: S++, + COMMENT_STARTING: S++, + COMMENT: S++, + COMMENT_ENDING: S++, + COMMENT_ENDED: S++, + CDATA: S++, + CDATA_ENDING: S++, + CDATA_ENDING_2: S++, + PROC_INST: S++, + PROC_INST_BODY: S++, + PROC_INST_ENDING: S++, + OPEN_TAG: S++, + OPEN_TAG_SLASH: S++, + ATTRIB: S++, + ATTRIB_NAME: S++, + ATTRIB_NAME_SAW_WHITE: S++, + ATTRIB_VALUE: S++, + ATTRIB_VALUE_QUOTED: S++, + ATTRIB_VALUE_CLOSED: S++, + ATTRIB_VALUE_UNQUOTED: S++, + ATTRIB_VALUE_ENTITY_Q: S++, + ATTRIB_VALUE_ENTITY_U: S++, + CLOSE_TAG: S++, + CLOSE_TAG_SAW_WHITE: S++, + SCRIPT: S++, + SCRIPT_ENDING: S++ + }; + sax$1.XML_ENTITIES = { + amp: "&", + gt: ">", + lt: "<", + quot: "\"", + apos: "'" + }; + sax$1.ENTITIES = { + amp: "&", + gt: ">", + lt: "<", + quot: "\"", + apos: "'", + AElig: 198, + Aacute: 193, + Acirc: 194, + Agrave: 192, + Aring: 197, + Atilde: 195, + Auml: 196, + Ccedil: 199, + ETH: 208, + Eacute: 201, + Ecirc: 202, + Egrave: 200, + Euml: 203, + Iacute: 205, + Icirc: 206, + Igrave: 204, + Iuml: 207, + Ntilde: 209, + Oacute: 211, + Ocirc: 212, + Ograve: 210, + Oslash: 216, + Otilde: 213, + Ouml: 214, + THORN: 222, + Uacute: 218, + Ucirc: 219, + Ugrave: 217, + Uuml: 220, + Yacute: 221, + aacute: 225, + acirc: 226, + aelig: 230, + agrave: 224, + aring: 229, + atilde: 227, + auml: 228, + ccedil: 231, + eacute: 233, + ecirc: 234, + egrave: 232, + eth: 240, + euml: 235, + iacute: 237, + icirc: 238, + igrave: 236, + iuml: 239, + ntilde: 241, + oacute: 243, + ocirc: 244, + ograve: 242, + oslash: 248, + otilde: 245, + ouml: 246, + szlig: 223, + thorn: 254, + uacute: 250, + ucirc: 251, + ugrave: 249, + uuml: 252, + yacute: 253, + yuml: 255, + copy: 169, + reg: 174, + nbsp: 160, + iexcl: 161, + cent: 162, + pound: 163, + curren: 164, + yen: 165, + brvbar: 166, + sect: 167, + uml: 168, + ordf: 170, + laquo: 171, + not: 172, + shy: 173, + macr: 175, + deg: 176, + plusmn: 177, + sup1: 185, + sup2: 178, + sup3: 179, + acute: 180, + micro: 181, + para: 182, + middot: 183, + cedil: 184, + ordm: 186, + raquo: 187, + frac14: 188, + frac12: 189, + frac34: 190, + iquest: 191, + times: 215, + divide: 247, + OElig: 338, + oelig: 339, + Scaron: 352, + scaron: 353, + Yuml: 376, + fnof: 402, + circ: 710, + tilde: 732, + Alpha: 913, + Beta: 914, + Gamma: 915, + Delta: 916, + Epsilon: 917, + Zeta: 918, + Eta: 919, + Theta: 920, + Iota: 921, + Kappa: 922, + Lambda: 923, + Mu: 924, + Nu: 925, + Xi: 926, + Omicron: 927, + Pi: 928, + Rho: 929, + Sigma: 931, + Tau: 932, + Upsilon: 933, + Phi: 934, + Chi: 935, + Psi: 936, + Omega: 937, + alpha: 945, + beta: 946, + gamma: 947, + delta: 948, + epsilon: 949, + zeta: 950, + eta: 951, + theta: 952, + iota: 953, + kappa: 954, + lambda: 955, + mu: 956, + nu: 957, + xi: 958, + omicron: 959, + pi: 960, + rho: 961, + sigmaf: 962, + sigma: 963, + tau: 964, + upsilon: 965, + phi: 966, + chi: 967, + psi: 968, + omega: 969, + thetasym: 977, + upsih: 978, + piv: 982, + ensp: 8194, + emsp: 8195, + thinsp: 8201, + zwnj: 8204, + zwj: 8205, + lrm: 8206, + rlm: 8207, + ndash: 8211, + mdash: 8212, + lsquo: 8216, + rsquo: 8217, + sbquo: 8218, + ldquo: 8220, + rdquo: 8221, + bdquo: 8222, + dagger: 8224, + Dagger: 8225, + bull: 8226, + hellip: 8230, + permil: 8240, + prime: 8242, + Prime: 8243, + lsaquo: 8249, + rsaquo: 8250, + oline: 8254, + frasl: 8260, + euro: 8364, + image: 8465, + weierp: 8472, + real: 8476, + trade: 8482, + alefsym: 8501, + larr: 8592, + uarr: 8593, + rarr: 8594, + darr: 8595, + harr: 8596, + crarr: 8629, + lArr: 8656, + uArr: 8657, + rArr: 8658, + dArr: 8659, + hArr: 8660, + forall: 8704, + part: 8706, + exist: 8707, + empty: 8709, + nabla: 8711, + isin: 8712, + notin: 8713, + ni: 8715, + prod: 8719, + sum: 8721, + minus: 8722, + lowast: 8727, + radic: 8730, + prop: 8733, + infin: 8734, + ang: 8736, + and: 8743, + or: 8744, + cap: 8745, + cup: 8746, + int: 8747, + there4: 8756, + sim: 8764, + cong: 8773, + asymp: 8776, + ne: 8800, + equiv: 8801, + le: 8804, + ge: 8805, + sub: 8834, + sup: 8835, + nsub: 8836, + sube: 8838, + supe: 8839, + oplus: 8853, + otimes: 8855, + perp: 8869, + sdot: 8901, + lceil: 8968, + rceil: 8969, + lfloor: 8970, + rfloor: 8971, + lang: 9001, + rang: 9002, + loz: 9674, + spades: 9824, + clubs: 9827, + hearts: 9829, + diams: 9830 + }; + Object.keys(sax$1.ENTITIES).forEach(function(key) { + var e = sax$1.ENTITIES[key]; + var s$1 = typeof e === "number" ? String.fromCharCode(e) : e; + sax$1.ENTITIES[key] = s$1; + }); + for (var s in sax$1.STATE) sax$1.STATE[sax$1.STATE[s]] = s; + S = sax$1.STATE; + function emit(parser, event, data) { + parser[event] && parser[event](data); + } + function emitNode(parser, nodeType, data) { + if (parser.textNode) closeText(parser); + emit(parser, nodeType, data); + } + function closeText(parser) { + parser.textNode = textopts(parser.opt, parser.textNode); + if (parser.textNode) emit(parser, "ontext", parser.textNode); + parser.textNode = ""; + } + function textopts(opt, text) { + if (opt.trim) text = text.trim(); + if (opt.normalize) text = text.replace(/\s+/g, " "); + return text; + } + function error(parser, er) { + closeText(parser); + if (parser.trackPosition) er += "\nLine: " + parser.line + "\nColumn: " + parser.column + "\nChar: " + parser.c; + er = new Error(er); + parser.error = er; + emit(parser, "onerror", er); + return parser; + } + function end(parser) { + if (parser.sawRoot && !parser.closedRoot) strictFail(parser, "Unclosed root tag"); + if (parser.state !== S.BEGIN && parser.state !== S.BEGIN_WHITESPACE && parser.state !== S.TEXT) error(parser, "Unexpected end"); + closeText(parser); + parser.c = ""; + parser.closed = true; + emit(parser, "onend"); + SAXParser.call(parser, parser.strict, parser.opt); + return parser; + } + function strictFail(parser, message) { + if (typeof parser !== "object" || !(parser instanceof SAXParser)) throw new Error("bad call to strictFail"); + if (parser.strict) error(parser, message); + } + function newTag(parser) { + if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase](); + var parent = parser.tags[parser.tags.length - 1] || parser; + var tag = parser.tag = { + name: parser.tagName, + attributes: {} + }; + if (parser.opt.xmlns) tag.ns = parent.ns; + parser.attribList.length = 0; + emitNode(parser, "onopentagstart", tag); + } + function qname(name, attribute) { + var i = name.indexOf(":"); + var qualName = i < 0 ? ["", name] : name.split(":"); + var prefix = qualName[0]; + var local = qualName[1]; + if (attribute && name === "xmlns") { + prefix = "xmlns"; + local = ""; + } + return { + prefix, + local + }; + } + function attrib(parser) { + if (!parser.strict) parser.attribName = parser.attribName[parser.looseCase](); + if (parser.attribList.indexOf(parser.attribName) !== -1 || parser.tag.attributes.hasOwnProperty(parser.attribName)) { + parser.attribName = parser.attribValue = ""; + return; + } + if (parser.opt.xmlns) { + var qn = qname(parser.attribName, true); + var prefix = qn.prefix; + var local = qn.local; + if (prefix === "xmlns") if (local === "xml" && parser.attribValue !== XML_NAMESPACE) strictFail(parser, "xml: prefix must be bound to " + XML_NAMESPACE + "\nActual: " + parser.attribValue); + else if (local === "xmlns" && parser.attribValue !== XMLNS_NAMESPACE) strictFail(parser, "xmlns: prefix must be bound to " + XMLNS_NAMESPACE + "\nActual: " + parser.attribValue); + else { + var tag = parser.tag; + var parent = parser.tags[parser.tags.length - 1] || parser; + if (tag.ns === parent.ns) tag.ns = Object.create(parent.ns); + tag.ns[local] = parser.attribValue; + } + parser.attribList.push([parser.attribName, parser.attribValue]); + } else { + parser.tag.attributes[parser.attribName] = parser.attribValue; + emitNode(parser, "onattribute", { + name: parser.attribName, + value: parser.attribValue + }); + } + parser.attribName = parser.attribValue = ""; + } + function openTag(parser, selfClosing) { + if (parser.opt.xmlns) { + var tag = parser.tag; + var qn = qname(parser.tagName); + tag.prefix = qn.prefix; + tag.local = qn.local; + tag.uri = tag.ns[qn.prefix] || ""; + if (tag.prefix && !tag.uri) { + strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(parser.tagName)); + tag.uri = qn.prefix; + } + var parent = parser.tags[parser.tags.length - 1] || parser; + if (tag.ns && parent.ns !== tag.ns) Object.keys(tag.ns).forEach(function(p) { + emitNode(parser, "onopennamespace", { + prefix: p, + uri: tag.ns[p] + }); + }); + for (var i = 0, l = parser.attribList.length; i < l; i++) { + var nv = parser.attribList[i]; + var name = nv[0]; + var value = nv[1]; + var qualName = qname(name, true); + var prefix = qualName.prefix; + var local = qualName.local; + var uri = prefix === "" ? "" : tag.ns[prefix] || ""; + var a = { + name, + value, + prefix, + local, + uri + }; + if (prefix && prefix !== "xmlns" && !uri) { + strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(prefix)); + a.uri = prefix; + } + parser.tag.attributes[name] = a; + emitNode(parser, "onattribute", a); + } + parser.attribList.length = 0; + } + parser.tag.isSelfClosing = !!selfClosing; + parser.sawRoot = true; + parser.tags.push(parser.tag); + emitNode(parser, "onopentag", parser.tag); + if (!selfClosing) { + if (!parser.noscript && parser.tagName.toLowerCase() === "script") parser.state = S.SCRIPT; + else parser.state = S.TEXT; + parser.tag = null; + parser.tagName = ""; + } + parser.attribName = parser.attribValue = ""; + parser.attribList.length = 0; + } + function closeTag(parser) { + if (!parser.tagName) { + strictFail(parser, "Weird empty close tag."); + parser.textNode += ""; + parser.state = S.TEXT; + return; + } + if (parser.script) { + if (parser.tagName !== "script") { + parser.script += ""; + parser.tagName = ""; + parser.state = S.SCRIPT; + return; + } + emitNode(parser, "onscript", parser.script); + parser.script = ""; + } + var t = parser.tags.length; + var tagName = parser.tagName; + if (!parser.strict) tagName = tagName[parser.looseCase](); + var closeTo = tagName; + while (t--) { + var close = parser.tags[t]; + if (close.name !== closeTo) strictFail(parser, "Unexpected close tag"); + else break; + } + if (t < 0) { + strictFail(parser, "Unmatched closing tag: " + parser.tagName); + parser.textNode += ""; + parser.state = S.TEXT; + return; + } + parser.tagName = tagName; + var s$1 = parser.tags.length; + while (s$1-- > t) { + var tag = parser.tag = parser.tags.pop(); + parser.tagName = parser.tag.name; + emitNode(parser, "onclosetag", parser.tagName); + var x = {}; + for (var i in tag.ns) x[i] = tag.ns[i]; + var parent = parser.tags[parser.tags.length - 1] || parser; + if (parser.opt.xmlns && tag.ns !== parent.ns) Object.keys(tag.ns).forEach(function(p) { + var n = tag.ns[p]; + emitNode(parser, "onclosenamespace", { + prefix: p, + uri: n + }); + }); + } + if (t === 0) parser.closedRoot = true; + parser.tagName = parser.attribValue = parser.attribName = ""; + parser.attribList.length = 0; + parser.state = S.TEXT; + } + function parseEntity(parser) { + var entity = parser.entity; + var entityLC = entity.toLowerCase(); + var num; + var numStr = ""; + if (parser.ENTITIES[entity]) return parser.ENTITIES[entity]; + if (parser.ENTITIES[entityLC]) return parser.ENTITIES[entityLC]; + entity = entityLC; + if (entity.charAt(0) === "#") if (entity.charAt(1) === "x") { + entity = entity.slice(2); + num = parseInt(entity, 16); + numStr = num.toString(16); + } else { + entity = entity.slice(1); + num = parseInt(entity, 10); + numStr = num.toString(10); + } + entity = entity.replace(/^0+/, ""); + if (isNaN(num) || numStr.toLowerCase() !== entity) { + strictFail(parser, "Invalid character entity"); + return "&" + parser.entity + ";"; + } + return String.fromCodePoint(num); + } + function beginWhiteSpace(parser, c) { + if (c === "<") { + parser.state = S.OPEN_WAKA; + parser.startTagPosition = parser.position; + } else if (!isWhitespace(c)) { + strictFail(parser, "Non-whitespace before first tag."); + parser.textNode = c; + parser.state = S.TEXT; + } + } + function charAt(chunk, i) { + var result = ""; + if (i < chunk.length) result = chunk.charAt(i); + return result; + } + function write(chunk) { + var parser = this; + if (this.error) throw this.error; + if (parser.closed) return error(parser, "Cannot write after close. Assign an onready handler."); + if (chunk === null) return end(parser); + if (typeof chunk === "object") chunk = chunk.toString(); + var i = 0; + var c = ""; + while (true) { + c = charAt(chunk, i++); + parser.c = c; + if (!c) break; + if (parser.trackPosition) { + parser.position++; + if (c === "\n") { + parser.line++; + parser.column = 0; + } else parser.column++; + } + switch (parser.state) { + case S.BEGIN: + parser.state = S.BEGIN_WHITESPACE; + if (c === "") continue; + beginWhiteSpace(parser, c); + continue; + case S.BEGIN_WHITESPACE: + beginWhiteSpace(parser, c); + continue; + case S.TEXT: + if (parser.sawRoot && !parser.closedRoot) { + var starti = i - 1; + while (c && c !== "<" && c !== "&") { + c = charAt(chunk, i++); + if (c && parser.trackPosition) { + parser.position++; + if (c === "\n") { + parser.line++; + parser.column = 0; + } else parser.column++; + } + } + parser.textNode += chunk.substring(starti, i - 1); + } + if (c === "<" && !(parser.sawRoot && parser.closedRoot && !parser.strict)) { + parser.state = S.OPEN_WAKA; + parser.startTagPosition = parser.position; + } else { + if (!isWhitespace(c) && (!parser.sawRoot || parser.closedRoot)) strictFail(parser, "Text data outside of root node."); + if (c === "&") parser.state = S.TEXT_ENTITY; + else parser.textNode += c; + } + continue; + case S.SCRIPT: + if (c === "<") parser.state = S.SCRIPT_ENDING; + else parser.script += c; + continue; + case S.SCRIPT_ENDING: + if (c === "/") parser.state = S.CLOSE_TAG; + else { + parser.script += "<" + c; + parser.state = S.SCRIPT; + } + continue; + case S.OPEN_WAKA: + if (c === "!") { + parser.state = S.SGML_DECL; + parser.sgmlDecl = ""; + } else if (isWhitespace(c)) {} else if (isMatch(nameStart, c)) { + parser.state = S.OPEN_TAG; + parser.tagName = c; + } else if (c === "/") { + parser.state = S.CLOSE_TAG; + parser.tagName = ""; + } else if (c === "?") { + parser.state = S.PROC_INST; + parser.procInstName = parser.procInstBody = ""; + } else { + strictFail(parser, "Unencoded <"); + if (parser.startTagPosition + 1 < parser.position) { + var pad = parser.position - parser.startTagPosition; + c = new Array(pad).join(" ") + c; + } + parser.textNode += "<" + c; + parser.state = S.TEXT; + } + continue; + case S.SGML_DECL: + if ((parser.sgmlDecl + c).toUpperCase() === CDATA) { + emitNode(parser, "onopencdata"); + parser.state = S.CDATA; + parser.sgmlDecl = ""; + parser.cdata = ""; + } else if (parser.sgmlDecl + c === "--") { + parser.state = S.COMMENT; + parser.comment = ""; + parser.sgmlDecl = ""; + } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) { + parser.state = S.DOCTYPE; + if (parser.doctype || parser.sawRoot) strictFail(parser, "Inappropriately located doctype declaration"); + parser.doctype = ""; + parser.sgmlDecl = ""; + } else if (c === ">") { + emitNode(parser, "onsgmldeclaration", parser.sgmlDecl); + parser.sgmlDecl = ""; + parser.state = S.TEXT; + } else if (isQuote(c)) { + parser.state = S.SGML_DECL_QUOTED; + parser.sgmlDecl += c; + } else parser.sgmlDecl += c; + continue; + case S.SGML_DECL_QUOTED: + if (c === parser.q) { + parser.state = S.SGML_DECL; + parser.q = ""; + } + parser.sgmlDecl += c; + continue; + case S.DOCTYPE: + if (c === ">") { + parser.state = S.TEXT; + emitNode(parser, "ondoctype", parser.doctype); + parser.doctype = true; + } else { + parser.doctype += c; + if (c === "[") parser.state = S.DOCTYPE_DTD; + else if (isQuote(c)) { + parser.state = S.DOCTYPE_QUOTED; + parser.q = c; + } + } + continue; + case S.DOCTYPE_QUOTED: + parser.doctype += c; + if (c === parser.q) { + parser.q = ""; + parser.state = S.DOCTYPE; + } + continue; + case S.DOCTYPE_DTD: + parser.doctype += c; + if (c === "]") parser.state = S.DOCTYPE; + else if (isQuote(c)) { + parser.state = S.DOCTYPE_DTD_QUOTED; + parser.q = c; + } + continue; + case S.DOCTYPE_DTD_QUOTED: + parser.doctype += c; + if (c === parser.q) { + parser.state = S.DOCTYPE_DTD; + parser.q = ""; + } + continue; + case S.COMMENT: + if (c === "-") parser.state = S.COMMENT_ENDING; + else parser.comment += c; + continue; + case S.COMMENT_ENDING: + if (c === "-") { + parser.state = S.COMMENT_ENDED; + parser.comment = textopts(parser.opt, parser.comment); + if (parser.comment) emitNode(parser, "oncomment", parser.comment); + parser.comment = ""; + } else { + parser.comment += "-" + c; + parser.state = S.COMMENT; + } + continue; + case S.COMMENT_ENDED: + if (c !== ">") { + strictFail(parser, "Malformed comment"); + parser.comment += "--" + c; + parser.state = S.COMMENT; + } else parser.state = S.TEXT; + continue; + case S.CDATA: + if (c === "]") parser.state = S.CDATA_ENDING; + else parser.cdata += c; + continue; + case S.CDATA_ENDING: + if (c === "]") parser.state = S.CDATA_ENDING_2; + else { + parser.cdata += "]" + c; + parser.state = S.CDATA; + } + continue; + case S.CDATA_ENDING_2: + if (c === ">") { + if (parser.cdata) emitNode(parser, "oncdata", parser.cdata); + emitNode(parser, "onclosecdata"); + parser.cdata = ""; + parser.state = S.TEXT; + } else if (c === "]") parser.cdata += "]"; + else { + parser.cdata += "]]" + c; + parser.state = S.CDATA; + } + continue; + case S.PROC_INST: + if (c === "?") parser.state = S.PROC_INST_ENDING; + else if (isWhitespace(c)) parser.state = S.PROC_INST_BODY; + else parser.procInstName += c; + continue; + case S.PROC_INST_BODY: + if (!parser.procInstBody && isWhitespace(c)) continue; + else if (c === "?") parser.state = S.PROC_INST_ENDING; + else parser.procInstBody += c; + continue; + case S.PROC_INST_ENDING: + if (c === ">") { + emitNode(parser, "onprocessinginstruction", { + name: parser.procInstName, + body: parser.procInstBody + }); + parser.procInstName = parser.procInstBody = ""; + parser.state = S.TEXT; + } else { + parser.procInstBody += "?" + c; + parser.state = S.PROC_INST_BODY; + } + continue; + case S.OPEN_TAG: + if (isMatch(nameBody, c)) parser.tagName += c; + else { + newTag(parser); + if (c === ">") openTag(parser); + else if (c === "/") parser.state = S.OPEN_TAG_SLASH; + else { + if (!isWhitespace(c)) strictFail(parser, "Invalid character in tag name"); + parser.state = S.ATTRIB; + } + } + continue; + case S.OPEN_TAG_SLASH: + if (c === ">") { + openTag(parser, true); + closeTag(parser); + } else { + strictFail(parser, "Forward-slash in opening tag not followed by >"); + parser.state = S.ATTRIB; + } + continue; + case S.ATTRIB: + if (isWhitespace(c)) continue; + else if (c === ">") openTag(parser); + else if (c === "/") parser.state = S.OPEN_TAG_SLASH; + else if (isMatch(nameStart, c)) { + parser.attribName = c; + parser.attribValue = ""; + parser.state = S.ATTRIB_NAME; + } else strictFail(parser, "Invalid attribute name"); + continue; + case S.ATTRIB_NAME: + if (c === "=") parser.state = S.ATTRIB_VALUE; + else if (c === ">") { + strictFail(parser, "Attribute without value"); + parser.attribValue = parser.attribName; + attrib(parser); + openTag(parser); + } else if (isWhitespace(c)) parser.state = S.ATTRIB_NAME_SAW_WHITE; + else if (isMatch(nameBody, c)) parser.attribName += c; + else strictFail(parser, "Invalid attribute name"); + continue; + case S.ATTRIB_NAME_SAW_WHITE: + if (c === "=") parser.state = S.ATTRIB_VALUE; + else if (isWhitespace(c)) continue; + else { + strictFail(parser, "Attribute without value"); + parser.tag.attributes[parser.attribName] = ""; + parser.attribValue = ""; + emitNode(parser, "onattribute", { + name: parser.attribName, + value: "" + }); + parser.attribName = ""; + if (c === ">") openTag(parser); + else if (isMatch(nameStart, c)) { + parser.attribName = c; + parser.state = S.ATTRIB_NAME; + } else { + strictFail(parser, "Invalid attribute name"); + parser.state = S.ATTRIB; + } + } + continue; + case S.ATTRIB_VALUE: + if (isWhitespace(c)) continue; + else if (isQuote(c)) { + parser.q = c; + parser.state = S.ATTRIB_VALUE_QUOTED; + } else { + strictFail(parser, "Unquoted attribute value"); + parser.state = S.ATTRIB_VALUE_UNQUOTED; + parser.attribValue = c; + } + continue; + case S.ATTRIB_VALUE_QUOTED: + if (c !== parser.q) { + if (c === "&") parser.state = S.ATTRIB_VALUE_ENTITY_Q; + else parser.attribValue += c; + continue; + } + attrib(parser); + parser.q = ""; + parser.state = S.ATTRIB_VALUE_CLOSED; + continue; + case S.ATTRIB_VALUE_CLOSED: + if (isWhitespace(c)) parser.state = S.ATTRIB; + else if (c === ">") openTag(parser); + else if (c === "/") parser.state = S.OPEN_TAG_SLASH; + else if (isMatch(nameStart, c)) { + strictFail(parser, "No whitespace between attributes"); + parser.attribName = c; + parser.attribValue = ""; + parser.state = S.ATTRIB_NAME; + } else strictFail(parser, "Invalid attribute name"); + continue; + case S.ATTRIB_VALUE_UNQUOTED: + if (!isAttribEnd(c)) { + if (c === "&") parser.state = S.ATTRIB_VALUE_ENTITY_U; + else parser.attribValue += c; + continue; + } + attrib(parser); + if (c === ">") openTag(parser); + else parser.state = S.ATTRIB; + continue; + case S.CLOSE_TAG: + if (!parser.tagName) if (isWhitespace(c)) continue; + else if (notMatch(nameStart, c)) if (parser.script) { + parser.script += "") closeTag(parser); + else if (isMatch(nameBody, c)) parser.tagName += c; + else if (parser.script) { + parser.script += "") closeTag(parser); + else strictFail(parser, "Invalid characters in closing tag"); + continue; + case S.TEXT_ENTITY: + case S.ATTRIB_VALUE_ENTITY_Q: + case S.ATTRIB_VALUE_ENTITY_U: + var returnState; + var buffer; + switch (parser.state) { + case S.TEXT_ENTITY: + returnState = S.TEXT; + buffer = "textNode"; + break; + case S.ATTRIB_VALUE_ENTITY_Q: + returnState = S.ATTRIB_VALUE_QUOTED; + buffer = "attribValue"; + break; + case S.ATTRIB_VALUE_ENTITY_U: + returnState = S.ATTRIB_VALUE_UNQUOTED; + buffer = "attribValue"; + break; + } + if (c === ";") if (parser.opt.unparsedEntities) { + var parsedEntity = parseEntity(parser); + parser.entity = ""; + parser.state = returnState; + parser.write(parsedEntity); + } else { + parser[buffer] += parseEntity(parser); + parser.entity = ""; + parser.state = returnState; + } + else if (isMatch(parser.entity.length ? entityBody : entityStart, c)) parser.entity += c; + else { + strictFail(parser, "Invalid character in entity name"); + parser[buffer] += "&" + parser.entity + c; + parser.entity = ""; + parser.state = returnState; + } + continue; + default: throw new Error(parser, "Unknown state: " + parser.state); + } + } + if (parser.position >= parser.bufferCheckPosition) checkBufferLength(parser); + return parser; + } + /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */ + /* istanbul ignore next */ + if (!String.fromCodePoint) (function() { + var stringFromCharCode = String.fromCharCode; + var floor = Math.floor; + var fromCodePoint = function() { + var MAX_SIZE = 16384; + var codeUnits = []; + var highSurrogate; + var lowSurrogate; + var index = -1; + var length = arguments.length; + if (!length) return ""; + var result = ""; + while (++index < length) { + var codePoint = Number(arguments[index]); + if (!isFinite(codePoint) || codePoint < 0 || codePoint > 1114111 || floor(codePoint) !== codePoint) throw RangeError("Invalid code point: " + codePoint); + if (codePoint <= 65535) codeUnits.push(codePoint); + else { + codePoint -= 65536; + highSurrogate = (codePoint >> 10) + 55296; + lowSurrogate = codePoint % 1024 + 56320; + codeUnits.push(highSurrogate, lowSurrogate); + } + if (index + 1 === length || codeUnits.length > MAX_SIZE) { + result += stringFromCharCode.apply(null, codeUnits); + codeUnits.length = 0; + } + } + return result; + }; + /* istanbul ignore next */ + if (Object.defineProperty) Object.defineProperty(String, "fromCodePoint", { + value: fromCodePoint, + configurable: true, + writable: true + }); + else String.fromCodePoint = fromCodePoint; + })(); + return sax$1; +}; +const sax = initializeSax(); + +//#endregion + +//# sourceMappingURL=sax.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/xml.js + + + + + +//#region src/output_parsers/xml.ts +const XML_FORMAT_INSTRUCTIONS = `The output should be formatted as a XML file. +1. Output should conform to the tags below. +2. If tags are not given, make them on your own. +3. Remember to always open and close all the tags. + +As an example, for the tags ["foo", "bar", "baz"]: +1. String "\n \n \n \n" is a well-formatted instance of the schema. +2. String "\n \n " is a badly-formatted instance. +3. String "\n \n \n" is a badly-formatted instance. + +Here are the output tags: +\`\`\` +{tags} +\`\`\``; +var XMLOutputParser = class extends BaseCumulativeTransformOutputParser { + tags; + constructor(fields) { + super(fields); + this.tags = fields?.tags; + } + static lc_name() { + return "XMLOutputParser"; + } + lc_namespace = ["langchain_core", "output_parsers"]; + lc_serializable = true; + _diff(prev, next) { + if (!next) return void 0; + if (!prev) return [{ + op: "replace", + path: "", + value: next + }]; + return compare(prev, next); + } + async parsePartialResult(generations) { + return parseXMLMarkdown(generations[0].text); + } + async parse(text) { + return parseXMLMarkdown(text); + } + getFormatInstructions() { + const withTags = !!(this.tags && this.tags.length > 0); + return withTags ? XML_FORMAT_INSTRUCTIONS.replace("{tags}", this.tags?.join(", ") ?? "") : XML_FORMAT_INSTRUCTIONS; + } +}; +const strip = (text) => text.split("\n").map((line) => line.replace(/^\s+/, "")).join("\n").trim(); +const parseParsedResult = (input) => { + if (Object.keys(input).length === 0) return {}; + const result = {}; + if (input.children.length > 0) { + result[input.name] = input.children.map(parseParsedResult); + return result; + } else { + result[input.name] = input.text ?? void 0; + return result; + } +}; +function parseXMLMarkdown(s) { + const cleanedString = strip(s); + const parser = sax.parser(true); + let parsedResult = {}; + const elementStack = []; + parser.onopentag = (node) => { + const element = { + name: node.name, + attributes: node.attributes, + children: [], + text: "", + isSelfClosing: node.isSelfClosing + }; + if (elementStack.length > 0) { + const parentElement = elementStack[elementStack.length - 1]; + parentElement.children.push(element); + } else parsedResult = element; + if (!node.isSelfClosing) elementStack.push(element); + }; + parser.onclosetag = () => { + if (elementStack.length > 0) { + const lastElement = elementStack.pop(); + if (elementStack.length === 0 && lastElement) parsedResult = lastElement; + } + }; + parser.ontext = (text) => { + if (elementStack.length > 0) { + const currentElement = elementStack[elementStack.length - 1]; + currentElement.text += text; + } + }; + parser.onattribute = (attr) => { + if (elementStack.length > 0) { + const currentElement = elementStack[elementStack.length - 1]; + currentElement.attributes[attr.name] = attr.value; + } + }; + const match = /```(xml)?(.*)```/s.exec(cleanedString); + const xmlString = match ? match[2] : cleanedString; + parser.write(xmlString).close(); + if (parsedResult && parsedResult.name === "?xml") parsedResult = parsedResult.children[0]; + return parseParsedResult(parsedResult); +} + +//#endregion + +//# sourceMappingURL=xml.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/index.js + + + + + + + + + + + +//#region src/output_parsers/index.ts +var output_parsers_exports = {}; +__export(output_parsers_exports, { + AsymmetricStructuredOutputParser: () => AsymmetricStructuredOutputParser, + BaseCumulativeTransformOutputParser: () => BaseCumulativeTransformOutputParser, + BaseLLMOutputParser: () => BaseLLMOutputParser, + BaseOutputParser: () => BaseOutputParser, + BaseTransformOutputParser: () => BaseTransformOutputParser, + BytesOutputParser: () => BytesOutputParser, + CommaSeparatedListOutputParser: () => CommaSeparatedListOutputParser, + CustomListOutputParser: () => CustomListOutputParser, + JsonMarkdownStructuredOutputParser: () => JsonMarkdownStructuredOutputParser, + JsonOutputParser: () => JsonOutputParser, + ListOutputParser: () => ListOutputParser, + MarkdownListOutputParser: () => MarkdownListOutputParser, + NumberedListOutputParser: () => NumberedListOutputParser, + OutputParserException: () => OutputParserException, + StringOutputParser: () => StringOutputParser, + StructuredOutputParser: () => StructuredOutputParser, + XMLOutputParser: () => XMLOutputParser, + XML_FORMAT_INSTRUCTIONS: () => XML_FORMAT_INSTRUCTIONS, + parseJsonMarkdown: () => parseJsonMarkdown, + parsePartialJson: () => parsePartialJson, + parseXMLMarkdown: () => parseXMLMarkdown +}); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/format.js +//#region src/utils/format.ts +var format_exports = {}; + +//#endregion + +//# sourceMappingURL=format.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/ml-distance/distances.js +//#region src/utils/ml-distance/distances.ts +/** +*Returns the Inner Product similarity between vectors a and b +* @link [Inner Product Similarity algorithm](https://www.naun.org/main/NAUN/ijmmas/mmmas-49.pdf) +* @param a - first vector +* @param b - second vector +* +*/ +function innerProduct(a, b) { + let ans = 0; + for (let i = 0; i < a.length; i++) ans += a[i] * b[i]; + return ans; +} + +//#endregion + +//# sourceMappingURL=distances.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/ml-distance-euclidean/euclidean.js +//#region src/utils/ml-distance-euclidean/euclidean.ts +function squaredEuclidean(p, q) { + let d = 0; + for (let i = 0; i < p.length; i++) d += (p[i] - q[i]) * (p[i] - q[i]); + return d; +} +function euclidean(p, q) { + return Math.sqrt(squaredEuclidean(p, q)); +} + +//#endregion + +//# sourceMappingURL=euclidean.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/math.js + + + + + +//#region src/utils/math.ts +var math_exports = {}; +__export(math_exports, { + cosineSimilarity: () => cosineSimilarity, + euclideanDistance: () => euclideanDistance, + innerProduct: () => innerProduct$1, + matrixFunc: () => matrixFunc, + maximalMarginalRelevance: () => maximalMarginalRelevance, + normalize: () => normalize +}); +/** +* Apply a row-wise function between two matrices with the same number of columns. +* +* @param {number[][]} X - The first matrix. +* @param {number[][]} Y - The second matrix. +* @param {VectorFunction} func - The function to apply. +* +* @throws {Error} If the number of columns in X and Y are not the same. +* +* @returns {number[][] | [[]]} A matrix where each row represents the result of applying the function between the corresponding rows of X and Y. +*/ +function matrixFunc(X, Y, func) { + if (X.length === 0 || X[0].length === 0 || Y.length === 0 || Y[0].length === 0) return [[]]; + if (X[0].length !== Y[0].length) throw new Error(`Number of columns in X and Y must be the same. X has shape ${[X.length, X[0].length]} and Y has shape ${[Y.length, Y[0].length]}.`); + return X.map((xVector) => Y.map((yVector) => func(xVector, yVector)).map((similarity) => Number.isNaN(similarity) ? 0 : similarity)); +} +function normalize(M, similarity = false) { + const max = matrixMaxVal(M); + return M.map((row) => row.map((val) => similarity ? 1 - val / max : val / max)); +} +/** +* This function calculates the row-wise cosine similarity between two matrices with the same number of columns. +* +* @param {number[][]} X - The first matrix. +* @param {number[][]} Y - The second matrix. +* +* @throws {Error} If the number of columns in X and Y are not the same. +* +* @returns {number[][] | [[]]} A matrix where each row represents the cosine similarity values between the corresponding rows of X and Y. +*/ +function cosineSimilarity(X, Y) { + return matrixFunc(X, Y, cosine); +} +function innerProduct$1(X, Y) { + return matrixFunc(X, Y, innerProduct); +} +function euclideanDistance(X, Y) { + return matrixFunc(X, Y, euclidean); +} +/** +* This function implements the Maximal Marginal Relevance algorithm +* to select a set of embeddings that maximizes the diversity and relevance to a query embedding. +* +* @param {number[]|number[][]} queryEmbedding - The query embedding. +* @param {number[][]} embeddingList - The list of embeddings to select from. +* @param {number} [lambda=0.5] - The trade-off parameter between relevance and diversity. +* @param {number} [k=4] - The maximum number of embeddings to select. +* +* @returns {number[]} The indexes of the selected embeddings in the embeddingList. +*/ +function maximalMarginalRelevance(queryEmbedding, embeddingList, lambda = .5, k = 4) { + if (Math.min(k, embeddingList.length) <= 0) return []; + const queryEmbeddingExpanded = Array.isArray(queryEmbedding[0]) ? queryEmbedding : [queryEmbedding]; + const similarityToQuery = cosineSimilarity(queryEmbeddingExpanded, embeddingList)[0]; + const mostSimilarEmbeddingIndex = argMax(similarityToQuery).maxIndex; + const selectedEmbeddings = [embeddingList[mostSimilarEmbeddingIndex]]; + const selectedEmbeddingsIndexes = [mostSimilarEmbeddingIndex]; + while (selectedEmbeddingsIndexes.length < Math.min(k, embeddingList.length)) { + let bestScore = -Infinity; + let bestIndex = -1; + const similarityToSelected = cosineSimilarity(embeddingList, selectedEmbeddings); + similarityToQuery.forEach((queryScore, queryScoreIndex) => { + if (selectedEmbeddingsIndexes.includes(queryScoreIndex)) return; + const maxSimilarityToSelected = Math.max(...similarityToSelected[queryScoreIndex]); + const score = lambda * queryScore - (1 - lambda) * maxSimilarityToSelected; + if (score > bestScore) { + bestScore = score; + bestIndex = queryScoreIndex; + } + }); + selectedEmbeddings.push(embeddingList[bestIndex]); + selectedEmbeddingsIndexes.push(bestIndex); + } + return selectedEmbeddingsIndexes; +} +/** +* Finds the index of the maximum value in the given array. +* @param {number[]} array - The input array. +* +* @returns {number} The index of the maximum value in the array. If the array is empty, returns -1. +*/ +function argMax(array) { + if (array.length === 0) return { + maxIndex: -1, + maxValue: NaN + }; + let maxValue = array[0]; + let maxIndex = 0; + for (let i = 1; i < array.length; i += 1) if (array[i] > maxValue) { + maxIndex = i; + maxValue = array[i]; + } + return { + maxIndex, + maxValue + }; +} +function matrixMaxVal(arrays) { + return arrays.reduce((acc, array) => Math.max(acc, argMax(array).maxValue), 0); +} + +//#endregion + +//# sourceMappingURL=math.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/import_map.js + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +//#region src/load/import_map.ts +var import_map_exports = {}; +__export(import_map_exports, { + agents: () => agents_exports, + caches: () => caches_exports, + callbacks__base: () => base_exports, + callbacks__manager: () => manager_exports, + callbacks__promises: () => promises_exports, + chat_history: () => chat_history_exports, + document_loaders__base: () => document_loaders_base_base_exports, + document_loaders__langsmith: () => langsmith_exports, + documents: () => documents_exports, + embeddings: () => embeddings_exports, + example_selectors: () => example_selectors_exports, + index: () => src_exports, + indexing: () => indexing_exports, + language_models__base: () => language_models_base_base_exports, + language_models__chat_models: () => chat_models_exports, + language_models__llms: () => llms_exports, + language_models__profile: () => profile_exports, + load__serializable: () => serializable_exports, + memory: () => memory_exports, + messages: () => messages_exports, + messages__tool: () => tool_exports, + output_parsers: () => output_parsers_exports, + output_parsers__openai_functions: () => openai_functions_exports, + output_parsers__openai_tools: () => openai_tools_exports, + outputs: () => outputs_exports, + prompt_values: () => prompt_values_exports, + prompts: () => prompts_exports, + retrievers: () => retrievers_exports, + retrievers__document_compressors: () => document_compressors_exports, + runnables: () => runnables_exports, + runnables__graph: () => graph_exports, + singletons: () => singletons_exports, + stores: () => stores_exports, + structured_query: () => structured_query_exports, + tools: () => tools_exports, + tracers__base: () => base_base_exports, + tracers__console: () => console_exports, + tracers__log_stream: () => log_stream_exports, + tracers__run_collector: () => run_collector_exports, + tracers__tracer_langchain: () => tracer_langchain_exports, + types__stream: () => stream_stream_exports, + utils__async_caller: () => async_caller_exports, + utils__chunk_array: () => chunk_array_exports, + utils__context: () => context_exports, + utils__env: () => env_exports, + utils__event_source_parse: () => event_source_parse_exports, + utils__format: () => format_exports, + utils__function_calling: () => function_calling_exports, + utils__hash: () => hash_exports, + utils__json_patch: () => json_patch_exports, + utils__json_schema: () => json_schema_exports, + utils__math: () => math_exports, + utils__stream: () => stream_exports, + utils__testing: () => testing_exports, + utils__tiktoken: () => tiktoken_exports, + utils__types: () => types_exports, + vectorstores: () => vectorstores_exports +}); + +//#endregion + +//# sourceMappingURL=import_map.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/index.js + + + + + + + +//#region src/load/index.ts +/** +* Default maximum recursion depth for deserialization. +* This provides protection against DoS attacks via deeply nested structures. +*/ +const DEFAULT_MAX_DEPTH = 50; +function combineAliasesAndInvert(constructor) { + const aliases = {}; + for (let current = constructor; current && current.prototype; current = Object.getPrototypeOf(current)) Object.assign(aliases, Reflect.get(current.prototype, "lc_aliases")); + return Object.entries(aliases).reduce((acc, [key, value]) => { + acc[value] = key; + return acc; + }, {}); +} +/** +* Recursively revive a value, handling escape markers and LC objects. +* +* This function handles: +* 1. Escaped dicts - unwrapped and returned as plain objects +* 2. LC secret objects - resolved from secretsMap or env +* 3. LC constructor objects - instantiated +* 4. Regular objects/arrays - recursed into +*/ +async function reviver(value) { + const { optionalImportsMap, optionalImportEntrypoints: optionalImportEntrypoints$1, importMap, secretsMap, secretsFromEnv, path, depth, maxDepth } = this; + const pathStr = path.join("."); + if (depth > maxDepth) throw new Error(`Maximum recursion depth (${maxDepth}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`); + if (typeof value !== "object" || value == null) return value; + if (Array.isArray(value)) return Promise.all(value.map((v, i) => reviver.call({ + ...this, + path: [...path, `${i}`], + depth: depth + 1 + }, v))); + const record = value; + if (isEscapedObject(record)) return unescapeValue(record); + if ("lc" in record && "type" in record && "id" in record && record.lc === 1 && record.type === "secret") { + const serialized = record; + const [key] = serialized.id; + if (key in secretsMap) return secretsMap[key]; + else if (secretsFromEnv) { + const secretValueInEnv = getEnvironmentVariable(key); + if (secretValueInEnv) return secretValueInEnv; + } + throw new Error(`Missing secret "${key}" at ${pathStr}`); + } + if ("lc" in record && "type" in record && "id" in record && record.lc === 1 && record.type === "not_implemented") { + const serialized = record; + const str = JSON.stringify(serialized); + throw new Error(`Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`); + } + if ("lc" in record && "type" in record && "id" in record && "kwargs" in record && record.lc === 1 && record.type === "constructor") { + const serialized = record; + const str = JSON.stringify(serialized); + const [name, ...namespaceReverse] = serialized.id.slice().reverse(); + const namespace = namespaceReverse.reverse(); + const importMaps = { + langchain_core: import_map_exports, + langchain: importMap + }; + let module = null; + const optionalImportNamespaceAliases = [namespace.join("/")]; + if (namespace[0] === "langchain_community") optionalImportNamespaceAliases.push(["langchain", ...namespace.slice(1)].join("/")); + const matchingNamespaceAlias = optionalImportNamespaceAliases.find((alias) => alias in optionalImportsMap); + if (optionalImportEntrypoints.concat(optionalImportEntrypoints$1).includes(namespace.join("/")) || matchingNamespaceAlias) if (matchingNamespaceAlias !== void 0) module = await optionalImportsMap[matchingNamespaceAlias]; + else throw new Error(`Missing key "${namespace.join("/")}" for ${pathStr} in load(optionalImportsMap={})`); + else { + let finalImportMap; + if (namespace[0] === "langchain" || namespace[0] === "langchain_core") { + finalImportMap = importMaps[namespace[0]]; + namespace.shift(); + } else throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); + if (namespace.length === 0) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); + let importMapKey; + do { + importMapKey = namespace.join("__"); + if (importMapKey in finalImportMap) break; + else namespace.pop(); + } while (namespace.length > 0); + if (importMapKey in finalImportMap) module = finalImportMap[importMapKey]; + } + if (typeof module !== "object" || module === null) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); + const builder = module[name] ?? Object.values(module).find((v) => typeof v === "function" && get_lc_unique_name(v) === name); + if (typeof builder !== "function") throw new Error(`Invalid identifer: ${pathStr} -> ${str}`); + const kwargs = await reviver.call({ + ...this, + path: [...path, "kwargs"], + depth: depth + 1 + }, serialized.kwargs); + const instance = new builder(mapKeys(kwargs, keyFromJson, combineAliasesAndInvert(builder))); + Object.defineProperty(instance.constructor, "name", { value: name }); + return instance; + } + const result = {}; + for (const [key, val] of Object.entries(record)) result[key] = await reviver.call({ + ...this, + path: [...path, key], + depth: depth + 1 + }, val); + return result; +} +/** +* Load a LangChain object from a JSON string. +* +* @param text - The JSON string to parse and load. +* @param options - Options for loading. +* @returns The loaded LangChain object. +* +* @example +* ```typescript +* import { load } from "@langchain/core/load"; +* import { AIMessage } from "@langchain/core/messages"; +* +* // Basic usage - secrets must be provided explicitly +* const msg = await load(jsonString); +* +* // With secrets from a map +* const msg = await load(jsonString, { +* secretsMap: { OPENAI_API_KEY: "sk-..." } +* }); +* +* // Allow loading secrets from environment (use with caution) +* const msg = await load(jsonString, { +* secretsFromEnv: true +* }); +* ``` +*/ +async function load(text, options) { + const json = JSON.parse(text); + const context = { + optionalImportsMap: options?.optionalImportsMap ?? {}, + optionalImportEntrypoints: options?.optionalImportEntrypoints ?? [], + secretsMap: options?.secretsMap ?? {}, + secretsFromEnv: options?.secretsFromEnv ?? false, + importMap: options?.importMap ?? {}, + path: ["$"], + depth: 0, + maxDepth: options?.maxDepth ?? DEFAULT_MAX_DEPTH + }; + return reviver.call(context, json); +} + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/serde/jsonplus.js + + + +//#region src/serde/jsonplus.ts +function isLangChainSerializedObject(value) { + return value !== null && value.lc === 1 && value.type === "constructor" && Array.isArray(value.id); +} +/** +* The replacer in stringify does not allow delegation to built-in LangChain +* serialization methods, and instead immediately calls `.toJSON()` and +* continues to stringify subfields. +* +* We therefore must start from the most nested elements in the input and +* deserialize upwards rather than top-down. +*/ +async function _reviver(value) { + if (value && typeof value === "object") if (Array.isArray(value)) { + const revivedArray = await Promise.all(value.map((item) => _reviver(item))); + return revivedArray; + } else { + const revivedObj = {}; + for (const [k, v] of Object.entries(value)) revivedObj[k] = await _reviver(v); + if (revivedObj.lc === 2 && revivedObj.type === "undefined") return void 0; + else if (revivedObj.lc === 2 && revivedObj.type === "constructor" && Array.isArray(revivedObj.id)) try { + const constructorName = revivedObj.id[revivedObj.id.length - 1]; + let constructor; + switch (constructorName) { + case "Set": + constructor = Set; + break; + case "Map": + constructor = Map; + break; + case "RegExp": + constructor = RegExp; + break; + case "Error": + constructor = Error; + break; + default: return revivedObj; + } + if (revivedObj.method) return constructor[revivedObj.method](...revivedObj.args || []); + else return new constructor(...revivedObj.args || []); + } catch (error) { + return revivedObj; + } + else if (isLangChainSerializedObject(revivedObj)) return load(JSON.stringify(revivedObj)); + return revivedObj; + } + return value; +} +function _encodeConstructorArgs(constructor, method, args, kwargs) { + return { + lc: 2, + type: "constructor", + id: [constructor.name], + method: method ?? null, + args: args ?? [], + kwargs: kwargs ?? {} + }; +} +function jsonplus_default(obj) { + if (obj === void 0) return { + lc: 2, + type: "undefined" + }; + else if (obj instanceof Set || obj instanceof Map) return _encodeConstructorArgs(obj.constructor, void 0, [Array.from(obj)]); + else if (obj instanceof RegExp) return _encodeConstructorArgs(RegExp, void 0, [obj.source, obj.flags]); + else if (obj instanceof Error) return _encodeConstructorArgs(obj.constructor, void 0, [obj.message]); + else if (obj?.lg_name === "Send") return { + node: obj.node, + args: obj.args + }; + else return obj; +} +var JsonPlusSerializer = class { + _dumps(obj) { + const encoder = new TextEncoder(); + return encoder.encode(fast_safe_stringify_stringify(obj, (_, value) => { + return jsonplus_default(value); + })); + } + async dumpsTyped(obj) { + if (obj instanceof Uint8Array) return ["bytes", obj]; + else return ["json", this._dumps(obj)]; + } + async _loads(data) { + const parsed = JSON.parse(data); + return _reviver(parsed); + } + async loadsTyped(type, data) { + if (type === "bytes") return typeof data === "string" ? new TextEncoder().encode(data) : data; + else if (type === "json") return this._loads(typeof data === "string" ? data : new TextDecoder().decode(data)); + else throw new Error(`Unknown serialization type: ${type}`); + } +}; + +//#endregion + +//# sourceMappingURL=jsonplus.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/base.js + + + + +//#region src/base.ts +function deepCopy(obj) { + if (typeof obj !== "object" || obj === null) return obj; + const newObj = Array.isArray(obj) ? [] : {}; + for (const key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = deepCopy(obj[key]); + return newObj; +} +/** @hidden */ +function emptyCheckpoint() { + return { + v: 4, + id: uuid6(-2), + ts: (/* @__PURE__ */ new Date()).toISOString(), + channel_values: {}, + channel_versions: {}, + versions_seen: {} + }; +} +/** @hidden */ +function copyCheckpoint(checkpoint) { + return { + v: checkpoint.v, + id: checkpoint.id, + ts: checkpoint.ts, + channel_values: { ...checkpoint.channel_values }, + channel_versions: { ...checkpoint.channel_versions }, + versions_seen: deepCopy(checkpoint.versions_seen) + }; +} +var BaseCheckpointSaver = class { + serde = new JsonPlusSerializer(); + constructor(serde) { + this.serde = serde || this.serde; + } + async get(config) { + const value = await this.getTuple(config); + return value ? value.checkpoint : void 0; + } + /** + * Generate the next version ID for a channel. + * + * Default is to use integer versions, incrementing by 1. If you override, you can use str/int/float versions, + * as long as they are monotonically increasing. + */ + getNextVersion(current) { + if (typeof current === "string") throw new Error("Please override this method to use string versions."); + return current !== void 0 && typeof current === "number" ? current + 1 : 1; + } +}; +function compareChannelVersions(a, b) { + if (typeof a === "number" && typeof b === "number") return Math.sign(a - b); + return String(a).localeCompare(String(b)); +} +function maxChannelVersion(...versions) { + return versions.reduce((max, version, idx) => { + if (idx === 0) return version; + return compareChannelVersions(max, version) >= 0 ? max : version; + }); +} +/** +* Mapping from error type to error index. +* Regular writes just map to their index in the list of writes being saved. +* Special writes (e.g. errors) map to negative indices, to avoid those writes from +* conflicting with regular writes. +* Each Checkpointer implementation should use this mapping in put_writes. +*/ +const WRITES_IDX_MAP = { + [types_ERROR]: -1, + [SCHEDULED]: -2, + [INTERRUPT]: -3, + [RESUME]: -4 +}; +function getCheckpointId(config) { + return config.configurable?.checkpoint_id || config.configurable?.thread_ts || ""; +} + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/memory.js + + + +//#region src/memory.ts +function _generateKey(threadId, checkpointNamespace, checkpointId) { + return JSON.stringify([ + threadId, + checkpointNamespace, + checkpointId + ]); +} +function _parseKey(key) { + const [threadId, checkpointNamespace, checkpointId] = JSON.parse(key); + return { + threadId, + checkpointNamespace, + checkpointId + }; +} +var MemorySaver = class extends BaseCheckpointSaver { + storage = {}; + writes = {}; + constructor(serde) { + super(serde); + } + /** @internal */ + async _migratePendingSends(mutableCheckpoint, threadId, checkpointNs, parentCheckpointId) { + const deseriablizableCheckpoint = mutableCheckpoint; + const parentKey = _generateKey(threadId, checkpointNs, parentCheckpointId); + const pendingSends = await Promise.all(Object.values(this.writes[parentKey] ?? {}).filter(([_taskId, channel]) => channel === TASKS).map(async ([_taskId, _channel, writes]) => await this.serde.loadsTyped("json", writes))); + deseriablizableCheckpoint.channel_values ??= {}; + deseriablizableCheckpoint.channel_values[TASKS] = pendingSends; + deseriablizableCheckpoint.channel_versions ??= {}; + deseriablizableCheckpoint.channel_versions[TASKS] = Object.keys(deseriablizableCheckpoint.channel_versions).length > 0 ? maxChannelVersion(...Object.values(deseriablizableCheckpoint.channel_versions)) : this.getNextVersion(void 0); + } + async getTuple(config) { + const thread_id = config.configurable?.thread_id; + const checkpoint_ns = config.configurable?.checkpoint_ns ?? ""; + let checkpoint_id = getCheckpointId(config); + if (checkpoint_id) { + const saved = this.storage[thread_id]?.[checkpoint_ns]?.[checkpoint_id]; + if (saved !== void 0) { + const [checkpoint, metadata, parentCheckpointId] = saved; + const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id); + const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); + if (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId); + const pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => { + return [ + taskId, + channel, + await this.serde.loadsTyped("json", value) + ]; + })); + const checkpointTuple = { + config, + checkpoint: deserializedCheckpoint, + metadata: await this.serde.loadsTyped("json", metadata), + pendingWrites + }; + if (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: { + thread_id, + checkpoint_ns, + checkpoint_id: parentCheckpointId + } }; + return checkpointTuple; + } + } else { + const checkpoints = this.storage[thread_id]?.[checkpoint_ns]; + if (checkpoints !== void 0) { + checkpoint_id = Object.keys(checkpoints).sort((a, b) => b.localeCompare(a))[0]; + const saved = checkpoints[checkpoint_id]; + const [checkpoint, metadata, parentCheckpointId] = saved; + const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id); + const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); + if (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId); + const pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => { + return [ + taskId, + channel, + await this.serde.loadsTyped("json", value) + ]; + })); + const checkpointTuple = { + config: { configurable: { + thread_id, + checkpoint_id, + checkpoint_ns + } }, + checkpoint: deserializedCheckpoint, + metadata: await this.serde.loadsTyped("json", metadata), + pendingWrites + }; + if (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: { + thread_id, + checkpoint_ns, + checkpoint_id: parentCheckpointId + } }; + return checkpointTuple; + } + } + return void 0; + } + async *list(config, options) { + let { before, limit, filter } = options ?? {}; + const threadIds = config.configurable?.thread_id ? [config.configurable?.thread_id] : Object.keys(this.storage); + const configCheckpointNamespace = config.configurable?.checkpoint_ns; + const configCheckpointId = config.configurable?.checkpoint_id; + for (const threadId of threadIds) for (const checkpointNamespace of Object.keys(this.storage[threadId] ?? {})) { + if (configCheckpointNamespace !== void 0 && checkpointNamespace !== configCheckpointNamespace) continue; + const checkpoints = this.storage[threadId]?.[checkpointNamespace] ?? {}; + const sortedCheckpoints = Object.entries(checkpoints).sort((a, b) => b[0].localeCompare(a[0])); + for (const [checkpointId, [checkpoint, metadataStr, parentCheckpointId]] of sortedCheckpoints) { + if (configCheckpointId && checkpointId !== configCheckpointId) continue; + if (before && before.configurable?.checkpoint_id && checkpointId >= before.configurable.checkpoint_id) continue; + const metadata = await this.serde.loadsTyped("json", metadataStr); + if (filter && !Object.entries(filter).every(([key$1, value]) => metadata[key$1] === value)) continue; + if (limit !== void 0) { + if (limit <= 0) break; + limit -= 1; + } + const key = _generateKey(threadId, checkpointNamespace, checkpointId); + const writes = Object.values(this.writes[key] || {}); + const pendingWrites = await Promise.all(writes.map(async ([taskId, channel, value]) => { + return [ + taskId, + channel, + await this.serde.loadsTyped("json", value) + ]; + })); + const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); + if (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, threadId, checkpointNamespace, parentCheckpointId); + const checkpointTuple = { + config: { configurable: { + thread_id: threadId, + checkpoint_ns: checkpointNamespace, + checkpoint_id: checkpointId + } }, + checkpoint: deserializedCheckpoint, + metadata, + pendingWrites + }; + if (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: { + thread_id: threadId, + checkpoint_ns: checkpointNamespace, + checkpoint_id: parentCheckpointId + } }; + yield checkpointTuple; + } + } + } + async put(config, checkpoint, metadata) { + const preparedCheckpoint = copyCheckpoint(checkpoint); + const threadId = config.configurable?.thread_id; + const checkpointNamespace = config.configurable?.checkpoint_ns ?? ""; + if (threadId === void 0) throw new Error(`Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property.`); + if (!this.storage[threadId]) this.storage[threadId] = {}; + if (!this.storage[threadId][checkpointNamespace]) this.storage[threadId][checkpointNamespace] = {}; + const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([this.serde.dumpsTyped(preparedCheckpoint), this.serde.dumpsTyped(metadata)]); + this.storage[threadId][checkpointNamespace][checkpoint.id] = [ + serializedCheckpoint, + serializedMetadata, + config.configurable?.checkpoint_id + ]; + return { configurable: { + thread_id: threadId, + checkpoint_ns: checkpointNamespace, + checkpoint_id: checkpoint.id + } }; + } + async putWrites(config, writes, taskId) { + const threadId = config.configurable?.thread_id; + const checkpointNamespace = config.configurable?.checkpoint_ns; + const checkpointId = config.configurable?.checkpoint_id; + if (threadId === void 0) throw new Error(`Failed to put writes. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property`); + if (checkpointId === void 0) throw new Error(`Failed to put writes. The passed RunnableConfig is missing a required "checkpoint_id" field in its "configurable" property.`); + const outerKey = _generateKey(threadId, checkpointNamespace, checkpointId); + const outerWrites_ = this.writes[outerKey]; + if (this.writes[outerKey] === void 0) this.writes[outerKey] = {}; + await Promise.all(writes.map(async ([channel, value], idx) => { + const [, serializedValue] = await this.serde.dumpsTyped(value); + const innerKey = [taskId, WRITES_IDX_MAP[channel] || idx]; + const innerKeyStr = `${innerKey[0]},${innerKey[1]}`; + if (innerKey[1] >= 0 && outerWrites_ && innerKeyStr in outerWrites_) return; + this.writes[outerKey][innerKeyStr] = [ + taskId, + channel, + serializedValue + ]; + })); + } + async deleteThread(threadId) { + delete this.storage[threadId]; + for (const key of Object.keys(this.writes)) if (_parseKey(key).threadId === threadId) delete this.writes[key]; + } +}; + +//#endregion + +//# sourceMappingURL=memory.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/base.js +//#region src/store/base.ts +/** +* Error thrown when an invalid namespace is provided. +*/ +var InvalidNamespaceError = class extends Error { + constructor(message) { + super(message); + this.name = "InvalidNamespaceError"; + } +}; +/** +* Validates the provided namespace. +* @param namespace The namespace to validate. +* @throws {InvalidNamespaceError} If the namespace is invalid. +*/ +function validateNamespace(namespace) { + if (namespace.length === 0) throw new InvalidNamespaceError("Namespace cannot be empty."); + for (const label of namespace) { + if (typeof label !== "string") throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels must be strings, but got ${typeof label}.`); + if (label.includes(".")) throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels cannot contain periods ('.').`); + if (label === "") throw new InvalidNamespaceError(`Namespace labels cannot be empty strings. Got ${label} in ${namespace}`); + } + if (namespace[0] === "langgraph") throw new InvalidNamespaceError(`Root label for namespace cannot be "langgraph". Got: ${namespace}`); +} +/** +* Utility function to get text at a specific JSON path +*/ +function getTextAtPath(obj, path) { + const parts = path.split("."); + let current = obj; + for (const part of parts) { + if (part.includes("[")) { + const [arrayName, indexStr] = part.split("["); + const index = indexStr.replace("]", ""); + if (!current[arrayName]) return []; + if (index === "*") { + const results = []; + for (const item of current[arrayName]) if (typeof item === "string") results.push(item); + return results; + } + const idx = parseInt(index, 10); + if (Number.isNaN(idx)) return []; + current = current[arrayName][idx]; + } else current = current[part]; + if (current === void 0) return []; + } + return typeof current === "string" ? [current] : []; +} +/** +* Tokenizes a JSON path into parts +*/ +function tokenizePath(path) { + return path.split("."); +} +/** +* Abstract base class for persistent key-value stores. +* +* Stores enable persistence and memory that can be shared across threads, +* scoped to user IDs, assistant IDs, or other arbitrary namespaces. +* +* Features: +* - Hierarchical namespaces for organization +* - Key-value storage with metadata +* - Vector similarity search (if configured) +* - Filtering and pagination +*/ +var base_BaseStore = class { + /** + * Retrieve a single item by its namespace and key. + * + * @param namespace Hierarchical path for the item + * @param key Unique identifier within the namespace + * @returns Promise resolving to the item or null if not found + */ + async get(namespace, key) { + return (await this.batch([{ + namespace, + key + }]))[0]; + } + /** + * Search for items within a namespace prefix. + * Supports both metadata filtering and vector similarity search. + * + * @param namespacePrefix Hierarchical path prefix to search within + * @param options Search options for filtering and pagination + * @returns Promise resolving to list of matching items with relevance scores + * + * @example + * // Search with filters + * await store.search(["documents"], { + * filter: { type: "report", status: "active" }, + * limit: 5, + * offset: 10 + * }); + * + * // Vector similarity search + * await store.search(["users", "content"], { + * query: "technical documentation about APIs", + * limit: 20 + * }); + */ + async search(namespacePrefix, options = {}) { + const { filter, limit = 10, offset = 0, query } = options; + return (await this.batch([{ + namespacePrefix, + filter, + limit, + offset, + query + }]))[0]; + } + /** + * Store or update an item. + * + * @param namespace Hierarchical path for the item + * @param key Unique identifier within the namespace + * @param value Object containing the item's data + * @param index Optional indexing configuration + * + * @example + * // Simple storage + * await store.put(["docs"], "report", { title: "Annual Report" }); + * + * // With specific field indexing + * await store.put( + * ["docs"], + * "report", + * { + * title: "Q4 Report", + * chapters: [{ content: "..." }, { content: "..." }] + * }, + * ["title", "chapters[*].content"] + * ); + */ + async put(namespace, key, value, index) { + validateNamespace(namespace); + await this.batch([{ + namespace, + key, + value, + index + }]); + } + /** + * Delete an item from the store. + * + * @param namespace Hierarchical path for the item + * @param key Unique identifier within the namespace + */ + async delete(namespace, key) { + await this.batch([{ + namespace, + key, + value: null + }]); + } + /** + * List and filter namespaces in the store. + * Used to explore data organization and navigate the namespace hierarchy. + * + * @param options Options for listing namespaces + * @returns Promise resolving to list of namespace paths + * + * @example + * // List all namespaces under "documents" + * await store.listNamespaces({ + * prefix: ["documents"], + * maxDepth: 2 + * }); + * + * // List namespaces ending with "v1" + * await store.listNamespaces({ + * suffix: ["v1"], + * limit: 50 + * }); + */ + async listNamespaces(options = {}) { + const { prefix, suffix, maxDepth, limit = 100, offset = 0 } = options; + const matchConditions = []; + if (prefix) matchConditions.push({ + matchType: "prefix", + path: prefix + }); + if (suffix) matchConditions.push({ + matchType: "suffix", + path: suffix + }); + return (await this.batch([{ + matchConditions: matchConditions.length ? matchConditions : void 0, + maxDepth, + limit, + offset + }]))[0]; + } + /** + * Start the store. Override if initialization is needed. + */ + start() {} + /** + * Stop the store. Override if cleanup is needed. + */ + stop() {} +}; + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/batch.js + + +//#region src/store/batch.ts +/** +* Extracts and returns the underlying store from an `AsyncBatchedStore`, +* or returns the input if it is not an `AsyncBatchedStore`. +*/ +const extractStore = (input) => { + if ("lg_name" in input && input.lg_name === "AsyncBatchedStore") return input.store; + return input; +}; +var AsyncBatchedStore = class extends base_BaseStore { + lg_name = "AsyncBatchedStore"; + store; + queue = /* @__PURE__ */ new Map(); + nextKey = 0; + running = false; + processingTask = null; + constructor(store) { + super(); + this.store = extractStore(store); + } + get isRunning() { + return this.running; + } + /** + * @ignore + * Batch is not implemented here as we're only extending `BaseStore` + * to allow it to be passed where `BaseStore` is expected, and implement + * the convenience methods (get, search, put, delete). + */ + async batch(_operations) { + throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong."); + } + async get(namespace, key) { + return this.enqueueOperation({ + namespace, + key + }); + } + async search(namespacePrefix, options) { + const { filter, limit = 10, offset = 0, query } = options || {}; + return this.enqueueOperation({ + namespacePrefix, + filter, + limit, + offset, + query + }); + } + async put(namespace, key, value) { + return this.enqueueOperation({ + namespace, + key, + value + }); + } + async delete(namespace, key) { + return this.enqueueOperation({ + namespace, + key, + value: null + }); + } + start() { + if (!this.running) { + this.running = true; + this.processingTask = this.processBatchQueue(); + } + } + async stop() { + this.running = false; + if (this.processingTask) await this.processingTask; + } + enqueueOperation(operation) { + return new Promise((resolve, reject) => { + const key = this.nextKey; + this.nextKey += 1; + this.queue.set(key, { + operation, + resolve, + reject + }); + }); + } + async processBatchQueue() { + while (this.running) { + await new Promise((resolve) => { + setTimeout(resolve, 0); + }); + if (this.queue.size === 0) continue; + const batch = new Map(this.queue); + this.queue.clear(); + try { + const operations = Array.from(batch.values()).map(({ operation }) => operation); + const results = await this.store.batch(operations); + batch.forEach(({ resolve }, key) => { + const index = Array.from(batch.keys()).indexOf(key); + resolve(results[index]); + }); + } catch (e) { + batch.forEach(({ reject }) => { + reject(e); + }); + } + } + } + toJSON() { + return { + queue: this.queue, + nextKey: this.nextKey, + running: this.running, + store: "[LangGraphStore]" + }; + } +}; + +//#endregion + +//# sourceMappingURL=batch.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/utils.js +//#region src/store/utils.ts +/** +* Tokenize a JSON path into parts. +* @example +* tokenizePath("metadata.title") // -> ["metadata", "title"] +* tokenizePath("chapters[*].content") // -> ["chapters[*]", "content"] +*/ +function utils_tokenizePath(path) { + if (!path) return []; + const tokens = []; + let current = []; + let i = 0; + while (i < path.length) { + const char = path[i]; + if (char === "[") { + if (current.length) { + tokens.push(current.join("")); + current = []; + } + let bracketCount = 1; + const indexChars = ["["]; + i += 1; + while (i < path.length && bracketCount > 0) { + if (path[i] === "[") bracketCount += 1; + else if (path[i] === "]") bracketCount -= 1; + indexChars.push(path[i]); + i += 1; + } + tokens.push(indexChars.join("")); + continue; + } else if (char === "{") { + if (current.length) { + tokens.push(current.join("")); + current = []; + } + let braceCount = 1; + const fieldChars = ["{"]; + i += 1; + while (i < path.length && braceCount > 0) { + if (path[i] === "{") braceCount += 1; + else if (path[i] === "}") braceCount -= 1; + fieldChars.push(path[i]); + i += 1; + } + tokens.push(fieldChars.join("")); + continue; + } else if (char === ".") { + if (current.length) { + tokens.push(current.join("")); + current = []; + } + } else current.push(char); + i += 1; + } + if (current.length) tokens.push(current.join("")); + return tokens; +} +/** +* Type guard to check if an object is a FilterOperators +*/ +function isFilterOperators(obj) { + return typeof obj === "object" && obj !== null && Object.keys(obj).every((key) => key === "$eq" || key === "$ne" || key === "$gt" || key === "$gte" || key === "$lt" || key === "$lte" || key === "$in" || key === "$nin"); +} +/** +* Compare values for filtering, supporting operator-based comparisons. +*/ +function compareValues(itemValue, filterValue) { + if (isFilterOperators(filterValue)) { + const operators = Object.keys(filterValue).filter((k) => k.startsWith("$")); + return operators.every((op) => { + const value = filterValue[op]; + switch (op) { + case "$eq": return itemValue === value; + case "$ne": return itemValue !== value; + case "$gt": return Number(itemValue) > Number(value); + case "$gte": return Number(itemValue) >= Number(value); + case "$lt": return Number(itemValue) < Number(value); + case "$lte": return Number(itemValue) <= Number(value); + case "$in": return Array.isArray(value) ? value.includes(itemValue) : false; + case "$nin": return Array.isArray(value) ? !value.includes(itemValue) : true; + default: return false; + } + }); + } + return itemValue === filterValue; +} +/** +* Extract text from a value at a specific JSON path. +* +* Supports: +* - Simple paths: "field1.field2" +* - Array indexing: "[0]", "[*]", "[-1]" +* - Wildcards: "*" +* - Multi-field selection: "{field1,field2}" +* - Nested paths in multi-field: "{field1,nested.field2}" +*/ +function utils_getTextAtPath(obj, path) { + if (!path || path === "$") return [JSON.stringify(obj, null, 2)]; + const tokens = Array.isArray(path) ? path : utils_tokenizePath(path); + function extractFromObj(obj$1, tokens$1, pos) { + if (pos >= tokens$1.length) { + if (typeof obj$1 === "string" || typeof obj$1 === "number" || typeof obj$1 === "boolean") return [String(obj$1)]; + if (obj$1 === null || obj$1 === void 0) return []; + if (Array.isArray(obj$1) || typeof obj$1 === "object") return [JSON.stringify(obj$1, null, 2)]; + return []; + } + const token = tokens$1[pos]; + const results = []; + if (pos === 0 && token === "$") results.push(JSON.stringify(obj$1, null, 2)); + if (token.startsWith("[") && token.endsWith("]")) { + if (!Array.isArray(obj$1)) return []; + const index = token.slice(1, -1); + if (index === "*") for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1)); + else try { + let idx = parseInt(index, 10); + if (idx < 0) idx = obj$1.length + idx; + if (idx >= 0 && idx < obj$1.length) results.push(...extractFromObj(obj$1[idx], tokens$1, pos + 1)); + } catch { + return []; + } + } else if (token.startsWith("{") && token.endsWith("}")) { + if (typeof obj$1 !== "object" || obj$1 === null) return []; + const fields = token.slice(1, -1).split(",").map((f) => f.trim()); + for (const field of fields) { + const nestedTokens = utils_tokenizePath(field); + if (nestedTokens.length) { + let currentObj = obj$1; + for (const nestedToken of nestedTokens) if (currentObj && typeof currentObj === "object" && nestedToken in currentObj) currentObj = currentObj[nestedToken]; + else { + currentObj = void 0; + break; + } + if (currentObj !== void 0) { + if (typeof currentObj === "string" || typeof currentObj === "number" || typeof currentObj === "boolean") results.push(String(currentObj)); + else if (Array.isArray(currentObj) || typeof currentObj === "object") results.push(JSON.stringify(currentObj, null, 2)); + } + } + } + } else if (token === "*") { + if (Array.isArray(obj$1)) for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1)); + else if (typeof obj$1 === "object" && obj$1 !== null) for (const value of Object.values(obj$1)) results.push(...extractFromObj(value, tokens$1, pos + 1)); + } else if (typeof obj$1 === "object" && obj$1 !== null && token in obj$1) results.push(...extractFromObj(obj$1[token], tokens$1, pos + 1)); + return results; + } + return extractFromObj(obj, tokens, 0); +} + +//#endregion + +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/memory.js + + + +//#region src/store/memory.ts +/** +* In-memory key-value store with optional vector search. +* +* A lightweight store implementation using JavaScript Maps. Supports basic +* key-value operations and vector search when configured with embeddings. +* +* @example +* ```typescript +* // Basic key-value storage +* const store = new InMemoryStore(); +* await store.put(["users", "123"], "prefs", { theme: "dark" }); +* const item = await store.get(["users", "123"], "prefs"); +* +* // Vector search with embeddings +* import { OpenAIEmbeddings } from "@langchain/openai"; +* const store = new InMemoryStore({ +* index: { +* dims: 1536, +* embeddings: new OpenAIEmbeddings({ modelName: "text-embedding-3-small" }), +* } +* }); +* +* // Store documents +* await store.put(["docs"], "doc1", { text: "Python tutorial" }); +* await store.put(["docs"], "doc2", { text: "TypeScript guide" }); +* +* // Search by similarity +* const results = await store.search(["docs"], { query: "python programming" }); +* ``` +* +* **Warning**: This store keeps all data in memory. Data is lost when the process exits. +* For persistence, use a database-backed store. +*/ +var memory_InMemoryStore = class extends base_BaseStore { + data = /* @__PURE__ */ new Map(); + vectors = /* @__PURE__ */ new Map(); + _indexConfig; + constructor(options) { + super(); + if (options?.index) this._indexConfig = { + ...options.index, + __tokenizedFields: (options.index.fields ?? ["$"]).map((p) => [p, p === "$" ? [p] : utils_tokenizePath(p)]) + }; + } + async batch(operations) { + const results = []; + const putOps = /* @__PURE__ */ new Map(); + const searchOps = /* @__PURE__ */ new Map(); + for (let i = 0; i < operations.length; i += 1) { + const op = operations[i]; + if ("key" in op && "namespace" in op && !("value" in op)) results.push(this.getOperation(op)); + else if ("namespacePrefix" in op) { + const candidates = this.filterItems(op); + searchOps.set(i, [op, candidates]); + results.push(null); + } else if ("value" in op) { + const key = `${op.namespace.join(":")}:${op.key}`; + putOps.set(key, op); + results.push(null); + } else if ("matchConditions" in op) results.push(this.listNamespacesOperation(op)); + } + if (searchOps.size > 0) if (this._indexConfig?.embeddings) { + const queries = /* @__PURE__ */ new Set(); + for (const [op] of searchOps.values()) if (op.query) queries.add(op.query); + const queryEmbeddings = queries.size > 0 ? await Promise.all(Array.from(queries).map((q) => this._indexConfig.embeddings.embedQuery(q))) : []; + const queryVectors = Object.fromEntries(Array.from(queries).map((q, i) => [q, queryEmbeddings[i]])); + for (const [i, [op, candidates]] of searchOps.entries()) if (op.query && queryVectors[op.query]) { + const queryVector = queryVectors[op.query]; + const scoredResults = this.scoreResults(candidates, queryVector, op.offset ?? 0, op.limit ?? 10); + results[i] = scoredResults; + } else results[i] = this.paginateResults(candidates.map((item) => ({ + ...item, + score: void 0 + })), op.offset ?? 0, op.limit ?? 10); + } else for (const [i, [op, candidates]] of searchOps.entries()) results[i] = this.paginateResults(candidates.map((item) => ({ + ...item, + score: void 0 + })), op.offset ?? 0, op.limit ?? 10); + if (putOps.size > 0 && this._indexConfig?.embeddings) { + const toEmbed = this.extractTexts(Array.from(putOps.values())); + if (Object.keys(toEmbed).length > 0) { + const embeddings = await this._indexConfig.embeddings.embedDocuments(Object.keys(toEmbed)); + this.insertVectors(toEmbed, embeddings); + } + } + for (const op of putOps.values()) this.putOperation(op); + return results; + } + getOperation(op) { + const namespaceKey = op.namespace.join(":"); + const item = this.data.get(namespaceKey)?.get(op.key); + return item ?? null; + } + putOperation(op) { + const namespaceKey = op.namespace.join(":"); + if (!this.data.has(namespaceKey)) this.data.set(namespaceKey, /* @__PURE__ */ new Map()); + const namespaceMap = this.data.get(namespaceKey); + if (op.value === null) namespaceMap.delete(op.key); + else { + const now = /* @__PURE__ */ new Date(); + if (namespaceMap.has(op.key)) { + const item = namespaceMap.get(op.key); + item.value = op.value; + item.updatedAt = now; + } else namespaceMap.set(op.key, { + value: op.value, + key: op.key, + namespace: op.namespace, + createdAt: now, + updatedAt: now + }); + } + } + listNamespacesOperation(op) { + const allNamespaces = Array.from(this.data.keys()).map((ns) => ns.split(":")); + let namespaces = allNamespaces; + if (op.matchConditions && op.matchConditions.length > 0) namespaces = namespaces.filter((ns) => op.matchConditions.every((condition) => this.doesMatch(condition, ns))); + if (op.maxDepth !== void 0) namespaces = Array.from(new Set(namespaces.map((ns) => ns.slice(0, op.maxDepth).join(":")))).map((ns) => ns.split(":")); + namespaces.sort((a, b) => a.join(":").localeCompare(b.join(":"))); + return namespaces.slice(op.offset ?? 0, (op.offset ?? 0) + (op.limit ?? namespaces.length)); + } + doesMatch(matchCondition, key) { + const { matchType, path } = matchCondition; + if (matchType === "prefix") { + if (path.length > key.length) return false; + return path.every((pElem, index) => { + const kElem = key[index]; + return pElem === "*" || kElem === pElem; + }); + } else if (matchType === "suffix") { + if (path.length > key.length) return false; + return path.every((pElem, index) => { + const kElem = key[key.length - path.length + index]; + return pElem === "*" || kElem === pElem; + }); + } + throw new Error(`Unsupported match type: ${matchType}`); + } + filterItems(op) { + const candidates = []; + for (const [namespace, items] of this.data.entries()) if (namespace.startsWith(op.namespacePrefix.join(":"))) candidates.push(...items.values()); + let filteredCandidates = candidates; + if (op.filter) filteredCandidates = candidates.filter((item) => Object.entries(op.filter).every(([key, value]) => compareValues(item.value[key], value))); + return filteredCandidates; + } + scoreResults(candidates, queryVector, offset = 0, limit = 10) { + const flatItems = []; + const flatVectors = []; + const scoreless = []; + for (const item of candidates) { + const vectors = this.getVectors(item); + if (vectors.length) for (const vector of vectors) { + flatItems.push(item); + flatVectors.push(vector); + } + else scoreless.push(item); + } + const scores = this.cosineSimilarity(queryVector, flatVectors); + const sortedResults = scores.map((score, i) => [score, flatItems[i]]).sort((a, b) => b[0] - a[0]); + const seen = /* @__PURE__ */ new Set(); + const kept = []; + for (const [score, item] of sortedResults) { + const key = `${item.namespace.join(":")}:${item.key}`; + if (seen.has(key)) continue; + const ix = seen.size; + if (ix >= offset + limit) break; + if (ix < offset) { + seen.add(key); + continue; + } + seen.add(key); + kept.push([score, item]); + } + if (scoreless.length && kept.length < limit) for (const item of scoreless.slice(0, limit - kept.length)) { + const key = `${item.namespace.join(":")}:${item.key}`; + if (!seen.has(key)) { + seen.add(key); + kept.push([void 0, item]); + } + } + return kept.map(([score, item]) => ({ + ...item, + score + })); + } + paginateResults(results, offset, limit) { + return results.slice(offset, offset + limit); + } + extractTexts(ops) { + if (!ops.length || !this._indexConfig) return {}; + const toEmbed = {}; + for (const op of ops) if (op.value !== null && op.index !== false) { + const paths = op.index === null || op.index === void 0 ? this._indexConfig.__tokenizedFields ?? [] : op.index.map((ix) => [ix, utils_tokenizePath(ix)]); + for (const [path, field] of paths) { + const texts = utils_getTextAtPath(op.value, field); + if (texts.length) if (texts.length > 1) texts.forEach((text, i) => { + if (!toEmbed[text]) toEmbed[text] = []; + toEmbed[text].push([ + op.namespace, + op.key, + `${path}.${i}` + ]); + }); + else { + if (!toEmbed[texts[0]]) toEmbed[texts[0]] = []; + toEmbed[texts[0]].push([ + op.namespace, + op.key, + path + ]); + } + } + } + return toEmbed; + } + insertVectors(texts, embeddings) { + for (const [text, metadata] of Object.entries(texts)) { + const embedding = embeddings.shift(); + if (!embedding) throw new Error(`No embedding found for text: ${text}`); + for (const [namespace, key, field] of metadata) { + const namespaceKey = namespace.join(":"); + if (!this.vectors.has(namespaceKey)) this.vectors.set(namespaceKey, /* @__PURE__ */ new Map()); + const namespaceMap = this.vectors.get(namespaceKey); + if (!namespaceMap.has(key)) namespaceMap.set(key, /* @__PURE__ */ new Map()); + const itemMap = namespaceMap.get(key); + itemMap.set(field, embedding); + } + } + } + getVectors(item) { + const namespaceKey = item.namespace.join(":"); + const itemKey = item.key; + if (!this.vectors.has(namespaceKey)) return []; + const namespaceMap = this.vectors.get(namespaceKey); + if (!namespaceMap.has(itemKey)) return []; + const itemMap = namespaceMap.get(itemKey); + const vectors = Array.from(itemMap.values()); + if (!vectors.length) return []; + return vectors; + } + cosineSimilarity(X, Y) { + if (!Y.length) return []; + const dotProducts = Y.map((vector) => vector.reduce((acc, val, i) => acc + val * X[i], 0)); + const magnitude1 = Math.sqrt(X.reduce((acc, val) => acc + val * val, 0)); + const magnitudes2 = Y.map((vector) => Math.sqrt(vector.reduce((acc, val) => acc + val * val, 0))); + return dotProducts.map((dot, i) => { + const magnitude2 = magnitudes2[i]; + return magnitude1 && magnitude2 ? dot / (magnitude1 * magnitude2) : 0; + }); + } + get indexConfig() { + return this._indexConfig; + } +}; +/** @deprecated Alias for InMemoryStore */ +var MemoryStore = class extends (/* unused pure expression or super */ null && (memory_InMemoryStore)) {}; + +//#endregion + +//# sourceMappingURL=memory.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/cache/base.js + + +//#region src/cache/base.ts +var base_BaseCache = class { + serde = new JsonPlusSerializer(); + /** + * Initialize the cache with a serializer. + * + * @param serde - The serializer to use. + */ + constructor(serde) { + this.serde = serde || this.serde; + } +}; + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/cache/memory.js + + +//#region src/cache/memory.ts +var memory_InMemoryCache = class extends (/* unused pure expression or super */ null && (BaseCache)) { + cache = {}; + async get(keys) { + if (!keys.length) return []; + const now = Date.now(); + return (await Promise.all(keys.map(async (fullKey) => { + const [namespace, key] = fullKey; + const strNamespace = namespace.join(","); + if (strNamespace in this.cache && key in this.cache[strNamespace]) { + const cached = this.cache[strNamespace][key]; + if (cached.exp == null || now < cached.exp) { + const value = await this.serde.loadsTyped(cached.enc, cached.val); + return [{ + key: fullKey, + value + }]; + } else delete this.cache[strNamespace][key]; + } + return []; + }))).flat(); + } + async set(pairs) { + const now = Date.now(); + for (const { key: fullKey, value, ttl } of pairs) { + const [namespace, key] = fullKey; + const strNamespace = namespace.join(","); + const [enc, val] = await this.serde.dumpsTyped(value); + const exp = ttl != null ? ttl * 1e3 + now : null; + this.cache[strNamespace] ??= {}; + this.cache[strNamespace][key] = { + enc, + val, + exp + }; + } + } + async clear(namespaces) { + if (!namespaces.length) { + this.cache = {}; + return; + } + for (const namespace of namespaces) { + const strNamespace = namespace.join(","); + if (strNamespace in this.cache) delete this.cache[strNamespace]; + } + } +}; + +//#endregion + +//# sourceMappingURL=memory.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/cache/index.js + + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/index.js + + + + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/base.js + + + +//#region src/channels/base.ts +function isBaseChannel(obj) { + return obj != null && obj.lg_is_channel === true; +} +/** @internal */ +var BaseChannel = class { + ValueType; + UpdateType; + /** @ignore */ + lg_is_channel = true; + /** + * Mark the current value of the channel as consumed. By default, no-op. + * A channel can use this method to modify its state, preventing the value + * from being consumed again. + * + * Returns True if the channel was updated, False otherwise. + */ + consume() { + return false; + } + /** + * Notify the channel that the Pregel run is finishing. By default, no-op. + * A channel can use this method to modify its state, preventing finish. + * + * Returns True if the channel was updated, False otherwise. + */ + finish() { + return false; + } + /** + * Return True if the channel is available (not empty), False otherwise. + * Subclasses should override this method to provide a more efficient + * implementation than calling get() and catching EmptyChannelError. + */ + isAvailable() { + try { + this.get(); + return true; + } catch (error) { + if (error.name === EmptyChannelError.unminifiable_name) return false; + throw error; + } + } +}; +const IS_ONLY_BASE_CHANNEL = Symbol.for("LG_IS_ONLY_BASE_CHANNEL"); +function getOnlyChannels(channels) { + if (channels[IS_ONLY_BASE_CHANNEL] === true) return channels; + const newChannels = {}; + for (const k in channels) { + if (!Object.prototype.hasOwnProperty.call(channels, k)) continue; + const value = channels[k]; + if (isBaseChannel(value)) newChannels[k] = value; + } + Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); + return newChannels; +} +function emptyChannels(channels, checkpoint) { + const filteredChannels = getOnlyChannels(channels); + const newChannels = {}; + for (const k in filteredChannels) { + if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) continue; + const channelValue = checkpoint.channel_values[k]; + newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue); + } + Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); + return newChannels; +} +function createCheckpoint(checkpoint, channels, step, options) { + let values; + if (channels === void 0) values = checkpoint.channel_values; + else { + values = {}; + for (const k in channels) { + if (!Object.prototype.hasOwnProperty.call(channels, k)) continue; + try { + values[k] = channels[k].checkpoint(); + } catch (error) { + if (error.name === EmptyChannelError.unminifiable_name) {} else throw error; + } + } + } + return { + v: 4, + id: options?.id ?? uuid6(step), + ts: (/* @__PURE__ */ new Date()).toISOString(), + channel_values: values, + channel_versions: checkpoint.channel_versions, + versions_seen: checkpoint.versions_seen + }; +} + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/binop.js + + + +//#region src/channels/binop.ts +/** +* Stores the result of applying a binary operator to the current value and each new value. +*/ +var BinaryOperatorAggregate = class BinaryOperatorAggregate extends BaseChannel { + lc_graph_name = "BinaryOperatorAggregate"; + value; + operator; + initialValueFactory; + constructor(operator, initialValueFactory) { + super(); + this.operator = operator; + this.initialValueFactory = initialValueFactory; + this.value = initialValueFactory?.(); + } + fromCheckpoint(checkpoint) { + const empty = new BinaryOperatorAggregate(this.operator, this.initialValueFactory); + if (typeof checkpoint !== "undefined") empty.value = checkpoint; + return empty; + } + update(values) { + let newValues = values; + if (!newValues.length) return false; + if (this.value === void 0) { + [this.value] = newValues; + newValues = newValues.slice(1); + } + for (const value of newValues) if (this.value !== void 0) this.value = this.operator(this.value, value); + return true; + } + get() { + if (this.value === void 0) throw new EmptyChannelError(); + return this.value; + } + checkpoint() { + if (this.value === void 0) throw new EmptyChannelError(); + return this.value; + } + isAvailable() { + return this.value !== void 0; + } +}; + +//#endregion + +//# sourceMappingURL=binop.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/last_value.js + + + +//#region src/channels/last_value.ts +/** +* Stores the last value received, can receive at most one value per step. +* +* Since `update` is only called once per step and value can only be of length 1, +* LastValue always stores the last value of a single node. If multiple nodes attempt to +* write to this channel in a single step, an error will be thrown. +* @internal +*/ +var LastValue = class LastValue extends BaseChannel { + lc_graph_name = "LastValue"; + value = []; + constructor(initialValueFactory) { + super(); + this.initialValueFactory = initialValueFactory; + if (initialValueFactory) this.value = [initialValueFactory()]; + } + fromCheckpoint(checkpoint) { + const empty = new LastValue(this.initialValueFactory); + if (typeof checkpoint !== "undefined") empty.value = [checkpoint]; + return empty; + } + update(values) { + if (values.length === 0) return false; + if (values.length !== 1) throw new InvalidUpdateError("LastValue can only receive one value per step.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); + this.value = [values[values.length - 1]]; + return true; + } + get() { + if (this.value.length === 0) throw new EmptyChannelError(); + return this.value[0]; + } + checkpoint() { + if (this.value.length === 0) throw new EmptyChannelError(); + return this.value[0]; + } + isAvailable() { + return this.value.length !== 0; + } +}; +/** +* Stores the last value received, but only made available after finish(). +* Once made available, clears the value. +*/ +var LastValueAfterFinish = class LastValueAfterFinish extends BaseChannel { + lc_graph_name = "LastValueAfterFinish"; + value = []; + finished = false; + fromCheckpoint(checkpoint) { + const empty = new LastValueAfterFinish(); + if (typeof checkpoint !== "undefined") { + const [value, finished] = checkpoint; + empty.value = [value]; + empty.finished = finished; + } + return empty; + } + update(values) { + if (values.length === 0) return false; + this.finished = false; + this.value = [values[values.length - 1]]; + return true; + } + get() { + if (this.value.length === 0 || !this.finished) throw new EmptyChannelError(); + return this.value[0]; + } + checkpoint() { + if (this.value.length === 0) return void 0; + return [this.value[0], this.finished]; + } + consume() { + if (this.finished) { + this.finished = false; + this.value = []; + return true; + } + return false; + } + finish() { + if (!this.finished && this.value.length > 0) { + this.finished = true; + return true; + } + return false; + } + isAvailable() { + return this.value.length !== 0 && this.finished; + } +}; + +//#endregion + +//# sourceMappingURL=last_value.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/annotation.js + + + +//#region src/graph/annotation.ts +/** +* Should not be instantiated directly. See {@link Annotation}. +*/ +var AnnotationRoot = class { + lc_graph_name = "AnnotationRoot"; + spec; + constructor(s) { + this.spec = s; + } +}; +/** +* Helper that instantiates channels within a StateGraph state. +* +* Can be used as a field in an {@link Annotation.Root} wrapper in one of two ways: +* 1. **Directly**: Creates a channel that stores the most recent value returned from a node. +* 2. **With a reducer**: Creates a channel that applies the reducer on a node's return value. +* +* @example +* ```ts +* import { StateGraph, Annotation } from "@langchain/langgraph"; +* +* // Define a state with a single string key named "currentOutput" +* const SimpleAnnotation = Annotation.Root({ +* currentOutput: Annotation, +* }); +* +* const graphBuilder = new StateGraph(SimpleAnnotation); +* +* // A node in the graph that returns an object with a "currentOutput" key +* // replaces the value in the state. You can get the state type as shown below: +* const myNode = (state: typeof SimpleAnnotation.State) => { +* return { +* currentOutput: "some_new_value", +* }; +* } +* +* const graph = graphBuilder +* .addNode("myNode", myNode) +* ... +* .compile(); +* ``` +* +* @example +* ```ts +* import { type BaseMessage, AIMessage } from "@langchain/core/messages"; +* import { StateGraph, Annotation } from "@langchain/langgraph"; +* +* // Define a state with a single key named "messages" that will +* // combine a returned BaseMessage or arrays of BaseMessages +* const AnnotationWithReducer = Annotation.Root({ +* messages: Annotation({ +* // Different types are allowed for updates +* reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => { +* if (Array.isArray(right)) { +* return left.concat(right); +* } +* return left.concat([right]); +* }, +* default: () => [], +* }), +* }); +* +* const graphBuilder = new StateGraph(AnnotationWithReducer); +* +* // A node in the graph that returns an object with a "messages" key +* // will update the state by combining the existing value with the returned one. +* const myNode = (state: typeof AnnotationWithReducer.State) => { +* return { +* messages: [new AIMessage("Some new response")], +* }; +* }; +* +* const graph = graphBuilder +* .addNode("myNode", myNode) +* ... +* .compile(); +* ``` +* @namespace +* @property Root +* Helper function that instantiates a StateGraph state. See {@link Annotation} for usage. +*/ +const Annotation = function(annotation) { + if (annotation) return getChannel(annotation); + else return new LastValue(); +}; +Annotation.Root = (sd) => new AnnotationRoot(sd); +function getChannel(reducer) { + if (typeof reducer === "object" && reducer && "reducer" in reducer && reducer.reducer) return new BinaryOperatorAggregate(reducer.reducer, reducer.default); + if (typeof reducer === "object" && reducer && "value" in reducer && reducer.value) return new BinaryOperatorAggregate(reducer.value, reducer.default); + return new LastValue(); +} + +//#endregion + +//# sourceMappingURL=annotation.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/constants.js +//#region src/constants.ts +/** Special reserved node name denoting the start of a graph. */ +const START = "__start__"; +/** Special reserved node name denoting the end of a graph. */ +const END = "__end__"; +const INPUT = "__input__"; +const COPY = "__copy__"; +const constants_ERROR = "__error__"; +/** Special reserved cache namespaces */ +const CACHE_NS_WRITES = "__pregel_ns_writes"; +const CONFIG_KEY_SEND = "__pregel_send"; +/** config key containing function used to call a node (push task) */ +const constants_CONFIG_KEY_CALL = "__pregel_call"; +const CONFIG_KEY_READ = "__pregel_read"; +const CONFIG_KEY_CHECKPOINTER = "__pregel_checkpointer"; +const CONFIG_KEY_RESUMING = "__pregel_resuming"; +const CONFIG_KEY_TASK_ID = "__pregel_task_id"; +const CONFIG_KEY_STREAM = "__pregel_stream"; +const CONFIG_KEY_RESUME_VALUE = "__pregel_resume_value"; +const CONFIG_KEY_RESUME_MAP = "__pregel_resume_map"; +const constants_CONFIG_KEY_SCRATCHPAD = "__pregel_scratchpad"; +/** config key containing state from previous invocation of graph for the given thread */ +const constants_CONFIG_KEY_PREVIOUS_STATE = "__pregel_previous"; +const CONFIG_KEY_DURABILITY = "__pregel_durability"; +const CONFIG_KEY_CHECKPOINT_ID = "checkpoint_id"; +const CONFIG_KEY_CHECKPOINT_NS = "checkpoint_ns"; +const CONFIG_KEY_NODE_FINISHED = "__pregel_node_finished"; +const CONFIG_KEY_CHECKPOINT_MAP = "checkpoint_map"; +const CONFIG_KEY_ABORT_SIGNALS = "__pregel_abort_signals"; +/** Special channel reserved for graph interrupts */ +const constants_INTERRUPT = "__interrupt__"; +/** Special channel reserved for graph resume */ +const constants_RESUME = "__resume__"; +/** Special channel reserved for cases when a task exits without any writes */ +const NO_WRITES = "__no_writes__"; +/** Special channel reserved for graph return */ +const RETURN = "__return__"; +/** Special channel reserved for graph previous state */ +const PREVIOUS = "__previous__"; +const TAG_HIDDEN = "langsmith:hidden"; +const TAG_NOSTREAM = "langsmith:nostream"; +const SELF = "__self__"; +const constants_TASKS = "__pregel_tasks"; +const PUSH = "__pregel_push"; +const PULL = "__pregel_pull"; +const NULL_TASK_ID = "00000000-0000-0000-0000-000000000000"; +const RESERVED = [ + TAG_HIDDEN, + INPUT, + constants_INTERRUPT, + constants_RESUME, + constants_ERROR, + NO_WRITES, + CONFIG_KEY_SEND, + CONFIG_KEY_READ, + CONFIG_KEY_CHECKPOINTER, + CONFIG_KEY_DURABILITY, + CONFIG_KEY_STREAM, + CONFIG_KEY_RESUMING, + CONFIG_KEY_TASK_ID, + constants_CONFIG_KEY_CALL, + CONFIG_KEY_RESUME_VALUE, + constants_CONFIG_KEY_SCRATCHPAD, + constants_CONFIG_KEY_PREVIOUS_STATE, + CONFIG_KEY_CHECKPOINT_MAP, + CONFIG_KEY_CHECKPOINT_NS, + CONFIG_KEY_CHECKPOINT_ID +]; +const CHECKPOINT_NAMESPACE_SEPARATOR = "|"; +const CHECKPOINT_NAMESPACE_END = ":"; +/** @internal */ +const COMMAND_SYMBOL = Symbol.for("langgraph.command"); +/** +* Instance of a {@link Command} class. +* +* This is used to avoid IntelliSense suggesting public fields +* of {@link Command} class when a plain object is expected. +* +* @see {@link Command} +* @internal +*/ +var CommandInstance = class { + [COMMAND_SYMBOL]; + constructor(args) { + this[COMMAND_SYMBOL] = args; + } +}; +function _isSendInterface(x) { + const operation = x; + return operation !== null && operation !== void 0 && typeof operation.node === "string" && operation.args !== void 0; +} +/** +* +* A message or packet to send to a specific node in the graph. +* +* The `Send` class is used within a `StateGraph`'s conditional edges to +* dynamically invoke a node with a custom state at the next step. +* +* Importantly, the sent state can differ from the core graph's state, +* allowing for flexible and dynamic workflow management. +* +* One such example is a "map-reduce" workflow where your graph invokes +* the same node multiple times in parallel with different states, +* before aggregating the results back into the main graph's state. +* +* @example +* ```typescript +* import { Annotation, Send, StateGraph } from "@langchain/langgraph"; +* +* const ChainState = Annotation.Root({ +* subjects: Annotation, +* jokes: Annotation({ +* reducer: (a, b) => a.concat(b), +* }), +* }); +* +* const continueToJokes = async (state: typeof ChainState.State) => { +* return state.subjects.map((subject) => { +* return new Send("generate_joke", { subjects: [subject] }); +* }); +* }; +* +* const graph = new StateGraph(ChainState) +* .addNode("generate_joke", (state) => ({ +* jokes: [`Joke about ${state.subjects}`], +* })) +* .addConditionalEdges("__start__", continueToJokes) +* .addEdge("generate_joke", "__end__") +* .compile(); +* +* const res = await graph.invoke({ subjects: ["cats", "dogs"] }); +* console.log(res); +* +* // Invoking with two subjects results in a generated joke for each +* // { subjects: ["cats", "dogs"], jokes: [`Joke about cats`, `Joke about dogs`] } +* ``` +*/ +var Send = class { + lg_name = "Send"; + node; + args; + constructor(node, args) { + this.node = node; + this.args = _deserializeCommandSendObjectGraph(args); + } + toJSON() { + return { + lg_name: this.lg_name, + node: this.node, + args: this.args + }; + } +}; +function _isSend(x) { + return x instanceof Send; +} +/** +* Checks if the given graph invoke / stream chunk contains interrupt. +* +* @example +* ```ts +* import { INTERRUPT, isInterrupted } from "@langchain/langgraph"; +* +* const values = await graph.invoke({ foo: "bar" }); +* if (isInterrupted(values)) { +* const interrupt = values[INTERRUPT][0].value; +* } +* ``` +* +* @param values - The values to check. +* @returns `true` if the values contain an interrupt, `false` otherwise. +*/ +function isInterrupted(values) { + if (!values || typeof values !== "object") return false; + if (!(constants_INTERRUPT in values)) return false; + return Array.isArray(values[constants_INTERRUPT]); +} +/** +* One or more commands to update the graph's state and send messages to nodes. +* Can be used to combine routing logic with state updates in lieu of conditional edges +* +* @example +* ```ts +* import { Annotation, Command } from "@langchain/langgraph"; +* +* // Define graph state +* const StateAnnotation = Annotation.Root({ +* foo: Annotation, +* }); +* +* // Define the nodes +* const nodeA = async (_state: typeof StateAnnotation.State) => { +* console.log("Called A"); +* // this is a replacement for a real conditional edge function +* const goto = Math.random() > .5 ? "nodeB" : "nodeC"; +* // note how Command allows you to BOTH update the graph state AND route to the next node +* return new Command({ +* // this is the state update +* update: { +* foo: "a", +* }, +* // this is a replacement for an edge +* goto, +* }); +* }; +* +* // Nodes B and C are unchanged +* const nodeB = async (state: typeof StateAnnotation.State) => { +* console.log("Called B"); +* return { +* foo: state.foo + "|b", +* }; +* } +* +* const nodeC = async (state: typeof StateAnnotation.State) => { +* console.log("Called C"); +* return { +* foo: state.foo + "|c", +* }; +* } +* +* import { StateGraph } from "@langchain/langgraph"; + +* // NOTE: there are no edges between nodes A, B and C! +* const graph = new StateGraph(StateAnnotation) +* .addNode("nodeA", nodeA, { +* ends: ["nodeB", "nodeC"], +* }) +* .addNode("nodeB", nodeB) +* .addNode("nodeC", nodeC) +* .addEdge("__start__", "nodeA") +* .compile(); +* +* await graph.invoke({ foo: "" }); +* +* // Randomly oscillates between +* // { foo: 'a|c' } and { foo: 'a|b' } +* ``` +*/ +var Command = class extends CommandInstance { + lg_name = "Command"; + lc_direct_tool_output = true; + /** + * Graph to send the command to. Supported values are: + * - None: the current graph (default) + * - The specific name of the graph to send the command to + * - {@link Command.PARENT}: closest parent graph (only supported when returned from a node in a subgraph) + */ + graph; + /** + * Update to apply to the graph's state as a result of executing the node that is returning the command. + * Written to the state as if the node had simply returned this value instead of the Command object. + */ + update; + /** + * Value to resume execution with. To be used together with {@link interrupt}. + */ + resume; + /** + * Can be one of the following: + * - name of the node to navigate to next (any node that belongs to the specified `graph`) + * - sequence of node names to navigate to next + * - {@link Send} object (to execute a node with the exact input provided in the {@link Send} object) + * - sequence of {@link Send} objects + */ + goto = []; + static PARENT = "__parent__"; + constructor(args) { + super(args); + this.resume = args.resume; + this.graph = args.graph; + this.update = args.update; + if (args.goto) this.goto = Array.isArray(args.goto) ? _deserializeCommandSendObjectGraph(args.goto) : [_deserializeCommandSendObjectGraph(args.goto)]; + } + /** + * Convert the update field to a list of {@link PendingWrite} tuples + * @returns List of {@link PendingWrite} tuples of the form `[channelKey, value]`. + * @internal + */ + _updateAsTuples() { + if (this.update && typeof this.update === "object" && !Array.isArray(this.update)) return Object.entries(this.update); + else if (Array.isArray(this.update) && this.update.every((t) => Array.isArray(t) && t.length === 2 && typeof t[0] === "string")) return this.update; + else return [["__root__", this.update]]; + } + toJSON() { + let serializedGoto; + if (typeof this.goto === "string") serializedGoto = this.goto; + else if (_isSend(this.goto)) serializedGoto = this.goto.toJSON(); + else serializedGoto = this.goto?.map((innerGoto) => { + if (typeof innerGoto === "string") return innerGoto; + else return innerGoto.toJSON(); + }); + return { + lg_name: this.lg_name, + update: this.update, + resume: this.resume, + goto: serializedGoto + }; + } +}; +/** +* A type guard to check if the given value is a {@link Command}. +* +* Useful for type narrowing when working with the {@link Command} object. +* +* @param x - The value to check. +* @returns `true` if the value is a {@link Command}, `false` otherwise. +*/ +function isCommand(x) { + if (typeof x !== "object") return false; + if (x === null || x === void 0) return false; + if ("lg_name" in x && x.lg_name === "Command") return true; + return false; +} +/** +* Reconstructs Command and Send objects from a deeply nested tree of anonymous objects +* matching their interfaces. +* +* This is only exported for testing purposes. It is NOT intended to be used outside of +* the Command and Send classes. +* +* @internal +* +* @param x - The command send tree to convert. +* @param seen - A map of seen objects to avoid infinite loops. +* @returns The converted command send tree. +*/ +function _deserializeCommandSendObjectGraph(x, seen = /* @__PURE__ */ new Map()) { + if (x !== void 0 && x !== null && typeof x === "object") { + if (seen.has(x)) return seen.get(x); + let result; + if (Array.isArray(x)) { + result = []; + seen.set(x, result); + x.forEach((item, index) => { + result[index] = _deserializeCommandSendObjectGraph(item, seen); + }); + } else if (isCommand(x) && !(x instanceof Command)) { + result = new Command(x); + seen.set(x, result); + } else if (_isSendInterface(x) && !(x instanceof Send)) { + result = new Send(x.node, x.args); + seen.set(x, result); + } else if (isCommand(x) || _isSend(x)) { + result = x; + seen.set(x, result); + } else if ("lc_serializable" in x && x.lc_serializable) { + result = x; + seen.set(x, result); + } else { + result = {}; + seen.set(x, result); + for (const [key, value] of Object.entries(x)) result[key] = _deserializeCommandSendObjectGraph(value, seen); + } + return result; + } + return x; +} + +//#endregion + +//# sourceMappingURL=constants.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/utils/config.js + + + +//#region src/pregel/utils/config.ts +const COPIABLE_KEYS = [ + "tags", + "metadata", + "callbacks", + "configurable" +]; +const CONFIG_KEYS = [ + "tags", + "metadata", + "callbacks", + "runName", + "maxConcurrency", + "recursionLimit", + "configurable", + "runId", + "outputKeys", + "streamMode", + "store", + "writer", + "interrupt", + "context", + "interruptBefore", + "interruptAfter", + "checkpointDuring", + "durability", + "signal" +]; +const config_DEFAULT_RECURSION_LIMIT = 25; +function config_ensureLangGraphConfig(...configs) { + const empty = { + tags: [], + metadata: {}, + callbacks: void 0, + recursionLimit: config_DEFAULT_RECURSION_LIMIT, + configurable: {} + }; + const implicitConfig = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); + if (implicitConfig !== void 0) { + for (const [k, v] of Object.entries(implicitConfig)) if (v !== void 0) if (COPIABLE_KEYS.includes(k)) { + let copiedValue; + if (Array.isArray(v)) copiedValue = [...v]; + else if (typeof v === "object") if (k === "callbacks" && "copy" in v && typeof v.copy === "function") copiedValue = v.copy(); + else copiedValue = { ...v }; + else copiedValue = v; + empty[k] = copiedValue; + } else empty[k] = v; + } + for (const config of configs) { + if (config === void 0) continue; + for (const [k, v] of Object.entries(config)) if (v !== void 0 && CONFIG_KEYS.includes(k)) empty[k] = v; + } + for (const [key, value] of Object.entries(empty.configurable)) { + empty.metadata = empty.metadata ?? {}; + if (!key.startsWith("__") && (typeof value === "string" || typeof value === "number" || typeof value === "boolean") && !(key in empty.metadata)) empty.metadata[key] = value; + } + return empty; +} +/** +* A helper utility function that returns the {@link BaseStore} that was set when the graph was initialized +* +* @returns a reference to the {@link BaseStore} that was set when the graph was initialized +*/ +function getStore(config) { + const runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig(); + if (runConfig === void 0) throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getStore` in such environment, pass the `config` from the node function directly."].join("\n")); + return runConfig?.store; +} +/** +* A helper utility function that returns the {@link LangGraphRunnableConfig#writer} if "custom" stream mode is enabled, otherwise undefined. +* +* @returns a reference to the {@link LangGraphRunnableConfig#writer} if "custom" stream mode is enabled, otherwise undefined +*/ +function getWriter(config) { + const runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig(); + if (runConfig === void 0) throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getWriter` in such environment, pass the `config` from the node function directly."].join("\n")); + return runConfig?.writer || runConfig?.configurable?.writer; +} +/** +* A helper utility function that returns the {@link LangGraphRunnableConfig} that was set when the graph was initialized. +* +* Note: This only works when running in an environment that supports node:async_hooks and AsyncLocalStorage. If you're running this in a +* web environment, access the LangGraphRunnableConfig from the node function directly. +* +* @returns the {@link LangGraphRunnableConfig} that was set when the graph was initialized +*/ +function getConfig() { + return async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); +} +/** +* A helper utility function that returns the input for the currently executing task +* +* @returns the input for the currently executing task +*/ +function getCurrentTaskInput(config) { + const runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig(); + if (runConfig === void 0) throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getCurrentTaskInput` in such environment, pass the `config` from the node function directly."].join("\n")); + if (runConfig.configurable?.[CONFIG_KEY_SCRATCHPAD]?.currentTaskInput === void 0) throw new Error("BUG: internal scratchpad not initialized."); + return runConfig.configurable[CONFIG_KEY_SCRATCHPAD].currentTaskInput; +} +function recastCheckpointNamespace(namespace) { + return namespace.split(CHECKPOINT_NAMESPACE_SEPARATOR).filter((part) => !part.match(/^\d+$/)).map((part) => part.split(CHECKPOINT_NAMESPACE_END)[0]).join(CHECKPOINT_NAMESPACE_SEPARATOR); +} +function getParentCheckpointNamespace(namespace) { + const parts = namespace.split(CHECKPOINT_NAMESPACE_SEPARATOR); + while (parts.length > 1 && parts[parts.length - 1].match(/^\d+$/)) parts.pop(); + return parts.slice(0, -1).join(CHECKPOINT_NAMESPACE_SEPARATOR); +} + +//#endregion + +//# sourceMappingURL=config.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/hash.js +//#region src/hash.ts +const n = (n$1) => BigInt(n$1); +const view = (data, offset = 0) => new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset); +const PRIME32_1 = n("0x9E3779B1"); +const PRIME32_2 = n("0x85EBCA77"); +const PRIME32_3 = n("0xC2B2AE3D"); +const PRIME64_1 = n("0x9E3779B185EBCA87"); +const PRIME64_2 = n("0xC2B2AE3D27D4EB4F"); +const PRIME64_3 = n("0x165667B19E3779F9"); +const PRIME64_4 = n("0x85EBCA77C2B2AE63"); +const PRIME64_5 = n("0x27D4EB2F165667C5"); +const PRIME_MX1 = n("0x165667919E3779F9"); +const PRIME_MX2 = n("0x9FB21C651E98DF25"); +const hash_hexToUint8Array = (hex) => { + const strLen = hex.length; + if (strLen % 2 !== 0) throw new Error("String should have an even number of characters"); + const maxLength = strLen / 2; + const bytes = new Uint8Array(maxLength); + let read = 0; + let write = 0; + while (write < maxLength) { + const slice = hex.slice(read, read += 2); + bytes[write] = Number.parseInt(slice, 16); + write += 1; + } + return view(bytes); +}; +const kkey = hash_hexToUint8Array("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"); +const mask128 = (n(1) << n(128)) - n(1); +const mask64 = (n(1) << n(64)) - n(1); +const mask32 = (n(1) << n(32)) - n(1); +const STRIPE_LEN = 64; +const ACC_NB = STRIPE_LEN / 8; +const _U64 = 8; +const _U32 = 4; +function hash_assert(a) { + if (!a) throw new Error("Assert failed"); +} +function bswap64(a) { + const scratchbuf = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)); + scratchbuf.setBigUint64(0, a, true); + return scratchbuf.getBigUint64(0, false); +} +function bswap32(input) { + let a = input; + a = (a & n(65535)) << n(16) | (a & n(4294901760)) >> n(16); + a = (a & n(16711935)) << n(8) | (a & n(4278255360)) >> n(8); + return a; +} +function XXH_mult32to64(a, b) { + return (a & mask32) * (b & mask32) & mask64; +} +function rotl32(a, b) { + return (a << b | a >> n(32) - b) & mask32; +} +function XXH3_accumulate_512(acc, dataView, keyView) { + for (let i = 0; i < ACC_NB; i += 1) { + const data_val = dataView.getBigUint64(i * 8, true); + const data_key = data_val ^ keyView.getBigUint64(i * 8, true); + acc[i ^ 1] += data_val; + acc[i] += XXH_mult32to64(data_key, data_key >> n(32)); + } + return acc; +} +function XXH3_accumulate(acc, dataView, keyView, nbStripes) { + for (let n$1 = 0; n$1 < nbStripes; n$1 += 1) XXH3_accumulate_512(acc, view(dataView, n$1 * STRIPE_LEN), view(keyView, n$1 * 8)); + return acc; +} +function XXH3_scrambleAcc(acc, key) { + for (let i = 0; i < ACC_NB; i += 1) { + const key64 = key.getBigUint64(i * 8, true); + let acc64 = acc[i]; + acc64 = xorshift64(acc64, n(47)); + acc64 ^= key64; + acc64 *= PRIME32_1; + acc[i] = acc64 & mask64; + } + return acc; +} +function XXH3_mix2Accs(acc, key) { + return XXH3_mul128_fold64(acc[0] ^ key.getBigUint64(0, true), acc[1] ^ key.getBigUint64(_U64, true)); +} +function XXH3_mergeAccs(acc, key, start) { + let result64 = start; + result64 += XXH3_mix2Accs(acc.slice(0), view(key, 0 * _U32)); + result64 += XXH3_mix2Accs(acc.slice(2), view(key, 4 * _U32)); + result64 += XXH3_mix2Accs(acc.slice(4), view(key, 8 * _U32)); + result64 += XXH3_mix2Accs(acc.slice(6), view(key, 12 * _U32)); + return XXH3_avalanche(result64 & mask64); +} +function XXH3_hashLong(input, data, secret, f_acc, f_scramble) { + let acc = input; + const nbStripesPerBlock = Math.floor((secret.byteLength - STRIPE_LEN) / 8); + const block_len = STRIPE_LEN * nbStripesPerBlock; + const nb_blocks = Math.floor((data.byteLength - 1) / block_len); + for (let n$1 = 0; n$1 < nb_blocks; n$1 += 1) { + acc = XXH3_accumulate(acc, view(data, n$1 * block_len), secret, nbStripesPerBlock); + acc = f_scramble(acc, view(secret, secret.byteLength - STRIPE_LEN)); + } + { + const nbStripes = Math.floor((data.byteLength - 1 - block_len * nb_blocks) / STRIPE_LEN); + acc = XXH3_accumulate(acc, view(data, nb_blocks * block_len), secret, nbStripes); + acc = f_acc(acc, view(data, data.byteLength - STRIPE_LEN), view(secret, secret.byteLength - STRIPE_LEN - 7)); + } + return acc; +} +function XXH3_hashLong_128b(data, secret) { + let acc = new BigUint64Array([ + PRIME32_3, + PRIME64_1, + PRIME64_2, + PRIME64_3, + PRIME64_4, + PRIME32_2, + PRIME64_5, + PRIME32_1 + ]); + hash_assert(data.byteLength > 128); + acc = XXH3_hashLong(acc, data, secret, XXH3_accumulate_512, XXH3_scrambleAcc); + hash_assert(acc.length * 8 === 64); + { + const low64 = XXH3_mergeAccs(acc, view(secret, 11), n(data.byteLength) * PRIME64_1 & mask64); + const high64 = XXH3_mergeAccs(acc, view(secret, secret.byteLength - STRIPE_LEN - 11), ~(n(data.byteLength) * PRIME64_2) & mask64); + return high64 << n(64) | low64; + } +} +function XXH3_mul128_fold64(a, b) { + const lll = a * b & mask128; + return lll & mask64 ^ lll >> n(64); +} +function XXH3_mix16B(dataView, keyView, seed) { + return XXH3_mul128_fold64((dataView.getBigUint64(0, true) ^ keyView.getBigUint64(0, true) + seed) & mask64, (dataView.getBigUint64(8, true) ^ keyView.getBigUint64(8, true) - seed) & mask64); +} +function XXH3_mix32B(acc, data1, data2, key, seed) { + let accl = acc & mask64; + let acch = acc >> n(64) & mask64; + accl += XXH3_mix16B(data1, key, seed); + accl ^= data2.getBigUint64(0, true) + data2.getBigUint64(8, true); + accl &= mask64; + acch += XXH3_mix16B(data2, view(key, 16), seed); + acch ^= data1.getBigUint64(0, true) + data1.getBigUint64(8, true); + acch &= mask64; + return acch << n(64) | accl; +} +function XXH3_avalanche(input) { + let h64 = input; + h64 ^= h64 >> n(37); + h64 *= PRIME_MX1; + h64 &= mask64; + h64 ^= h64 >> n(32); + return h64; +} +function XXH3_avalanche64(input) { + let h64 = input; + h64 ^= h64 >> n(33); + h64 *= PRIME64_2; + h64 &= mask64; + h64 ^= h64 >> n(29); + h64 *= PRIME64_3; + h64 &= mask64; + h64 ^= h64 >> n(32); + return h64; +} +function XXH3_len_1to3_128b(data, key32, seed) { + const len = data.byteLength; + hash_assert(len > 0 && len <= 3); + const combined = n(data.getUint8(len - 1)) | n(len << 8) | n(data.getUint8(0) << 16) | n(data.getUint8(len >> 1) << 24); + const blow = (n(key32.getUint32(0, true)) ^ n(key32.getUint32(4, true))) + seed; + const low = (combined ^ blow) & mask64; + const bhigh = (n(key32.getUint32(8, true)) ^ n(key32.getUint32(12, true))) - seed; + const high = (rotl32(bswap32(combined), n(13)) ^ bhigh) & mask64; + return (XXH3_avalanche64(high) & mask64) << n(64) | XXH3_avalanche64(low); +} +function xorshift64(b, shift) { + return b ^ b >> shift; +} +function XXH3_len_4to8_128b(data, key32, seed) { + const len = data.byteLength; + hash_assert(len >= 4 && len <= 8); + { + const l1 = data.getUint32(0, true); + const l2 = data.getUint32(len - 4, true); + const l64 = n(l1) | n(l2) << n(32); + const bitflip = (key32.getBigUint64(16, true) ^ key32.getBigUint64(24, true)) + seed & mask64; + const keyed = l64 ^ bitflip; + let m128 = keyed * (PRIME64_1 + (n(len) << n(2))) & mask128; + m128 += (m128 & mask64) << n(65); + m128 &= mask128; + m128 ^= m128 >> n(67); + return xorshift64(xorshift64(m128 & mask64, n(35)) * PRIME_MX2 & mask64, n(28)) | XXH3_avalanche(m128 >> n(64)) << n(64); + } +} +function XXH3_len_9to16_128b(data, key64, seed) { + const len = data.byteLength; + hash_assert(len >= 9 && len <= 16); + { + const bitflipl = (key64.getBigUint64(32, true) ^ key64.getBigUint64(40, true)) + seed & mask64; + const bitfliph = (key64.getBigUint64(48, true) ^ key64.getBigUint64(56, true)) - seed & mask64; + const ll1 = data.getBigUint64(0, true); + let ll2 = data.getBigUint64(len - 8, true); + let m128 = (ll1 ^ ll2 ^ bitflipl) * PRIME64_1; + const m128_l = (m128 & mask64) + (n(len - 1) << n(54)); + m128 = m128 & (mask128 ^ mask64) | m128_l; + ll2 ^= bitfliph; + m128 += ll2 + (ll2 & mask32) * (PRIME32_2 - n(1)) << n(64); + m128 &= mask128; + m128 ^= bswap64(m128 >> n(64)); + let h128 = (m128 & mask64) * PRIME64_2; + h128 += (m128 >> n(64)) * PRIME64_2 << n(64); + h128 &= mask128; + return XXH3_avalanche(h128 & mask64) | XXH3_avalanche(h128 >> n(64)) << n(64); + } +} +function XXH3_len_0to16_128b(data, seed) { + const len = data.byteLength; + hash_assert(len <= 16); + if (len > 8) return XXH3_len_9to16_128b(data, kkey, seed); + if (len >= 4) return XXH3_len_4to8_128b(data, kkey, seed); + if (len > 0) return XXH3_len_1to3_128b(data, kkey, seed); + return XXH3_avalanche64(seed ^ kkey.getBigUint64(64, true) ^ kkey.getBigUint64(72, true)) | XXH3_avalanche64(seed ^ kkey.getBigUint64(80, true) ^ kkey.getBigUint64(88, true)) << n(64); +} +function inv64(x) { + return ~x + n(1) & mask64; +} +function XXH3_len_17to128_128b(data, secret, seed) { + let acc = n(data.byteLength) * PRIME64_1 & mask64; + let i = n(data.byteLength - 1) / n(32); + while (i >= 0) { + const ni = Number(i); + acc = XXH3_mix32B(acc, view(data, 16 * ni), view(data, data.byteLength - 16 * (ni + 1)), view(secret, 32 * ni), seed); + i -= n(1); + } + let h128l = acc + (acc >> n(64)) & mask64; + h128l = XXH3_avalanche(h128l); + let h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2; + h128h &= mask64; + h128h = inv64(XXH3_avalanche(h128h)); + return h128l | h128h << n(64); +} +function XXH3_len_129to240_128b(data, secret, seed) { + let acc = n(data.byteLength) * PRIME64_1 & mask64; + for (let i = 32; i < 160; i += 32) acc = XXH3_mix32B(acc, view(data, i - 32), view(data, i - 16), view(secret, i - 32), seed); + acc = XXH3_avalanche(acc & mask64) | XXH3_avalanche(acc >> n(64)) << n(64); + for (let i = 160; i <= data.byteLength; i += 32) acc = XXH3_mix32B(acc, view(data, i - 32), view(data, i - 16), view(secret, 3 + i - 160), seed); + acc = XXH3_mix32B(acc, view(data, data.byteLength - 16), view(data, data.byteLength - 32), view(secret, 103), inv64(seed)); + let h128l = acc + (acc >> n(64)) & mask64; + h128l = XXH3_avalanche(h128l); + let h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2; + h128h &= mask64; + h128h = inv64(XXH3_avalanche(h128h)); + return h128l | h128h << n(64); +} +function XXH3(input, seed = n(0)) { + const encoder = new TextEncoder(); + const data = view(typeof input === "string" ? encoder.encode(input) : input); + const len = data.byteLength; + const hexDigest = (data$1) => data$1.toString(16).padStart(32, "0"); + if (len <= 16) return hexDigest(XXH3_len_0to16_128b(data, seed)); + if (len <= 128) return hexDigest(XXH3_len_17to128_128b(data, kkey, seed)); + if (len <= 240) return hexDigest(XXH3_len_129to240_128b(data, kkey, seed)); + return hexDigest(XXH3_hashLong_128b(data, kkey)); +} +function isXXH3(value) { + return /^[0-9a-f]{32}$/.test(value); +} + +//#endregion + +//# sourceMappingURL=hash.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/interrupt.js + + + + + +//#region src/interrupt.ts +/** +* Interrupts the execution of a graph node. +* This function can be used to pause execution of a node, and return the value of the `resume` +* input when the graph is re-invoked using `Command`. +* Multiple interrupts can be called within a single node, and each will be handled sequentially. +* +* When an interrupt is called: +* 1. If there's a `resume` value available (from a previous `Command`), it returns that value. +* 2. Otherwise, it throws a `GraphInterrupt` with the provided value +* 3. The graph can be resumed by passing a `Command` with a `resume` value +* +* Because the `interrupt` function propagates by throwing a special `GraphInterrupt` error, +* you should avoid using `try/catch` blocks around the `interrupt` function, +* or if you do, ensure that the `GraphInterrupt` error is thrown again within your `catch` block. +* +* @param value - The value to include in the interrupt. This will be available in task.interrupts[].value +* @returns The `resume` value provided when the graph is re-invoked with a Command +* +* @example +* ```typescript +* // Define a node that uses multiple interrupts +* const nodeWithInterrupts = () => { +* // First interrupt - will pause execution and include {value: 1} in task values +* const answer1 = interrupt({ value: 1 }); +* +* // Second interrupt - only called after first interrupt is resumed +* const answer2 = interrupt({ value: 2 }); +* +* // Use the resume values +* return { myKey: answer1 + " " + answer2 }; +* }; +* +* // Resume the graph after first interrupt +* await graph.stream(new Command({ resume: "answer 1" })); +* +* // Resume the graph after second interrupt +* await graph.stream(new Command({ resume: "answer 2" })); +* // Final result: { myKey: "answer 1 answer 2" } +* ``` +* +* @throws {Error} If called outside the context of a graph +* @throws {GraphInterrupt} When no resume value is available +*/ +function interrupt(value) { + const config = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); + if (!config) throw new Error("Called interrupt() outside the context of a graph."); + const conf = config.configurable; + if (!conf) throw new Error("No configurable found in config"); + const checkpointer = conf[CONFIG_KEY_CHECKPOINTER]; + if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const scratchpad = conf[constants_CONFIG_KEY_SCRATCHPAD]; + scratchpad.interruptCounter += 1; + const idx = scratchpad.interruptCounter; + if (scratchpad.resume.length > 0 && idx < scratchpad.resume.length) { + conf[CONFIG_KEY_SEND]?.([[constants_RESUME, scratchpad.resume]]); + return scratchpad.resume[idx]; + } + if (scratchpad.nullResume !== void 0) { + if (scratchpad.resume.length !== idx) throw new Error(`Resume length mismatch: ${scratchpad.resume.length} !== ${idx}`); + const v = scratchpad.consumeNullResume(); + scratchpad.resume.push(v); + conf[CONFIG_KEY_SEND]?.([[constants_RESUME, scratchpad.resume]]); + return v; + } + const ns = conf[CONFIG_KEY_CHECKPOINT_NS]?.split(CHECKPOINT_NAMESPACE_SEPARATOR); + const id = ns ? XXH3(ns.join(CHECKPOINT_NAMESPACE_SEPARATOR)) : void 0; + throw new GraphInterrupt([{ + id, + value + }]); +} + +//#endregion + +//# sourceMappingURL=interrupt.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/utils.js + + + + +//#region src/utils.ts +var RunnableCallable = class extends Runnable { + lc_namespace = ["langgraph"]; + func; + tags; + config; + trace = true; + recurse = true; + constructor(fields) { + super(); + this.name = fields.name ?? fields.func.name; + this.func = fields.func; + this.config = fields.tags ? { tags: fields.tags } : void 0; + this.trace = fields.trace ?? this.trace; + this.recurse = fields.recurse ?? this.recurse; + } + async _tracedInvoke(input, config, runManager) { + return new Promise((resolve, reject) => { + const childConfig = config_patchConfig(config, { callbacks: runManager?.getChild() }); + async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { + try { + const output = await this.func(input, childConfig); + resolve(output); + } catch (e) { + reject(e); + } + }); + }); + } + async invoke(input, options) { + let returnValue; + const config = config_ensureLangGraphConfig(options); + const mergedConfig = mergeConfigs(this.config, config); + if (this.trace) returnValue = await this._callWithConfig(this._tracedInvoke, input, mergedConfig); + else returnValue = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig)); + if (Runnable.isRunnable(returnValue) && this.recurse) return await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig)); + return returnValue; + } +}; +function* prefixGenerator(generator, prefix) { + if (prefix === void 0) yield* generator; + else for (const value of generator) yield [prefix, value]; +} +async function gatherIterator(i) { + const out = []; + for await (const item of await i) out.push(item); + return out; +} +function gatherIteratorSync(i) { + const out = []; + for (const item of i) out.push(item); + return out; +} +function patchConfigurable(config, patch) { + if (!config) return { configurable: patch }; + else if (!("configurable" in config)) return { + ...config, + configurable: patch + }; + else return { + ...config, + configurable: { + ...config.configurable, + ...patch + } + }; +} +function utils_isAsyncGeneratorFunction(val) { + return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(async function* () {}).constructor; +} +function utils_isGeneratorFunction(val) { + return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(function* () {}).constructor; +} + +//#endregion + +//# sourceMappingURL=utils.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/write.js + + + + + +//#region src/pregel/write.ts +const SKIP_WRITE = { [Symbol.for("LG_SKIP_WRITE")]: true }; +function _isSkipWrite(x) { + return typeof x === "object" && x?.[Symbol.for("LG_SKIP_WRITE")] !== void 0; +} +const PASSTHROUGH = { [Symbol.for("LG_PASSTHROUGH")]: true }; +function _isPassthrough(x) { + return typeof x === "object" && x?.[Symbol.for("LG_PASSTHROUGH")] !== void 0; +} +const IS_WRITER = Symbol("IS_WRITER"); +/** +* Mapping of write channels to Runnables that return the value to be written, +* or None to skip writing. +*/ +var ChannelWrite = class ChannelWrite extends RunnableCallable { + writes; + constructor(writes, tags) { + const name = `ChannelWrite<${writes.map((packet) => { + if (_isSend(packet)) return packet.node; + else if ("channel" in packet) return packet.channel; + return "..."; + }).join(",")}>`; + super({ + writes, + name, + tags, + func: async (input, config) => { + return this._write(input, config ?? {}); + } + }); + this.writes = writes; + } + async _write(input, config) { + const writes = this.writes.map((write) => { + if (_isChannelWriteTupleEntry(write) && _isPassthrough(write.value)) return { + mapper: write.mapper, + value: input + }; + else if (_isChannelWriteEntry(write) && _isPassthrough(write.value)) return { + channel: write.channel, + value: input, + skipNone: write.skipNone, + mapper: write.mapper + }; + else return write; + }); + await ChannelWrite.doWrite(config, writes); + return input; + } + static async doWrite(config, writes) { + for (const w of writes) { + if (_isChannelWriteEntry(w)) { + if (w.channel === constants_TASKS) throw new InvalidUpdateError("Cannot write to the reserved channel TASKS"); + if (_isPassthrough(w.value)) throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); + } + if (_isChannelWriteTupleEntry(w)) { + if (_isPassthrough(w.value)) throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); + } + } + const writeEntries = []; + for (const w of writes) if (_isSend(w)) writeEntries.push([constants_TASKS, w]); + else if (_isChannelWriteTupleEntry(w)) { + const mappedResult = await w.mapper.invoke(w.value, config); + if (mappedResult != null && mappedResult.length > 0) writeEntries.push(...mappedResult); + } else if (_isChannelWriteEntry(w)) { + const mappedValue = w.mapper !== void 0 ? await w.mapper.invoke(w.value, config) : w.value; + if (_isSkipWrite(mappedValue)) continue; + if (w.skipNone && mappedValue === void 0) continue; + writeEntries.push([w.channel, mappedValue]); + } else throw new Error(`Invalid write entry: ${JSON.stringify(w)}`); + const write = config.configurable?.[CONFIG_KEY_SEND]; + write(writeEntries); + } + static isWriter(runnable) { + return runnable instanceof ChannelWrite || IS_WRITER in runnable && !!runnable[IS_WRITER]; + } + static registerWriter(runnable) { + return Object.defineProperty(runnable, IS_WRITER, { value: true }); + } +}; +function _isChannelWriteEntry(x) { + return x !== void 0 && typeof x.channel === "string"; +} +function _isChannelWriteTupleEntry(x) { + return x !== void 0 && !_isChannelWriteEntry(x) && Runnable.isRunnable(x.mapper); +} + +//#endregion + +//# sourceMappingURL=write.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/read.js + + + + + +//#region src/pregel/read.ts +var ChannelRead = class ChannelRead extends RunnableCallable { + lc_graph_name = "ChannelRead"; + channel; + fresh = false; + mapper; + constructor(channel, mapper, fresh = false) { + super({ func: (_, config) => ChannelRead.doRead(config, this.channel, this.fresh, this.mapper) }); + this.fresh = fresh; + this.mapper = mapper; + this.channel = channel; + this.name = Array.isArray(channel) ? `ChannelRead<${channel.join(",")}>` : `ChannelRead<${channel}>`; + } + static doRead(config, channel, fresh, mapper) { + const read = config.configurable?.[CONFIG_KEY_READ]; + if (!read) throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process"); + if (mapper) return mapper(read(channel, fresh)); + else return read(channel, fresh); + } +}; +const defaultRunnableBound = /* @__PURE__ */ new RunnablePassthrough(); +var PregelNode = class PregelNode extends RunnableBinding { + lc_graph_name = "PregelNode"; + channels; + triggers = []; + mapper; + writers = []; + bound = defaultRunnableBound; + kwargs = {}; + metadata = {}; + tags = []; + retryPolicy; + cachePolicy; + subgraphs; + ends; + constructor(fields) { + const { channels, triggers, mapper, writers, bound, kwargs, metadata, retryPolicy, cachePolicy, tags, subgraphs, ends } = fields; + const mergedTags = [...fields.config?.tags ? fields.config.tags : [], ...tags ?? []]; + super({ + ...fields, + bound: fields.bound ?? defaultRunnableBound, + config: { + ...fields.config ? fields.config : {}, + tags: mergedTags + } + }); + this.channels = channels; + this.triggers = triggers; + this.mapper = mapper; + this.writers = writers ?? this.writers; + this.bound = bound ?? this.bound; + this.kwargs = kwargs ?? this.kwargs; + this.metadata = metadata ?? this.metadata; + this.tags = mergedTags; + this.retryPolicy = retryPolicy; + this.cachePolicy = cachePolicy; + this.subgraphs = subgraphs; + this.ends = ends; + } + getWriters() { + const newWriters = [...this.writers]; + while (newWriters.length > 1 && newWriters[newWriters.length - 1] instanceof ChannelWrite && newWriters[newWriters.length - 2] instanceof ChannelWrite) { + const endWriters = newWriters.slice(-2); + const combinedWrites = endWriters[0].writes.concat(endWriters[1].writes); + newWriters[newWriters.length - 2] = new ChannelWrite(combinedWrites, endWriters[0].config?.tags); + newWriters.pop(); + } + return newWriters; + } + getNode() { + const writers = this.getWriters(); + if (this.bound === defaultRunnableBound && writers.length === 0) return void 0; + else if (this.bound === defaultRunnableBound && writers.length === 1) return writers[0]; + else if (this.bound === defaultRunnableBound) return new RunnableSequence({ + first: writers[0], + middle: writers.slice(1, writers.length - 1), + last: writers[writers.length - 1], + omitSequenceTags: true + }); + else if (writers.length > 0) return new RunnableSequence({ + first: this.bound, + middle: writers.slice(0, writers.length - 1), + last: writers[writers.length - 1], + omitSequenceTags: true + }); + else return this.bound; + } + join(channels) { + if (!Array.isArray(channels)) throw new Error("channels must be a list"); + if (typeof this.channels !== "object") throw new Error("all channels must be named when using .join()"); + return new PregelNode({ + channels: { + ...this.channels, + ...Object.fromEntries(channels.map((chan) => [chan, chan])) + }, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: this.bound, + kwargs: this.kwargs, + config: this.config, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); + } + pipe(coerceable) { + if (ChannelWrite.isWriter(coerceable)) return new PregelNode({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: [...this.writers, coerceable], + bound: this.bound, + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); + else if (this.bound === defaultRunnableBound) return new PregelNode({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: _coerceToRunnable(coerceable), + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); + else return new PregelNode({ + channels: this.channels, + triggers: this.triggers, + mapper: this.mapper, + writers: this.writers, + bound: this.bound.pipe(coerceable), + config: this.config, + kwargs: this.kwargs, + retryPolicy: this.retryPolicy, + cachePolicy: this.cachePolicy + }); + } +}; + +//#endregion + +//# sourceMappingURL=read.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/utils/subgraph.js +//#region src/pregel/utils/subgraph.ts +function isRunnableSequence(x) { + return "steps" in x && Array.isArray(x.steps); +} +function isPregelLike(x) { + return "lg_is_pregel" in x && x.lg_is_pregel === true; +} +function findSubgraphPregel(candidate) { + const candidates = [candidate]; + for (const candidate$1 of candidates) if (isPregelLike(candidate$1)) return candidate$1; + else if (isRunnableSequence(candidate$1)) candidates.push(...candidate$1.steps); + return void 0; +} + +//#endregion + +//# sourceMappingURL=subgraph.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/io.js + + + + +//#region src/pregel/io.ts +function readChannel(channels, chan, catchErrors = true, returnException = false) { + try { + return channels[chan].get(); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) { + if (returnException) return e; + else if (catchErrors) return null; + } + throw e; + } +} +function readChannels(channels, select, skipEmpty = true) { + if (Array.isArray(select)) { + const values = {}; + for (const k of select) try { + values[k] = readChannel(channels, k, !skipEmpty); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) continue; + } + return values; + } else return readChannel(channels, select); +} +/** +* Map input chunk to a sequence of pending writes in the form (channel, value). +*/ +function* mapCommand(cmd, pendingWrites) { + if (cmd.graph === Command.PARENT) throw new InvalidUpdateError("There is no parent graph."); + if (cmd.goto) { + let sends; + if (Array.isArray(cmd.goto)) sends = cmd.goto; + else sends = [cmd.goto]; + for (const send of sends) if (_isSend(send)) yield [ + NULL_TASK_ID, + constants_TASKS, + send + ]; + else if (typeof send === "string") yield [ + NULL_TASK_ID, + `branch:to:${send}`, + "__start__" + ]; + else throw new Error(`In Command.send, expected Send or string, got ${typeof send}`); + } + if (cmd.resume) if (typeof cmd.resume === "object" && Object.keys(cmd.resume).length && Object.keys(cmd.resume).every(isXXH3)) for (const [tid, resume] of Object.entries(cmd.resume)) { + const existing = pendingWrites.filter((w) => w[0] === tid && w[1] === constants_RESUME).map((w) => w[2]).slice(0, 1) ?? []; + existing.push(resume); + yield [ + tid, + constants_RESUME, + existing + ]; + } + else yield [ + NULL_TASK_ID, + constants_RESUME, + cmd.resume + ]; + if (cmd.update) { + if (typeof cmd.update !== "object" || !cmd.update) throw new Error("Expected cmd.update to be a dict mapping channel names to update values"); + if (Array.isArray(cmd.update)) for (const [k, v] of cmd.update) yield [ + NULL_TASK_ID, + k, + v + ]; + else for (const [k, v] of Object.entries(cmd.update)) yield [ + NULL_TASK_ID, + k, + v + ]; + } +} +/** +* Map input chunk to a sequence of pending writes in the form [channel, value]. +*/ +function* mapInput(inputChannels, chunk) { + if (chunk !== void 0 && chunk !== null) if (Array.isArray(inputChannels) && typeof chunk === "object" && !Array.isArray(chunk)) { + for (const k in chunk) if (inputChannels.includes(k)) yield [k, chunk[k]]; + } else if (Array.isArray(inputChannels)) throw new Error(`Input chunk must be an object when "inputChannels" is an array`); + else yield [inputChannels, chunk]; +} +/** +* Map pending writes (a sequence of tuples (channel, value)) to output chunk. +*/ +function* mapOutputValues(outputChannels, pendingWrites, channels) { + if (Array.isArray(outputChannels)) { + if (pendingWrites === true || pendingWrites.find(([chan, _]) => outputChannels.includes(chan))) yield readChannels(channels, outputChannels); + } else if (pendingWrites === true || pendingWrites.some(([chan, _]) => chan === outputChannels)) yield readChannel(channels, outputChannels); +} +/** +* Map pending writes (a sequence of tuples (channel, value)) to output chunk. +* @internal +* +* @param outputChannels - The channels to output. +* @param tasks - The tasks to output. +* @param cached - Whether the output is cached. +* +* @returns A generator that yields the output chunk (if any). +*/ +function* mapOutputUpdates(outputChannels, tasks, cached) { + const outputTasks = tasks.filter(([task, ww]) => { + return (task.config === void 0 || !task.config.tags?.includes(TAG_HIDDEN)) && ww[0][0] !== constants_ERROR && ww[0][0] !== constants_INTERRUPT; + }); + if (!outputTasks.length) return; + let updated; + if (outputTasks.some(([task]) => task.writes.some(([chan, _]) => chan === RETURN))) updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === RETURN).map(([_, value]) => [task.name, value])); + else if (!Array.isArray(outputChannels)) updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === outputChannels).map(([_, value]) => [task.name, value])); + else updated = outputTasks.flatMap(([task]) => { + const { writes } = task; + const counts = {}; + for (const [chan] of writes) if (outputChannels.includes(chan)) counts[chan] = (counts[chan] || 0) + 1; + if (Object.values(counts).some((count) => count > 1)) return writes.filter(([chan]) => outputChannels.includes(chan)).map(([chan, value]) => [task.name, { [chan]: value }]); + else return [[task.name, Object.fromEntries(writes.filter(([chan]) => outputChannels.includes(chan)))]]; + }); + const grouped = {}; + for (const [node, value] of updated) { + if (!(node in grouped)) grouped[node] = []; + grouped[node].push(value); + } + const flattened = {}; + for (const node in grouped) if (grouped[node].length === 1) { + const [write] = grouped[node]; + flattened[node] = write; + } else flattened[node] = grouped[node]; + if (cached) flattened["__metadata__"] = { cached }; + yield flattened; +} + +//#endregion + +//# sourceMappingURL=io.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/utils/index.js + + +//#region src/pregel/utils/index.ts +function getNullChannelVersion(currentVersions) { + const startVersion = typeof currentVersions[START]; + if (startVersion === "number") return 0; + if (startVersion === "string") return ""; + for (const key in currentVersions) { + if (!Object.prototype.hasOwnProperty.call(currentVersions, key)) continue; + const versionType = typeof currentVersions[key]; + if (versionType === "number") return 0; + if (versionType === "string") return ""; + break; + } + return void 0; +} +function getNewChannelVersions(previousVersions, currentVersions) { + if (Object.keys(previousVersions).length > 0) { + const nullVersion = getNullChannelVersion(currentVersions); + return Object.fromEntries(Object.entries(currentVersions).filter(([k, v]) => v > (previousVersions[k] ?? nullVersion))); + } else return currentVersions; +} +function utils_coerceToDict(value, defaultKey) { + return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; +} +function utils_patchConfigurable(config, patch) { + if (config === null) return { configurable: patch }; + else if (config?.configurable === void 0) return { + ...config, + configurable: patch + }; + else return { + ...config, + configurable: { + ...config.configurable, + ...patch + } + }; +} +function patchCheckpointMap(config, metadata) { + const parents = metadata?.parents ?? {}; + if (Object.keys(parents).length > 0) return utils_patchConfigurable(config, { [CONFIG_KEY_CHECKPOINT_MAP]: { + ...parents, + [config.configurable?.checkpoint_ns ?? ""]: config.configurable?.checkpoint_id + } }); + else return config; +} +/** +* Combine multiple abort signals into a single abort signal. +* @param signals - The abort signals to combine. +* @returns A combined abort signal and a dispose function to remove the abort listener if unused. +*/ +function combineAbortSignals(...x) { + const signals = [...new Set(x.filter(Boolean))]; + if (signals.length === 0) return { + signal: void 0, + dispose: void 0 + }; + if (signals.length === 1) return { + signal: signals[0], + dispose: void 0 + }; + const combinedController = new AbortController(); + const listener = () => { + const reason = signals.find((s) => s.aborted)?.reason; + combinedController.abort(reason); + signals.forEach((s) => s.removeEventListener("abort", listener)); + }; + signals.forEach((s) => s.addEventListener("abort", listener, { once: true })); + const hasAlreadyAbortedSignal = signals.find((s) => s.aborted); + if (hasAlreadyAbortedSignal) combinedController.abort(hasAlreadyAbortedSignal.reason); + return { + signal: combinedController.signal, + dispose: () => { + signals.forEach((s) => s.removeEventListener("abort", listener)); + } + }; +} +/** +* Combine multiple callbacks into a single callback. +* @param callback1 - The first callback to combine. +* @param callback2 - The second callback to combine. +* @returns A single callback that is a combination of the input callbacks. +*/ +const combineCallbacks = (callback1, callback2) => { + if (!callback1 && !callback2) return void 0; + if (!callback1) return callback2; + if (!callback2) return callback1; + if (Array.isArray(callback1) && Array.isArray(callback2)) return [...callback1, ...callback2]; + if (Array.isArray(callback1)) return [...callback1, callback2]; + if (Array.isArray(callback2)) return [callback1, ...callback2]; + return [callback1, callback2]; +}; + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/types.js +//#region src/pregel/types.ts +var Call = class { + func; + name; + input; + retry; + cache; + callbacks; + __lg_type = "call"; + constructor({ func, name, input, retry, cache, callbacks }) { + this.func = func; + this.name = name; + this.input = input; + this.retry = retry; + this.cache = cache; + this.callbacks = callbacks; + } +}; +function isCall(value) { + return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "call"; +} + +//#endregion + +//# sourceMappingURL=types.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/call.js + + + + + + +//#region src/pregel/call.ts +/** +* Wraps a user function in a Runnable that writes the returned value to the RETURN channel. +*/ +function getRunnableForFunc(name, func) { + const run = new RunnableCallable({ + func: (input) => func(...input), + name, + trace: false, + recurse: false + }); + return new RunnableSequence({ + name, + first: run, + last: new ChannelWrite([{ + channel: RETURN, + value: PASSTHROUGH + }], [TAG_HIDDEN]) + }); +} +function getRunnableForEntrypoint(name, func) { + const run = new RunnableCallable({ + func: (input, config) => { + return func(input, config); + }, + name, + trace: false, + recurse: false + }); + return run; +} +function call_call({ func, name, cache, retry }, ...args) { + const config = AsyncLocalStorageProviderSingleton.getRunnableConfig(); + if (typeof config.configurable?.[CONFIG_KEY_CALL] === "function") return config.configurable[CONFIG_KEY_CALL](func, name, args, { + retry, + cache, + callbacks: config.callbacks + }); + throw new Error("Async local storage not initialized. Please call initializeAsyncLocalStorageSingleton() before using this function."); +} + +//#endregion + +//# sourceMappingURL=call.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/algo.js + + + + + + + + + + + +//#region src/pregel/algo.ts +const increment = (current) => { + return current !== void 0 ? current + 1 : 1; +}; +function triggersNextStep(updatedChannels, triggerToNodes) { + if (triggerToNodes == null) return false; + for (const chan of updatedChannels) if (triggerToNodes[chan]) return true; + return false; +} +function maxChannelMapVersion(channelVersions) { + let maxVersion; + for (const chan in channelVersions) { + if (!Object.prototype.hasOwnProperty.call(channelVersions, chan)) continue; + if (maxVersion == null) maxVersion = channelVersions[chan]; + else maxVersion = maxChannelVersion(maxVersion, channelVersions[chan]); + } + return maxVersion; +} +function shouldInterrupt(checkpoint, interruptNodes, tasks) { + const nullVersion = getNullChannelVersion(checkpoint.channel_versions); + const seen = checkpoint.versions_seen[constants_INTERRUPT] ?? {}; + let anyChannelUpdated = false; + if ((checkpoint.channel_versions[START] ?? nullVersion) > (seen[START] ?? nullVersion)) anyChannelUpdated = true; + else for (const chan in checkpoint.channel_versions) { + if (!Object.prototype.hasOwnProperty.call(checkpoint.channel_versions, chan)) continue; + if (checkpoint.channel_versions[chan] > (seen[chan] ?? nullVersion)) { + anyChannelUpdated = true; + break; + } + } + const anyTriggeredNodeInInterruptNodes = tasks.some((task) => interruptNodes === "*" ? !task.config?.tags?.includes(TAG_HIDDEN) : interruptNodes.includes(task.name)); + return anyChannelUpdated && anyTriggeredNodeInInterruptNodes; +} +function _localRead(checkpoint, channels, task, select, fresh = false) { + let updated = /* @__PURE__ */ new Set(); + if (!Array.isArray(select)) { + for (const [c] of task.writes) if (c === select) { + updated = new Set([c]); + break; + } + updated = updated || /* @__PURE__ */ new Set(); + } else updated = new Set(select.filter((c) => task.writes.some(([key, _]) => key === c))); + let values; + if (fresh && updated.size > 0) { + const localChannels = Object.fromEntries(Object.entries(channels).filter(([k, _]) => updated.has(k))); + const newCheckpoint = createCheckpoint(checkpoint, localChannels, -1); + const newChannels = emptyChannels(localChannels, newCheckpoint); + _applyWrites(copyCheckpoint(newCheckpoint), newChannels, [task], void 0, void 0); + values = readChannels({ + ...channels, + ...newChannels + }, select); + } else values = readChannels(channels, select); + return values; +} +function _localWrite(commit, processes, writes) { + for (const [chan, value] of writes) if ([PUSH, constants_TASKS].includes(chan) && value != null) { + if (!_isSend(value)) throw new InvalidUpdateError(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(value)}`); + if (!(value.node in processes)) throw new InvalidUpdateError(`Invalid node name "${value.node}" in Send packet`); + } + commit(writes); +} +const IGNORE = new Set([ + NO_WRITES, + PUSH, + constants_RESUME, + constants_INTERRUPT, + RETURN, + constants_ERROR +]); +function _applyWrites(checkpoint, channels, tasks, getNextVersion, triggerToNodes) { + tasks.sort((a, b) => { + const aPath = a.path?.slice(0, 3) || []; + const bPath = b.path?.slice(0, 3) || []; + for (let i = 0; i < Math.min(aPath.length, bPath.length); i += 1) { + if (aPath[i] < bPath[i]) return -1; + if (aPath[i] > bPath[i]) return 1; + } + return aPath.length - bPath.length; + }); + const bumpStep = tasks.some((task) => task.triggers.length > 0); + const onlyChannels = getOnlyChannels(channels); + for (const task of tasks) { + checkpoint.versions_seen[task.name] ??= {}; + for (const chan of task.triggers) if (chan in checkpoint.channel_versions) checkpoint.versions_seen[task.name][chan] = checkpoint.channel_versions[chan]; + } + let maxVersion = maxChannelMapVersion(checkpoint.channel_versions); + const channelsToConsume = new Set(tasks.flatMap((task) => task.triggers).filter((chan) => !RESERVED.includes(chan))); + let usedNewVersion = false; + for (const chan of channelsToConsume) if (chan in onlyChannels && onlyChannels[chan].consume()) { + if (getNextVersion !== void 0) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + usedNewVersion = true; + } + } + const pendingWritesByChannel = {}; + for (const task of tasks) for (const [chan, val] of task.writes) if (IGNORE.has(chan)) {} else if (chan in onlyChannels) { + pendingWritesByChannel[chan] ??= []; + pendingWritesByChannel[chan].push(val); + } + if (maxVersion != null && getNextVersion != null) maxVersion = usedNewVersion ? getNextVersion(maxVersion) : maxVersion; + const updatedChannels = /* @__PURE__ */ new Set(); + for (const [chan, vals] of Object.entries(pendingWritesByChannel)) if (chan in onlyChannels) { + const channel = onlyChannels[chan]; + let updated; + try { + updated = channel.update(vals); + } catch (e) { + if (e.name === InvalidUpdateError.unminifiable_name) { + const wrappedError = new InvalidUpdateError(`Invalid update for channel "${chan}" with values ${JSON.stringify(vals)}: ${e.message}`); + wrappedError.lc_error_code = e.lc_error_code; + throw wrappedError; + } else throw e; + } + if (updated && getNextVersion !== void 0) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) updatedChannels.add(chan); + } + } + if (bumpStep) for (const chan in onlyChannels) { + if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue; + const channel = onlyChannels[chan]; + if (channel.isAvailable() && !updatedChannels.has(chan)) { + const updated = channel.update([]); + if (updated && getNextVersion !== void 0) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) updatedChannels.add(chan); + } + } + } + if (bumpStep && !triggersNextStep(updatedChannels, triggerToNodes)) for (const chan in onlyChannels) { + if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue; + const channel = onlyChannels[chan]; + if (channel.finish() && getNextVersion !== void 0) { + checkpoint.channel_versions[chan] = getNextVersion(maxVersion); + if (channel.isAvailable()) updatedChannels.add(chan); + } + } + return updatedChannels; +} +function* candidateNodes(checkpoint, processes, extra) { + if (extra.updatedChannels != null && extra.triggerToNodes != null) { + const triggeredNodes = /* @__PURE__ */ new Set(); + for (const channel of extra.updatedChannels) { + const nodeIds = extra.triggerToNodes[channel]; + for (const id of nodeIds ?? []) triggeredNodes.add(id); + } + yield* [...triggeredNodes].sort(); + return; + } + const isEmptyChannelVersions = (() => { + for (const chan in checkpoint.channel_versions) if (checkpoint.channel_versions[chan] !== null) return false; + return true; + })(); + if (isEmptyChannelVersions) return; + for (const name in processes) { + if (!Object.prototype.hasOwnProperty.call(processes, name)) continue; + yield name; + } +} +/** +* Prepare the set of tasks that will make up the next Pregel step. +* This is the union of all PUSH tasks (Sends) and PULL tasks (nodes triggered +* by edges). +*/ +function _prepareNextTasks(checkpoint, pendingWrites, processes, channels, config, forExecution, extra) { + const tasks = {}; + const tasksChannel = channels[constants_TASKS]; + if (tasksChannel?.isAvailable()) { + const len = tasksChannel.get().length; + for (let i = 0; i < len; i += 1) { + const task = _prepareSingleTask([PUSH, i], checkpoint, pendingWrites, processes, channels, config, forExecution, extra); + if (task !== void 0) tasks[task.id] = task; + } + } + for (const name of candidateNodes(checkpoint, processes, extra)) { + const task = _prepareSingleTask([PULL, name], checkpoint, pendingWrites, processes, channels, config, forExecution, extra); + if (task !== void 0) tasks[task.id] = task; + } + return tasks; +} +/** +* Prepares a single task for the next Pregel step, given a task path, which +* uniquely identifies a PUSH or PULL task within the graph. +*/ +function _prepareSingleTask(taskPath, checkpoint, pendingWrites, processes, channels, config, forExecution, extra) { + const { step, checkpointer, manager } = extra; + const configurable = config.configurable ?? {}; + const parentNamespace = configurable.checkpoint_ns ?? ""; + if (taskPath[0] === PUSH && isCall(taskPath[taskPath.length - 1])) { + const call = taskPath[taskPath.length - 1]; + const proc = getRunnableForFunc(call.name, call.func); + const triggers = [PUSH]; + const checkpointNamespace = parentNamespace === "" ? call.name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${call.name}`; + const id = uuid5(JSON.stringify([ + checkpointNamespace, + step.toString(), + call.name, + PUSH, + taskPath[1], + taskPath[2] + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${id}`; + const outputTaskPath = [...taskPath.slice(0, 3), true]; + const metadata = { + langgraph_step: step, + langgraph_node: call.name, + langgraph_triggers: triggers, + langgraph_path: outputTaskPath, + langgraph_checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const writes = []; + const task = { + name: call.name, + input: call.input, + proc, + writes, + config: config_patchConfig(mergeConfigs(config, { + metadata, + store: extra.store ?? config.store + }), { + runName: call.name, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID]: id, + [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { + name: call.name, + writes, + triggers, + path: outputTaskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER], + [CONFIG_KEY_CHECKPOINT_MAP]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP], + [parentNamespace]: checkpoint.id + }, + [constants_CONFIG_KEY_SCRATCHPAD]: _scratchpad({ + pendingWrites: pendingWrites ?? [], + taskId: id, + currentTaskInput: call.input, + resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], + namespaceHash: XXH3(taskCheckpointNamespace) + }), + [constants_CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], + checkpoint_id: void 0, + checkpoint_ns: taskCheckpointNamespace + } + }), + triggers, + retry_policy: call.retry, + cache_key: call.cache ? { + key: XXH3((call.cache.keyFunc ?? JSON.stringify)([call.input])), + ns: [CACHE_NS_WRITES, call.name ?? "__dynamic__"], + ttl: call.cache.ttl + } : void 0, + id, + path: outputTaskPath, + writers: [] + }; + return task; + } else return { + id, + name: call.name, + interrupts: [], + path: outputTaskPath + }; + } else if (taskPath[0] === PUSH) { + const index = typeof taskPath[1] === "number" ? taskPath[1] : parseInt(taskPath[1], 10); + if (!channels[constants_TASKS]?.isAvailable()) return void 0; + const sends = channels[constants_TASKS].get(); + if (index < 0 || index >= sends.length) return void 0; + const packet = _isSendInterface(sends[index]) && !_isSend(sends[index]) ? new Send(sends[index].node, sends[index].args) : sends[index]; + if (!_isSendInterface(packet)) { + console.warn(`Ignoring invalid packet ${JSON.stringify(packet)} in pending sends.`); + return void 0; + } + if (!(packet.node in processes)) { + console.warn(`Ignoring unknown node name ${packet.node} in pending sends.`); + return void 0; + } + const triggers = [PUSH]; + const checkpointNamespace = parentNamespace === "" ? packet.node : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${packet.node}`; + const taskId = uuid5(JSON.stringify([ + checkpointNamespace, + step.toString(), + packet.node, + PUSH, + index.toString() + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${taskId}`; + let metadata = { + langgraph_step: step, + langgraph_node: packet.node, + langgraph_triggers: triggers, + langgraph_path: taskPath.slice(0, 3), + langgraph_checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const proc = processes[packet.node]; + const node = proc.getNode(); + if (node !== void 0) { + if (proc.metadata !== void 0) metadata = { + ...metadata, + ...proc.metadata + }; + const writes = []; + return { + name: packet.node, + input: packet.args, + proc: node, + subgraphs: proc.subgraphs, + writes, + config: config_patchConfig(mergeConfigs(config, { + metadata, + tags: proc.tags, + store: extra.store ?? config.store + }), { + runName: packet.node, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID]: taskId, + [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { + name: packet.node, + writes, + triggers, + path: taskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER], + [CONFIG_KEY_CHECKPOINT_MAP]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP], + [parentNamespace]: checkpoint.id + }, + [constants_CONFIG_KEY_SCRATCHPAD]: _scratchpad({ + pendingWrites: pendingWrites ?? [], + taskId, + currentTaskInput: packet.args, + resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], + namespaceHash: XXH3(taskCheckpointNamespace) + }), + [constants_CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], + checkpoint_id: void 0, + checkpoint_ns: taskCheckpointNamespace + } + }), + triggers, + retry_policy: proc.retryPolicy, + cache_key: proc.cachePolicy ? { + key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([packet.args])), + ns: [ + CACHE_NS_WRITES, + proc.name ?? "__dynamic__", + packet.node + ], + ttl: proc.cachePolicy.ttl + } : void 0, + id: taskId, + path: taskPath, + writers: proc.getWriters() + }; + } + } else return { + id: taskId, + name: packet.node, + interrupts: [], + path: taskPath + }; + } else if (taskPath[0] === PULL) { + const name = taskPath[1].toString(); + const proc = processes[name]; + if (proc === void 0) return void 0; + if (pendingWrites?.length) { + const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${name}`; + const taskId = uuid5(JSON.stringify([ + checkpointNamespace, + step.toString(), + name, + PULL, + name + ]), checkpoint.id); + const hasSuccessfulWrites = pendingWrites.some((w) => w[0] === taskId && w[1] !== constants_ERROR); + if (hasSuccessfulWrites) return void 0; + } + const nullVersion = getNullChannelVersion(checkpoint.channel_versions); + if (nullVersion === void 0) return void 0; + const seen = checkpoint.versions_seen[name] ?? {}; + const trigger = proc.triggers.find((chan) => { + if (!channels[chan].isAvailable()) return false; + return (checkpoint.channel_versions[chan] ?? nullVersion) > (seen[chan] ?? nullVersion); + }); + if (trigger !== void 0) { + const val = _procInput(proc, channels, forExecution); + if (val === void 0) return void 0; + const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${name}`; + const taskId = uuid5(JSON.stringify([ + checkpointNamespace, + step.toString(), + name, + PULL, + [trigger] + ]), checkpoint.id); + const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${taskId}`; + let metadata = { + langgraph_step: step, + langgraph_node: name, + langgraph_triggers: [trigger], + langgraph_path: taskPath, + langgraph_checkpoint_ns: taskCheckpointNamespace + }; + if (forExecution) { + const node = proc.getNode(); + if (node !== void 0) { + if (proc.metadata !== void 0) metadata = { + ...metadata, + ...proc.metadata + }; + const writes = []; + return { + name, + input: val, + proc: node, + subgraphs: proc.subgraphs, + writes, + config: config_patchConfig(mergeConfigs(config, { + metadata, + tags: proc.tags, + store: extra.store ?? config.store + }), { + runName: name, + callbacks: manager?.getChild(`graph:step:${step}`), + configurable: { + [CONFIG_KEY_TASK_ID]: taskId, + [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => { + writes.push(...items); + }, processes, writes_), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { + name, + writes, + triggers: [trigger], + path: taskPath + }, select_, fresh_), + [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER], + [CONFIG_KEY_CHECKPOINT_MAP]: { + ...configurable[CONFIG_KEY_CHECKPOINT_MAP], + [parentNamespace]: checkpoint.id + }, + [constants_CONFIG_KEY_SCRATCHPAD]: _scratchpad({ + pendingWrites: pendingWrites ?? [], + taskId, + currentTaskInput: val, + resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], + namespaceHash: XXH3(taskCheckpointNamespace) + }), + [constants_CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], + checkpoint_id: void 0, + checkpoint_ns: taskCheckpointNamespace + } + }), + triggers: [trigger], + retry_policy: proc.retryPolicy, + cache_key: proc.cachePolicy ? { + key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([val])), + ns: [ + CACHE_NS_WRITES, + proc.name ?? "__dynamic__", + name + ], + ttl: proc.cachePolicy.ttl + } : void 0, + id: taskId, + path: taskPath, + writers: proc.getWriters() + }; + } + } else return { + id: taskId, + name, + interrupts: [], + path: taskPath + }; + } + } + return void 0; +} +/** +* Function injected under CONFIG_KEY_READ in task config, to read current state. +* Used by conditional edges to read a copy of the state with reflecting the writes +* from that node only. +* +* @internal +*/ +function _procInput(proc, channels, forExecution) { + let val; + if (typeof proc.channels === "object" && !Array.isArray(proc.channels)) { + val = {}; + for (const [k, chan] of Object.entries(proc.channels)) if (proc.triggers.includes(chan)) try { + val[k] = readChannel(channels, chan, false); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) return void 0; + else throw e; + } + else if (chan in channels) try { + val[k] = readChannel(channels, chan, false); + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) continue; + else throw e; + } + } else if (Array.isArray(proc.channels)) { + let successfulRead = false; + for (const chan of proc.channels) try { + val = readChannel(channels, chan, false); + successfulRead = true; + break; + } catch (e) { + if (e.name === EmptyChannelError.unminifiable_name) continue; + else throw e; + } + if (!successfulRead) return void 0; + } else throw new Error(`Invalid channels type, expected list or dict, got ${proc.channels}`); + if (forExecution && proc.mapper !== void 0) val = proc.mapper(val); + return val; +} +function _scratchpad({ pendingWrites, taskId, currentTaskInput, resumeMap, namespaceHash }) { + const nullResume = pendingWrites.find(([writeTaskId, chan]) => writeTaskId === NULL_TASK_ID && chan === constants_RESUME)?.[2]; + const resume = (() => { + const result = pendingWrites.filter(([writeTaskId, chan]) => writeTaskId === taskId && chan === constants_RESUME).flatMap(([_writeTaskId, _chan, resume$1]) => resume$1); + if (resumeMap != null && namespaceHash in resumeMap) { + const mappedResume = resumeMap[namespaceHash]; + result.push(mappedResume); + } + return result; + })(); + const scratchpad = { + callCounter: 0, + interruptCounter: -1, + resume, + nullResume, + subgraphCounter: 0, + currentTaskInput, + consumeNullResume: () => { + if (scratchpad.nullResume) { + delete scratchpad.nullResume; + pendingWrites.splice(pendingWrites.findIndex(([writeTaskId, chan]) => writeTaskId === NULL_TASK_ID && chan === constants_RESUME), 1); + return nullResume; + } + return void 0; + } + }; + return scratchpad; +} + +//#endregion + +//# sourceMappingURL=algo.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/debug.js + + + + +//#region src/pregel/debug.ts +const COLORS_MAP = { + blue: { + start: "\x1B[34m", + end: "\x1B[0m" + }, + green: { + start: "\x1B[32m", + end: "\x1B[0m" + }, + yellow: { + start: "\x1B[33;1m", + end: "\x1B[0m" + } +}; +/** +* Wrap some text in a color for printing to the console. +*/ +const debug_wrap = (color, text) => `${color.start}${text}${color.end}`; +function* mapDebugTasks(tasks) { + for (const { id, name, input, config, triggers, writes } of tasks) { + if (config?.tags?.includes(TAG_HIDDEN)) continue; + const interrupts = writes.filter(([writeId, n]) => { + return writeId === id && n === constants_INTERRUPT; + }).map(([, v]) => { + return v; + }); + yield { + id, + name, + input, + triggers, + interrupts + }; + } +} +function isMultipleChannelWrite(value) { + if (typeof value !== "object" || value === null) return false; + return "$writes" in value && Array.isArray(value.$writes); +} +function mapTaskResultWrites(writes) { + const result = {}; + for (const [channel, value] of writes) { + const strChannel = String(channel); + if (strChannel in result) { + const channelWrites = isMultipleChannelWrite(result[strChannel]) ? result[strChannel].$writes : [result[strChannel]]; + channelWrites.push(value); + result[strChannel] = { $writes: channelWrites }; + } else result[strChannel] = value; + } + return result; +} +function* mapDebugTaskResults(tasks, streamChannels) { + for (const [{ id, name, config }, writes] of tasks) { + if (config?.tags?.includes(TAG_HIDDEN)) continue; + yield { + id, + name, + result: mapTaskResultWrites(writes.filter(([channel]) => { + return Array.isArray(streamChannels) ? streamChannels.includes(channel) : channel === streamChannels; + })), + interrupts: writes.filter((w) => w[0] === constants_INTERRUPT).map((w) => w[1]) + }; + } +} +function* mapDebugCheckpoint(config, channels, streamChannels, metadata, tasks, pendingWrites, parentConfig, outputKeys) { + function formatConfig(config$1) { + const pyConfig = {}; + if (config$1.callbacks != null) pyConfig.callbacks = config$1.callbacks; + if (config$1.configurable != null) pyConfig.configurable = config$1.configurable; + if (config$1.maxConcurrency != null) pyConfig.max_concurrency = config$1.maxConcurrency; + if (config$1.metadata != null) pyConfig.metadata = config$1.metadata; + if (config$1.recursionLimit != null) pyConfig.recursion_limit = config$1.recursionLimit; + if (config$1.runId != null) pyConfig.run_id = config$1.runId; + if (config$1.runName != null) pyConfig.run_name = config$1.runName; + if (config$1.tags != null) pyConfig.tags = config$1.tags; + return pyConfig; + } + const parentNs = config.configurable?.checkpoint_ns; + const taskStates = {}; + for (const task of tasks) { + const candidates = task.subgraphs?.length ? task.subgraphs : [task.proc]; + if (!candidates.find(findSubgraphPregel)) continue; + let taskNs = `${task.name}:${task.id}`; + if (parentNs) taskNs = `${parentNs}|${taskNs}`; + taskStates[task.id] = { configurable: { + thread_id: config.configurable?.thread_id, + checkpoint_ns: taskNs + } }; + } + yield { + config: formatConfig(config), + values: readChannels(channels, streamChannels), + metadata, + next: tasks.map((task) => task.name), + tasks: tasksWithWrites(tasks, pendingWrites, taskStates, outputKeys), + parentConfig: parentConfig ? formatConfig(parentConfig) : void 0 + }; +} +function tasksWithWrites(tasks, pendingWrites, states, outputKeys) { + return tasks.map((task) => { + const error = pendingWrites.find(([id, n]) => id === task.id && n === constants_ERROR)?.[2]; + const interrupts = pendingWrites.filter(([id, n]) => id === task.id && n === constants_INTERRUPT).map(([, , v]) => v); + const result = (() => { + if (error || interrupts.length || !pendingWrites.length) return void 0; + const idx = pendingWrites.findIndex(([tid, n]) => tid === task.id && n === RETURN); + if (idx >= 0) return pendingWrites[idx][2]; + if (typeof outputKeys === "string") return pendingWrites.find(([tid, n]) => tid === task.id && n === outputKeys)?.[2]; + if (Array.isArray(outputKeys)) { + const results = pendingWrites.filter(([tid, n]) => tid === task.id && outputKeys.includes(n)).map(([, n, v]) => [n, v]); + if (!results.length) return void 0; + return mapTaskResultWrites(results); + } + return void 0; + })(); + if (error) return { + id: task.id, + name: task.name, + path: task.path, + error, + interrupts, + result + }; + const taskState = states?.[task.id]; + return { + id: task.id, + name: task.name, + path: task.path, + interrupts, + ...taskState !== void 0 ? { state: taskState } : {}, + result + }; + }); +} +function printStepCheckpoint(step, channels, whitelist) { + console.log([ + `${debug_wrap(COLORS_MAP.blue, `[${step}:checkpoint]`)}`, + `\x1b[1m State at the end of step ${step}:\x1b[0m\n`, + JSON.stringify(readChannels(channels, whitelist), null, 2) + ].join("")); +} +function printStepTasks(step, nextTasks) { + const nTasks = nextTasks.length; + console.log([ + `${debug_wrap(COLORS_MAP.blue, `[${step}:tasks]`)}`, + `\x1b[1m Starting step ${step} with ${nTasks} task${nTasks === 1 ? "" : "s"}:\x1b[0m\n`, + nextTasks.map((task) => `- ${debug_wrap(COLORS_MAP.green, String(task.name))} -> ${JSON.stringify(task.input, null, 2)}`).join("\n") + ].join("")); +} +function printStepWrites(step, writes, whitelist) { + const byChannel = {}; + for (const [channel, value] of writes) if (whitelist.includes(channel)) { + if (!byChannel[channel]) byChannel[channel] = []; + byChannel[channel].push(value); + } + console.log([ + `${debug_wrap(COLORS_MAP.blue, `[${step}:writes]`)}`, + `\x1b[1m Finished step ${step} with writes to ${Object.keys(byChannel).length} channel${Object.keys(byChannel).length !== 1 ? "s" : ""}:\x1b[0m\n`, + Object.entries(byChannel).map(([name, vals]) => `- ${debug_wrap(COLORS_MAP.yellow, name)} -> ${vals.map((v) => JSON.stringify(v)).join(", ")}`).join("\n") + ].join("")); +} + +//#endregion + +//# sourceMappingURL=debug.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/stream.js + + +//#region src/pregel/stream.ts +/** +* A wrapper around an IterableReadableStream that allows for aborting the stream when +* {@link cancel} is called. +*/ +var IterableReadableStreamWithAbortSignal = class extends IterableReadableStream { + _abortController; + _innerReader; + /** + * @param readableStream - The stream to wrap. + * @param abortController - The abort controller to use. Optional. One will be created if not provided. + */ + constructor(readableStream, abortController) { + const reader = readableStream.getReader(); + const ac = abortController ?? new AbortController(); + super({ start(controller) { + return pump(); + function pump() { + return reader.read().then(({ done, value }) => { + if (done) { + controller.close(); + return; + } + controller.enqueue(value); + return pump(); + }); + } + } }); + this._abortController = ac; + this._innerReader = reader; + } + /** + * Aborts the stream, abandoning any pending operations in progress. Calling this triggers an + * {@link AbortSignal} that is propagated to the tasks that are producing the data for this stream. + * @param reason - The reason for aborting the stream. Optional. + */ + async cancel(reason) { + this._abortController.abort(reason); + this._innerReader.releaseLock(); + } + /** + * The {@link AbortSignal} for the stream. Aborted when {@link cancel} is called. + */ + get signal() { + return this._abortController.signal; + } +}; +var IterableReadableWritableStream = class extends IterableReadableStream { + modes; + controller; + passthroughFn; + _closed = false; + get closed() { + return this._closed; + } + constructor(params) { + let streamControllerPromiseResolver; + const streamControllerPromise = new Promise((resolve) => { + streamControllerPromiseResolver = resolve; + }); + super({ start: (controller) => { + streamControllerPromiseResolver(controller); + } }); + streamControllerPromise.then((controller) => { + this.controller = controller; + }); + this.passthroughFn = params.passthroughFn; + this.modes = params.modes; + } + push(chunk) { + this.passthroughFn?.(chunk); + this.controller.enqueue(chunk); + } + close() { + try { + this.controller.close(); + } catch (e) {} finally { + this._closed = true; + } + } + error(e) { + this.controller.error(e); + } +}; +function _stringifyAsDict(obj) { + return JSON.stringify(obj, function(key, value) { + const rawValue = this[key]; + if (rawValue != null && typeof rawValue === "object" && "toDict" in rawValue && typeof rawValue.toDict === "function") { + const { type, data } = rawValue.toDict(); + return { + ...data, + type + }; + } + return value; + }); +} +function _serializeError(error) { + if (error instanceof Error) return { + error: error.name, + message: error.message + }; + return { + error: "Error", + message: JSON.stringify(error) + }; +} +function _isRunnableConfig(config) { + if (typeof config !== "object" || config == null) return false; + return "configurable" in config && typeof config.configurable === "object" && config.configurable != null; +} +function _extractCheckpointFromConfig(config) { + if (!_isRunnableConfig(config) || !config.configurable.thread_id) return null; + return { + thread_id: config.configurable.thread_id, + checkpoint_ns: config.configurable.checkpoint_ns || "", + checkpoint_id: config.configurable.checkpoint_id || null, + checkpoint_map: config.configurable.checkpoint_map || null + }; +} +function _serializeConfig(config) { + if (_isRunnableConfig(config)) { + const configurable = Object.fromEntries(Object.entries(config.configurable).filter(([key]) => !key.startsWith("__"))); + const newConfig = { + ...config, + configurable + }; + delete newConfig.callbacks; + return newConfig; + } + return config; +} +function _serializeCheckpoint(payload) { + const result = { + ...payload, + checkpoint: _extractCheckpointFromConfig(payload.config), + parent_checkpoint: _extractCheckpointFromConfig(payload.parentConfig), + config: _serializeConfig(payload.config), + parent_config: _serializeConfig(payload.parentConfig), + tasks: payload.tasks.map((task) => { + if (_isRunnableConfig(task.state)) { + const checkpoint = _extractCheckpointFromConfig(task.state); + if (checkpoint != null) { + const cloneTask = { + ...task, + checkpoint + }; + delete cloneTask.state; + return cloneTask; + } + } + return task; + }) + }; + delete result.parentConfig; + return result; +} +function toEventStream(stream) { + const encoder = new TextEncoder(); + return new ReadableStream({ async start(controller) { + const enqueueChunk = (sse) => { + controller.enqueue(encoder.encode(`event: ${sse.event}\ndata: ${_stringifyAsDict(sse.data)}\n\n`)); + }; + try { + for await (const payload of stream) { + const [ns, mode, chunk] = payload; + let data = chunk; + if (mode === "debug") { + const debugChunk = chunk; + if (debugChunk.type === "checkpoint") data = { + ...debugChunk, + payload: _serializeCheckpoint(debugChunk.payload) + }; + } + if (mode === "checkpoints") data = _serializeCheckpoint(chunk); + const event = ns?.length ? `${mode}|${ns.join("|")}` : mode; + enqueueChunk({ + event, + data + }); + } + } catch (error) { + enqueueChunk({ + event: "error", + data: _serializeError(error) + }); + } + controller.close(); + } }); +} + +//#endregion + +//# sourceMappingURL=stream.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/loop.js + + + + + + + + + + + + +//#region src/pregel/loop.ts +const INPUT_DONE = Symbol.for("INPUT_DONE"); +const INPUT_RESUMING = Symbol.for("INPUT_RESUMING"); +const DEFAULT_LOOP_LIMIT = 25; +function createDuplexStream(...streams) { + return new IterableReadableWritableStream({ + passthroughFn: (value) => { + for (const stream of streams) if (stream.modes.has(value[1])) stream.push(value); + }, + modes: new Set(streams.flatMap((s) => Array.from(s.modes))) + }); +} +var AsyncBatchedCache = class extends base_BaseCache { + cache; + queue = Promise.resolve(); + constructor(cache) { + super(); + this.cache = cache; + } + async get(keys) { + return this.enqueueOperation("get", keys); + } + async set(pairs) { + return this.enqueueOperation("set", pairs); + } + async clear(namespaces) { + return this.enqueueOperation("clear", namespaces); + } + async stop() { + await this.queue; + } + enqueueOperation(type, ...args) { + const newPromise = this.queue.then(() => { + return this.cache[type](...args); + }); + this.queue = newPromise.then(() => void 0, () => void 0); + return newPromise; + } +}; +var PregelLoop = class PregelLoop { + input; + output; + config; + checkpointer; + checkpointerGetNextVersion; + channels; + checkpoint; + checkpointIdSaved; + checkpointConfig; + checkpointMetadata; + checkpointNamespace; + checkpointPendingWrites = []; + checkpointPreviousVersions; + step; + stop; + durability; + outputKeys; + streamKeys; + nodes; + skipDoneTasks; + prevCheckpointConfig; + updatedChannels; + status = "pending"; + tasks = {}; + stream; + checkpointerPromises = []; + isNested; + _checkpointerChainedPromise = Promise.resolve(); + store; + cache; + manager; + interruptAfter; + interruptBefore; + toInterrupt = []; + debug = false; + triggerToNodes; + get isResuming() { + let hasChannelVersions = false; + if (START in this.checkpoint.channel_versions) hasChannelVersions = true; + else for (const chan in this.checkpoint.channel_versions) if (Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions, chan)) { + hasChannelVersions = true; + break; + } + const configHasResumingFlag = this.config.configurable?.[CONFIG_KEY_RESUMING] !== void 0; + const configIsResuming = configHasResumingFlag && this.config.configurable?.[CONFIG_KEY_RESUMING]; + const inputIsNullOrUndefined = this.input === null || this.input === void 0; + const inputIsCommandResuming = isCommand(this.input) && this.input.resume != null; + const inputIsResuming = this.input === INPUT_RESUMING; + const runIdMatchesPrevious = !this.isNested && this.config.metadata?.run_id !== void 0 && this.checkpointMetadata?.run_id !== void 0 && this.config.metadata.run_id === this.checkpointMetadata?.run_id; + return hasChannelVersions && (configIsResuming || inputIsNullOrUndefined || inputIsCommandResuming || inputIsResuming || runIdMatchesPrevious); + } + constructor(params) { + this.input = params.input; + this.checkpointer = params.checkpointer; + if (this.checkpointer !== void 0) this.checkpointerGetNextVersion = this.checkpointer.getNextVersion.bind(this.checkpointer); + else this.checkpointerGetNextVersion = increment; + this.checkpoint = params.checkpoint; + this.checkpointMetadata = params.checkpointMetadata; + this.checkpointPreviousVersions = params.checkpointPreviousVersions; + this.channels = params.channels; + this.checkpointPendingWrites = params.checkpointPendingWrites; + this.step = params.step; + this.stop = params.stop; + this.config = params.config; + this.checkpointConfig = params.checkpointConfig; + this.isNested = params.isNested; + this.manager = params.manager; + this.outputKeys = params.outputKeys; + this.streamKeys = params.streamKeys; + this.nodes = params.nodes; + this.skipDoneTasks = params.skipDoneTasks; + this.store = params.store; + this.cache = params.cache ? new AsyncBatchedCache(params.cache) : void 0; + this.stream = params.stream; + this.checkpointNamespace = params.checkpointNamespace; + this.prevCheckpointConfig = params.prevCheckpointConfig; + this.interruptAfter = params.interruptAfter; + this.interruptBefore = params.interruptBefore; + this.durability = params.durability; + this.debug = params.debug; + this.triggerToNodes = params.triggerToNodes; + } + static async initialize(params) { + let { config, stream } = params; + if (stream !== void 0 && config.configurable?.[CONFIG_KEY_STREAM] !== void 0) stream = createDuplexStream(stream, config.configurable[CONFIG_KEY_STREAM]); + const skipDoneTasks = config.configurable ? !("checkpoint_id" in config.configurable) : true; + const scratchpad = config.configurable?.[constants_CONFIG_KEY_SCRATCHPAD]; + if (config.configurable && scratchpad) { + if (scratchpad.subgraphCounter > 0) config = utils_patchConfigurable(config, { [CONFIG_KEY_CHECKPOINT_NS]: [config.configurable[CONFIG_KEY_CHECKPOINT_NS], scratchpad.subgraphCounter.toString()].join(CHECKPOINT_NAMESPACE_SEPARATOR) }); + scratchpad.subgraphCounter += 1; + } + const isNested = CONFIG_KEY_READ in (config.configurable ?? {}); + if (!isNested && config.configurable?.checkpoint_ns !== void 0 && config.configurable?.checkpoint_ns !== "") config = utils_patchConfigurable(config, { + checkpoint_ns: "", + checkpoint_id: void 0 + }); + let checkpointConfig = config; + if (config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP] !== void 0 && config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP]?.[config.configurable?.checkpoint_ns]) checkpointConfig = utils_patchConfigurable(config, { checkpoint_id: config.configurable[CONFIG_KEY_CHECKPOINT_MAP][config.configurable?.checkpoint_ns] }); + const checkpointNamespace = config.configurable?.checkpoint_ns?.split(CHECKPOINT_NAMESPACE_SEPARATOR) ?? []; + const saved = await params.checkpointer?.getTuple(checkpointConfig) ?? { + config, + checkpoint: emptyCheckpoint(), + metadata: { + source: "input", + step: -2, + parents: {} + }, + pendingWrites: [] + }; + checkpointConfig = { + ...config, + ...saved.config, + configurable: { + checkpoint_ns: "", + ...config.configurable, + ...saved.config.configurable + } + }; + const prevCheckpointConfig = saved.parentConfig; + const checkpoint = copyCheckpoint(saved.checkpoint); + const checkpointMetadata = { ...saved.metadata }; + const checkpointPendingWrites = saved.pendingWrites ?? []; + const channels = emptyChannels(params.channelSpecs, checkpoint); + const step = (checkpointMetadata.step ?? 0) + 1; + const stop = step + (config.recursionLimit ?? DEFAULT_LOOP_LIMIT) + 1; + const checkpointPreviousVersions = { ...checkpoint.channel_versions }; + const store = params.store ? new AsyncBatchedStore(params.store) : void 0; + if (store) await store.start(); + return new PregelLoop({ + input: params.input, + config, + checkpointer: params.checkpointer, + checkpoint, + checkpointMetadata, + checkpointConfig, + prevCheckpointConfig, + checkpointNamespace, + channels, + isNested, + manager: params.manager, + skipDoneTasks, + step, + stop, + checkpointPreviousVersions, + checkpointPendingWrites, + outputKeys: params.outputKeys ?? [], + streamKeys: params.streamKeys ?? [], + nodes: params.nodes, + stream, + store, + cache: params.cache, + interruptAfter: params.interruptAfter, + interruptBefore: params.interruptBefore, + durability: params.durability, + debug: params.debug, + triggerToNodes: params.triggerToNodes + }); + } + _checkpointerPutAfterPrevious(input) { + this._checkpointerChainedPromise = this._checkpointerChainedPromise.then(() => { + return this.checkpointer?.put(input.config, input.checkpoint, input.metadata, input.newVersions); + }); + this.checkpointerPromises.push(this._checkpointerChainedPromise); + } + /** + * Put writes for a task, to be read by the next tick. + * @param taskId + * @param writes + */ + putWrites(taskId, writes) { + let writesCopy = writes; + if (writesCopy.length === 0) return; + if (writesCopy.every(([key]) => key in WRITES_IDX_MAP)) writesCopy = Array.from(new Map(writesCopy.map((w) => [w[0], w])).values()); + this.checkpointPendingWrites = this.checkpointPendingWrites.filter((w) => w[0] !== taskId); + for (const [c, v] of writesCopy) this.checkpointPendingWrites.push([ + taskId, + c, + v + ]); + const config = utils_patchConfigurable(this.checkpointConfig, { + [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", + [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id + }); + if (this.durability !== "exit" && this.checkpointer != null) this.checkpointerPromises.push(this.checkpointer.putWrites(config, writesCopy, taskId)); + if (this.tasks) this._outputWrites(taskId, writesCopy); + if (!writes.length || !this.cache || !this.tasks) return; + const task = this.tasks[taskId]; + if (task == null || task.cache_key == null) return; + if (writes[0][0] === constants_ERROR || writes[0][0] === constants_INTERRUPT) return; + this.cache.set([{ + key: [task.cache_key.ns, task.cache_key.key], + value: task.writes, + ttl: task.cache_key.ttl + }]); + } + _outputWrites(taskId, writes, cached = false) { + const task = this.tasks[taskId]; + if (task !== void 0) { + if (task.config !== void 0 && (task.config.tags ?? []).includes(TAG_HIDDEN)) return; + if (writes.length > 0) { + if (writes[0][0] === constants_INTERRUPT) { + if (task.path?.[0] === PUSH && task.path?.at(-1) === true) return; + const interruptWrites = writes.filter((w) => w[0] === constants_INTERRUPT).flatMap((w) => w[1]); + this._emit([["updates", { [constants_INTERRUPT]: interruptWrites }], ["values", { [constants_INTERRUPT]: interruptWrites }]]); + } else if (writes[0][0] !== constants_ERROR) this._emit(gatherIteratorSync(prefixGenerator(mapOutputUpdates(this.outputKeys, [[task, writes]], cached), "updates"))); + } + if (!cached) this._emit(gatherIteratorSync(prefixGenerator(mapDebugTaskResults([[task, writes]], this.streamKeys), "tasks"))); + } + } + async _matchCachedWrites() { + if (!this.cache) return []; + const matched = []; + const serializeKey = ([ns, key]) => { + return `ns:${ns.join(",")}|key:${key}`; + }; + const keys = []; + const keyMap = {}; + for (const task of Object.values(this.tasks)) if (task.cache_key != null && !task.writes.length) { + keys.push([task.cache_key.ns, task.cache_key.key]); + keyMap[serializeKey([task.cache_key.ns, task.cache_key.key])] = task; + } + if (keys.length === 0) return []; + const cache = await this.cache.get(keys); + for (const { key, value } of cache) { + const task = keyMap[serializeKey(key)]; + if (task != null) { + task.writes.push(...value); + matched.push({ + task, + result: value + }); + } + } + return matched; + } + /** + * Execute a single iteration of the Pregel loop. + * Returns true if more iterations are needed. + * @param params + */ + async tick(params) { + if (this.store && !this.store.isRunning) await this.store?.start(); + const { inputKeys = [] } = params; + if (this.status !== "pending") throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`); + if (![INPUT_DONE, INPUT_RESUMING].includes(this.input)) await this._first(inputKeys); + else if (this.toInterrupt.length > 0) { + this.status = "interrupt_before"; + throw new GraphInterrupt(); + } else if (Object.values(this.tasks).every((task) => task.writes.length > 0)) { + const writes = Object.values(this.tasks).flatMap((t) => t.writes); + this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); + const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, writes, this.channels), "values")); + this._emit(valuesOutput); + this.checkpointPendingWrites = []; + await this._putCheckpoint({ source: "loop" }); + if (shouldInterrupt(this.checkpoint, this.interruptAfter, Object.values(this.tasks))) { + this.status = "interrupt_after"; + throw new GraphInterrupt(); + } + if (this.config.configurable?.[CONFIG_KEY_RESUMING] !== void 0) delete this.config.configurable?.[CONFIG_KEY_RESUMING]; + } else return false; + if (this.step > this.stop) { + this.status = "out_of_steps"; + return false; + } + const nextTasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { + step: this.step, + checkpointer: this.checkpointer, + isResuming: this.isResuming, + manager: this.manager, + store: this.store, + stream: this.stream, + triggerToNodes: this.triggerToNodes, + updatedChannels: this.updatedChannels + }); + this.tasks = nextTasks; + if (this.checkpointer) this._emit(await gatherIterator(prefixGenerator(mapDebugCheckpoint(this.checkpointConfig, this.channels, this.streamKeys, this.checkpointMetadata, Object.values(this.tasks), this.checkpointPendingWrites, this.prevCheckpointConfig, this.outputKeys), "checkpoints"))); + if (Object.values(this.tasks).length === 0) { + this.status = "done"; + return false; + } + if (this.skipDoneTasks && this.checkpointPendingWrites.length > 0) { + for (const [tid, k, v] of this.checkpointPendingWrites) { + if (k === constants_ERROR || k === constants_INTERRUPT || k === constants_RESUME) continue; + const task = Object.values(this.tasks).find((t) => t.id === tid); + if (task) task.writes.push([k, v]); + } + for (const task of Object.values(this.tasks)) if (task.writes.length > 0) this._outputWrites(task.id, task.writes, true); + } + if (Object.values(this.tasks).every((task) => task.writes.length > 0)) return this.tick({ inputKeys }); + if (shouldInterrupt(this.checkpoint, this.interruptBefore, Object.values(this.tasks))) { + this.status = "interrupt_before"; + throw new GraphInterrupt(); + } + const debugOutput = await gatherIterator(prefixGenerator(mapDebugTasks(Object.values(this.tasks)), "tasks")); + this._emit(debugOutput); + return true; + } + async finishAndHandleError(error) { + if (this.durability === "exit" && (!this.isNested || typeof error !== "undefined" || this.checkpointNamespace.every((part) => !part.includes(CHECKPOINT_NAMESPACE_END)))) { + this._putCheckpoint(this.checkpointMetadata); + this._flushPendingWrites(); + } + const suppress = this._suppressInterrupt(error); + if (suppress || error === void 0) this.output = readChannels(this.channels, this.outputKeys); + if (suppress) { + if (this.tasks !== void 0 && this.checkpointPendingWrites.length > 0 && Object.values(this.tasks).some((task) => task.writes.length > 0)) { + this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); + this._emit(gatherIteratorSync(prefixGenerator(mapOutputValues(this.outputKeys, Object.values(this.tasks).flatMap((t) => t.writes), this.channels), "values"))); + } + if (isGraphInterrupt(error) && !error.interrupts.length) this._emit([["updates", { [constants_INTERRUPT]: [] }], ["values", { [constants_INTERRUPT]: [] }]]); + } + return suppress; + } + async acceptPush(task, writeIdx, call) { + if (this.interruptAfter?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptAfter, [task])) { + this.toInterrupt.push(task); + return; + } + const pushed = _prepareSingleTask([ + PUSH, + task.path ?? [], + writeIdx, + task.id, + call + ], this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, task.config ?? {}, true, { + step: this.step, + checkpointer: this.checkpointer, + manager: this.manager, + store: this.store, + stream: this.stream + }); + if (!pushed) return; + if (this.interruptBefore?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptBefore, [pushed])) { + this.toInterrupt.push(pushed); + return; + } + this._emit(gatherIteratorSync(prefixGenerator(mapDebugTasks([pushed]), "tasks"))); + if (this.debug) printStepTasks(this.step, [pushed]); + this.tasks[pushed.id] = pushed; + if (this.skipDoneTasks) this._matchWrites({ [pushed.id]: pushed }); + const tasks = await this._matchCachedWrites(); + for (const { task: task$1 } of tasks) this._outputWrites(task$1.id, task$1.writes, true); + return pushed; + } + _suppressInterrupt(e) { + return isGraphInterrupt(e) && !this.isNested; + } + async _first(inputKeys) { + const { configurable } = this.config; + const scratchpad = configurable?.[constants_CONFIG_KEY_SCRATCHPAD]; + if (scratchpad && scratchpad.nullResume !== void 0) this.putWrites(NULL_TASK_ID, [[constants_RESUME, scratchpad.nullResume]]); + if (isCommand(this.input)) { + const hasResume = this.input.resume != null; + if (this.input.resume != null && typeof this.input.resume === "object" && Object.keys(this.input.resume).every(isXXH3)) { + this.config.configurable ??= {}; + this.config.configurable[CONFIG_KEY_RESUME_MAP] = this.input.resume; + } + if (hasResume && this.checkpointer == null) throw new Error("Cannot use Command(resume=...) without checkpointer"); + const writes = {}; + for (const [tid, key, value] of mapCommand(this.input, this.checkpointPendingWrites)) { + writes[tid] ??= []; + writes[tid].push([key, value]); + } + if (Object.keys(writes).length === 0) throw new EmptyInputError("Received empty Command input"); + for (const [tid, ws] of Object.entries(writes)) this.putWrites(tid, ws); + } + const nullWrites = (this.checkpointPendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); + if (nullWrites.length > 0) _applyWrites(this.checkpoint, this.channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], this.checkpointerGetNextVersion, this.triggerToNodes); + const isCommandUpdateOrGoto = isCommand(this.input) && nullWrites.length > 0; + if (this.isResuming || isCommandUpdateOrGoto) { + for (const channelName in this.channels) { + if (!Object.prototype.hasOwnProperty.call(this.channels, channelName)) continue; + if (this.checkpoint.channel_versions[channelName] !== void 0) { + const version = this.checkpoint.channel_versions[channelName]; + this.checkpoint.versions_seen[constants_INTERRUPT] = { + ...this.checkpoint.versions_seen[constants_INTERRUPT], + [channelName]: version + }; + } + } + const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, true, this.channels), "values")); + this._emit(valuesOutput); + } + if (this.isResuming) this.input = INPUT_RESUMING; + else if (isCommandUpdateOrGoto) { + await this._putCheckpoint({ source: "input" }); + this.input = INPUT_DONE; + } else { + const inputWrites = await gatherIterator(mapInput(inputKeys, this.input)); + if (inputWrites.length > 0) { + const discardTasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { step: this.step }); + this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(discardTasks).concat([{ + name: INPUT, + writes: inputWrites, + triggers: [] + }]), this.checkpointerGetNextVersion, this.triggerToNodes); + await this._putCheckpoint({ source: "input" }); + this.input = INPUT_DONE; + } else if (!(CONFIG_KEY_RESUMING in (this.config.configurable ?? {}))) throw new EmptyInputError(`Received no input writes for ${JSON.stringify(inputKeys, null, 2)}`); + else this.input = INPUT_DONE; + } + if (!this.isNested) this.config = utils_patchConfigurable(this.config, { [CONFIG_KEY_RESUMING]: this.isResuming }); + } + _emit(values) { + for (const [mode, payload] of values) { + if (this.stream.modes.has(mode)) this.stream.push([ + this.checkpointNamespace, + mode, + payload + ]); + if ((mode === "checkpoints" || mode === "tasks") && this.stream.modes.has("debug")) { + const step = mode === "checkpoints" ? this.step - 1 : this.step; + const timestamp = (/* @__PURE__ */ new Date()).toISOString(); + const type = (() => { + if (mode === "checkpoints") return "checkpoint"; + else if (typeof payload === "object" && payload != null && "result" in payload) return "task_result"; + else return "task"; + })(); + this.stream.push([ + this.checkpointNamespace, + "debug", + { + step, + type, + timestamp, + payload + } + ]); + } + } + } + _putCheckpoint(inputMetadata) { + const exiting = this.checkpointMetadata === inputMetadata; + const doCheckpoint = this.checkpointer != null && (this.durability !== "exit" || exiting); + const storeCheckpoint = (checkpoint) => { + this.prevCheckpointConfig = this.checkpointConfig?.configurable?.checkpoint_id ? this.checkpointConfig : void 0; + this.checkpointConfig = utils_patchConfigurable(this.checkpointConfig, { [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "" }); + const channelVersions = { ...this.checkpoint.channel_versions }; + const newVersions = getNewChannelVersions(this.checkpointPreviousVersions, channelVersions); + this.checkpointPreviousVersions = channelVersions; + this._checkpointerPutAfterPrevious({ + config: { ...this.checkpointConfig }, + checkpoint: copyCheckpoint(checkpoint), + metadata: { ...this.checkpointMetadata }, + newVersions + }); + this.checkpointConfig = { + ...this.checkpointConfig, + configurable: { + ...this.checkpointConfig.configurable, + checkpoint_id: this.checkpoint.id + } + }; + }; + if (!exiting) this.checkpointMetadata = { + ...inputMetadata, + step: this.step, + parents: this.config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP] ?? {} + }; + this.checkpoint = createCheckpoint(this.checkpoint, doCheckpoint ? this.channels : void 0, this.step, exiting ? { id: this.checkpoint.id } : void 0); + if (doCheckpoint) storeCheckpoint(this.checkpoint); + if (!exiting) this.step += 1; + } + _flushPendingWrites() { + if (this.checkpointer == null) return; + if (this.checkpointPendingWrites.length === 0) return; + const config = utils_patchConfigurable(this.checkpointConfig, { + [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", + [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id + }); + const byTask = {}; + for (const [tid, key, value] of this.checkpointPendingWrites) { + byTask[tid] ??= []; + byTask[tid].push([key, value]); + } + for (const [tid, ws] of Object.entries(byTask)) this.checkpointerPromises.push(this.checkpointer.putWrites(config, ws, tid)); + } + _matchWrites(tasks) { + for (const [tid, k, v] of this.checkpointPendingWrites) { + if (k === constants_ERROR || k === constants_INTERRUPT || k === constants_RESUME) continue; + const task = Object.values(tasks).find((t) => t.id === tid); + if (task) task.writes.push([k, v]); + } + for (const task of Object.values(tasks)) if (task.writes.length > 0) this._outputWrites(task.id, task.writes, true); + } +}; + +//#endregion + +//# sourceMappingURL=loop.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/messages.js + + + + +//#region src/pregel/messages.ts +function messages_isChatGenerationChunk(x) { + return isBaseMessage(x?.message); +} +/** +* A callback handler that implements stream_mode=messages. +* Collects messages from (1) chat model stream events and (2) node outputs. +*/ +var StreamMessagesHandler = class extends BaseCallbackHandler { + name = "StreamMessagesHandler"; + streamFn; + metadatas = {}; + seen = {}; + emittedChatModelRunIds = {}; + stableMessageIdMap = {}; + lc_prefer_streaming = true; + constructor(streamFn) { + super(); + this.streamFn = streamFn; + } + _emit(meta, message, runId, dedupe = false) { + if (dedupe && message.id !== void 0 && this.seen[message.id] !== void 0) return; + let messageId = message.id; + if (runId != null) if (isToolMessage(message)) messageId ??= `run-${runId}-tool-${message.tool_call_id}`; + else { + if (messageId == null || messageId === `run-${runId}`) messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; + this.stableMessageIdMap[runId] ??= messageId; + } + if (messageId !== message.id) { + message.id = messageId; + message.lc_kwargs.id = messageId; + } + if (message.id != null) this.seen[message.id] = message; + this.streamFn([ + meta[0], + "messages", + [message, meta[1]] + ]); + } + handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { + if (metadata && (!tags || !tags.includes(TAG_NOSTREAM) && !tags.includes("nostream"))) this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { + tags, + name, + ...metadata + }]; + } + handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, fields) { + const chunk = fields?.chunk; + this.emittedChatModelRunIds[runId] = true; + if (this.metadatas[runId] !== void 0) if (messages_isChatGenerationChunk(chunk)) this._emit(this.metadatas[runId], chunk.message, runId); + else this._emit(this.metadatas[runId], new AIMessageChunk({ content: token }), runId); + } + handleLLMEnd(output, runId) { + if (this.metadatas[runId] === void 0) return; + if (!this.emittedChatModelRunIds[runId]) { + const chatGeneration = output.generations?.[0]?.[0]; + if (isBaseMessage(chatGeneration?.message)) this._emit(this.metadatas[runId], chatGeneration?.message, runId, true); + delete this.emittedChatModelRunIds[runId]; + } + delete this.metadatas[runId]; + delete this.stableMessageIdMap[runId]; + } + handleLLMError(_err, runId) { + delete this.metadatas[runId]; + } + handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { + if (metadata !== void 0 && name === metadata.langgraph_node && (tags === void 0 || !tags.includes(TAG_HIDDEN))) { + this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { + tags, + name, + ...metadata + }]; + if (typeof inputs === "object") { + for (const value of Object.values(inputs)) if ((isBaseMessage(value) || isBaseMessageChunk(value)) && value.id !== void 0) this.seen[value.id] = value; + else if (Array.isArray(value)) { + for (const item of value) if ((isBaseMessage(item) || isBaseMessageChunk(item)) && item.id !== void 0) this.seen[item.id] = item; + } + } + } + } + handleChainEnd(outputs, runId) { + const metadata = this.metadatas[runId]; + delete this.metadatas[runId]; + if (metadata !== void 0) { + if (isBaseMessage(outputs)) this._emit(metadata, outputs, runId, true); + else if (Array.isArray(outputs)) { + for (const value of outputs) if (isBaseMessage(value)) this._emit(metadata, value, runId, true); + } else if (outputs != null && typeof outputs === "object") { + for (const value of Object.values(outputs)) if (isBaseMessage(value)) this._emit(metadata, value, runId, true); + else if (Array.isArray(value)) { + for (const item of value) if (isBaseMessage(item)) this._emit(metadata, item, runId, true); + } + } + } + } + handleChainError(_err, runId) { + delete this.metadatas[runId]; + } +}; + +//#endregion + +//# sourceMappingURL=messages.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/retry.js + + + + + +//#region src/pregel/retry.ts +const DEFAULT_INITIAL_INTERVAL = 500; +const DEFAULT_BACKOFF_FACTOR = 2; +const DEFAULT_MAX_INTERVAL = 128e3; +const DEFAULT_MAX_RETRIES = 3; +const DEFAULT_STATUS_NO_RETRY = [ + 400, + 401, + 402, + 403, + 404, + 405, + 406, + 407, + 409 +]; +const DEFAULT_RETRY_ON_HANDLER = (error) => { + if (error.message.startsWith("Cancel") || error.message.startsWith("AbortError") || error.name === "AbortError") return false; + if (error.name === "GraphValueError") return false; + if (error?.code === "ECONNABORTED") return false; + const status = error?.response?.status ?? error?.status; + if (status && DEFAULT_STATUS_NO_RETRY.includes(+status)) return false; + if (error?.error?.code === "insufficient_quota") return false; + return true; +}; +async function _runWithRetry(pregelTask, retryPolicy, configurable, signal) { + const resolvedRetryPolicy = pregelTask.retry_policy ?? retryPolicy; + let interval = resolvedRetryPolicy !== void 0 ? resolvedRetryPolicy.initialInterval ?? DEFAULT_INITIAL_INTERVAL : 0; + let attempts = 0; + let error; + let result; + let { config } = pregelTask; + if (configurable) config = utils_patchConfigurable(config, configurable); + config = { + ...config, + signal + }; + while (true) { + if (signal?.aborted) break; + pregelTask.writes.splice(0, pregelTask.writes.length); + error = void 0; + try { + result = await pregelTask.proc.invoke(pregelTask.input, config); + break; + } catch (e) { + error = e; + error.pregelTaskId = pregelTask.id; + if (isParentCommand(error)) { + const ns = config?.configurable?.checkpoint_ns; + const cmd = error.command; + if (cmd.graph === ns) { + for (const writer of pregelTask.writers) await writer.invoke(cmd, config); + error = void 0; + break; + } else if (cmd.graph === Command.PARENT) { + const parentNs = getParentCheckpointNamespace(ns); + error.command = new Command({ + ...error.command, + graph: parentNs + }); + } + } + if (isGraphBubbleUp(error)) break; + if (resolvedRetryPolicy === void 0) break; + attempts += 1; + if (attempts >= (resolvedRetryPolicy.maxAttempts ?? DEFAULT_MAX_RETRIES)) break; + const retryOn = resolvedRetryPolicy.retryOn ?? DEFAULT_RETRY_ON_HANDLER; + if (!retryOn(error)) break; + interval = Math.min(resolvedRetryPolicy.maxInterval ?? DEFAULT_MAX_INTERVAL, interval * (resolvedRetryPolicy.backoffFactor ?? DEFAULT_BACKOFF_FACTOR)); + const intervalWithJitter = resolvedRetryPolicy.jitter ? Math.floor(interval + Math.random() * 1e3) : interval; + await new Promise((resolve) => setTimeout(resolve, intervalWithJitter)); + const errorName = error.name ?? error.constructor.unminifiable_name ?? error.constructor.name; + if (resolvedRetryPolicy?.logWarning ?? true) console.log(`Retrying task "${String(pregelTask.name)}" after ${interval.toFixed(2)}ms (attempt ${attempts}) after ${errorName}: ${error}`); + config = utils_patchConfigurable(config, { [CONFIG_KEY_RESUMING]: true }); + } + } + return { + task: pregelTask, + result, + error, + signalAborted: signal?.aborted + }; +} + +//#endregion + +//# sourceMappingURL=retry.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/runner.js + + + + + + +//#region src/pregel/runner.ts +const PROMISE_ADDED_SYMBOL = Symbol.for("promiseAdded"); +function createPromiseBarrier() { + const barrier = { + next: () => void 0, + wait: Promise.resolve(PROMISE_ADDED_SYMBOL) + }; + function waitHandler(resolve) { + barrier.next = () => { + barrier.wait = new Promise(waitHandler); + resolve(PROMISE_ADDED_SYMBOL); + }; + } + barrier.wait = new Promise(waitHandler); + return barrier; +} +/** +* Responsible for handling task execution on each tick of the {@link PregelLoop}. +*/ +var PregelRunner = class { + nodeFinished; + loop; + /** + * Construct a new PregelRunner, which executes tasks from the provided PregelLoop. + * @param loop - The PregelLoop that produces tasks for this runner to execute. + */ + constructor({ loop, nodeFinished }) { + this.loop = loop; + this.nodeFinished = nodeFinished; + } + /** + * Execute tasks from the current step of the PregelLoop. + * + * Note: this method does NOT call {@link PregelLoop}#tick. That must be handled externally. + * @param options - Options for the execution. + */ + async tick(options = {}) { + const { timeout, retryPolicy, onStepWrite, maxConcurrency } = options; + const nodeErrors = /* @__PURE__ */ new Set(); + let graphBubbleUp; + const exceptionSignalController = new AbortController(); + const exceptionSignal = exceptionSignalController.signal; + const stepTimeoutSignal = timeout ? AbortSignal.timeout(timeout) : void 0; + const pendingTasks = Object.values(this.loop.tasks).filter((t) => t.writes.length === 0); + const { signals, disposeCombinedSignal } = this._initializeAbortSignals({ + exceptionSignal, + stepTimeoutSignal, + signal: options.signal + }); + const taskStream = this._executeTasksWithRetry(pendingTasks, { + signals, + retryPolicy, + maxConcurrency + }); + for await (const { task, error, signalAborted } of taskStream) { + this._commit(task, error); + if (isGraphInterrupt(error)) graphBubbleUp = error; + else if (isGraphBubbleUp(error) && !isGraphInterrupt(graphBubbleUp)) graphBubbleUp = error; + else if (error && (nodeErrors.size === 0 || !signalAborted)) { + exceptionSignalController.abort(); + nodeErrors.add(error); + } + } + disposeCombinedSignal?.(); + onStepWrite?.(this.loop.step, Object.values(this.loop.tasks).map((task) => task.writes).flat()); + if (nodeErrors.size === 1) throw Array.from(nodeErrors)[0]; + else if (nodeErrors.size > 1) throw new AggregateError(Array.from(nodeErrors), `Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`); + if (isGraphInterrupt(graphBubbleUp)) throw graphBubbleUp; + if (isGraphBubbleUp(graphBubbleUp) && this.loop.isNested) throw graphBubbleUp; + } + /** + * Initializes the current AbortSignals for the PregelRunner, handling the various ways that + * AbortSignals must be chained together so that the PregelLoop can be interrupted if necessary + * while still allowing nodes to gracefully exit. + * + * This method must only be called once per PregelRunner#tick. It has the side effect of updating + * the PregelLoop#config with the new AbortSignals so they may be propagated correctly to future + * ticks and subgraph calls. + * + * @param options - Options for the initialization. + * @returns The current abort signals. + * @internal + */ + _initializeAbortSignals({ exceptionSignal, stepTimeoutSignal, signal }) { + const previousSignals = this.loop.config.configurable?.[CONFIG_KEY_ABORT_SIGNALS] ?? {}; + const externalAbortSignal = previousSignals.externalAbortSignal ?? signal; + const timeoutAbortSignal = stepTimeoutSignal ?? previousSignals.timeoutAbortSignal; + const { signal: composedAbortSignal, dispose: disposeCombinedSignal } = combineAbortSignals(externalAbortSignal, timeoutAbortSignal, exceptionSignal); + const signals = { + externalAbortSignal, + timeoutAbortSignal, + composedAbortSignal + }; + this.loop.config = utils_patchConfigurable(this.loop.config, { [CONFIG_KEY_ABORT_SIGNALS]: signals }); + return { + signals, + disposeCombinedSignal + }; + } + /** + * Concurrently executes tasks with the requested retry policy, yielding a {@link SettledPregelTask} for each task as it completes. + * @param tasks - The tasks to execute. + * @param options - Options for the execution. + */ + async *_executeTasksWithRetry(tasks, options) { + const { retryPolicy, maxConcurrency, signals } = options ?? {}; + const barrier = createPromiseBarrier(); + const executingTasksMap = {}; + const thisCall = { + executingTasksMap, + barrier, + retryPolicy, + scheduleTask: async (task, writeIdx, call$1) => this.loop.acceptPush(task, writeIdx, call$1) + }; + if (signals?.composedAbortSignal?.aborted) throw new Error("Abort"); + let startedTasksCount = 0; + let listener; + const timeoutOrCancelSignal = combineAbortSignals(signals?.externalAbortSignal, signals?.timeoutAbortSignal); + const abortPromise = timeoutOrCancelSignal.signal ? new Promise((_resolve, reject) => { + listener = () => reject(/* @__PURE__ */ new Error("Abort")); + timeoutOrCancelSignal.signal?.addEventListener("abort", listener, { once: true }); + }) : void 0; + while ((startedTasksCount === 0 || Object.keys(executingTasksMap).length > 0) && tasks.length) { + for (; Object.values(executingTasksMap).length < (maxConcurrency ?? tasks.length) && startedTasksCount < tasks.length; startedTasksCount += 1) { + const task = tasks[startedTasksCount]; + executingTasksMap[task.id] = _runWithRetry(task, retryPolicy, { [constants_CONFIG_KEY_CALL]: runner_call?.bind(thisCall, this, task) }, signals?.composedAbortSignal).catch((error) => { + return { + task, + error, + signalAborted: signals?.composedAbortSignal?.aborted + }; + }); + } + const settledTask = await Promise.race([ + ...Object.values(executingTasksMap), + ...abortPromise ? [abortPromise] : [], + barrier.wait + ]); + if (settledTask === PROMISE_ADDED_SYMBOL) continue; + yield settledTask; + if (listener != null) { + timeoutOrCancelSignal.signal?.removeEventListener("abort", listener); + timeoutOrCancelSignal.dispose?.(); + } + delete executingTasksMap[settledTask.task.id]; + } + } + /** + * Determines what writes to apply based on whether the task completed successfully, and what type of error occurred. + * + * Throws an error if the error is a {@link GraphBubbleUp} error and {@link PregelLoop}#isNested is true. + * + * @param task - The task to commit. + * @param error - The error that occurred, if any. + */ + _commit(task, error) { + if (error !== void 0) if (isGraphInterrupt(error)) { + if (error.interrupts.length) { + const interrupts = error.interrupts.map((interrupt) => [constants_INTERRUPT, interrupt]); + const resumes = task.writes.filter((w) => w[0] === constants_RESUME); + if (resumes.length) interrupts.push(...resumes); + this.loop.putWrites(task.id, interrupts); + } + } else if (isGraphBubbleUp(error) && task.writes.length) this.loop.putWrites(task.id, task.writes); + else this.loop.putWrites(task.id, [[constants_ERROR, { + message: error.message, + name: error.name + }]]); + else { + if (this.nodeFinished && (task.config?.tags == null || !task.config.tags.includes(TAG_HIDDEN))) this.nodeFinished(String(task.name)); + if (task.writes.length === 0) task.writes.push([NO_WRITES, null]); + this.loop.putWrites(task.id, task.writes); + } + } +}; +async function runner_call(runner, task, func, name, input, options = {}) { + const scratchpad = task.config?.configurable?.[constants_CONFIG_KEY_SCRATCHPAD]; + if (!scratchpad) throw new Error(`BUG: No scratchpad found on task ${task.name}__${task.id}`); + const cnt = scratchpad.callCounter; + scratchpad.callCounter += 1; + const wcall = new Call({ + func, + name, + input, + cache: options.cache, + retry: options.retry, + callbacks: options.callbacks + }); + const nextTask = await this.scheduleTask(task, cnt, wcall); + if (!nextTask) return void 0; + const existingPromise = this.executingTasksMap[nextTask.id]; + if (existingPromise !== void 0) return existingPromise; + if (nextTask.writes.length > 0) { + const returns = nextTask.writes.filter(([c]) => c === RETURN); + const errors = nextTask.writes.filter(([c]) => c === constants_ERROR); + if (returns.length > 0) { + if (returns.length === 1) return Promise.resolve(returns[0][1]); + throw new Error(`BUG: multiple returns found for task ${nextTask.name}__${nextTask.id}`); + } + if (errors.length > 0) { + if (errors.length === 1) { + const errorValue = errors[0][1]; + const error = errorValue instanceof Error ? errorValue : new Error(String(errorValue)); + return Promise.reject(error); + } + throw new Error(`BUG: multiple errors found for task ${nextTask.name}__${nextTask.id}`); + } + return void 0; + } else { + const prom = _runWithRetry(nextTask, options.retry, { [constants_CONFIG_KEY_CALL]: runner_call.bind(this, runner, nextTask) }); + this.executingTasksMap[nextTask.id] = prom; + this.barrier.next(); + return prom.then(({ result, error }) => { + if (error) return Promise.reject(error); + return result; + }); + } +} + +//#endregion + +//# sourceMappingURL=runner.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/validate.js + + + +//#region src/pregel/validate.ts +var GraphValidationError = class extends Error { + constructor(message) { + super(message); + this.name = "GraphValidationError"; + } +}; +function validateGraph({ nodes, channels, inputChannels, outputChannels, streamChannels, interruptAfterNodes, interruptBeforeNodes }) { + if (!channels) throw new GraphValidationError("Channels not provided"); + const subscribedChannels = /* @__PURE__ */ new Set(); + const allOutputChannels = /* @__PURE__ */ new Set(); + for (const [name, node] of Object.entries(nodes)) { + if (name === constants_INTERRUPT) throw new GraphValidationError(`"Node name ${constants_INTERRUPT} is reserved"`); + if (node.constructor === PregelNode) node.triggers.forEach((trigger) => subscribedChannels.add(trigger)); + else throw new GraphValidationError(`Invalid node type ${typeof node}, expected PregelNode`); + } + for (const chan of subscribedChannels) if (!(chan in channels)) throw new GraphValidationError(`Subscribed channel '${String(chan)}' not in channels`); + if (!Array.isArray(inputChannels)) { + if (!subscribedChannels.has(inputChannels)) throw new GraphValidationError(`Input channel ${String(inputChannels)} is not subscribed to by any node`); + } else if (inputChannels.every((channel) => !subscribedChannels.has(channel))) throw new GraphValidationError(`None of the input channels ${inputChannels} are subscribed to by any node`); + if (!Array.isArray(outputChannels)) allOutputChannels.add(outputChannels); + else outputChannels.forEach((chan) => allOutputChannels.add(chan)); + if (streamChannels && !Array.isArray(streamChannels)) allOutputChannels.add(streamChannels); + else if (Array.isArray(streamChannels)) streamChannels.forEach((chan) => allOutputChannels.add(chan)); + for (const chan of allOutputChannels) if (!(chan in channels)) throw new GraphValidationError(`Output channel '${String(chan)}' not in channels`); + if (interruptAfterNodes && interruptAfterNodes !== "*") { + for (const node of interruptAfterNodes) if (!(node in nodes)) throw new GraphValidationError(`Node ${String(node)} not in nodes`); + } + if (interruptBeforeNodes && interruptBeforeNodes !== "*") { + for (const node of interruptBeforeNodes) if (!(node in nodes)) throw new GraphValidationError(`Node ${String(node)} not in nodes`); + } +} +function validateKeys(keys, channels) { + if (Array.isArray(keys)) { + for (const key of keys) if (!(key in channels)) throw new Error(`Key ${String(key)} not found in channels`); + } else if (!(keys in channels)) throw new Error(`Key ${String(keys)} not found in channels`); +} + +//#endregion + +//# sourceMappingURL=validate.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/topic.js + + + +//#region src/channels/topic.ts +/** +* A configurable PubSub Topic. +*/ +var Topic = class Topic extends BaseChannel { + lc_graph_name = "Topic"; + unique = false; + accumulate = false; + seen; + values; + constructor(fields) { + super(); + this.unique = fields?.unique ?? this.unique; + this.accumulate = fields?.accumulate ?? this.accumulate; + this.seen = /* @__PURE__ */ new Set(); + this.values = []; + } + fromCheckpoint(checkpoint) { + const empty = new Topic({ + unique: this.unique, + accumulate: this.accumulate + }); + if (typeof checkpoint !== "undefined") { + empty.seen = new Set(checkpoint[0]); + empty.values = checkpoint[1]; + } + return empty; + } + update(values) { + let updated = false; + if (!this.accumulate) { + updated = this.values.length > 0; + this.values = []; + } + const flatValues = values.flat(); + if (flatValues.length > 0) if (this.unique) { + for (const value of flatValues) if (!this.seen.has(value)) { + updated = true; + this.seen.add(value); + this.values.push(value); + } + } else { + updated = true; + this.values.push(...flatValues); + } + return updated; + } + get() { + if (this.values.length === 0) throw new EmptyChannelError(); + return this.values; + } + checkpoint() { + return [[...this.seen], this.values]; + } + isAvailable() { + return this.values.length !== 0; + } +}; + +//#endregion + +//# sourceMappingURL=topic.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/index.js + + + + + + + + + + + + + + + + + + + + + + +//#region src/pregel/index.ts +/** +* Utility class for working with channels in the Pregel system. +* Provides static methods for subscribing to channels and writing to them. +* +* Channels are the communication pathways between nodes in a Pregel graph. +* They enable message passing and state updates between different parts of the graph. +*/ +var Channel = class { + static subscribeTo(channels, options) { + const { key, tags } = { + key: void 0, + tags: void 0, + ...options ?? {} + }; + if (Array.isArray(channels) && key !== void 0) throw new Error("Can't specify a key when subscribing to multiple channels"); + let channelMappingOrArray; + if (typeof channels === "string") if (key) channelMappingOrArray = { [key]: channels }; + else channelMappingOrArray = [channels]; + else channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan])); + const triggers = Array.isArray(channels) ? channels : [channels]; + return new PregelNode({ + channels: channelMappingOrArray, + triggers, + tags + }); + } + /** + * Creates a ChannelWrite that specifies how to write values to channels. + * This is used to define how nodes send output to channels. + * + * @example + * ```typescript + * // Write to multiple channels + * const write = Channel.writeTo(["output", "state"]); + * + * // Write with specific values + * const write = Channel.writeTo(["output"], { + * state: "completed", + * result: calculateResult() + * }); + * + * // Write with a transformation function + * const write = Channel.writeTo(["output"], { + * result: (x) => processResult(x) + * }); + * ``` + * + * @param channels - Array of channel names to write to + * @param writes - Optional map of channel names to values or transformations + * @returns A ChannelWrite object that can be used to write to the specified channels + */ + static writeTo(channels, writes) { + const channelWriteEntries = []; + for (const channel of channels) channelWriteEntries.push({ + channel, + value: PASSTHROUGH, + skipNone: false + }); + for (const [key, value] of Object.entries(writes ?? {})) if (Runnable.isRunnable(value) || typeof value === "function") channelWriteEntries.push({ + channel: key, + value: PASSTHROUGH, + skipNone: true, + mapper: _coerceToRunnable(value) + }); + else channelWriteEntries.push({ + channel: key, + value, + skipNone: false + }); + return new ChannelWrite(channelWriteEntries); + } +}; +var PartialRunnable = class extends Runnable { + lc_namespace = ["langgraph", "pregel"]; + invoke(_input, _options) { + throw new Error("Not implemented"); + } + withConfig(_config) { + return super.withConfig(_config); + } + stream(input, options) { + return super.stream(input, options); + } +}; +/** +* The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model +* inspired by [Google's Pregel system](https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/). +* It provides the foundation for building reliable, controllable agent workflows that can evolve state over time. +* +* Key features: +* - Message passing between nodes in discrete "supersteps" +* - Built-in persistence layer through checkpointers +* - First-class streaming support for values, updates, and events +* - Human-in-the-loop capabilities via interrupts +* - Support for parallel node execution within supersteps +* +* The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs: +* - {@link StateGraph}: The main graph class for building agent workflows +* - Compiling a {@link StateGraph} will return a {@link CompiledGraph} instance, which extends `Pregel` +* - Functional API: A declarative approach using tasks and entrypoints +* - A `Pregel` instance is returned by the {@link entrypoint} function +* +* @example +* ```typescript +* // Using StateGraph API +* const graph = new StateGraph(annotation) +* .addNode("nodeA", myNodeFunction) +* .addEdge("nodeA", "nodeB") +* .compile(); +* +* // The compiled graph is a Pregel instance +* const result = await graph.invoke(input); +* ``` +* +* @example +* ```typescript +* // Using Functional API +* import { task, entrypoint } from "@langchain/langgraph"; +* import { MemorySaver } from "@langchain/langgraph-checkpoint"; +* +* // Define tasks that can be composed +* const addOne = task("add", async (x: number) => x + 1); +* +* // Create a workflow using the entrypoint function +* const workflow = entrypoint({ +* name: "workflow", +* checkpointer: new MemorySaver() +* }, async (numbers: number[]) => { +* // Tasks can be run in parallel +* const results = await Promise.all(numbers.map(n => addOne(n))); +* return results; +* }); +* +* // The workflow is a Pregel instance +* const result = await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4] +* ``` +* +* @typeParam Nodes - Mapping of node names to their {@link PregelNode} implementations +* @typeParam Channels - Mapping of channel names to their {@link BaseChannel} or {@link ManagedValueSpec} implementations +* @typeParam ContextType - Type of context that can be passed to the graph +* @typeParam InputType - Type of input values accepted by the graph +* @typeParam OutputType - Type of output values produced by the graph +*/ +var Pregel = class extends PartialRunnable { + /** + * Name of the class when serialized + * @internal + */ + static lc_name() { + return "LangGraph"; + } + /** @internal LangChain namespace for serialization necessary because Pregel extends Runnable */ + lc_namespace = ["langgraph", "pregel"]; + /** @internal Flag indicating this is a Pregel instance - necessary for serialization */ + lg_is_pregel = true; + /** The nodes in the graph, mapping node names to their PregelNode instances */ + nodes; + /** The channels in the graph, mapping channel names to their BaseChannel or ManagedValueSpec instances */ + channels; + /** + * The input channels for the graph. These channels receive the initial input when the graph is invoked. + * Can be a single channel key or an array of channel keys. + */ + inputChannels; + /** + * The output channels for the graph. These channels contain the final output when the graph completes. + * Can be a single channel key or an array of channel keys. + */ + outputChannels; + /** Whether to automatically validate the graph structure when it is compiled. Defaults to true. */ + autoValidate = true; + /** + * The streaming modes enabled for this graph. Defaults to ["values"]. + * Supported modes: + * - "values": Streams the full state after each step + * - "updates": Streams state updates after each step + * - "messages": Streams messages from within nodes + * - "custom": Streams custom events from within nodes + * - "debug": Streams events related to the execution of the graph - useful for tracing & debugging graph execution + */ + streamMode = ["values"]; + /** + * Optional channels to stream. If not specified, all channels will be streamed. + * Can be a single channel key or an array of channel keys. + */ + streamChannels; + /** + * Optional array of node names or "all" to interrupt after executing these nodes. + * Used for implementing human-in-the-loop workflows. + */ + interruptAfter; + /** + * Optional array of node names or "all" to interrupt before executing these nodes. + * Used for implementing human-in-the-loop workflows. + */ + interruptBefore; + /** Optional timeout in milliseconds for the execution of each superstep */ + stepTimeout; + /** Whether to enable debug logging. Defaults to false. */ + debug = false; + /** + * Optional checkpointer for persisting graph state. + * When provided, saves a checkpoint of the graph state at every superstep. + * When false or undefined, checkpointing is disabled, and the graph will not be able to save or restore state. + */ + checkpointer; + /** Optional retry policy for handling failures in node execution */ + retryPolicy; + /** The default configuration for graph execution, can be overridden on a per-invocation basis */ + config; + /** + * Optional long-term memory store for the graph, allows for persistence & retrieval of data across threads + */ + store; + /** + * Optional cache for the graph, useful for caching tasks. + */ + cache; + /** + * Optional interrupt helper function. + * @internal + */ + userInterrupt; + /** + * The trigger to node mapping for the graph run. + * @internal + */ + triggerToNodes = {}; + /** + * Constructor for Pregel - meant for internal use only. + * + * @internal + */ + constructor(fields) { + super(fields); + let { streamMode } = fields; + if (streamMode != null && !Array.isArray(streamMode)) streamMode = [streamMode]; + this.nodes = fields.nodes; + this.channels = fields.channels; + if (constants_TASKS in this.channels && "lc_graph_name" in this.channels[constants_TASKS] && this.channels[constants_TASKS].lc_graph_name !== "Topic") throw new Error(`Channel '${constants_TASKS}' is reserved and cannot be used in the graph.`); + else this.channels[constants_TASKS] = new Topic({ accumulate: false }); + this.autoValidate = fields.autoValidate ?? this.autoValidate; + this.streamMode = streamMode ?? this.streamMode; + this.inputChannels = fields.inputChannels; + this.outputChannels = fields.outputChannels; + this.streamChannels = fields.streamChannels ?? this.streamChannels; + this.interruptAfter = fields.interruptAfter; + this.interruptBefore = fields.interruptBefore; + this.stepTimeout = fields.stepTimeout ?? this.stepTimeout; + this.debug = fields.debug ?? this.debug; + this.checkpointer = fields.checkpointer; + this.retryPolicy = fields.retryPolicy; + this.config = fields.config; + this.store = fields.store; + this.cache = fields.cache; + this.name = fields.name; + this.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes; + this.userInterrupt = fields.userInterrupt; + if (this.autoValidate) this.validate(); + } + /** + * Creates a new instance of the Pregel graph with updated configuration. + * This method follows the immutable pattern - instead of modifying the current instance, + * it returns a new instance with the merged configuration. + * + * @example + * ```typescript + * // Create a new instance with debug enabled + * const debugGraph = graph.withConfig({ debug: true }); + * + * // Create a new instance with a specific thread ID + * const threadGraph = graph.withConfig({ + * configurable: { thread_id: "123" } + * }); + * ``` + * + * @param config - The configuration to merge with the current configuration + * @returns A new Pregel instance with the merged configuration + */ + withConfig(config) { + const mergedConfig = mergeConfigs(this.config, config); + return new this.constructor({ + ...this, + config: mergedConfig + }); + } + /** + * Validates the graph structure to ensure it is well-formed. + * Checks for: + * - No orphaned nodes + * - Valid input/output channel configurations + * - Valid interrupt configurations + * + * @returns this - The Pregel instance for method chaining + * @throws {GraphValidationError} If the graph structure is invalid + */ + validate() { + validateGraph({ + nodes: this.nodes, + channels: this.channels, + outputChannels: this.outputChannels, + inputChannels: this.inputChannels, + streamChannels: this.streamChannels, + interruptAfterNodes: this.interruptAfter, + interruptBeforeNodes: this.interruptBefore + }); + for (const [name, node] of Object.entries(this.nodes)) for (const trigger of node.triggers) { + this.triggerToNodes[trigger] ??= []; + this.triggerToNodes[trigger].push(name); + } + return this; + } + /** + * Gets a list of all channels that should be streamed. + * If streamChannels is specified, returns those channels. + * Otherwise, returns all channels in the graph. + * + * @returns Array of channel keys to stream + */ + get streamChannelsList() { + if (Array.isArray(this.streamChannels)) return this.streamChannels; + else if (this.streamChannels) return [this.streamChannels]; + else return Object.keys(this.channels); + } + /** + * Gets the channels to stream in their original format. + * If streamChannels is specified, returns it as-is (either single key or array). + * Otherwise, returns all channels in the graph as an array. + * + * @returns Channel keys to stream, either as a single key or array + */ + get streamChannelsAsIs() { + if (this.streamChannels) return this.streamChannels; + else return Object.keys(this.channels); + } + /** + * Gets a drawable representation of the graph structure. + * This is an async version of getGraph() and is the preferred method to use. + * + * @param config - Configuration for generating the graph visualization + * @returns A representation of the graph that can be visualized + */ + async getGraphAsync(config) { + return this.getGraph(config); + } + /** + * Gets all subgraphs within this graph. + * A subgraph is a Pregel instance that is nested within a node of this graph. + * + * @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release. + * @param namespace - Optional namespace to filter subgraphs + * @param recurse - Whether to recursively get subgraphs of subgraphs + * @returns Generator yielding tuples of [name, subgraph] + */ + *getSubgraphs(namespace, recurse) { + for (const [name, node] of Object.entries(this.nodes)) { + if (namespace !== void 0) { + if (!namespace.startsWith(name)) continue; + } + const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound]; + for (const candidate of candidates) { + const graph = findSubgraphPregel(candidate); + if (graph !== void 0) { + if (name === namespace) { + yield [name, graph]; + return; + } + if (namespace === void 0) yield [name, graph]; + if (recurse) { + let newNamespace = namespace; + if (namespace !== void 0) newNamespace = namespace.slice(name.length + 1); + for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) yield [`${name}${CHECKPOINT_NAMESPACE_SEPARATOR}${subgraphName}`, subgraph]; + } + } + } + } + } + /** + * Gets all subgraphs within this graph asynchronously. + * A subgraph is a Pregel instance that is nested within a node of this graph. + * + * @param namespace - Optional namespace to filter subgraphs + * @param recurse - Whether to recursively get subgraphs of subgraphs + * @returns AsyncGenerator yielding tuples of [name, subgraph] + */ + async *getSubgraphsAsync(namespace, recurse) { + yield* this.getSubgraphs(namespace, recurse); + } + /** + * Prepares a state snapshot from saved checkpoint data. + * This is an internal method used by getState and getStateHistory. + * + * @param config - Configuration for preparing the snapshot + * @param saved - Optional saved checkpoint data + * @param subgraphCheckpointer - Optional checkpointer for subgraphs + * @param applyPendingWrites - Whether to apply pending writes to tasks and then to channels + * @returns A snapshot of the graph state + * @internal + */ + async _prepareStateSnapshot({ config, saved, subgraphCheckpointer, applyPendingWrites = false }) { + if (saved === void 0) return { + values: {}, + next: [], + config, + tasks: [] + }; + const channels = emptyChannels(this.channels, saved.checkpoint); + if (saved.pendingWrites?.length) { + const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === NULL_TASK_ID).map(([_, channel, value]) => [String(channel), value]); + if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], void 0, this.triggerToNodes); + } + const nextTasks = Object.values(_prepareNextTasks(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { + step: (saved.metadata?.step ?? -1) + 1, + store: this.store + })); + const subgraphs = await gatherIterator(this.getSubgraphsAsync()); + const parentNamespace = saved.config.configurable?.checkpoint_ns ?? ""; + const taskStates = {}; + for (const task of nextTasks) { + const matchingSubgraph = subgraphs.find(([name]) => name === task.name); + if (!matchingSubgraph) continue; + let taskNs = `${String(task.name)}${CHECKPOINT_NAMESPACE_END}${task.id}`; + if (parentNamespace) taskNs = `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${taskNs}`; + if (subgraphCheckpointer === void 0) { + const config$1 = { configurable: { + thread_id: saved.config.configurable?.thread_id, + checkpoint_ns: taskNs + } }; + taskStates[task.id] = config$1; + } else { + const subgraphConfig = { configurable: { + [CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer, + thread_id: saved.config.configurable?.thread_id, + checkpoint_ns: taskNs + } }; + const pregel = matchingSubgraph[1]; + taskStates[task.id] = await pregel.getState(subgraphConfig, { subgraphs: true }); + } + } + if (applyPendingWrites && saved.pendingWrites?.length) { + const nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task])); + for (const [taskId, channel, value] of saved.pendingWrites) { + if ([ + constants_ERROR, + constants_INTERRUPT, + SCHEDULED + ].includes(channel)) continue; + if (!(taskId in nextTaskById)) continue; + nextTaskById[taskId].writes.push([String(channel), value]); + } + const tasksWithWrites$1 = nextTasks.filter((task) => task.writes.length > 0); + if (tasksWithWrites$1.length > 0) _applyWrites(saved.checkpoint, channels, tasksWithWrites$1, void 0, this.triggerToNodes); + } + let metadata = saved?.metadata; + if (metadata && saved?.config?.configurable?.thread_id) metadata = { + ...metadata, + thread_id: saved.config.configurable.thread_id + }; + const nextList = nextTasks.filter((task) => task.writes.length === 0).map((task) => task.name); + return { + values: readChannels(channels, this.streamChannelsAsIs), + next: nextList, + tasks: tasksWithWrites(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs), + metadata, + config: patchCheckpointMap(saved.config, saved.metadata), + createdAt: saved.checkpoint.ts, + parentConfig: saved.parentConfig + }; + } + /** + * Gets the current state of the graph. + * Requires a checkpointer to be configured. + * + * @param config - Configuration for retrieving the state + * @param options - Additional options + * @returns A snapshot of the current graph state + * @throws {GraphValueError} If no checkpointer is configured + */ + async getState(config, options) { + const checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer; + if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const checkpointNamespace = config.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) { + const recastNamespace = recastCheckpointNamespace(checkpointNamespace); + for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) return await subgraph.getState(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), { subgraphs: options?.subgraphs }); + throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`); + } + const mergedConfig = mergeConfigs(this.config, config); + const saved = await checkpointer.getTuple(config); + const snapshot = await this._prepareStateSnapshot({ + config: mergedConfig, + saved, + subgraphCheckpointer: options?.subgraphs ? checkpointer : void 0, + applyPendingWrites: !config.configurable?.checkpoint_id + }); + return snapshot; + } + /** + * Gets the history of graph states. + * Requires a checkpointer to be configured. + * Useful for: + * - Debugging execution history + * - Implementing time travel + * - Analyzing graph behavior + * + * @param config - Configuration for retrieving the history + * @param options - Options for filtering the history + * @returns An async iterator of state snapshots + * @throws {Error} If no checkpointer is configured + */ + async *getStateHistory(config, options) { + const checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer; + if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + const checkpointNamespace = config.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) { + const recastNamespace = recastCheckpointNamespace(checkpointNamespace); + for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) { + yield* pregel.getStateHistory(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), options); + return; + } + throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`); + } + const mergedConfig = mergeConfigs(this.config, config, { configurable: { checkpoint_ns: checkpointNamespace } }); + for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) yield this._prepareStateSnapshot({ + config: checkpointTuple.config, + saved: checkpointTuple + }); + } + /** + * Apply updates to the graph state in bulk. + * Requires a checkpointer to be configured. + * + * This method is useful for recreating a thread + * from a list of updates, especially if a checkpoint + * is created as a result of multiple tasks. + * + * @internal The API might change in the future. + * + * @param startConfig - Configuration for the update + * @param updates - The list of updates to apply to graph state + * @returns Updated configuration + * @throws {GraphValueError} If no checkpointer is configured + * @throws {InvalidUpdateError} If the update cannot be attributed to a node or an update can be only applied in sequence. + */ + async bulkUpdateState(startConfig, supersteps) { + const checkpointer = startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer; + if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); + if (supersteps.length === 0) throw new Error("No supersteps provided"); + if (supersteps.some((s) => s.updates.length === 0)) throw new Error("No updates provided"); + const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? ""; + if (checkpointNamespace !== "" && startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) { + const recastNamespace = recastCheckpointNamespace(checkpointNamespace); + for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) return await pregel.bulkUpdateState(patchConfigurable(startConfig, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), supersteps); + throw new Error(`Subgraph "${recastNamespace}" not found`); + } + const updateSuperStep = async (inputConfig, updates) => { + const config = this.config ? mergeConfigs(this.config, inputConfig) : inputConfig; + const saved = await checkpointer.getTuple(config); + const checkpoint = saved !== void 0 ? copyCheckpoint(saved.checkpoint) : emptyCheckpoint(); + const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions }; + const step = saved?.metadata?.step ?? -1; + let checkpointConfig = patchConfigurable(config, { checkpoint_ns: config.configurable?.checkpoint_ns ?? "" }); + let checkpointMetadata = config.metadata ?? {}; + if (saved?.config.configurable) { + checkpointConfig = patchConfigurable(config, saved.config.configurable); + checkpointMetadata = { + ...saved.metadata, + ...checkpointMetadata + }; + } + const { values, asNode } = updates[0]; + if (values == null && asNode === void 0) { + if (updates.length > 1) throw new InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`); + const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, void 0, step), { + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, {}); + return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0); + } + const channels = emptyChannels(this.channels, checkpoint); + if (values === null && asNode === END) { + if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when clearing state`); + if (saved) { + const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, { + step: (saved.metadata?.step ?? -1) + 1, + checkpointer, + store: this.store + }); + const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); + if (nullWrites.length > 0) _applyWrites(checkpoint, channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); + for (const [taskId, k, v] of saved.pendingWrites || []) { + if ([ + constants_ERROR, + constants_INTERRUPT, + SCHEDULED + ].includes(k)) continue; + if (!(taskId in nextTasks)) continue; + nextTasks[taskId].writes.push([k, v]); + } + _applyWrites(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); + } + const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step), { + ...checkpointMetadata, + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)); + return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0); + } + if (asNode === COPY) { + if (updates.length > 1) throw new InvalidUpdateError(`Cannot copy checkpoint with multiple updates`); + if (saved == null) throw new InvalidUpdateError(`Cannot copy a non-existent checkpoint`); + const isCopyWithUpdates = (values$1) => { + if (!Array.isArray(values$1)) return false; + if (values$1.length === 0) return false; + return values$1.every((v) => Array.isArray(v) && v.length === 2); + }; + const nextCheckpoint = createCheckpoint(checkpoint, void 0, step); + const nextConfig$1 = await checkpointer.put(saved.parentConfig ?? patchConfigurable(saved.config, { checkpoint_id: void 0 }), nextCheckpoint, { + source: "fork", + step: step + 1, + parents: saved.metadata?.parents ?? {} + }, {}); + if (isCopyWithUpdates(values)) { + const nextTasks = _prepareNextTasks(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig$1, false, { step: step + 2 }); + const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => { + acc[name] ??= []; + acc[name].push({ id }); + return acc; + }, {}); + const userGroupBy = values.reduce((acc, item) => { + const [values$1, asNode$1] = item; + acc[asNode$1] ??= []; + const targetIdx = acc[asNode$1].length; + const taskId = tasksGroupBy[asNode$1]?.[targetIdx]?.id; + acc[asNode$1].push({ + values: values$1, + asNode: asNode$1, + taskId + }); + return acc; + }, {}); + return updateSuperStep(patchCheckpointMap(nextConfig$1, saved.metadata), Object.values(userGroupBy).flat()); + } + return patchCheckpointMap(nextConfig$1, saved.metadata); + } + if (asNode === INPUT) { + if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when updating as input`); + const inputWrites = await gatherIterator(mapInput(this.inputChannels, values)); + if (inputWrites.length === 0) throw new InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`); + _applyWrites(checkpoint, channels, [{ + name: INPUT, + writes: inputWrites, + triggers: [] + }], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); + const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1; + const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, nextStep), { + source: "input", + step: nextStep, + parents: saved?.metadata?.parents ?? {} + }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)); + await checkpointer.putWrites(nextConfig$1, inputWrites, uuid5(INPUT, checkpoint.id)); + return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0); + } + if (config.configurable?.checkpoint_id === void 0 && saved?.pendingWrites !== void 0 && saved.pendingWrites.length > 0) { + const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { + store: this.store, + checkpointer: this.checkpointer, + step: (saved.metadata?.step ?? -1) + 1 + }); + const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); + if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{ + name: INPUT, + writes: nullWrites, + triggers: [] + }], void 0, this.triggerToNodes); + for (const [tid, k, v] of saved.pendingWrites) { + if ([ + constants_ERROR, + constants_INTERRUPT, + SCHEDULED + ].includes(k) || nextTasks[tid] === void 0) continue; + nextTasks[tid].writes.push([k, v]); + } + const tasks$1 = Object.values(nextTasks).filter((task) => { + return task.writes.length > 0; + }); + if (tasks$1.length > 0) _applyWrites(checkpoint, channels, tasks$1, void 0, this.triggerToNodes); + } + const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => { + return Object.values(seenVersions); + }).flat().find((v) => !!v); + const validUpdates = []; + if (updates.length === 1) { + let { values: values$1, asNode: asNode$1, taskId } = updates[0]; + if (asNode$1 === void 0 && Object.keys(this.nodes).length === 1) [asNode$1] = Object.keys(this.nodes); + else if (asNode$1 === void 0 && nonNullVersion === void 0) { + if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== void 0) asNode$1 = this.inputChannels; + } else if (asNode$1 === void 0) { + const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n, seen]) => { + return Object.values(seen).map((v) => { + return [v, n]; + }); + }).flat().filter(([_, v]) => v !== constants_INTERRUPT).sort(([aNumber], [bNumber]) => compareChannelVersions(aNumber, bNumber)); + if (lastSeenByNode) { + if (lastSeenByNode.length === 1) asNode$1 = lastSeenByNode[0][1]; + else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) asNode$1 = lastSeenByNode[lastSeenByNode.length - 1][1]; + } + } + if (asNode$1 === void 0) throw new InvalidUpdateError(`Ambiguous update, specify "asNode"`); + validUpdates.push({ + values: values$1, + asNode: asNode$1, + taskId + }); + } else for (const { asNode: asNode$1, values: values$1, taskId } of updates) { + if (asNode$1 == null) throw new InvalidUpdateError(`"asNode" is required when applying multiple updates`); + validUpdates.push({ + values: values$1, + asNode: asNode$1, + taskId + }); + } + const tasks = []; + for (const { asNode: asNode$1, values: values$1, taskId } of validUpdates) { + if (this.nodes[asNode$1] === void 0) throw new InvalidUpdateError(`Node "${asNode$1.toString()}" does not exist`); + const writers = this.nodes[asNode$1].getWriters(); + if (!writers.length) throw new InvalidUpdateError(`No writers found for node "${asNode$1.toString()}"`); + tasks.push({ + name: asNode$1, + input: values$1, + proc: writers.length > 1 ? RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0], + writes: [], + triggers: [constants_INTERRUPT], + id: taskId ?? uuid5(constants_INTERRUPT, checkpoint.id), + writers: [] + }); + } + for (const task of tasks) await task.proc.invoke(task.input, config_patchConfig({ + ...config, + store: config?.store ?? this.store + }, { + runName: config.runName ?? `${this.getName()}UpdateState`, + configurable: { + [CONFIG_KEY_SEND]: (items) => task.writes.push(...items), + [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, task, select_, fresh_) + } + })); + for (const task of tasks) { + const channelWrites = task.writes.filter((w) => w[0] !== PUSH); + if (saved !== void 0 && channelWrites.length > 0) await checkpointer.putWrites(checkpointConfig, channelWrites, task.id); + } + _applyWrites(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); + const newVersions = getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions); + const nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step + 1), { + source: "update", + step: step + 1, + parents: saved?.metadata?.parents ?? {} + }, newVersions); + for (const task of tasks) { + const pushWrites = task.writes.filter((w) => w[0] === PUSH); + if (pushWrites.length > 0) await checkpointer.putWrites(nextConfig, pushWrites, task.id); + } + return patchCheckpointMap(nextConfig, saved ? saved.metadata : void 0); + }; + let currentConfig = startConfig; + for (const { updates } of supersteps) currentConfig = await updateSuperStep(currentConfig, updates); + return currentConfig; + } + /** + * Updates the state of the graph with new values. + * Requires a checkpointer to be configured. + * + * This method can be used for: + * - Implementing human-in-the-loop workflows + * - Modifying graph state during breakpoints + * - Integrating external inputs into the graph + * + * @param inputConfig - Configuration for the update + * @param values - The values to update the state with + * @param asNode - Optional node name to attribute the update to + * @returns Updated configuration + * @throws {GraphValueError} If no checkpointer is configured + * @throws {InvalidUpdateError} If the update cannot be attributed to a node + */ + async updateState(inputConfig, values, asNode) { + return this.bulkUpdateState(inputConfig, [{ updates: [{ + values, + asNode + }] }]); + } + /** + * Gets the default values for various graph configuration options. + * This is an internal method used to process and normalize configuration options. + * + * @param config - The input configuration options + * @returns A tuple containing normalized values for: + * - debug mode + * - stream modes + * - input keys + * - output keys + * - remaining config + * - interrupt before nodes + * - interrupt after nodes + * - checkpointer + * - store + * - whether stream mode is single + * - node cache + * - whether checkpoint during is enabled + * @internal + */ + _defaults(config) { + const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore,...rest } = config; + let streamModeSingle = true; + const defaultDebug = debug !== void 0 ? debug : this.debug; + let defaultOutputKeys = outputKeys; + if (defaultOutputKeys === void 0) defaultOutputKeys = this.streamChannelsAsIs; + else validateKeys(defaultOutputKeys, this.channels); + let defaultInputKeys = inputKeys; + if (defaultInputKeys === void 0) defaultInputKeys = this.inputChannels; + else validateKeys(defaultInputKeys, this.channels); + const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? []; + const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? []; + let defaultStreamMode; + if (streamMode !== void 0) { + defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode]; + streamModeSingle = typeof streamMode === "string"; + } else { + if (config.configurable?.[CONFIG_KEY_TASK_ID] !== void 0) defaultStreamMode = ["values"]; + else defaultStreamMode = this.streamMode; + streamModeSingle = true; + } + let defaultCheckpointer; + if (this.checkpointer === false) defaultCheckpointer = void 0; + else if (config !== void 0 && config.configurable?.[CONFIG_KEY_CHECKPOINTER] !== void 0) defaultCheckpointer = config.configurable[CONFIG_KEY_CHECKPOINTER]; + else if (this.checkpointer === true) throw new Error("checkpointer: true cannot be used for root graphs."); + else defaultCheckpointer = this.checkpointer; + const defaultStore = config.store ?? this.store; + const defaultCache = config.cache ?? this.cache; + if (config.durability != null && config.checkpointDuring != null) throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time."); + const checkpointDuringDurability = (() => { + if (config.checkpointDuring == null) return void 0; + if (config.checkpointDuring === false) return "exit"; + return "async"; + })(); + const defaultDurability = config.durability ?? checkpointDuringDurability ?? config?.configurable?.[CONFIG_KEY_DURABILITY] ?? "async"; + return [ + defaultDebug, + defaultStreamMode, + defaultInputKeys, + defaultOutputKeys, + rest, + defaultInterruptBefore, + defaultInterruptAfter, + defaultCheckpointer, + defaultStore, + streamModeSingle, + defaultCache, + defaultDurability + ]; + } + /** + * Streams the execution of the graph, emitting state updates as they occur. + * This is the primary method for observing graph execution in real-time. + * + * Stream modes: + * - "values": Emits complete state after each step + * - "updates": Emits only state changes after each step + * - "debug": Emits detailed debug information + * - "messages": Emits messages from within nodes + * - "custom": Emits custom events from within nodes + * - "checkpoints": Emits checkpoints from within nodes + * - "tasks": Emits tasks from within nodes + * + * @param input - The input to start graph execution with + * @param options - Configuration options for streaming + * @returns An async iterable stream of graph state updates + */ + async stream(input, options) { + const abortController = new AbortController(); + const config = { + recursionLimit: this.config?.recursionLimit, + ...options, + signal: combineAbortSignals(options?.signal, abortController.signal).signal + }; + const stream = await super.stream(input, config); + return new IterableReadableStreamWithAbortSignal(options?.encoding === "text/event-stream" ? toEventStream(stream) : stream, abortController); + } + streamEvents(input, options, streamOptions) { + const abortController = new AbortController(); + const config = { + recursionLimit: this.config?.recursionLimit, + ...options, + callbacks: combineCallbacks(this.config?.callbacks, options?.callbacks), + signal: combineAbortSignals(options?.signal, abortController.signal).signal + }; + return new IterableReadableStreamWithAbortSignal(super.streamEvents(input, config, streamOptions), abortController); + } + /** + * Validates the input for the graph. + * @param input - The input to validate + * @returns The validated input + * @internal + */ + async _validateInput(input) { + return input; + } + /** + * Validates the context options for the graph. + * @param context - The context options to validate + * @returns The validated context options + * @internal + */ + async _validateContext(context) { + return context; + } + /** + * Internal iterator used by stream() to generate state updates. + * This method handles the core logic of graph execution and streaming. + * + * @param input - The input to start graph execution with + * @param options - Configuration options for streaming + * @returns AsyncGenerator yielding state updates + * @internal + */ + async *_streamIterator(input, options) { + const streamEncoding = "version" in (options ?? {}) ? void 0 : options?.encoding ?? void 0; + const streamSubgraphs = options?.subgraphs; + const inputConfig = config_ensureLangGraphConfig(this.config, options); + if (inputConfig.recursionLimit === void 0 || inputConfig.recursionLimit < 1) throw new Error(`Passed "recursionLimit" must be at least 1.`); + if (this.checkpointer !== void 0 && this.checkpointer !== false && inputConfig.configurable === void 0) throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`); + const validInput = await this._validateInput(input); + const { runId,...restConfig } = inputConfig; + const [debug, streamMode, , outputKeys, config, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache, durability] = this._defaults(restConfig); + if (typeof config.context !== "undefined") config.context = await this._validateContext(config.context); + else config.configurable = await this._validateContext(config.configurable); + const stream = new IterableReadableWritableStream({ modes: new Set(streamMode) }); + if (this.checkpointer === true) { + config.configurable ??= {}; + const ns = config.configurable[CONFIG_KEY_CHECKPOINT_NS] ?? ""; + config.configurable[CONFIG_KEY_CHECKPOINT_NS] = ns.split(CHECKPOINT_NAMESPACE_SEPARATOR).map((part) => part.split(CHECKPOINT_NAMESPACE_END)[0]).join(CHECKPOINT_NAMESPACE_SEPARATOR); + } + if (streamMode.includes("messages")) { + const messageStreamer = new StreamMessagesHandler((chunk) => stream.push(chunk)); + const { callbacks } = config; + if (callbacks === void 0) config.callbacks = [messageStreamer]; + else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(messageStreamer); + else { + const copiedCallbacks = callbacks.copy(); + copiedCallbacks.addHandler(messageStreamer, true); + config.callbacks = copiedCallbacks; + } + } + config.writer ??= (chunk) => { + if (!streamMode.includes("custom")) return; + const ns = (getConfig()?.configurable?.[CONFIG_KEY_CHECKPOINT_NS])?.split(CHECKPOINT_NAMESPACE_SEPARATOR).slice(0, -1); + stream.push([ + ns ?? [], + "custom", + chunk + ]); + }; + config.interrupt ??= this.userInterrupt ?? interrupt; + const callbackManager = await getCallbackManagerForConfig(config); + const runManager = await callbackManager?.handleChainStart(this.toJSON(), utils_coerceToDict(input, "input"), runId, void 0, void 0, void 0, config?.runName ?? this.getName()); + const channelSpecs = getOnlyChannels(this.channels); + let loop; + let loopError; + /** + * The PregelLoop will yield events from concurrent tasks as soon as they are + * generated. Each task can push multiple events onto the stream in any order. + * + * We use a separate background method and stream here in order to yield events + * from the loop to the main stream and therefore back to the user as soon as + * they are available. + */ + const createAndRunLoop = async () => { + try { + loop = await PregelLoop.initialize({ + input: validInput, + config, + checkpointer, + nodes: this.nodes, + channelSpecs, + outputKeys, + streamKeys: this.streamChannelsAsIs, + store, + cache, + stream, + interruptAfter, + interruptBefore, + manager: runManager, + debug: this.debug, + triggerToNodes: this.triggerToNodes, + durability + }); + const runner = new PregelRunner({ + loop, + nodeFinished: config.configurable?.[CONFIG_KEY_NODE_FINISHED] + }); + if (options?.subgraphs) loop.config.configurable = { + ...loop.config.configurable, + [CONFIG_KEY_STREAM]: loop.stream + }; + await this._runLoop({ + loop, + runner, + debug, + config + }); + if (durability === "sync") await Promise.all(loop?.checkpointerPromises ?? []); + } catch (e) { + loopError = e; + } finally { + try { + if (loop) { + await loop.store?.stop(); + await loop.cache?.stop(); + } + await Promise.all(loop?.checkpointerPromises ?? []); + } catch (e) { + loopError = loopError ?? e; + } + if (loopError) stream.error(loopError); + else stream.close(); + } + }; + const runLoopPromise = createAndRunLoop(); + try { + for await (const chunk of stream) { + if (chunk === void 0) throw new Error("Data structure error."); + const [namespace, mode, payload] = chunk; + if (streamMode.includes(mode)) { + if (streamEncoding === "text/event-stream") { + if (streamSubgraphs) yield [ + namespace, + mode, + payload + ]; + else yield [ + null, + mode, + payload + ]; + continue; + } + if (streamSubgraphs && !streamModeSingle) yield [ + namespace, + mode, + payload + ]; + else if (!streamModeSingle) yield [mode, payload]; + else if (streamSubgraphs) yield [namespace, payload]; + else yield payload; + } + } + } catch (e) { + await runManager?.handleChainError(loopError); + throw e; + } finally { + await runLoopPromise; + } + await runManager?.handleChainEnd(loop?.output ?? {}, runId, void 0, void 0, void 0); + } + /** + * Run the graph with a single input and config. + * @param input The input to the graph. + * @param options The configuration to use for the run. + */ + async invoke(input, options) { + const streamMode = options?.streamMode ?? "values"; + const config = { + ...options, + outputKeys: options?.outputKeys ?? this.outputChannels, + streamMode, + encoding: void 0 + }; + const chunks = []; + const stream = await this.stream(input, config); + const interruptChunks = []; + let latest; + for await (const chunk of stream) if (streamMode === "values") if (isInterrupted(chunk)) interruptChunks.push(chunk[constants_INTERRUPT]); + else latest = chunk; + else chunks.push(chunk); + if (streamMode === "values") { + if (interruptChunks.length > 0) { + const interrupts = interruptChunks.flat(1); + if (latest == null) return { [constants_INTERRUPT]: interrupts }; + if (typeof latest === "object") return { + ...latest, + [constants_INTERRUPT]: interrupts + }; + } + return latest; + } + return chunks; + } + async _runLoop(params) { + const { loop, runner, debug, config } = params; + let tickError; + try { + while (await loop.tick({ inputKeys: this.inputChannels })) { + for (const { task } of await loop._matchCachedWrites()) loop._outputWrites(task.id, task.writes, true); + if (debug) printStepCheckpoint(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList); + if (debug) printStepTasks(loop.step, Object.values(loop.tasks)); + await runner.tick({ + timeout: this.stepTimeout, + retryPolicy: this.retryPolicy, + onStepWrite: (step, writes) => { + if (debug) printStepWrites(step, writes, this.streamChannelsList); + }, + maxConcurrency: config.maxConcurrency, + signal: config.signal + }); + } + if (loop.status === "out_of_steps") throw new GraphRecursionError([ + `Recursion limit of ${config.recursionLimit} reached`, + "without hitting a stop condition. You can increase the", + `limit by setting the "recursionLimit" config key.` + ].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" }); + } catch (e) { + tickError = e; + const suppress = await loop.finishAndHandleError(tickError); + if (!suppress) throw e; + } finally { + if (tickError === void 0) await loop.finishAndHandleError(); + } + } + async clearCache() { + await this.cache?.clear([]); + } +}; + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/ephemeral_value.js + + + +//#region src/channels/ephemeral_value.ts +/** +* Stores the value received in the step immediately preceding, clears after. +*/ +var EphemeralValue = class EphemeralValue extends BaseChannel { + lc_graph_name = "EphemeralValue"; + guard; + value = []; + constructor(guard = true) { + super(); + this.guard = guard; + } + fromCheckpoint(checkpoint) { + const empty = new EphemeralValue(this.guard); + if (typeof checkpoint !== "undefined") empty.value = [checkpoint]; + return empty; + } + update(values) { + if (values.length === 0) { + const updated = this.value.length > 0; + this.value = []; + return updated; + } + if (values.length !== 1 && this.guard) throw new InvalidUpdateError("EphemeralValue can only receive one value per step."); + this.value = [values[values.length - 1]]; + return true; + } + get() { + if (this.value.length === 0) throw new EmptyChannelError(); + return this.value[0]; + } + checkpoint() { + if (this.value.length === 0) throw new EmptyChannelError(); + return this.value[0]; + } + isAvailable() { + return this.value.length !== 0; + } +}; + +//#endregion + +//# sourceMappingURL=ephemeral_value.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/graph.js + + + + + + + + + + + + + +//#region src/graph/graph.ts +var Branch = class { + path; + ends; + constructor(options) { + if (Runnable.isRunnable(options.path)) this.path = options.path; + else this.path = _coerceToRunnable(options.path).withConfig({ runName: `Branch` }); + this.ends = Array.isArray(options.pathMap) ? options.pathMap.reduce((acc, n) => { + acc[n] = n; + return acc; + }, {}) : options.pathMap; + } + run(writer, reader) { + return ChannelWrite.registerWriter(new RunnableCallable({ + name: "", + trace: false, + func: async (input, config) => { + try { + return await this._route(input, config, writer, reader); + } catch (e) { + if (e.name === NodeInterrupt.unminifiable_name) console.warn("[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.\nNodeInterrupt should only be thrown inside a node, not in edge conditions."); + throw e; + } + } + })); + } + async _route(input, config, writer, reader) { + let result = await this.path.invoke(reader ? reader(config) : input, config); + if (!Array.isArray(result)) result = [result]; + let destinations; + if (this.ends) destinations = result.map((r) => _isSend(r) ? r : this.ends[r]); + else destinations = result; + if (destinations.some((dest) => !dest)) throw new Error("Branch condition returned unknown or null destination"); + if (destinations.filter(_isSend).some((packet) => packet.node === END)) throw new InvalidUpdateError("Cannot send a packet to the END node"); + const writeResult = await writer(destinations, config); + return writeResult ?? input; + } +}; +var Graph$1 = class { + nodes; + edges; + branches; + entryPoint; + compiled = false; + constructor() { + this.nodes = {}; + this.edges = /* @__PURE__ */ new Set(); + this.branches = {}; + } + warnIfCompiled(message) { + if (this.compiled) console.warn(message); + } + get allEdges() { + return this.edges; + } + addNode(...args) { + function isMutlipleNodes(args$1) { + return args$1.length >= 1 && typeof args$1[0] !== "string"; + } + const nodes = isMutlipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]) : [[ + args[0], + args[1], + args[2] + ]]; + if (nodes.length === 0) throw new Error("No nodes provided in `addNode`"); + for (const [key, action, options] of nodes) { + for (const reservedChar of [CHECKPOINT_NAMESPACE_SEPARATOR, CHECKPOINT_NAMESPACE_END]) if (key.includes(reservedChar)) throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); + this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); + if (key in this.nodes) throw new Error(`Node \`${key}\` already present.`); + if (key === END) throw new Error(`Node \`${key}\` is reserved.`); + const runnable = _coerceToRunnable(action); + this.nodes[key] = { + runnable, + metadata: options?.metadata, + subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, + ends: options?.ends + }; + } + return this; + } + addEdge(startKey, endKey) { + this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`); + if (startKey === END) throw new Error("END cannot be a start node"); + if (endKey === START) throw new Error("START cannot be an end node"); + if (Array.from(this.edges).some(([start]) => start === startKey) && !("channels" in this)) throw new Error(`Already found path for ${startKey}. For multiple edges, use StateGraph.`); + this.edges.add([startKey, endKey]); + return this; + } + addConditionalEdges(source, path, pathMap) { + const options = typeof source === "object" ? source : { + source, + path, + pathMap + }; + this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); + if (!Runnable.isRunnable(options.path)) { + const pathDisplayValues = Array.isArray(options.pathMap) ? options.pathMap.join(",") : Object.keys(options.pathMap ?? {}).join(","); + options.path = _coerceToRunnable(options.path).withConfig({ runName: `Branch<${options.source}${pathDisplayValues !== "" ? `,${pathDisplayValues}` : ""}>`.slice(0, 63) }); + } + const name = options.path.getName() === "RunnableLambda" ? "condition" : options.path.getName(); + if (this.branches[options.source] && this.branches[options.source][name]) throw new Error(`Condition \`${name}\` already present for node \`${source}\``); + this.branches[options.source] ??= {}; + this.branches[options.source][name] = new Branch(options); + return this; + } + /** + * @deprecated use `addEdge(START, key)` instead + */ + setEntryPoint(key) { + this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."); + return this.addEdge(START, key); + } + /** + * @deprecated use `addEdge(key, END)` instead + */ + setFinishPoint(key) { + this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."); + return this.addEdge(key, END); + } + compile({ checkpointer, interruptBefore, interruptAfter, name } = {}) { + this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); + const compiled = new CompiledGraph({ + builder: this, + checkpointer, + interruptAfter, + interruptBefore, + autoValidate: false, + nodes: {}, + channels: { + [START]: new EphemeralValue(), + [END]: new EphemeralValue() + }, + inputChannels: START, + outputChannels: END, + streamChannels: [], + streamMode: "values", + name + }); + for (const [key, node] of Object.entries(this.nodes)) compiled.attachNode(key, node); + for (const [start, end] of this.edges) compiled.attachEdge(start, end); + for (const [start, branches] of Object.entries(this.branches)) for (const [name$1, branch] of Object.entries(branches)) compiled.attachBranch(start, name$1, branch); + return compiled.validate(); + } + validate(interrupt) { + const allSources = new Set([...this.allEdges].map(([src, _]) => src)); + for (const [start] of Object.entries(this.branches)) allSources.add(start); + for (const source of allSources) if (source !== START && !(source in this.nodes)) throw new Error(`Found edge starting at unknown node \`${source}\``); + const allTargets = new Set([...this.allEdges].map(([_, target]) => target)); + for (const [start, branches] of Object.entries(this.branches)) for (const branch of Object.values(branches)) if (branch.ends != null) for (const end of Object.values(branch.ends)) allTargets.add(end); + else { + allTargets.add(END); + for (const node of Object.keys(this.nodes)) if (node !== start) allTargets.add(node); + } + for (const node of Object.values(this.nodes)) for (const target of node.ends ?? []) allTargets.add(target); + for (const node of Object.keys(this.nodes)) if (!allTargets.has(node)) throw new UnreachableNodeError([ + `Node \`${node}\` is not reachable.`, + "", + "If you are returning Command objects from your node,", + "make sure you are passing names of potential destination nodes as an \"ends\" array", + "into \".addNode(..., { ends: [\"node1\", \"node2\"] })\"." + ].join("\n"), { lc_error_code: "UNREACHABLE_NODE" }); + for (const target of allTargets) if (target !== END && !(target in this.nodes)) throw new Error(`Found edge ending at unknown node \`${target}\``); + if (interrupt) { + for (const node of interrupt) if (!(node in this.nodes)) throw new Error(`Interrupt node \`${node}\` is not present`); + } + this.compiled = true; + } +}; +var CompiledGraph = class extends Pregel { + builder; + constructor({ builder,...rest }) { + super(rest); + this.builder = builder; + } + attachNode(key, node) { + this.channels[key] = new EphemeralValue(); + this.nodes[key] = new PregelNode({ + channels: [], + triggers: [], + metadata: node.metadata, + subgraphs: node.subgraphs, + ends: node.ends + }).pipe(node.runnable).pipe(new ChannelWrite([{ + channel: key, + value: PASSTHROUGH + }], [TAG_HIDDEN])); + this.streamChannels.push(key); + } + attachEdge(start, end) { + if (end === END) { + if (start === START) throw new Error("Cannot have an edge from START to END"); + this.nodes[start].writers.push(new ChannelWrite([{ + channel: END, + value: PASSTHROUGH + }], [TAG_HIDDEN])); + } else { + this.nodes[end].triggers.push(start); + this.nodes[end].channels.push(start); + } + } + attachBranch(start, name, branch) { + if (start === START && !this.nodes[START]) this.nodes[START] = Channel.subscribeTo(START, { tags: [TAG_HIDDEN] }); + this.nodes[start].pipe(branch.run((dests) => { + const writes = dests.map((dest) => { + if (_isSend(dest)) return dest; + return { + channel: dest === END ? END : `branch:${start}:${name}:${dest}`, + value: PASSTHROUGH + }; + }); + return new ChannelWrite(writes, [TAG_HIDDEN]); + })); + const ends = branch.ends ? Object.values(branch.ends) : Object.keys(this.nodes); + for (const end of ends) if (end !== END) { + const channelName = `branch:${start}:${name}:${end}`; + this.channels[channelName] = new EphemeralValue(); + this.nodes[end].triggers.push(channelName); + this.nodes[end].channels.push(channelName); + } + } + /** + * Returns a drawable representation of the computation graph. + */ + async getGraphAsync(config) { + const xray = config?.xray; + const graph = new Graph(); + const startNodes = { [START]: graph.addNode({ schema: any() }, START) }; + const endNodes = {}; + let subgraphs = {}; + if (xray) subgraphs = Object.fromEntries((await gatherIterator(this.getSubgraphsAsync())).filter((x) => isCompiledGraph(x[1]))); + function addEdge(start, end, label, conditional = false) { + if (end === END && endNodes[END] === void 0) endNodes[END] = graph.addNode({ schema: any() }, END); + if (startNodes[start] === void 0) return; + if (endNodes[end] === void 0) throw new Error(`End node ${end} not found!`); + return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional); + } + for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { + const displayKey = _escapeMermaidKeywords(key); + const node = nodeSpec.runnable; + const metadata = nodeSpec.metadata ?? {}; + if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) metadata.__interrupt = "before,after"; + else if (this.interruptBefore?.includes(key)) metadata.__interrupt = "before"; + else if (this.interruptAfter?.includes(key)) metadata.__interrupt = "after"; + if (xray) { + const newXrayValue = typeof xray === "number" ? xray - 1 : xray; + const drawableSubgraph = subgraphs[key] !== void 0 ? await subgraphs[key].getGraphAsync({ + ...config, + xray: newXrayValue + }) : node.getGraph(config); + drawableSubgraph.trimFirstNode(); + drawableSubgraph.trimLastNode(); + if (Object.keys(drawableSubgraph.nodes).length > 1) { + const [e, s] = graph.extend(drawableSubgraph, displayKey); + if (e === void 0) throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); + function _isRunnableInterface(thing) { + return thing ? thing.lc_runnable : false; + } + function _nodeDataStr(id, data) { + if (id !== void 0 && !wrapper_validate(id)) return id; + else if (_isRunnableInterface(data)) try { + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; + return dataStr; + } catch (error) { + return data.getName(); + } + else return data.name ?? "UnknownSchema"; + } + if (s !== void 0) startNodes[displayKey] = { + name: _nodeDataStr(s.id, s.data), + ...s + }; + endNodes[displayKey] = { + name: _nodeDataStr(e.id, e.data), + ...e + }; + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } + const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { + if (a < b) return -1; + else if (b > a) return 1; + else return 0; + }); + for (const [start, end] of sortedEdges) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); + for (const [start, branches] of Object.entries(this.builder.branches)) { + const defaultEnds = { + ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), + [END]: END + }; + for (const branch of Object.values(branches)) { + let ends; + if (branch.ends !== void 0) ends = branch.ends; + else ends = defaultEnds; + for (const [label, end] of Object.entries(ends)) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); + } + } + for (const [key, node] of Object.entries(this.builder.nodes)) if (node.ends !== void 0) for (const end of node.ends) addEdge(_escapeMermaidKeywords(key), _escapeMermaidKeywords(end), void 0, true); + return graph; + } + /** + * Returns a drawable representation of the computation graph. + * + * @deprecated Use getGraphAsync instead. The async method will be the default in the next minor core release. + */ + getGraph(config) { + const xray = config?.xray; + const graph = new Graph(); + const startNodes = { [START]: graph.addNode({ schema: any() }, START) }; + const endNodes = {}; + let subgraphs = {}; + if (xray) subgraphs = Object.fromEntries(gatherIteratorSync(this.getSubgraphs()).filter((x) => isCompiledGraph(x[1]))); + function addEdge(start, end, label, conditional = false) { + if (end === END && endNodes[END] === void 0) endNodes[END] = graph.addNode({ schema: any() }, END); + return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional); + } + for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { + const displayKey = _escapeMermaidKeywords(key); + const node = nodeSpec.runnable; + const metadata = nodeSpec.metadata ?? {}; + if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) metadata.__interrupt = "before,after"; + else if (this.interruptBefore?.includes(key)) metadata.__interrupt = "before"; + else if (this.interruptAfter?.includes(key)) metadata.__interrupt = "after"; + if (xray) { + const newXrayValue = typeof xray === "number" ? xray - 1 : xray; + const drawableSubgraph = subgraphs[key] !== void 0 ? subgraphs[key].getGraph({ + ...config, + xray: newXrayValue + }) : node.getGraph(config); + drawableSubgraph.trimFirstNode(); + drawableSubgraph.trimLastNode(); + if (Object.keys(drawableSubgraph.nodes).length > 1) { + const [e, s] = graph.extend(drawableSubgraph, displayKey); + if (e === void 0) throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); + function _isRunnableInterface(thing) { + return thing ? thing.lc_runnable : false; + } + function _nodeDataStr(id, data) { + if (id !== void 0 && !wrapper_validate(id)) return id; + else if (_isRunnableInterface(data)) try { + let dataStr = data.getName(); + dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; + return dataStr; + } catch (error) { + return data.getName(); + } + else return data.name ?? "UnknownSchema"; + } + if (s !== void 0) startNodes[displayKey] = { + name: _nodeDataStr(s.id, s.data), + ...s + }; + endNodes[displayKey] = { + name: _nodeDataStr(e.id, e.data), + ...e + }; + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } else { + const newNode = graph.addNode(node, displayKey, metadata); + startNodes[displayKey] = newNode; + endNodes[displayKey] = newNode; + } + } + const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { + if (a < b) return -1; + else if (b > a) return 1; + else return 0; + }); + for (const [start, end] of sortedEdges) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); + for (const [start, branches] of Object.entries(this.builder.branches)) { + const defaultEnds = { + ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), + [END]: END + }; + for (const branch of Object.values(branches)) { + let ends; + if (branch.ends !== void 0) ends = branch.ends; + else ends = defaultEnds; + for (const [label, end] of Object.entries(ends)) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); + } + } + return graph; + } +}; +function isCompiledGraph(x) { + return typeof x.attachNode === "function" && typeof x.attachEdge === "function"; +} +function _escapeMermaidKeywords(key) { + if (key === "subgraph") return `"${key}"`; + return key; +} + +//#endregion + +//# sourceMappingURL=graph.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/named_barrier_value.js + + + +//#region src/channels/named_barrier_value.ts +const areSetsEqual = (a, b) => a.size === b.size && [...a].every((value) => b.has(value)); +/** +* A channel that waits until all named values are received before making the value available. +* +* This ensures that if node N and node M both write to channel C, the value of C will not be updated +* until N and M have completed updating. +*/ +var NamedBarrierValue = class NamedBarrierValue extends BaseChannel { + lc_graph_name = "NamedBarrierValue"; + names; + seen; + constructor(names) { + super(); + this.names = names; + this.seen = /* @__PURE__ */ new Set(); + } + fromCheckpoint(checkpoint) { + const empty = new NamedBarrierValue(this.names); + if (typeof checkpoint !== "undefined") empty.seen = new Set(checkpoint); + return empty; + } + update(values) { + let updated = false; + for (const nodeName of values) if (this.names.has(nodeName)) { + if (!this.seen.has(nodeName)) { + this.seen.add(nodeName); + updated = true; + } + } else throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); + return updated; + } + get() { + if (!areSetsEqual(this.names, this.seen)) throw new EmptyChannelError(); + return void 0; + } + checkpoint() { + return [...this.seen]; + } + consume() { + if (this.seen && this.names && areSetsEqual(this.seen, this.names)) { + this.seen = /* @__PURE__ */ new Set(); + return true; + } + return false; + } + isAvailable() { + return !!this.names && areSetsEqual(this.names, this.seen); + } +}; +/** +* A channel that waits until all named values are received before making the value ready to be made available. +* It is only made available after finish() is called. +* @internal +*/ +var NamedBarrierValueAfterFinish = class NamedBarrierValueAfterFinish extends BaseChannel { + lc_graph_name = "NamedBarrierValueAfterFinish"; + names; + seen; + finished; + constructor(names) { + super(); + this.names = names; + this.seen = /* @__PURE__ */ new Set(); + this.finished = false; + } + fromCheckpoint(checkpoint) { + const empty = new NamedBarrierValueAfterFinish(this.names); + if (typeof checkpoint !== "undefined") { + const [seen, finished] = checkpoint; + empty.seen = new Set(seen); + empty.finished = finished; + } + return empty; + } + update(values) { + let updated = false; + for (const nodeName of values) if (this.names.has(nodeName) && !this.seen.has(nodeName)) { + this.seen.add(nodeName); + updated = true; + } else if (!this.names.has(nodeName)) throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); + return updated; + } + get() { + if (!this.finished || !areSetsEqual(this.names, this.seen)) throw new EmptyChannelError(); + return void 0; + } + checkpoint() { + return [[...this.seen], this.finished]; + } + consume() { + if (this.finished && this.seen && this.names && areSetsEqual(this.seen, this.names)) { + this.seen = /* @__PURE__ */ new Set(); + this.finished = false; + return true; + } + return false; + } + finish() { + if (!this.finished && !!this.names && areSetsEqual(this.names, this.seen)) { + this.finished = true; + return true; + } + return false; + } + isAvailable() { + return this.finished && !!this.names && areSetsEqual(this.names, this.seen); + } +}; + +//#endregion + +//# sourceMappingURL=named_barrier_value.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/zod/meta.js + + + + +//#region src/graph/zod/meta.ts +const META_EXTRAS_DESCRIPTION_PREFIX = "lg:"; +/** +* A registry for storing and managing metadata associated with schemas. +* This class provides methods to get, extend, remove, and check metadata for a given schema. +*/ +var SchemaMetaRegistry = class { + /** + * Internal map storing schema metadata. + * @internal + */ + _map = /* @__PURE__ */ new WeakMap(); + /** + * Cache for extended schfemas. + * @internal + */ + _extensionCache = /* @__PURE__ */ new Map(); + /** + * Retrieves the metadata associated with a given schema. + * @template TValue The value type of the schema. + * @template TUpdate The update type of the schema (defaults to TValue). + * @param schema The schema to retrieve metadata for. + * @returns The associated SchemaMeta, or undefined if not present. + */ + get(schema) { + return this._map.get(schema); + } + /** + * Extends or sets the metadata for a given schema. + * @template TValue The value type of the schema. + * @template TUpdate The update type of the schema (defaults to TValue). + * @param schema The schema to extend metadata for. + * @param predicate A function that receives the existing metadata (or undefined) and returns the new metadata. + */ + extend(schema, predicate) { + const existingMeta = this.get(schema); + this._map.set(schema, predicate(existingMeta)); + } + /** + * Removes the metadata associated with a given schema. + * @param schema The schema to remove metadata for. + * @returns The SchemaMetaRegistry instance (for chaining). + */ + remove(schema) { + this._map.delete(schema); + return this; + } + /** + * Checks if metadata exists for a given schema. + * @param schema The schema to check. + * @returns True if metadata exists, false otherwise. + */ + has(schema) { + return this._map.has(schema); + } + /** + * Returns a mapping of channel instances for each property in the schema + * using the associated metadata in the registry. + * + * This is used to create the `channels` object that's passed to the `Graph` constructor. + * + * @template T The shape of the schema. + * @param schema The schema to extract channels from. + * @returns A mapping from property names to channel instances. + */ + getChannelsForSchema(schema) { + const channels = {}; + const shape = getInteropZodObjectShape(schema); + for (const [key, channelSchema] of Object.entries(shape)) { + const meta = this.get(channelSchema); + if (meta?.reducer) channels[key] = new BinaryOperatorAggregate(meta.reducer.fn, meta.default); + else channels[key] = new LastValue(meta?.default); + } + return channels; + } + /** + * Returns a modified schema that introspectively looks at all keys of the provided + * object schema, and applies the augmentations based on meta provided with those keys + * in the registry and the selectors provided in the `effects` parameter. + * + * This assumes that the passed in schema is the "root" schema object for a graph where + * the keys of the schema are the channels of the graph. Because we need to represent + * the input of a graph in a couple of different ways, the `effects` parameter allows + * us to apply those augmentations based on pre determined conditions. + * + * @param schema The root schema object to extend. + * @param effects The effects that are being applied. + * @returns The extended schema. + */ + getExtendedChannelSchemas(schema, effects) { + if (Object.keys(effects).length === 0) return schema; + const cacheKey = Object.entries(effects).filter(([, v]) => v === true).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v}`).join("|"); + const cache = this._extensionCache.get(cacheKey) ?? /* @__PURE__ */ new WeakMap(); + if (cache.has(schema)) return cache.get(schema); + let modifiedSchema = schema; + if (effects.withReducerSchema || effects.withJsonSchemaExtrasAsDescription) { + const newShapeEntries = Object.entries(getInteropZodObjectShape(schema)).map(([key, schema$1]) => { + const meta = this.get(schema$1); + let outputSchema = effects.withReducerSchema ? meta?.reducer?.schema ?? schema$1 : schema$1; + if (effects.withJsonSchemaExtrasAsDescription && meta?.jsonSchemaExtra) { + const description = getSchemaDescription(outputSchema) ?? getSchemaDescription(schema$1); + const strExtras = JSON.stringify({ + ...meta.jsonSchemaExtra, + description + }); + outputSchema = outputSchema.describe(`${META_EXTRAS_DESCRIPTION_PREFIX}${strExtras}`); + } + return [key, outputSchema]; + }); + modifiedSchema = extendInteropZodObject(schema, Object.fromEntries(newShapeEntries)); + if (isZodSchemaV3(modifiedSchema)) modifiedSchema._def.unknownKeys = "strip"; + } + if (effects.asPartial) modifiedSchema = interopZodObjectPartial(modifiedSchema); + cache.set(schema, modifiedSchema); + this._extensionCache.set(cacheKey, cache); + return modifiedSchema; + } +}; +const schemaMetaRegistry = new SchemaMetaRegistry(); +function withLangGraph(schema, meta) { + if (meta.reducer && !meta.default) { + const defaultValueGetter = getInteropZodDefaultGetter(schema); + if (defaultValueGetter != null) meta.default = defaultValueGetter; + } + if (meta.reducer) { + const schemaWithReducer = Object.assign(schema, { lg_reducer_schema: meta.reducer?.schema ?? schema }); + schemaMetaRegistry.extend(schemaWithReducer, () => meta); + return schemaWithReducer; + } else { + schemaMetaRegistry.extend(schema, () => meta); + return schema; + } +} + +//#endregion + +//# sourceMappingURL=meta.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/state.js + + + + + + + + + + + + + + + + +//#region src/graph/state.ts +const state_ROOT = "__root__"; +const PartialStateSchema = Symbol.for("langgraph.state.partial"); +/** +* A graph whose nodes communicate by reading and writing to a shared state. +* Each node takes a defined `State` as input and returns a `Partial`. +* +* Each state key can optionally be annotated with a reducer function that +* will be used to aggregate the values of that key received from multiple nodes. +* The signature of a reducer function is (left: Value, right: UpdateValue) => Value. +* +* See {@link Annotation} for more on defining state. +* +* After adding nodes and edges to your graph, you must call `.compile()` on it before +* you can use it. +* +* @example +* ```ts +* import { +* type BaseMessage, +* AIMessage, +* HumanMessage, +* } from "@langchain/core/messages"; +* import { StateGraph, Annotation } from "@langchain/langgraph"; +* +* // Define a state with a single key named "messages" that will +* // combine a returned BaseMessage or arrays of BaseMessages +* const StateAnnotation = Annotation.Root({ +* sentiment: Annotation, +* messages: Annotation({ +* reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => { +* if (Array.isArray(right)) { +* return left.concat(right); +* } +* return left.concat([right]); +* }, +* default: () => [], +* }), +* }); +* +* const graphBuilder = new StateGraph(StateAnnotation); +* +* // A node in the graph that returns an object with a "messages" key +* // will update the state by combining the existing value with the returned one. +* const myNode = (state: typeof StateAnnotation.State) => { +* return { +* messages: [new AIMessage("Some new response")], +* sentiment: "positive", +* }; +* }; +* +* const graph = graphBuilder +* .addNode("myNode", myNode) +* .addEdge("__start__", "myNode") +* .addEdge("myNode", "__end__") +* .compile(); +* +* await graph.invoke({ messages: [new HumanMessage("how are you?")] }); +* +* // { +* // messages: [HumanMessage("how are you?"), AIMessage("Some new response")], +* // sentiment: "positive", +* // } +* ``` +*/ +var StateGraph = class extends Graph$1 { + channels = {}; + waitingEdges = /* @__PURE__ */ new Set(); + /** @internal */ + _schemaDefinition; + /** @internal */ + _schemaRuntimeDefinition; + /** @internal */ + _inputDefinition; + /** @internal */ + _inputRuntimeDefinition; + /** @internal */ + _outputDefinition; + /** @internal */ + _outputRuntimeDefinition; + /** + * Map schemas to managed values + * @internal + */ + _schemaDefinitions = /* @__PURE__ */ new Map(); + /** @internal */ + _metaRegistry = schemaMetaRegistry; + /** @internal Used only for typing. */ + _configSchema; + /** @internal */ + _configRuntimeSchema; + /** @internal */ + _interrupt; + /** @internal */ + _writer; + constructor(fields, contextSchema) { + super(); + if (isZodStateGraphArgsWithStateSchema(fields)) { + const stateDef = this._metaRegistry.getChannelsForSchema(fields.state); + const inputDef = fields.input != null ? this._metaRegistry.getChannelsForSchema(fields.input) : stateDef; + const outputDef = fields.output != null ? this._metaRegistry.getChannelsForSchema(fields.output) : stateDef; + this._schemaDefinition = stateDef; + this._schemaRuntimeDefinition = fields.state; + this._inputDefinition = inputDef; + this._inputRuntimeDefinition = fields.input ?? PartialStateSchema; + this._outputDefinition = outputDef; + this._outputRuntimeDefinition = fields.output ?? fields.state; + } else if (isInteropZodObject(fields)) { + const stateDef = this._metaRegistry.getChannelsForSchema(fields); + this._schemaDefinition = stateDef; + this._schemaRuntimeDefinition = fields; + this._inputDefinition = stateDef; + this._inputRuntimeDefinition = PartialStateSchema; + this._outputDefinition = stateDef; + this._outputRuntimeDefinition = fields; + } else if (isStateGraphArgsWithInputOutputSchemas(fields)) { + this._schemaDefinition = fields.input.spec; + this._inputDefinition = fields.input.spec; + this._outputDefinition = fields.output.spec; + } else if (isStateGraphArgsWithStateSchema(fields)) { + this._schemaDefinition = fields.stateSchema.spec; + this._inputDefinition = fields.input?.spec ?? this._schemaDefinition; + this._outputDefinition = fields.output?.spec ?? this._schemaDefinition; + } else if (isStateDefinition(fields) || isAnnotationRoot(fields)) { + const spec = isAnnotationRoot(fields) ? fields.spec : fields; + this._schemaDefinition = spec; + } else if (isStateGraphArgs(fields)) { + const spec = _getChannels(fields.channels); + this._schemaDefinition = spec; + } else throw new Error("Invalid StateGraph input. Make sure to pass a valid Annotation.Root or Zod schema."); + this._inputDefinition ??= this._schemaDefinition; + this._outputDefinition ??= this._schemaDefinition; + this._addSchema(this._schemaDefinition); + this._addSchema(this._inputDefinition); + this._addSchema(this._outputDefinition); + function isOptions(options) { + return typeof options === "object" && options != null && !("spec" in options) && !isInteropZodObject(options); + } + if (isOptions(contextSchema)) { + if (isInteropZodObject(contextSchema.context)) this._configRuntimeSchema = contextSchema.context; + this._interrupt = contextSchema.interrupt; + this._writer = contextSchema.writer; + } else if (isInteropZodObject(contextSchema)) this._configRuntimeSchema = contextSchema; + } + get allEdges() { + return new Set([...this.edges, ...Array.from(this.waitingEdges).flatMap(([starts, end]) => starts.map((start) => [start, end]))]); + } + _addSchema(stateDefinition) { + if (this._schemaDefinitions.has(stateDefinition)) return; + this._schemaDefinitions.set(stateDefinition, stateDefinition); + for (const [key, val] of Object.entries(stateDefinition)) { + let channel; + if (typeof val === "function") channel = val(); + else channel = val; + if (this.channels[key] !== void 0) { + if (this.channels[key] !== channel) { + if (channel.lc_graph_name !== "LastValue") throw new Error(`Channel "${key}" already exists with a different type.`); + } + } else this.channels[key] = channel; + } + } + addNode(...args) { + function isMultipleNodes(args$1) { + return args$1.length >= 1 && typeof args$1[0] !== "string"; + } + const nodes = isMultipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]).map(([key, action]) => [key, action]) : [[ + args[0], + args[1], + args[2] + ]]; + if (nodes.length === 0) throw new Error("No nodes provided in `addNode`"); + for (const [key, action, options] of nodes) { + if (key in this.channels) throw new Error(`${key} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`); + for (const reservedChar of [CHECKPOINT_NAMESPACE_SEPARATOR, CHECKPOINT_NAMESPACE_END]) if (key.includes(reservedChar)) throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); + this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); + if (key in this.nodes) throw new Error(`Node \`${key}\` already present.`); + if (key === END || key === START) throw new Error(`Node \`${key}\` is reserved.`); + let inputSpec = this._schemaDefinition; + if (options?.input !== void 0) { + if (isInteropZodObject(options.input)) inputSpec = this._metaRegistry.getChannelsForSchema(options.input); + else if (options.input.spec !== void 0) inputSpec = options.input.spec; + } + if (inputSpec !== void 0) this._addSchema(inputSpec); + let runnable; + if (Runnable.isRunnable(action)) runnable = action; + else if (typeof action === "function") runnable = new RunnableCallable({ + func: action, + name: key, + trace: false + }); + else runnable = _coerceToRunnable(action); + let cachePolicy = options?.cachePolicy; + if (typeof cachePolicy === "boolean") cachePolicy = cachePolicy ? {} : void 0; + const nodeSpec = { + runnable, + retryPolicy: options?.retryPolicy, + cachePolicy, + metadata: options?.metadata, + input: inputSpec ?? this._schemaDefinition, + subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, + ends: options?.ends, + defer: options?.defer + }; + this.nodes[key] = nodeSpec; + } + return this; + } + addEdge(startKey, endKey) { + if (typeof startKey === "string") return super.addEdge(startKey, endKey); + if (this.compiled) console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); + for (const start of startKey) { + if (start === END) throw new Error("END cannot be a start node"); + if (!Object.keys(this.nodes).some((node) => node === start)) throw new Error(`Need to add a node named "${start}" first`); + } + if (endKey === END) throw new Error("END cannot be an end node"); + if (!Object.keys(this.nodes).some((node) => node === endKey)) throw new Error(`Need to add a node named "${endKey}" first`); + this.waitingEdges.add([startKey, endKey]); + return this; + } + addSequence(nodes) { + const parsedNodes = Array.isArray(nodes) ? nodes : Object.entries(nodes); + if (parsedNodes.length === 0) throw new Error("Sequence requires at least one node."); + let previousNode; + for (const [key, action, options] of parsedNodes) { + if (key in this.nodes) throw new Error(`Node names must be unique: node with the name "${key}" already exists.`); + const validKey = key; + this.addNode(validKey, action, options); + if (previousNode != null) this.addEdge(previousNode, validKey); + previousNode = validKey; + } + return this; + } + compile({ checkpointer, store, cache, interruptBefore, interruptAfter, name, description } = {}) { + this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); + const outputKeys = Object.keys(this._schemaDefinitions.get(this._outputDefinition)); + const outputChannels = outputKeys.length === 1 && outputKeys[0] === state_ROOT ? state_ROOT : outputKeys; + const streamKeys = Object.keys(this.channels); + const streamChannels = streamKeys.length === 1 && streamKeys[0] === state_ROOT ? state_ROOT : streamKeys; + const userInterrupt = this._interrupt; + const compiled = new CompiledStateGraph({ + builder: this, + checkpointer, + interruptAfter, + interruptBefore, + autoValidate: false, + nodes: {}, + channels: { + ...this.channels, + [START]: new EphemeralValue() + }, + inputChannels: START, + outputChannels, + streamChannels, + streamMode: "updates", + store, + cache, + name, + description, + userInterrupt + }); + compiled.attachNode(START); + for (const [key, node] of Object.entries(this.nodes)) compiled.attachNode(key, node); + compiled.attachBranch(START, SELF, _getControlBranch(), { withReader: false }); + for (const [key] of Object.entries(this.nodes)) compiled.attachBranch(key, SELF, _getControlBranch(), { withReader: false }); + for (const [start, end] of this.edges) compiled.attachEdge(start, end); + for (const [starts, end] of this.waitingEdges) compiled.attachEdge(starts, end); + for (const [start, branches] of Object.entries(this.branches)) for (const [name$1, branch] of Object.entries(branches)) compiled.attachBranch(start, name$1, branch); + return compiled.validate(); + } +}; +function _getChannels(schema) { + const channels = {}; + for (const [name, val] of Object.entries(schema)) if (name === state_ROOT) channels[name] = getChannel(val); + else channels[name] = getChannel(val); + return channels; +} +/** +* Final result from building and compiling a {@link StateGraph}. +* Should not be instantiated directly, only using the StateGraph `.compile()` +* instance method. +*/ +var CompiledStateGraph = class extends CompiledGraph { + /** + * The description of the compiled graph. + * This is used by the supervisor agent to describe the handoff to the agent. + */ + description; + /** @internal */ + _metaRegistry = schemaMetaRegistry; + constructor({ description,...rest }) { + super(rest); + this.description = description; + } + attachNode(key, node) { + let outputKeys; + if (key === START) outputKeys = Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([k]) => k); + else outputKeys = Object.keys(this.builder.channels); + function _getRoot(input) { + if (isCommand(input)) { + if (input.graph === Command.PARENT) return null; + return input._updateAsTuples(); + } else if (Array.isArray(input) && input.length > 0 && input.some((i) => isCommand(i))) { + const updates = []; + for (const i of input) if (isCommand(i)) { + if (i.graph === Command.PARENT) continue; + updates.push(...i._updateAsTuples()); + } else updates.push([state_ROOT, i]); + return updates; + } else if (input != null) return [[state_ROOT, input]]; + return null; + } + const nodeKey = key; + function _getUpdates(input) { + if (!input) return null; + else if (isCommand(input)) { + if (input.graph === Command.PARENT) return null; + return input._updateAsTuples().filter(([k]) => outputKeys.includes(k)); + } else if (Array.isArray(input) && input.length > 0 && input.some(isCommand)) { + const updates = []; + for (const item of input) if (isCommand(item)) { + if (item.graph === Command.PARENT) continue; + updates.push(...item._updateAsTuples().filter(([k]) => outputKeys.includes(k))); + } else { + const itemUpdates = _getUpdates(item); + if (itemUpdates) updates.push(...itemUpdates ?? []); + } + return updates; + } else if (typeof input === "object" && !Array.isArray(input)) return Object.entries(input).filter(([k]) => outputKeys.includes(k)); + else { + const typeofInput = Array.isArray(input) ? "array" : typeof input; + throw new InvalidUpdateError(`Expected node "${nodeKey.toString()}" to return an object or an array containing at least one Command object, received ${typeofInput}`, { lc_error_code: "INVALID_GRAPH_NODE_RETURN_VALUE" }); + } + } + const stateWriteEntries = [{ + value: PASSTHROUGH, + mapper: new RunnableCallable({ + func: outputKeys.length && outputKeys[0] === state_ROOT ? _getRoot : _getUpdates, + trace: false, + recurse: false + }) + }]; + if (key === START) this.nodes[key] = new PregelNode({ + tags: [TAG_HIDDEN], + triggers: [START], + channels: [START], + writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])] + }); + else { + const inputDefinition = node?.input ?? this.builder._schemaDefinition; + const inputValues = Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(inputDefinition)).map((k) => [k, k])); + const isSingleInput = Object.keys(inputValues).length === 1 && state_ROOT in inputValues; + const branchChannel = `branch:to:${key}`; + this.channels[branchChannel] = node?.defer ? new LastValueAfterFinish() : new EphemeralValue(false); + this.nodes[key] = new PregelNode({ + triggers: [branchChannel], + channels: isSingleInput ? Object.keys(inputValues) : inputValues, + writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])], + mapper: isSingleInput ? void 0 : (input) => { + return Object.fromEntries(Object.entries(input).filter(([k]) => k in inputValues)); + }, + bound: node?.runnable, + metadata: node?.metadata, + retryPolicy: node?.retryPolicy, + cachePolicy: node?.cachePolicy, + subgraphs: node?.subgraphs, + ends: node?.ends + }); + } + } + attachEdge(starts, end) { + if (end === END) return; + if (typeof starts === "string") this.nodes[starts].writers.push(new ChannelWrite([{ + channel: `branch:to:${end}`, + value: null + }], [TAG_HIDDEN])); + else if (Array.isArray(starts)) { + const channelName = `join:${starts.join("+")}:${end}`; + this.channels[channelName] = this.builder.nodes[end].defer ? new NamedBarrierValueAfterFinish(new Set(starts)) : new NamedBarrierValue(new Set(starts)); + this.nodes[end].triggers.push(channelName); + for (const start of starts) this.nodes[start].writers.push(new ChannelWrite([{ + channel: channelName, + value: start + }], [TAG_HIDDEN])); + } + } + attachBranch(start, _, branch, options = { withReader: true }) { + const branchWriter = async (packets, config) => { + const filteredPackets = packets.filter((p) => p !== END); + if (!filteredPackets.length) return; + const writes = filteredPackets.map((p) => { + if (_isSend(p)) return p; + return { + channel: p === END ? p : `branch:to:${p}`, + value: start + }; + }); + await ChannelWrite.doWrite({ + ...config, + tags: (config.tags ?? []).concat([TAG_HIDDEN]) + }, writes); + }; + this.nodes[start].writers.push(branch.run(branchWriter, options.withReader ? (config) => ChannelRead.doRead(config, this.streamChannels ?? this.outputChannels, true) : void 0)); + } + async _validateInput(input) { + if (input == null) return input; + const schema = (() => { + const input$1 = this.builder._inputRuntimeDefinition; + const schema$1 = this.builder._schemaRuntimeDefinition; + const apply = (schema$2) => { + if (schema$2 == null) return void 0; + return this._metaRegistry.getExtendedChannelSchemas(schema$2, { withReducerSchema: true }); + }; + if (isInteropZodObject(input$1)) return apply(input$1); + if (input$1 === PartialStateSchema) return interopZodObjectPartial(apply(schema$1)); + return void 0; + })(); + if (isCommand(input)) { + const parsedInput = input; + if (input.update && schema != null) parsedInput.update = interopParse(schema, input.update); + return parsedInput; + } + if (schema != null) return interopParse(schema, input); + return input; + } + isInterrupted(input) { + return isInterrupted(input); + } + async _validateContext(config) { + const configSchema = this.builder._configRuntimeSchema; + if (isInteropZodObject(configSchema)) interopParse(configSchema, config); + return config; + } +}; +function isStateDefinition(obj) { + return typeof obj === "object" && obj !== null && !Array.isArray(obj) && Object.keys(obj).length > 0 && Object.values(obj).every((v) => typeof v === "function" || isBaseChannel(v)); +} +function isAnnotationRoot(obj) { + return typeof obj === "object" && obj !== null && "lc_graph_name" in obj && obj.lc_graph_name === "AnnotationRoot"; +} +function isStateGraphArgs(obj) { + return typeof obj === "object" && obj !== null && obj.channels !== void 0; +} +function isStateGraphArgsWithStateSchema(obj) { + return typeof obj === "object" && obj !== null && obj.stateSchema !== void 0; +} +function isStateGraphArgsWithInputOutputSchemas(obj) { + return typeof obj === "object" && obj !== null && obj.stateSchema === void 0 && obj.input !== void 0 && obj.output !== void 0; +} +function isZodStateGraphArgsWithStateSchema(value) { + if (typeof value !== "object" || value == null) return false; + if (!("state" in value) || !isInteropZodObject(value.state)) return false; + if ("input" in value && !isInteropZodObject(value.input)) return false; + if ("output" in value && !isInteropZodObject(value.output)) return false; + return true; +} +function _controlBranch(value) { + if (_isSend(value)) return [value]; + const commands = []; + if (isCommand(value)) commands.push(value); + else if (Array.isArray(value)) commands.push(...value.filter(isCommand)); + const destinations = []; + for (const command of commands) { + if (command.graph === Command.PARENT) throw new ParentCommand(command); + if (_isSend(command.goto)) destinations.push(command.goto); + else if (typeof command.goto === "string") destinations.push(command.goto); + else if (Array.isArray(command.goto)) destinations.push(...command.goto); + } + return destinations; +} +function _getControlBranch() { + const CONTROL_BRANCH_PATH = new RunnableCallable({ + func: _controlBranch, + tags: [TAG_HIDDEN], + trace: false, + recurse: false, + name: "" + }); + return new Branch({ path: CONTROL_BRANCH_PATH }); +} + +//#endregion + +//# sourceMappingURL=state.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/message.js + + + + + +//#region src/graph/message.ts +const REMOVE_ALL_MESSAGES = "__remove_all__"; +/** +* Prebuilt reducer that combines returned messages. +* Can handle standard messages and special modifiers like {@link RemoveMessage} +* instances. +*/ +function messagesStateReducer(left, right) { + const leftArray = Array.isArray(left) ? left : [left]; + const rightArray = Array.isArray(right) ? right : [right]; + const leftMessages = leftArray.map(utils_coerceMessageLikeToMessage); + const rightMessages = rightArray.map(utils_coerceMessageLikeToMessage); + for (const m of leftMessages) if (m.id === null || m.id === void 0) { + m.id = v4(); + m.lc_kwargs.id = m.id; + } + let removeAllIdx; + for (let i = 0; i < rightMessages.length; i += 1) { + const m = rightMessages[i]; + if (m.id === null || m.id === void 0) { + m.id = v4(); + m.lc_kwargs.id = m.id; + } + if (m.getType() === "remove" && m.id === REMOVE_ALL_MESSAGES) removeAllIdx = i; + } + if (removeAllIdx != null) return rightMessages.slice(removeAllIdx + 1); + const merged = [...leftMessages]; + const mergedById = new Map(merged.map((m, i) => [m.id, i])); + const idsToRemove = /* @__PURE__ */ new Set(); + for (const m of rightMessages) { + const existingIdx = mergedById.get(m.id); + if (existingIdx !== void 0) if (m.getType() === "remove") idsToRemove.add(m.id); + else { + idsToRemove.delete(m.id); + merged[existingIdx] = m; + } + else { + if (m.getType() === "remove") throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${m.id}')`); + mergedById.set(m.id, merged.length); + merged.push(m); + } + } + return merged.filter((m) => !idsToRemove.has(m.id)); +} +/** @ignore */ +var MessageGraph = class extends StateGraph { + constructor() { + super({ channels: { __root__: { + reducer: messagesStateReducer, + default: () => [] + } } }); + } +}; +/** +* Manually push a message to a message stream. +* +* This is useful when you need to push a manually created message before the node +* has finished executing. +* +* When a message is pushed, it will be automatically persisted to the state after the node has finished executing. +* To disable persisting, set `options.stateKey` to `null`. +* +* @param message The message to push. The message must have an ID set, otherwise an error will be thrown. +* @param options RunnableConfig / Runtime coming from node context. +*/ +function pushMessage(message, options) { + const { stateKey: userStateKey,...userConfig } = options ?? {}; + const config = ensureLangGraphConfig(userConfig); + let stateKey = userStateKey ?? "messages"; + if (userStateKey === null) stateKey = void 0; + const validMessage = coerceMessageLikeToMessage(message); + if (!validMessage.id) throw new Error("Message ID is required."); + const callbacks = (() => { + if (Array.isArray(config.callbacks)) return config.callbacks; + if (typeof config.callbacks !== "undefined") return config.callbacks.handlers; + return []; + })(); + const messagesHandler = callbacks.find((cb) => "name" in cb && cb.name === "StreamMessagesHandler"); + if (messagesHandler) { + const metadata = config.metadata ?? {}; + const namespace = (metadata.langgraph_checkpoint_ns ?? "").split("|"); + messagesHandler._emit([namespace, metadata], validMessage, void 0, false); + } + if (stateKey) config.configurable?.__pregel_send?.([[stateKey, validMessage]]); + return validMessage; +} + +//#endregion + +//# sourceMappingURL=message.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/func/index.js + + + + + + + + + + +//#region src/func/index.ts +/** +* Define a LangGraph task using the `task` function. +* +* Tasks can only be called from within an {@link entrypoint} or from within a StateGraph. +* A task can be called like a regular function with the following differences: +* +* - When a checkpointer is enabled, the function inputs and outputs must be serializable. +* - The wrapped function can only be called from within an entrypoint or StateGraph. +* - Calling the function produces a promise. This makes it easy to parallelize tasks. +* +* @typeParam ArgsT - The type of arguments the task function accepts +* @typeParam OutputT - The type of value the task function returns +* @param optionsOrName - Either an {@link TaskOptions} object, or a string for the name of the task +* @param func - The function that executes this task +* @returns A proxy function that accepts the same arguments as the original and always returns the result as a Promise +* +* @example basic example +* ```typescript +* const addOne = task("add", async (a: number) => a + 1); +* +* const workflow = entrypoint("example", async (numbers: number[]) => { +* const promises = numbers.map(n => addOne(n)); +* const results = await Promise.all(promises); +* return results; +* }); +* +* // Call the entrypoint +* await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4] +* ``` +* +* @example using a retry policy +* ```typescript +* const addOne = task({ +* name: "add", +* retry: { maxAttempts: 3 } +* }, +* async (a: number) => a + 1 +* ); +* +* const workflow = entrypoint("example", async (numbers: number[]) => { +* const promises = numbers.map(n => addOne(n)); +* const results = await Promise.all(promises); +* return results; +* }); +* ``` +* @category Functional API +*/ +function task(optionsOrName, func) { + const options = typeof optionsOrName === "string" ? { + name: optionsOrName, + retry: void 0, + cachePolicy: void 0 + } : optionsOrName; + const { name, retry } = options; + if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write."); + const cachePolicy = options.cachePolicy ?? ("cache" in options ? options.cache : void 0); + let cache; + if (typeof cachePolicy === "boolean") cache = cachePolicy ? {} : void 0; + else cache = cachePolicy; + return (...args) => { + return call({ + func, + name, + retry, + cache + }, ...args); + }; +} +/** +* Define a LangGraph workflow using the `entrypoint` function. +* +* ### Function signature +* +* The wrapped function must accept at most **two parameters**. The first parameter +* is the input to the function. The second (optional) parameter is a +* {@link LangGraphRunnableConfig} object. If you wish to pass multiple parameters to +* the function, you can pass them as an object. +* +* ### Helper functions +* +* #### Streaming +* To write data to the "custom" stream, use the {@link getWriter} function, or the +* {@link LangGraphRunnableConfig.writer} property. +* +* #### State management +* The {@link getPreviousState} function can be used to access the previous state +* that was returned from the last invocation of the entrypoint on the same thread id. +* +* If you wish to save state other than the return value, you can use the +* {@link entrypoint.final} function. +* +* @typeParam InputT - The type of input the entrypoint accepts +* @typeParam OutputT - The type of output the entrypoint produces +* @param optionsOrName - Either an {@link EntrypointOptions} object, or a string for the name of the entrypoint +* @param func - The function that executes this entrypoint +* @returns A {@link Pregel} instance that can be run to execute the workflow +* +* @example Using entrypoint and tasks +* ```typescript +* import { task, entrypoint } from "@langchain/langgraph"; +* import { MemorySaver } from "@langchain/langgraph-checkpoint"; +* import { interrupt, Command } from "@langchain/langgraph"; +* +* const composeEssay = task("compose", async (topic: string) => { +* await new Promise(r => setTimeout(r, 1000)); // Simulate slow operation +* return `An essay about ${topic}`; +* }); +* +* const reviewWorkflow = entrypoint({ +* name: "review", +* checkpointer: new MemorySaver() +* }, async (topic: string) => { +* const essay = await composeEssay(topic); +* const humanReview = await interrupt({ +* question: "Please provide a review", +* essay +* }); +* return { +* essay, +* review: humanReview +* }; +* }); +* +* // Example configuration for the workflow +* const config = { +* configurable: { +* thread_id: "some_thread" +* } +* }; +* +* // Topic for the essay +* const topic = "cats"; +* +* // Stream the workflow to generate the essay and await human review +* for await (const result of reviewWorkflow.stream(topic, config)) { +* console.log(result); +* } +* +* // Example human review provided after the interrupt +* const humanReview = "This essay is great."; +* +* // Resume the workflow with the provided human review +* for await (const result of reviewWorkflow.stream(new Command({ resume: humanReview }), config)) { +* console.log(result); +* } +* ``` +* +* @example Accessing the previous return value +* ```typescript +* import { entrypoint, getPreviousState } from "@langchain/langgraph"; +* import { MemorySaver } from "@langchain/langgraph-checkpoint"; +* +* const accumulator = entrypoint({ +* name: "accumulator", +* checkpointer: new MemorySaver() +* }, async (input: string) => { +* const previous = getPreviousState(); +* return previous !== undefined ? `${previous } ${input}` : input; +* }); +* +* const config = { +* configurable: { +* thread_id: "some_thread" +* } +* }; +* await accumulator.invoke("hello", config); // returns "hello" +* await accumulator.invoke("world", config); // returns "hello world" +* ``` +* +* @example Using entrypoint.final to save a value +* ```typescript +* import { entrypoint, getPreviousState } from "@langchain/langgraph"; +* import { MemorySaver } from "@langchain/langgraph-checkpoint"; +* +* const myWorkflow = entrypoint({ +* name: "accumulator", +* checkpointer: new MemorySaver() +* }, async (num: number) => { +* const previous = getPreviousState(); +* +* // This will return the previous value to the caller, saving +* // 2 * num to the checkpoint, which will be used in the next invocation +* // for the `previous` parameter. +* return entrypoint.final({ +* value: previous ?? 0, +* save: 2 * num +* }); +* }); +* +* const config = { +* configurable: { +* thread_id: "some_thread" +* } +* }; +* +* await myWorkflow.invoke(3, config); // 0 (previous was undefined) +* await myWorkflow.invoke(1, config); // 6 (previous was 3 * 2 from the previous invocation) +* ``` +* @category Functional API +*/ +const entrypoint = function entrypoint$1(optionsOrName, func) { + const { name, checkpointer, store, cache } = typeof optionsOrName === "string" ? { + name: optionsOrName, + checkpointer: void 0, + store: void 0 + } : optionsOrName; + if (utils_isAsyncGeneratorFunction(func) || utils_isGeneratorFunction(func)) throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write."); + const streamMode = "updates"; + const bound = getRunnableForEntrypoint(name, func); + function isEntrypointFinal(value) { + return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "__pregel_final"; + } + const pluckReturnValue = new RunnableCallable({ + name: "pluckReturnValue", + func: (value) => { + return isEntrypointFinal(value) ? value.value : value; + } + }); + const pluckSaveValue = new RunnableCallable({ + name: "pluckSaveValue", + func: (value) => { + return isEntrypointFinal(value) ? value.save : value; + } + }); + const entrypointNode = new PregelNode({ + bound, + triggers: [START], + channels: [START], + writers: [new ChannelWrite([{ + channel: END, + value: PASSTHROUGH, + mapper: pluckReturnValue + }, { + channel: PREVIOUS, + value: PASSTHROUGH, + mapper: pluckSaveValue + }], [TAG_HIDDEN])] + }); + return new Pregel({ + name, + checkpointer, + nodes: { [name]: entrypointNode }, + channels: { + [START]: new EphemeralValue(), + [END]: new LastValue(), + [PREVIOUS]: new LastValue() + }, + inputChannels: START, + outputChannels: END, + streamChannels: END, + streamMode, + store, + cache + }); +}; +entrypoint.final = function final({ value, save }) { + return { + value, + save, + __lg_type: "__pregel_final" + }; +}; +/** +* A helper utility function for use with the functional API that returns the previous +* state from the checkpoint from the last invocation of the current thread. +* +* This function allows workflows to access state that was saved in previous runs +* using {@link entrypoint.final}. +* +* @typeParam StateT - The type of the state that was previously saved +* @returns The previous saved state from the last invocation of the current thread +* +* @example +* ```typescript +* const previousState = getPreviousState<{ counter: number }>(); +* const newCount = (previousState?.counter ?? 0) + 1; +* ``` +* @category Functional API +*/ +function getPreviousState() { + const config = AsyncLocalStorageProviderSingleton.getRunnableConfig(); + return config.configurable?.[CONFIG_KEY_PREVIOUS_STATE]; +} + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/messages_annotation.js + + + + + +//#region src/graph/messages_annotation.ts +/** +* Prebuilt state annotation that combines returned messages. +* Can handle standard messages and special modifiers like {@link RemoveMessage} +* instances. +* +* Specifically, importing and using the prebuilt MessagesAnnotation like this: +* +* @example +* ```ts +* import { MessagesAnnotation, StateGraph } from "@langchain/langgraph"; +* +* const graph = new StateGraph(MessagesAnnotation) +* .addNode(...) +* ... +* ``` +* +* Is equivalent to initializing your state manually like this: +* +* @example +* ```ts +* import { BaseMessage } from "@langchain/core/messages"; +* import { Annotation, StateGraph, messagesStateReducer } from "@langchain/langgraph"; +* +* export const StateAnnotation = Annotation.Root({ +* messages: Annotation({ +* reducer: messagesStateReducer, +* default: () => [], +* }), +* }); +* +* const graph = new StateGraph(StateAnnotation) +* .addNode(...) +* ... +* ``` +*/ +const MessagesAnnotation = Annotation.Root({ messages: Annotation({ + reducer: messagesStateReducer, + default: () => [] +}) }); +/** +* Prebuilt schema meta for Zod state definition. +* +* @example +* ```ts +* import { z } from "zod/v4-mini"; +* import { MessagesZodState, StateGraph } from "@langchain/langgraph"; +* +* const AgentState = z.object({ +* messages: z.custom().register(registry, MessagesZodMeta), +* }); +* ``` +*/ +const MessagesZodMeta = { + reducer: { fn: messagesStateReducer }, + jsonSchemaExtra: { langgraph_type: "messages" }, + default: () => [] +}; +/** +* Prebuilt state object that uses Zod to combine returned messages. +* This utility is synonymous with the `MessagesAnnotation` annotation, +* but uses Zod as the way to express messages state. +* +* You can use import and use this prebuilt schema like this: +* +* @example +* ```ts +* import { MessagesZodState, StateGraph } from "@langchain/langgraph"; +* +* const graph = new StateGraph(MessagesZodState) +* .addNode(...) +* ... +* ``` +* +* Which is equivalent to initializing the schema object manually like this: +* +* @example +* ```ts +* import { z } from "zod"; +* import type { BaseMessage, BaseMessageLike } from "@langchain/core/messages"; +* import { StateGraph, messagesStateReducer } from "@langchain/langgraph"; +* import "@langchain/langgraph/zod"; +* +* const AgentState = z.object({ +* messages: z +* .custom() +* .default(() => []) +* .langgraph.reducer( +* messagesStateReducer, +* z.custom() +* ), +* }); +* const graph = new StateGraph(AgentState) +* .addNode(...) +* ... +* ``` +*/ +const MessagesZodState = objectType({ messages: withLangGraph(custom(), MessagesZodMeta) }); + +//#endregion + +//# sourceMappingURL=messages_annotation.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/index.js + + + + + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/any_value.js + + + +//#region src/channels/any_value.ts +/** +* Stores the last value received, assumes that if multiple values are received, they are all equal. +* +* Note: Unlike 'LastValue' if multiple nodes write to this channel in a single step, the values +* will be continuously overwritten. +*/ +var AnyValue = class AnyValue extends BaseChannel { + lc_graph_name = "AnyValue"; + value = []; + constructor() { + super(); + } + fromCheckpoint(checkpoint) { + const empty = new AnyValue(); + if (typeof checkpoint !== "undefined") empty.value = [checkpoint]; + return empty; + } + update(values) { + if (values.length === 0) { + const updated = this.value.length > 0; + this.value = []; + return updated; + } + this.value = [values[values.length - 1]]; + return false; + } + get() { + if (this.value.length === 0) throw new EmptyChannelError(); + return this.value[0]; + } + checkpoint() { + if (this.value.length === 0) throw new EmptyChannelError(); + return this.value[0]; + } + isAvailable() { + return this.value.length !== 0; + } +}; + +//#endregion + +//# sourceMappingURL=any_value.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/dynamic_barrier_value.js + + + + +//#region src/channels/dynamic_barrier_value.ts +function isWaitForNames(v) { + return v.__names !== void 0; +} +/** +* A channel that switches between two states +* +* - in the "priming" state it can't be read from. +* - if it receives a WaitForNames update, it switches to the "waiting" state. +* - in the "waiting" state it collects named values until all are received. +* - once all named values are received, it can be read once, and it switches +* back to the "priming" state. +*/ +var DynamicBarrierValue = class DynamicBarrierValue extends BaseChannel { + lc_graph_name = "DynamicBarrierValue"; + names; + seen; + constructor() { + super(); + this.names = void 0; + this.seen = /* @__PURE__ */ new Set(); + } + fromCheckpoint(checkpoint) { + const empty = new DynamicBarrierValue(); + if (typeof checkpoint !== "undefined") { + empty.names = new Set(checkpoint[0]); + empty.seen = new Set(checkpoint[1]); + } + return empty; + } + update(values) { + const waitForNames = values.filter(isWaitForNames); + if (waitForNames.length > 0) { + if (waitForNames.length > 1) throw new InvalidUpdateError("Received multiple WaitForNames updates in the same step."); + this.names = new Set(waitForNames[0].__names); + return true; + } else if (this.names !== void 0) { + let updated = false; + for (const value of values) { + if (isWaitForNames(value)) throw new Error("Assertion Error: Received unexpected WaitForNames instance."); + if (this.names.has(value) && !this.seen.has(value)) { + this.seen.add(value); + updated = true; + } + } + return updated; + } + return false; + } + consume() { + if (this.seen && this.names && areSetsEqual(this.seen, this.names)) { + this.seen = /* @__PURE__ */ new Set(); + this.names = void 0; + return true; + } + return false; + } + get() { + if (!this.names || !areSetsEqual(this.names, this.seen)) throw new EmptyChannelError(); + return void 0; + } + checkpoint() { + return [this.names ? [...this.names] : void 0, [...this.seen]]; + } + isAvailable() { + return !!this.names && areSetsEqual(this.names, this.seen); + } +}; + +//#endregion + +//# sourceMappingURL=dynamic_barrier_value.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/index.js + + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/web.js + + + + + + + + + + + + + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/writer.js + + +//#region src/writer.ts +function writer(chunk) { + const config = AsyncLocalStorageProviderSingleton.getRunnableConfig(); + if (!config) throw new Error("Called interrupt() outside the context of a graph."); + const conf = config.configurable; + if (!conf) throw new Error("No configurable found in config"); + return conf.writer?.(chunk); +} + +//#endregion + +//# sourceMappingURL=writer.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/index.js + + + + + + + + + + + + + + + + +//#region src/index.ts +initializeAsyncLocalStorageSingleton(); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./src/tools/pr-analysis-tools.ts +/** + * PR Analysis Tools for LangChain Agent + * These tools are used by the agent to analyze different aspects of PR changes + */ + + +/** + * Parse git diff into structured file changes + */ +function parseDiff(diff) { + const files = []; + const lines = diff.split('\n'); + let currentFile = null; + let currentDiff = []; + for (let i = 0; i < lines.length; i++) { + const line = lines[i]; + // New file detected + if (line.startsWith('diff --git')) { + // Save previous file + if (currentFile) { + files.push({ + ...currentFile, + diff: currentDiff.join('\n'), + }); + } + // Parse file path + const match = line.match(/^diff --git a\/(.+?) b\/(.+?)$/); + if (match) { + const filePath = match[2] !== '/dev/null' ? match[2] : match[1]; + currentFile = { + path: filePath, + additions: 0, + deletions: 0, + language: detectLanguage(filePath), + }; + currentDiff = [line]; + } + } + else if (line.startsWith('new file') && currentFile) { + currentFile.status = 'A'; + currentDiff.push(line); + } + else if (line.startsWith('deleted file') && currentFile) { + currentFile.status = 'D'; + currentDiff.push(line); + } + else if (line.startsWith('rename from') && currentFile) { + currentFile.status = 'R'; + const oldPath = line.replace('rename from ', '').trim(); + currentFile.oldPath = oldPath; + currentDiff.push(line); + } + else if (line.startsWith('+') && !line.startsWith('+++') && currentFile) { + currentFile.additions = (currentFile.additions || 0) + 1; + currentDiff.push(line); + } + else if (line.startsWith('-') && !line.startsWith('---') && currentFile) { + currentFile.deletions = (currentFile.deletions || 0) + 1; + currentDiff.push(line); + } + else if (currentFile) { + currentDiff.push(line); + } + } + // Save last file + if (currentFile) { + files.push({ + ...currentFile, + diff: currentDiff.join('\n'), + }); + } + return files; +} +/** + * Detect programming language from file extension + */ +function detectLanguage(filePath) { + const ext = filePath.split('.').pop()?.toLowerCase(); + const languageMap = { + ts: 'typescript', + tsx: 'typescript', + js: 'javascript', + jsx: 'javascript', + py: 'python', + java: 'java', + go: 'go', + rs: 'rust', + rb: 'ruby', + php: 'php', + cs: 'csharp', + cpp: 'cpp', + c: 'c', + swift: 'swift', + kt: 'kotlin', + yaml: 'yaml', + yml: 'yaml', + json: 'json', + md: 'markdown', + }; + return languageMap[ext || ''] || 'unknown'; +} +/** + * Create file analyzer tool + */ +function createFileAnalyzerTool() { + return new tools_DynamicStructuredTool({ + name: 'analyze_file', + description: 'Analyze a specific file from the diff to identify risks, complexity, and provide recommendations', + schema: object({ + filePath: schemas_string().describe('Path of the file to analyze'), + diffContent: schemas_string().describe('The diff content for this file'), + }), + func: async ({ filePath, diffContent }) => { + // Parse the diff to extract changes + const additions = (diffContent.match(/^\+[^+]/gm) || []).length; + const deletions = (diffContent.match(/^-[^-]/gm) || []).length; + const totalChanges = additions + deletions; + // Basic complexity scoring + let complexity = 1; + if (totalChanges > 100) + complexity = 4; + else if (totalChanges > 50) + complexity = 3; + else if (totalChanges > 20) + complexity = 2; + // Detect potential risks + const risks = []; + // Check for security-related patterns + if (/eval\(|exec\(|system\(/i.test(diffContent)) { + risks.push('Potentially dangerous function calls detected (eval, exec, system)'); + } + if (/password|secret|api[_-]?key|token/i.test(diffContent) && /['"]/i.test(diffContent)) { + risks.push('Possible hardcoded credentials or secrets'); + } + if (/TODO|FIXME|XXX|HACK/i.test(diffContent)) { + risks.push('Contains TODO/FIXME comments indicating incomplete work'); + } + if (totalChanges > 200) { + risks.push('Very large change set - difficult to review thoroughly'); + } + // Check for error handling + const hasTryCatch = /try\s*{|catch\s*\(/i.test(diffContent); + const hasThrow = /throw\s+/i.test(diffContent); + if (hasThrow && !hasTryCatch) { + risks.push('Throws errors without apparent error handling'); + } + return JSON.stringify({ + path: filePath, + additions, + deletions, + complexity, + risks, + language: detectLanguage(filePath), + }); + }, + }); +} +/** + * Create risk detector tool + */ +function createRiskDetectorTool() { + return new tools_DynamicStructuredTool({ + name: 'detect_risks', + description: 'Detect security, quality, and breaking change risks in the PR', + schema: object({ + diff: schemas_string().describe('The full diff to analyze for risks'), + context: schemas_string().optional().describe('Additional context about the changes'), + }), + func: async ({ diff, context }) => { + const risks = []; + // Security risks + if (/sql.*=.*\+|SQL.*=.*\+/i.test(diff)) { + risks.push({ + type: 'security', + severity: 'high', + description: 'Potential SQL injection - string concatenation in SQL queries', + }); + } + if (/innerHTML|dangerouslySetInnerHTML/i.test(diff)) { + risks.push({ + type: 'security', + severity: 'medium', + description: 'XSS risk - using innerHTML or dangerouslySetInnerHTML', + }); + } + // Breaking changes + if (/export\s+(interface|type|class|function)\s+\w+/i.test(diff) && /-.*export/i.test(diff)) { + risks.push({ + type: 'breaking', + severity: 'high', + description: 'Potential breaking change - modified or removed export', + }); + } + // Code quality + if ((diff.match(/console\.log/g) || []).length > 3) { + risks.push({ + type: 'quality', + severity: 'low', + description: 'Multiple console.log statements - consider using proper logging', + }); + } + // Performance + if (/for.*for|while.*while/i.test(diff) && /O\(n\^2\)/i.test(diff)) { + risks.push({ + type: 'performance', + severity: 'medium', + description: 'Nested loops detected - potential O(n²) complexity', + }); + } + return JSON.stringify({ + riskCount: risks.length, + risks, + context: context || 'No additional context provided', + }); + }, + }); +} +/** + * Create complexity scorer tool + */ +function createComplexityScorerTool() { + return new tools_DynamicStructuredTool({ + name: 'score_complexity', + description: 'Calculate overall complexity score for the PR (1-5 scale)', + schema: object({ + filesAnalyzed: array(any()).describe('Array of analyzed files'), + totalChanges: schemas_number().describe('Total lines changed'), + }), + func: async ({ filesAnalyzed, totalChanges }) => { + let score = 1; + // Factor 1: Total changes + if (totalChanges > 500) + score = Math.max(score, 5); + else if (totalChanges > 300) + score = Math.max(score, 4); + else if (totalChanges > 150) + score = Math.max(score, 3); + else if (totalChanges > 50) + score = Math.max(score, 2); + // Factor 2: Number of files + const fileCount = filesAnalyzed.length; + if (fileCount > 20) + score = Math.max(score, 5); + else if (fileCount > 10) + score = Math.max(score, 4); + else if (fileCount > 5) + score = Math.max(score, 3); + // Factor 3: File complexity average + const avgFileComplexity = filesAnalyzed.reduce((sum, f) => sum + (f.complexity || 1), 0) / Math.max(fileCount, 1); + if (avgFileComplexity >= 4) + score = Math.max(score, 5); + else if (avgFileComplexity >= 3) + score = Math.max(score, 4); + return JSON.stringify({ + overallComplexity: Math.min(score, 5), + factors: { + totalChanges, + fileCount, + avgFileComplexity: avgFileComplexity.toFixed(1), + }, + recommendation: score >= 4 + ? 'High complexity - consider breaking into smaller PRs' + : score >= 3 + ? 'Moderate complexity - ensure thorough testing' + : 'Low complexity - straightforward changes', + }); + }, + }); +} +/** + * Create summary generator tool + */ +function createSummaryGeneratorTool() { + return new tools_DynamicStructuredTool({ + name: 'generate_summary', + description: 'Generate a concise summary of PR changes', + schema: object({ + files: array(any()).describe('Array of changed files'), + title: schemas_string().optional().describe('PR title'), + }), + func: async ({ files, title }) => { + const filesByType = {}; + let totalAdditions = 0; + let totalDeletions = 0; + files.forEach((file) => { + const lang = file.language || 'other'; + filesByType[lang] = (filesByType[lang] || 0) + 1; + totalAdditions += file.additions || 0; + totalDeletions += file.deletions || 0; + }); + const mainLanguage = Object.entries(filesByType).sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown'; + return JSON.stringify({ + title: title || 'Untitled PR', + fileCount: files.length, + totalAdditions, + totalDeletions, + netChange: totalAdditions - totalDeletions, + mainLanguage, + filesByType, + summary: `Changes ${files.length} file(s) with ${totalAdditions} additions and ${totalDeletions} deletions. Primary language: ${mainLanguage}.`, + }); + }, + }); +} +/** + * Create code suggestion tool for fixing issues based on reviewer comments + */ +function createCodeSuggestionTool() { + return new DynamicStructuredTool({ + name: 'suggest_code_fix', + description: 'Generate a code fix suggestion based on a reviewer comment and the associated code snippet', + schema: z.object({ + reviewerComment: z.string().describe('The reviewer\'s comment describing the issue'), + codeSnippet: z.string().describe('The original code snippet to be fixed'), + filePath: z.string().describe('Path of the file containing the code'), + prTitle: z.string().optional().describe('PR title for context'), + prContext: z.string().optional().describe('Additional PR context (repo, branch, etc.)'), + }), + func: async ({ reviewerComment, codeSnippet, filePath, prTitle, prContext }) => { + // Build the fix prompt + const prompt = `You are an expert software engineer and code-fixer. You will take a reviewer comment and the associated code snippet and produce the corrected code snippet only. + +Context: +${prContext || '(no additional context)'} +- PR Title: ${prTitle || '(unknown)'} +- File: ${filePath} + +Reviewer comment: +${reviewerComment.trim()} + +Original code snippet: +\`\`\` +${codeSnippet} +\`\`\` + +Task: +1) Apply the reviewer's requested changes to the provided code snippet. +2) Output rules (MUST follow exactly): + - Return only the corrected code snippet (no explanations, no markdown fences, no extra text). + - If only a few lines changed you may return only the updated lines, but prefer returning the full corrected snippet when structural/context changes are required. + - Preserve original code style and indentation. + - If no changes are needed, reply with exactly: NO CHANGE + - Do not include filenames, metadata, or commentary. + +Produce the corrected code now.`; + return JSON.stringify({ + filePath, + originalCode: codeSnippet, + reviewerComment, + prompt, + status: 'ready', + message: 'Code suggestion prompt prepared. The agent will use this to generate the fix.', + }); + }, + }); +} + +// EXTERNAL MODULE: external "fs" +var external_fs_ = __nccwpck_require__(9896); +// EXTERNAL MODULE: external "path" +var external_path_ = __nccwpck_require__(6928); +;// CONCATENATED MODULE: ./src/utils/arch-docs-parser.ts +/** + * Arch-Docs Parser + * Parses .arch-docs markdown files for RAG system + */ + + +/** + * Check if .arch-docs folder exists + */ +function archDocsExists(repoPath = process.cwd()) { + const archDocsPath = external_path_.join(repoPath, '.arch-docs'); + return external_fs_.existsSync(archDocsPath) && external_fs_.statSync(archDocsPath).isDirectory(); +} +/** + * Get all markdown files from .arch-docs folder + */ +function getArchDocsFiles(repoPath = process.cwd()) { + const archDocsPath = external_path_.join(repoPath, '.arch-docs'); + if (!archDocsExists(repoPath)) { + return []; + } + try { + const files = external_fs_.readdirSync(archDocsPath); + return files + .filter(file => file.endsWith('.md')) + .map(file => external_path_.join(archDocsPath, file)); + } + catch (error) { + console.warn('Error reading .arch-docs folder:', error); + return []; + } +} +/** + * Parse a markdown file into structured sections + */ +function parseMarkdownFile(filePath) { + const content = external_fs_.readFileSync(filePath, 'utf-8'); + const filename = external_path_.basename(filePath, '.md'); + const lines = content.split('\n'); + const sections = []; + let currentSection; + let title = filename.charAt(0).toUpperCase() + filename.slice(1).replace(/-/g, ' '); + for (let index = 0; index < lines.length; index++) { + const line = lines[index]; + const headingMatch = line.match(/^(#{1,6})\s+(.+)$/); + if (headingMatch) { + // Save previous section + if (currentSection) { + currentSection.lineEnd = index - 1; + sections.push(currentSection); + } + // Extract title from first heading + if (sections.length === 0 && headingMatch[1].length === 1) { + title = headingMatch[2]; + } + // Start new section + currentSection = { + heading: headingMatch[2], + level: headingMatch[1].length, + content: '', + lineStart: index, + lineEnd: index, + }; + } + else if (currentSection) { + // Add content to current section + currentSection.content += line + '\n'; + } + } + // Save last section + if (currentSection) { + currentSection.lineEnd = lines.length - 1; + sections.push(currentSection); + } + return { + filename, + title, + content, + sections, + }; +} +/** + * Parse all arch-docs files + */ +function parseAllArchDocs(repoPath = process.cwd()) { + const files = getArchDocsFiles(repoPath); + return files.map(file => parseMarkdownFile(file)); +} +/** + * Search arch-docs by keyword (simple text search) + */ +function searchArchDocs(docs, query, maxResults = 5) { + const results = []; + const queryLower = query.toLowerCase(); + const queryWords = queryLower.split(/\s+/).filter(w => w.length > 2); + for (const doc of docs) { + for (const section of doc.sections) { + const sectionText = (section.heading + ' ' + section.content).toLowerCase(); + // Calculate relevance score + let relevance = 0; + // Exact phrase match + if (sectionText.includes(queryLower)) { + relevance += 10; + } + // Word matches + for (const word of queryWords) { + const matches = (sectionText.match(new RegExp(word, 'g')) || []).length; + relevance += matches * 2; + } + // Heading match bonus + if (section.heading.toLowerCase().includes(queryLower)) { + relevance += 5; + } + if (relevance > 0) { + results.push({ doc, section, relevance }); + } + } + } + // Sort by relevance and return top results + return results + .sort((a, b) => b.relevance - a.relevance) + .slice(0, maxResults); +} +/** + * Get specific arch-docs by filename + */ +function getArchDocByFilename(docs, filename) { + return docs.find(doc => doc.filename === filename); +} +/** + * Get arch-docs summary (index.md content if available) + */ +function getArchDocsSummary(docs) { + const indexDoc = getArchDocByFilename(docs, 'index'); + if (indexDoc) { + return indexDoc.content; + } + // Fallback: create summary from available docs + const fileList = docs.map(doc => `- ${doc.title} (${doc.filename}.md)`).join('\n'); + return `Available Architecture Documentation:\n\n${fileList}`; +} + +;// CONCATENATED MODULE: ./src/utils/arch-docs-rag.ts +/** + * Arch-Docs RAG System + * Retrieval Augmented Generation for architecture documentation + */ + +/** + * Build context from arch-docs based on PR analysis needs + */ +function buildArchDocsContext(docs, prContext) { + if (docs.length === 0) { + return { + available: false, + summary: '', + relevantDocs: [], + totalDocs: 0, + }; + } + // Extract keywords from PR context + const keywords = extractKeywords(prContext); + // Search for relevant sections + const relevantResults = new Map(); + // Search for each keyword and aggregate results + for (const keyword of keywords) { + const results = searchArchDocs(docs, keyword, 3); + for (const result of results) { + const key = `${result.doc.filename}:${result.section.heading}`; + const existing = relevantResults.get(key); + if (!existing || result.relevance > existing.relevance) { + relevantResults.set(key, result); + } + } + } + // Also always include key documents + const keyDocs = ['architecture', 'patterns', 'file-structure', 'security']; + for (const keyDoc of keyDocs) { + const doc = docs.find(d => d.filename === keyDoc); + if (doc && doc.sections.length > 0) { + const key = `${doc.filename}:${doc.sections[0].heading}`; + if (!relevantResults.has(key)) { + relevantResults.set(key, { + doc, + section: doc.sections[0], + relevance: 3, // Base relevance for key docs + }); + } + } + } + // Convert to array and sort by relevance + const sortedResults = Array.from(relevantResults.values()) + .sort((a, b) => b.relevance - a.relevance) + .slice(0, 10); // Top 10 most relevant sections + // Build context + const relevantDocs = sortedResults.map(result => ({ + filename: result.doc.filename, + title: result.doc.title, + section: result.section.heading, + content: result.section.content.trim(), + relevance: result.relevance, + })); + // Build summary + const summary = buildContextSummary(docs, relevantDocs); + return { + available: true, + summary, + relevantDocs, + totalDocs: docs.length, + }; +} +/** + * Extract keywords from PR context for semantic search + */ +function extractKeywords(prContext) { + const keywords = new Set(); + // From title + if (prContext.title) { + const titleWords = prContext.title + .toLowerCase() + .split(/\s+/) + .filter(w => w.length > 3 && !isCommonWord(w)); + titleWords.forEach(w => keywords.add(w)); + } + // From file paths + for (const file of prContext.files) { + const pathParts = file.path.split(/[\/\-_\.]/); + for (const part of pathParts) { + if (part.length > 3 && !isCommonWord(part.toLowerCase())) { + keywords.add(part.toLowerCase()); + } + } + // Extract from file extensions and directories + if (file.path.includes('test')) + keywords.add('testing'); + if (file.path.includes('api')) + keywords.add('api'); + if (file.path.includes('auth')) + keywords.add('authentication'); + if (file.path.includes('db') || file.path.includes('database')) + keywords.add('database'); + if (file.path.includes('security')) + keywords.add('security'); + if (file.path.includes('schema')) + keywords.add('schema'); + if (file.path.includes('config')) + keywords.add('configuration'); + if (file.path.includes('migration')) + keywords.add('migration'); + } + // From diff content (look for imports, function names, etc.) + if (prContext.diff) { + // Extract import statements + const importMatches = prContext.diff.matchAll(/import\s+.*?\s+from\s+['"]([^'"]+)['"]/g); + for (const match of importMatches) { + const importPath = match[1]; + const parts = importPath.split(/[\/\-_]/); + for (const part of parts) { + if (part.length > 3 && !isCommonWord(part)) { + keywords.add(part); + } + } + } + // Extract class and function names + const classMatches = prContext.diff.matchAll(/class\s+(\w+)/g); + for (const match of classMatches) { + keywords.add(match[1].toLowerCase()); + } + const functionMatches = prContext.diff.matchAll(/function\s+(\w+)/g); + for (const match of functionMatches) { + if (match[1].length > 3) { + keywords.add(match[1].toLowerCase()); + } + } + } + return Array.from(keywords).slice(0, 20); // Limit to top 20 keywords +} +/** + * Check if a word is too common to be useful + */ +function isCommonWord(word) { + const commonWords = new Set([ + 'the', 'and', 'for', 'that', 'this', 'with', 'from', 'have', 'been', + 'will', 'your', 'more', 'when', 'some', 'them', 'than', 'into', 'only', + 'other', 'then', 'also', 'make', 'made', 'like', 'time', 'very', 'just', + 'file', 'code', 'test', 'docs', 'info', 'data', 'type', 'name', 'index', + ]); + return commonWords.has(word); +} +/** + * Build a summary of the context + */ +function buildContextSummary(docs, relevantDocs) { + const docTitles = docs.map(d => d.title).join(', '); + const relevantCount = relevantDocs.length; + let summary = `Architecture Documentation Context:\n`; + summary += `- Total documents: ${docs.length}\n`; + summary += `- Available: ${docTitles}\n`; + summary += `- Relevant sections retrieved: ${relevantCount}\n\n`; + if (relevantCount > 0) { + summary += `Most relevant sections:\n`; + relevantDocs.slice(0, 5).forEach((doc, i) => { + summary += `${i + 1}. ${doc.title} - ${doc.section} (relevance: ${doc.relevance})\n`; + }); + } + return summary; +} +/** + * Format arch-docs context for inclusion in prompts + */ +function formatArchDocsForPrompt(context) { + if (!context.available || context.relevantDocs.length === 0) { + return ''; + } + let prompt = '\n## Repository Architecture Context\n\n'; + prompt += 'The following sections from the architecture documentation are relevant to this PR:\n\n'; + for (const doc of context.relevantDocs) { + prompt += `### ${doc.title} - ${doc.section}\n\n`; + prompt += doc.content + '\n\n'; + prompt += '---\n\n'; + } + return prompt; +} +/** + * Get specific context for risk analysis + */ +function getSecurityContext(docs) { + const securityDoc = docs.find(d => d.filename === 'security'); + if (securityDoc) { + return securityDoc.content; + } + return ''; +} +/** + * Get specific context for architecture understanding + */ +function getArchitectureContext(docs) { + const archDoc = docs.find(d => d.filename === 'architecture'); + if (archDoc) { + return archDoc.content; + } + return ''; +} +/** + * Get specific context for patterns + */ +function getPatternsContext(docs) { + const patternsDoc = docs.find(d => d.filename === 'patterns'); + if (patternsDoc) { + return patternsDoc.content; + } + return ''; +} + +;// CONCATENATED MODULE: ./src/agents/base-pr-agent-workflow.ts +/** + * Base PR Agent Workflow using LangGraph + * Follows architecture-doc-generator patterns with self-refinement + */ + + + + + +/** + * Agent workflow state + */ +const PRAgentState = Annotation.Root({ + // Input context + context: Annotation({ + reducer: (_, update) => update, + }), + // Current iteration + iteration: Annotation({ + reducer: (_, update) => update, + default: () => 0, + }), + // File analyses + fileAnalyses: Annotation({ + reducer: (_, update) => update, + default: () => new Map(), + }), + // Current analysis state + currentSummary: Annotation({ + reducer: (_, update) => update, + default: () => '', + }), + currentRisks: Annotation({ + reducer: (_, update) => update, + default: () => [], + }), + currentComplexity: Annotation({ + reducer: (_, update) => update, + default: () => 1, + }), + // Quality metrics + clarityScore: Annotation({ + reducer: (_, update) => update, + default: () => 0, + }), + missingInformation: Annotation({ + reducer: (_, update) => update, + default: () => [], + }), + // Recommendations + recommendations: Annotation({ + reducer: (_, update) => update, + default: () => [], + }), + // Insights and reasoning + insights: Annotation({ + reducer: (current, update) => [...current, ...update], + default: () => [], + }), + reasoning: Annotation({ + reducer: (current, update) => [...current, ...update], + default: () => [], + }), + // Arch-docs tracking + archDocsInfluencedStages: Annotation({ + reducer: (current, update) => [...current, ...update], + default: () => [], + }), + archDocsKeyInsights: Annotation({ + reducer: (current, update) => [...current, ...update], + default: () => [], + }), + // Token tracking + totalInputTokens: Annotation({ + reducer: (current, update) => current + update, + default: () => 0, + }), + totalOutputTokens: Annotation({ + reducer: (current, update) => current + update, + default: () => 0, + }), +}); +/** + * Base class for PR agents with self-refinement workflow + */ +class BasePRAgentWorkflow { + model; + workflow; + checkpointer = new MemorySaver(); + tools; + constructor(model) { + this.model = model; + // Initialize tools + this.tools = [ + createFileAnalyzerTool(), + createRiskDetectorTool(), + createComplexityScorerTool(), + createSummaryGeneratorTool(), + ]; + this.workflow = this.buildWorkflow(); + } + /** + * Build the PR analysis workflow + */ + buildWorkflow() { + const graph = new StateGraph(PRAgentState); + // Define nodes + graph.addNode('analyzeFiles', this.analyzeFilesNode.bind(this)); + graph.addNode('detectRisks', this.detectRisksNode.bind(this)); + graph.addNode('calculateComplexity', this.calculateComplexityNode.bind(this)); + graph.addNode('generateSummary', this.generateSummaryNode.bind(this)); + graph.addNode('evaluateQuality', this.evaluateQualityNode.bind(this)); + graph.addNode('refineAnalysis', this.refineAnalysisNode.bind(this)); + graph.addNode('finalize', this.finalizeNode.bind(this)); + // Set entry point + const entryPoint = 'analyzeFiles'; + graph.setEntryPoint(entryPoint); + // Build workflow graph + graph.addEdge(entryPoint, 'detectRisks'); + graph.addEdge('detectRisks', 'calculateComplexity'); + graph.addEdge('calculateComplexity', 'generateSummary'); + graph.addEdge('generateSummary', 'evaluateQuality'); + // Conditional: refine or finalize + graph.addConditionalEdges('evaluateQuality', this.shouldRefine.bind(this), { + refine: 'refineAnalysis', + finalize: 'finalize', + }); + // After refinement, evaluate again + graph.addEdge('refineAnalysis', 'evaluateQuality'); + // End after finalization + graph.addEdge('finalize', END); + return graph.compile({ checkpointer: this.checkpointer }); + } + /** + * Execute the agent workflow + */ + async execute(context, options) { + const startTime = Date.now(); + // Fast path: skip self-refinement + if (options?.skipSelfRefinement) { + return this.executeFastPath(context, startTime); + } + const config = { + maxIterations: 3, + clarityThreshold: 80, + skipSelfRefinement: false, + }; + const initialState = { + context, + iteration: 0, + fileAnalyses: new Map(), + currentSummary: '', + currentRisks: [], + currentComplexity: 1, + clarityScore: 0, + missingInformation: [], + recommendations: [], + insights: [], + reasoning: [], + totalInputTokens: 0, + totalOutputTokens: 0, + }; + const workflowConfig = { + configurable: { + thread_id: `pr-agent-${Date.now()}`, + maxIterations: config.maxIterations, + clarityThreshold: config.clarityThreshold, + }, + recursionLimit: 50, + }; + let finalState = initialState; + let totalInputTokens = 0; + let totalOutputTokens = 0; + // Execute workflow - stream returns state updates + try { + for await (const state of await this.workflow.stream(initialState, workflowConfig)) { + // Get the last node's state + const nodeNames = Object.keys(state); + if (nodeNames.length > 0) { + const lastNodeName = nodeNames[nodeNames.length - 1]; + finalState = state[lastNodeName] || finalState; + // Extract token counts if present + const stateAny = finalState; + if (stateAny.totalInputTokens !== undefined) { + totalInputTokens = stateAny.totalInputTokens; + } + if (stateAny.totalOutputTokens !== undefined) { + totalOutputTokens = stateAny.totalOutputTokens; + } + } + } + } + catch (error) { + console.error('Workflow execution error:', error); + throw error; + } + const executionTime = Date.now() - startTime; + // Build arch-docs impact summary with deduplication + const stateAny = finalState; + const archDocsImpact = context.archDocs?.available ? { + used: true, + docsAvailable: context.archDocs.totalDocs, + sectionsUsed: context.archDocs.relevantDocs.length, + influencedStages: [...new Set(stateAny.archDocsInfluencedStages || [])], + keyInsights: [...new Set(stateAny.archDocsKeyInsights || [])], + } : undefined; + return { + summary: finalState.currentSummary, + fileAnalyses: finalState.fileAnalyses, + overallComplexity: finalState.currentComplexity, + overallRisks: finalState.currentRisks, + recommendations: finalState.recommendations, + insights: finalState.insights, + reasoning: finalState.reasoning, + provider: 'ai', + model: this.model.modelName || 'unknown', + totalTokensUsed: totalInputTokens + totalOutputTokens, + executionTime, + mode: context.mode, + archDocsImpact, + }; + } + /** + * Fast path execution - skip refinement loop but still use LLM for detailed analysis + */ + async executeFastPath(context, startTime) { + // Initialize state + const initialState = { + context, + iteration: 0, + fileAnalyses: new Map(), + currentSummary: '', + currentRisks: [], + currentComplexity: 1, + clarityScore: 0, + missingInformation: [], + recommendations: [], + insights: [], + reasoning: [], + totalInputTokens: 0, + totalOutputTokens: 0, + }; + // Execute workflow nodes sequentially (skip refinement loop) + let state = initialState; + try { + // 1. Analyze files + state = await this.analyzeFilesNode(state); + // 2. Detect risks + state = await this.detectRisksNode(state); + // 3. Calculate complexity + state = await this.calculateComplexityNode(state); + // 4. Generate summary + state = await this.generateSummaryNode(state); + // 5. Generate recommendations (skip quality evaluation) + state = await this.refineAnalysisNode(state); + // 6. Finalize + state = await this.finalizeNode(state); + const executionTime = Date.now() - startTime; + // Build arch-docs impact summary with deduplication + const stateAny = state; + const archDocsImpact = context.archDocs?.available ? { + used: true, + docsAvailable: context.archDocs.totalDocs, + sectionsUsed: context.archDocs.relevantDocs.length, + influencedStages: [...new Set(stateAny.archDocsInfluencedStages || [])], + keyInsights: [...new Set(stateAny.archDocsKeyInsights || [])], + } : undefined; + return { + summary: state.currentSummary, + fileAnalyses: state.fileAnalyses, + overallComplexity: state.currentComplexity, + overallRisks: state.currentRisks, + recommendations: state.recommendations, + insights: state.insights, + reasoning: [...state.reasoning, 'Fast path: Self-refinement evaluation skipped for speed'], + provider: 'ai', + model: this.model.modelName || 'unknown', + totalTokensUsed: state.totalInputTokens + state.totalOutputTokens, + executionTime, + mode: context.mode, + archDocsImpact, + }; + } + catch (error) { + console.error('Fast path execution error:', error); + throw error; + } + } + // Workflow nodes + async analyzeFilesNode(state) { + const { context } = state; + const files = parseDiff(context.diff); + console.log(`🔍 Analyzing ${files.length} files...`); + // Show arch-docs status if available + if (context.archDocs?.available) { + console.log(`📚 Using architecture documentation (${context.archDocs.totalDocs} docs, ${context.archDocs.relevantDocs.length} relevant sections)`); + } + const fileAnalyses = new Map(); + // Build arch-docs context if available + let archDocsContext = ''; + if (context.archDocs?.available) { + archDocsContext = formatArchDocsForPrompt(context.archDocs); + } + // Analyze files in batches for detailed insights + const filesToAnalyze = files.slice(0, 15); // Limit to 15 files for detailed analysis + const importantFiles = filesToAnalyze.filter(f => f.additions + f.deletions > 20 || // Significant changes + f.path.includes('config') || + f.path.includes('schema') || + f.path.includes('migration') || + f.path.includes('test')).slice(0, 5); // Top 5 important files + // Get detailed analysis for important files + if (importantFiles.length > 0) { + try { + const fileDetailsPrompt = `Analyze these files from a pull request. For EACH file, provide a detailed analysis considering the repository's architecture standards. +${archDocsContext ? '\n' + archDocsContext : ''} + +Files to analyze: +${importantFiles.map(f => ` +File: ${f.path} +Status: ${f.status || 'modified'} +Changes: +${f.additions} -${f.deletions} +Diff preview: +\`\`\` +${f.diff.substring(0, 500)} +\`\`\` +`).join('\n---\n')} + +${archDocsContext ? `CRITICAL INSTRUCTIONS: +- For EACH file, reference the relevant architecture documentation sections above +- Explain how the changes align with or diverge from established patterns +- Identify specific guidelines that apply to each file +- Mention which parts of the architecture are affected +- Compare changes against documented standards + +` : ''} + +Respond with a JSON object mapping file paths to analysis objects: +{ + "path/to/file": { + "summary": "Description that references relevant arch-docs patterns/guidelines", + "risks": ["risk with arch-docs context", "risk2"], + "complexity": 1-5, + "recommendations": ["recommendation based on arch-docs standards"] + } +} + +${archDocsContext ? 'Each summary MUST reference the specific architecture documentation that applies to this file.' : ''}`; + const response = await this.model.invoke(fileDetailsPrompt); + const content = response.content; + // Track tokens + const usage = response.response_metadata?.usage; + const inputTokens = usage?.input_tokens || 0; + const outputTokens = usage?.output_tokens || 0; + // Parse detailed file analyses + try { + const jsonMatch = content.match(/\{[\s\S]*\}/); + if (jsonMatch) { + const detailedAnalyses = JSON.parse(jsonMatch[0]); + // Apply detailed analysis to file analyses + for (const file of importantFiles) { + const detail = detailedAnalyses[file.path]; + if (detail) { + fileAnalyses.set(file.path, { + path: file.path, + summary: detail.summary || `${file.status || 'M'}: +${file.additions} -${file.deletions}`, + risks: Array.isArray(detail.risks) ? detail.risks : [], + complexity: detail.complexity || Math.min(5, Math.floor((file.additions + file.deletions) / 50) + 1), + changes: { + additions: file.additions, + deletions: file.deletions, + }, + recommendations: Array.isArray(detail.recommendations) ? detail.recommendations : [], + }); + } + } + } + } + catch (parseError) { + console.warn('Failed to parse file analysis JSON, using basic analysis'); + } + // Update state with token tracking + state = { + ...state, + totalInputTokens: (state.totalInputTokens || 0) + inputTokens, + totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens, + }; + } + catch (error) { + console.warn('Error in detailed file analysis, falling back to basic:', error); + } + } + // Add basic analysis for remaining files + for (const file of filesToAnalyze) { + if (!fileAnalyses.has(file.path)) { + const analysis = { + path: file.path, + summary: `${file.status || 'M'}: +${file.additions} -${file.deletions}`, + risks: [], + complexity: Math.min(5, Math.floor((file.additions + file.deletions) / 50) + 1), + changes: { + additions: file.additions, + deletions: file.deletions, + }, + recommendations: [], + }; + fileAnalyses.set(file.path, analysis); + } + } + // Track arch-docs usage + const newInsights = [`Analyzed ${files.length} files (${importantFiles.length} in detail)`]; + const hasArchDocsContext = archDocsContext && archDocsContext.length > 0; + const archDocsStages = hasArchDocsContext ? ['file-analysis'] : []; + const archDocsInsights = []; + if (hasArchDocsContext && context.archDocs?.available) { + archDocsInsights.push(`Applied ${context.archDocs.relevantDocs.length} architecture documentation sections to analyze files in context of repository standards`); + } + return { + ...state, + fileAnalyses, + insights: newInsights, + archDocsInfluencedStages: archDocsStages, + archDocsKeyInsights: archDocsInsights, + }; + } + async detectRisksNode(state) { + const { context, fileAnalyses } = state; + console.log('⚠️ Detecting risks...'); + // Build context for risk analysis + const fileList = Array.from(fileAnalyses.entries()) + .slice(0, 15) + .map(([path, analysis]) => `${path} (+${analysis.changes.additions} -${analysis.changes.deletions})`) + .join('\n'); + // Get a sample of the diff for risk analysis (limit size) + const diffSample = context.diff.substring(0, 8000); // First 8KB for context + // Add security context from arch-docs if available + let securityContext = ''; + let allDocs = []; + let securityDoc = null; + let patternsDoc = null; + if (context.archDocs?.available) { + allDocs = parseAllArchDocs(); + const secDoc = getSecurityContext(allDocs); + if (secDoc) { + securityContext = `\n## Security Guidelines from Repository Documentation\n\n${secDoc.substring(0, 3000)}\n`; + securityDoc = allDocs.find(d => d.filename === 'security'); + } + // Also get patterns that might indicate risks + const patterns = getPatternsContext(allDocs); + if (patterns) { + securityContext += `\n## Repository Patterns and Best Practices\n\n${patterns.substring(0, 2000)}\n`; + patternsDoc = allDocs.find(d => d.filename === 'patterns'); + } + } + const riskPrompt = `You are a security and code quality expert analyzing a pull request for potential risks. +${securityContext} + +Analyze the following changes and identify SPECIFIC risks in these categories: +1. **Security Risks**: Exposed credentials, insecure patterns, authentication/authorization issues +2. **Breaking Changes**: API changes, database schema changes, removed functionality +3. **Performance Concerns**: Inefficient algorithms, memory leaks, N+1 queries +4. **Code Quality**: Complex logic, missing error handling, lack of tests +5. **Operational Risks**: Configuration changes, deployment concerns, dependency updates + +PR Title: ${context.title || 'No title provided'} + +Files changed: +${fileList} + +Diff sample: +\`\`\` +${diffSample} +\`\`\` + +${securityContext ? `CRITICAL INSTRUCTIONS: +- You MUST reference the repository documentation guidelines above when identifying each risk +- For EVERY risk you identify, find the relevant guideline from the documentation +- Explain HOW the code change violates or conflicts with the documented standards +- Quote the specific guideline that makes this a risk +- Be specific about why this matters based on the repository's own standards + +Example format for a risk with documentation: +{ + "description": "File exceeds maximum line count recommended for maintainability", + "archDocsSource": "code-quality.md", + "archDocsExcerpt": "Keep individual files under 500 lines to maintain testability and readability", + "reason": "This file contains 990 lines, nearly 2x the repository standard, which increases maintenance burden and makes comprehensive testing more difficult" +} +` : ''} + +Provide a JSON array of risk objects. Each risk MUST include: +- description: Clear, specific description of the risk +${securityContext ? `- archDocsSource: REQUIRED - Which documentation file from above this relates to (e.g., "security.md", "patterns.md", "code-quality.md") +- archDocsExcerpt: REQUIRED - Direct quote from the repository documentation that this violates +- reason: REQUIRED - Detailed explanation of why this is a risk based on the specific guideline quoted above +` : ''} + +Format: +${securityContext ? `[ + { + "description": "Specific risk description", + "archDocsSource": "documentation-file.md", + "archDocsExcerpt": "Exact quote from the documentation", + "reason": "Detailed explanation connecting the code change to the guideline violation" + } +] + +DO NOT return simple string arrays. Each risk MUST be an object with archDocsSource, archDocsExcerpt, and reason fields.` : '["risk 1", "risk 2", ...]'} + +Only include risks that are actually present. If no significant risks, return an empty array [].`; + try { + const response = await this.model.invoke(riskPrompt); + const content = response.content; + // Track tokens + const usage = response.response_metadata?.usage; + const inputTokens = usage?.input_tokens || 0; + const outputTokens = usage?.output_tokens || 0; + // Parse JSON response + let risks = []; + let hasArchDocsEnhancement = false; + try { + // Extract JSON from markdown code blocks if present + const jsonMatch = content.match(/\[[\s\S]*\]/); + if (jsonMatch) { + const parsedRisks = JSON.parse(jsonMatch[0]); + // Check if risks have arch-docs references + if (parsedRisks.length > 0 && typeof parsedRisks[0] === 'object' && 'archDocsSource' in parsedRisks[0]) { + // Transform to our RiskItem format + risks = parsedRisks.map((r) => ({ + description: r.description, + archDocsReference: r.archDocsSource ? { + source: r.archDocsSource, + excerpt: r.archDocsExcerpt || '', + reason: r.reason || '', + } : undefined, + })); + hasArchDocsEnhancement = true; + } + else if (parsedRisks.length > 0 && typeof parsedRisks[0] === 'string') { + // Legacy format - just strings + risks = parsedRisks; + } + else { + risks = parsedRisks; + } + } + } + catch (parseError) { + console.warn('Failed to parse risk JSON, extracting manually'); + // Fallback: extract bullet points as strings + const lines = content.split('\n'); + risks = lines + .filter(line => line.trim().startsWith('-') || line.trim().startsWith('•')) + .map(line => line.replace(/^[-•]\s*/, '').trim()) + .filter(line => line.length > 0); + } + // Add basic pattern-based checks with arch-docs enhancement + const patternRisks = []; + if (context.diff.includes('password') || context.diff.includes('secret') || context.diff.includes('api_key')) { + const riskDesc = 'Potential credentials or sensitive data in code changes'; + if (securityDoc) { + // Always enhance with arch-docs if available + patternRisks.push({ + description: riskDesc, + archDocsReference: { + source: 'security.md', + excerpt: 'Never commit credentials, API keys, or secrets to the repository. Use environment variables for all sensitive configuration.', + reason: 'Code changes contain keywords like "password", "secret", or "api_key" which may indicate hardcoded credentials. This violates the repository security policy requiring all secrets to be externalized via environment variables.', + }, + }); + } + else { + patternRisks.push(riskDesc); + } + } + if (fileAnalyses.size > 20) { + const qualityDoc = allDocs.find(d => d.filename === 'code-quality'); + if (qualityDoc && securityContext) { + patternRisks.push({ + description: `Large change set (${fileAnalyses.size} files) increases review complexity and error risk`, + archDocsReference: { + source: 'code-quality.md', + excerpt: 'Keep pull requests focused and under 15 files when possible for thorough review', + reason: `This PR modifies ${fileAnalyses.size} files, exceeding the recommended limit. Large PRs are harder to review thoroughly and increase the likelihood of missing critical issues.`, + }, + }); + } + else { + patternRisks.push(`Large change set (${fileAnalyses.size} files) - may be difficult to review thoroughly`); + } + } + if (context.diff.includes('DROP TABLE') || context.diff.includes('ALTER TABLE')) { + if (securityContext) { + patternRisks.push({ + description: 'Database schema changes detected - requires careful migration planning', + archDocsReference: { + source: 'patterns.md', + excerpt: 'All database schema changes must be backwards-compatible and include rollback procedures', + reason: 'The changes include database schema modifications (DROP TABLE or ALTER TABLE) which can cause data loss or application downtime if not properly planned and tested.', + }, + }); + } + else { + patternRisks.push('Database schema changes detected - requires careful migration planning'); + } + } + // Merge risks, avoiding duplicates (for string risks) + let allRisks; + if (hasArchDocsEnhancement) { + // Keep structured risks + allRisks = [...risks, ...patternRisks]; + } + else { + // Deduplicate string risks + allRisks = [...new Set([...risks, ...patternRisks])]; + } + // Track arch-docs usage in risk detection + const archDocsStages = securityContext ? ['risk-detection'] : []; + const archDocsInsights = []; + if (securityContext && context.archDocs?.available) { + const enhancedCount = allRisks.filter(r => typeof r === 'object' && r.archDocsReference).length; + if (enhancedCount > 0) { + archDocsInsights.push(`Linked ${enhancedCount} risks to specific repository security guidelines and best practices`); + } + } + return { + ...state, + currentRisks: allRisks, + insights: [`Identified ${allRisks.length} potential risks`], + totalInputTokens: (state.totalInputTokens || 0) + inputTokens, + totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens, + archDocsInfluencedStages: archDocsStages, + archDocsKeyInsights: archDocsInsights, + }; + } + catch (error) { + console.error('Error in risk detection:', error); + // Fallback to basic pattern matching + const basicRisks = []; + if (context.diff.includes('password') || context.diff.includes('secret')) { + basicRisks.push('Potential credentials in diff'); + } + if (fileAnalyses.size > 15) { + basicRisks.push('Large change set - difficult to review'); + } + return { + ...state, + currentRisks: basicRisks, + insights: [`Identified ${basicRisks.length} potential risks (basic analysis)`], + }; + } + } + async calculateComplexityNode(state) { + const { fileAnalyses, context } = state; + console.log('📊 Calculating complexity...'); + const complexities = Array.from(fileAnalyses.values()).map(f => f.complexity); + const avgComplexity = complexities.length > 0 + ? complexities.reduce((a, b) => a + b, 0) / complexities.length + : 1; + // Track arch-docs influence on complexity + const archDocsStages = context.archDocs?.available ? ['complexity-calculation'] : []; + const archDocsInsights = []; + if (context.archDocs?.available) { + // Check if patterns documentation helped understand complexity + const allDocs = parseAllArchDocs(); + const patterns = getPatternsContext(allDocs); + if (patterns) { + archDocsInsights.push(`Evaluated complexity against repository design patterns and coding standards`); + } + } + return { + ...state, + currentComplexity: Math.round(avgComplexity), + archDocsInfluencedStages: archDocsStages, + archDocsKeyInsights: archDocsInsights, + }; + } + async generateSummaryNode(state) { + const { context, fileAnalyses, currentRisks, currentComplexity } = state; + console.log('📝 Generating detailed summary...'); + const totalFiles = fileAnalyses.size; + const totalAdditions = Array.from(fileAnalyses.values()).reduce((sum, f) => sum + f.changes.additions, 0); + const totalDeletions = Array.from(fileAnalyses.values()).reduce((sum, f) => sum + f.changes.deletions, 0); + // Build file list with changes + const fileList = Array.from(fileAnalyses.entries()) + .slice(0, 20) + .map(([path, analysis]) => `- ${path}: +${analysis.changes.additions} -${analysis.changes.deletions} (complexity: ${analysis.complexity}/5)`) + .join('\n'); + // Add patterns context from arch-docs if available + let patternsContext = ''; + if (context.archDocs?.available) { + const allDocs = parseAllArchDocs(); + const patterns = getPatternsContext(allDocs); + if (patterns) { + patternsContext = `\n## Design Patterns from Repository Documentation\n\n${patterns.substring(0, 2000)}\n`; + } + } + // Create comprehensive prompt for LLM + const summaryPrompt = `You are analyzing a pull request. Provide a DETAILED and COMPREHENSIVE summary that covers: + +1. **Overall Purpose**: What is this PR trying to accomplish? What problem does it solve? +2. **Key Changes**: What are the main changes being made? Group related changes together. +3. **Impact Analysis**: What parts of the system are affected? What are the implications? +4. **Technical Details**: Mention important technical aspects (new dependencies, API changes, data model changes, etc.) +5. **Patterns Observed**: Any design patterns, refactoring, or architectural changes? +${patternsContext} + +PR Title: ${context.title || 'No title provided'} + +Statistics: +- Files changed: ${totalFiles} +- Lines added: ${totalAdditions} +- Lines deleted: ${totalDeletions} +- Overall complexity: ${currentComplexity}/5 +- Risks identified: ${currentRisks.length} + +Files changed: +${fileList} + +${currentRisks.length > 0 ? `\nRisks detected:\n${currentRisks.map(r => `- ${r}`).join('\n')}` : ''} + +${patternsContext ? 'Consider the design patterns and architecture from the repository documentation when analyzing the changes.\n' : ''} + +Provide a detailed, well-structured summary (3-5 paragraphs) that would help a reviewer understand the scope and purpose of this PR.`; + try { + const response = await this.model.invoke(summaryPrompt); + const detailedSummary = response.content; + // Track token usage + const usage = response.response_metadata?.usage; + const inputTokens = usage?.input_tokens || 0; + const outputTokens = usage?.output_tokens || 0; + // Track arch-docs usage in summary + const archDocsStages = patternsContext ? ['summary-generation'] : []; + const archDocsInsights = []; + if (patternsContext && context.archDocs?.available) { + archDocsInsights.push(`Generated summary aligned with repository architecture and established patterns`); + } + return { + ...state, + currentSummary: detailedSummary, + totalInputTokens: inputTokens, + totalOutputTokens: outputTokens, + archDocsInfluencedStages: archDocsStages, + archDocsKeyInsights: archDocsInsights, + }; + } + catch (error) { + console.error('Error generating summary:', error); + // Fallback to basic summary + const fallbackSummary = `PR Analysis Summary: +- Files changed: ${totalFiles} +- Additions: ${totalAdditions} +- Deletions: ${totalDeletions} +- Overall complexity: ${currentComplexity}/5 +- Risks identified: ${currentRisks.length} + +${context.title ? `Title: ${context.title}` : ''}`; + return { + ...state, + currentSummary: fallbackSummary, + }; + } + } + async evaluateQualityNode(state) { + const { iteration } = state; + console.log(`🔍 Evaluating quality (iteration ${iteration + 1})...`); + // Simple quality check + const clarityScore = 85; // Placeholder + return { + ...state, + clarityScore, + iteration: iteration + 1, + }; + } + async refineAnalysisNode(state) { + const { currentSummary, currentRisks, fileAnalyses, context } = state; + console.log('🔄 Refining analysis...'); + // Build arch-docs context for refinement + let archDocsRefinementContext = ''; + if (context.archDocs?.available) { + const allDocs = parseAllArchDocs(); + // Get recommendations from arch-docs + const recommendationsDoc = allDocs.find(d => d.filename === 'recommendations'); + if (recommendationsDoc) { + archDocsRefinementContext += `\n## Repository Improvement Guidelines\n\n${recommendationsDoc.content.substring(0, 2000)}\n`; + } + // Get code quality guidelines + const qualityDoc = allDocs.find(d => d.filename === 'code-quality'); + if (qualityDoc) { + archDocsRefinementContext += `\n## Code Quality Standards\n\n${qualityDoc.content.substring(0, 2000)}\n`; + } + // Get KPI metrics + const kpiDoc = allDocs.find(d => d.filename === 'kpi'); + if (kpiDoc) { + archDocsRefinementContext += `\n## Repository Health KPIs\n\n${kpiDoc.content.substring(0, 1500)}\n`; + } + } + // Generate comprehensive recommendations + const refinementPrompt = `Based on this PR analysis, provide specific, actionable recommendations for the developer and reviewers. +${archDocsRefinementContext} + +PR Summary: +${currentSummary} + +Risks Identified: +${currentRisks.map(r => `- ${r}`).join('\n')} + +Files Changed: ${fileAnalyses.size} + +Consider: +1. Code organization and structure improvements +2. Testing recommendations +3. Documentation needs +4. Performance optimizations +5. Security enhancements +6. Review process suggestions +${archDocsRefinementContext ? '7. Alignment with repository standards and KPIs from arch-docs\n' : ''} + +${archDocsRefinementContext ? 'Use the repository guidelines and standards above to ensure recommendations align with established practices.\n' : ''} + +Provide a JSON array of 3-5 specific, actionable recommendations: +["recommendation 1", "recommendation 2", ...]`; + try { + const response = await this.model.invoke(refinementPrompt); + const content = response.content; + // Track tokens + const usage = response.response_metadata?.usage; + const inputTokens = usage?.input_tokens || 0; + const outputTokens = usage?.output_tokens || 0; + // Parse recommendations + let recommendations = []; + try { + const jsonMatch = content.match(/\[[\s\S]*\]/); + if (jsonMatch) { + recommendations = JSON.parse(jsonMatch[0]); + } + } + catch (parseError) { + // Fallback: extract bullet points + const lines = content.split('\n'); + recommendations = lines + .filter(line => line.trim().startsWith('-') || line.trim().startsWith('•') || /^\d+\./.test(line.trim())) + .map(line => line.replace(/^[-•]\s*/, '').replace(/^\d+\.\s*/, '').trim()) + .filter(line => line.length > 0) + .slice(0, 5); + } + // Add default recommendations if none found + if (recommendations.length === 0) { + recommendations = [ + 'Ensure comprehensive test coverage for new functionality', + 'Update relevant documentation', + 'Consider performance implications of changes', + ]; + } + // Track arch-docs usage in refinement + const archDocsStages = archDocsRefinementContext ? ['refinement'] : []; + const archDocsInsights = []; + if (archDocsRefinementContext && context.archDocs?.available) { + archDocsInsights.push(`Generated ${recommendations.length} recommendations based on repository quality standards and KPIs`); + } + return { + ...state, + recommendations, + totalInputTokens: (state.totalInputTokens || 0) + inputTokens, + totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens, + archDocsInfluencedStages: archDocsStages, + archDocsKeyInsights: archDocsInsights, + }; + } + catch (error) { + console.error('Error refining analysis:', error); + return { + ...state, + recommendations: [ + 'Review changes carefully for potential side effects', + 'Ensure test coverage is adequate', + 'Update documentation as needed', + ], + }; + } + } + async finalizeNode(state) { + console.log('✨ Finalizing analysis...'); + return state; + } + shouldRefine(state) { + // Use defaults if config not accessible + const maxIterations = 3; + const clarityThreshold = 80; + if (state.iteration >= maxIterations) { + console.log(`⏹️ Stopping: Max iterations (${maxIterations}) reached`); + return 'finalize'; + } + if (state.clarityScore >= clarityThreshold) { + console.log(`✅ Stopping: Clarity threshold (${clarityThreshold}) achieved`); + return 'finalize'; + } + console.log(`🔄 Continuing: Iteration ${state.iteration}, clarity ${state.clarityScore}`); + return 'refine'; + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/output_parsers.js + + + +//#region src/output_parsers.ts +var AnthropicToolsOutputParser = class extends BaseLLMOutputParser { + static lc_name() { + return "AnthropicToolsOutputParser"; + } + lc_namespace = [ + "langchain", + "anthropic", + "output_parsers" + ]; + returnId = false; + /** The type of tool calls to return. */ + keyName; + /** Whether to return only the first tool call. */ + returnSingle = false; + zodSchema; + constructor(params) { + super(params); + this.keyName = params.keyName; + this.returnSingle = params.returnSingle ?? this.returnSingle; + this.zodSchema = params.zodSchema; + } + async _validateResult(result) { + let parsedResult = result; + if (typeof result === "string") try { + parsedResult = JSON.parse(result); + } catch (e) { + throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(e.message)}`, result); + } + else parsedResult = result; + if (this.zodSchema === void 0) return parsedResult; + const zodParsedResult = await interopSafeParseAsync(this.zodSchema, parsedResult); + if (zodParsedResult.success) return zodParsedResult.data; + else throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.issues)}`, JSON.stringify(parsedResult, null, 2)); + } + async parseResult(generations) { + const tools = generations.flatMap((generation) => { + const { message } = generation; + if (!Array.isArray(message.content)) return []; + const tool$1 = extractToolCalls(message.content)[0]; + return tool$1; + }); + if (tools[0] === void 0) throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser."); + const [tool] = tools; + const validatedResult = await this._validateResult(tool.args); + return validatedResult; + } +}; +function extractToolCalls(content) { + const toolCalls = []; + for (const block of content) if (block.type === "tool_use") toolCalls.push({ + name: block.name, + args: block.input, + id: block.id, + type: "tool_call" + }); + return toolCalls; +} + +//#endregion + +//# sourceMappingURL=output_parsers.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/tools.js + + +//#region src/utils/tools.ts +function handleToolChoice(toolChoice) { + if (!toolChoice) return void 0; + else if (toolChoice === "any") return { type: "any" }; + else if (toolChoice === "auto") return { type: "auto" }; + else if (toolChoice === "none") return { type: "none" }; + else if (typeof toolChoice === "string") return { + type: "tool", + name: toolChoice + }; + else return toolChoice; +} +const AnthropicToolExtrasSchema = object({ + cache_control: schemas_custom().optional().nullable(), + defer_loading: schemas_boolean().optional(), + input_examples: array(unknown()).optional(), + allowed_callers: array(unknown()).optional() +}); +/** +* Mapping of Anthropic tool types to their required beta feature flags. +* +* This constant defines which beta header is needed for specific tool types +* when making requests to the Anthropic API. Beta features are experimental +* capabilities that may change or be removed. +*/ +const ANTHROPIC_TOOL_BETAS = { + tool_search_tool_regex_20251119: "advanced-tool-use-2025-11-20", + tool_search_tool_bm25_20251119: "advanced-tool-use-2025-11-20", + memory_20250818: "context-management-2025-06-27", + web_fetch_20250910: "web-fetch-2025-09-10", + code_execution_20250825: "code-execution-2025-08-25", + computer_20251124: "computer-use-2025-11-24", + computer_20250124: "computer-use-2025-01-24", + mcp_toolset: "mcp-client-2025-11-20" +}; + +//#endregion + +//# sourceMappingURL=tools.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/content.js + + +//#region src/utils/content.ts +function _isAnthropicThinkingBlock(block) { + return typeof block === "object" && block !== null && "type" in block && block.type === "thinking"; +} +function _isAnthropicRedactedThinkingBlock(block) { + return typeof block === "object" && block !== null && "type" in block && block.type === "redacted_thinking"; +} +function _isAnthropicSearchResultBlock(block) { + return typeof block === "object" && block !== null && "type" in block && block.type === "search_result"; +} +function _isAnthropicImageBlockParam(block) { + if (typeof block !== "object" || block == null) return false; + if (!("type" in block) || block.type !== "image") return false; + if (!("source" in block) || typeof block.source !== "object" || block.source == null) return false; + if (!("type" in block.source)) return false; + if (block.source.type === "base64") { + if (!("media_type" in block.source)) return false; + if (typeof block.source.media_type !== "string") return false; + if (!("data" in block.source)) return false; + if (typeof block.source.data !== "string") return false; + return true; + } + if (block.source.type === "url") { + if (!("url" in block.source)) return false; + if (typeof block.source.url !== "string") return false; + return true; + } + return false; +} +const standardContentBlockConverter = { + providerName: "anthropic", + fromStandardTextBlock(block) { + return { + type: "text", + text: block.text, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + }, + fromStandardImageBlock(block) { + if (block.source_type === "url") { + const data = parseBase64DataUrl({ + dataUrl: block.url, + asTypedArray: false + }); + if (data) return { + type: "image", + source: { + type: "base64", + data: data.data, + media_type: data.mime_type + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + else return { + type: "image", + source: { + type: "url", + url: block.url + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + } else if (block.source_type === "base64") return { + type: "image", + source: { + type: "base64", + data: block.data, + media_type: block.mime_type ?? "" + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} + }; + else throw new Error(`Unsupported image source type: ${block.source_type}`); + }, + fromStandardFileBlock(block) { + const mime_type = (block.mime_type ?? "").split(";")[0]; + if (block.source_type === "url") { + if (mime_type === "application/pdf" || mime_type === "") return { + type: "document", + source: { + type: "url", + url: block.url + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + throw new Error(`Unsupported file mime type for file url source: ${block.mime_type}`); + } else if (block.source_type === "text") if (mime_type === "text/plain" || mime_type === "") return { + type: "document", + source: { + type: "text", + data: block.text, + media_type: block.mime_type ?? "" + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + else throw new Error(`Unsupported file mime type for file text source: ${block.mime_type}`); + else if (block.source_type === "base64") if (mime_type === "application/pdf" || mime_type === "") return { + type: "document", + source: { + type: "base64", + data: block.data, + media_type: "application/pdf" + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + else if ([ + "image/jpeg", + "image/png", + "image/gif", + "image/webp" + ].includes(mime_type)) return { + type: "document", + source: { + type: "content", + content: [{ + type: "image", + source: { + type: "base64", + data: block.data, + media_type: mime_type + } + }] + }, + ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, + ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, + ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, + ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} + }; + else throw new Error(`Unsupported file mime type for file base64 source: ${block.mime_type}`); + else throw new Error(`Unsupported file source type: ${block.source_type}`); + } +}; + +//#endregion + +//# sourceMappingURL=content.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/index.js +//#region src/utils/index.ts +const dist_utils_iife = (fn) => fn(); + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/standard.js + + +//#region src/utils/standard.ts +function _isStandardAnnotation(annotation) { + return typeof annotation === "object" && annotation !== null && "type" in annotation && annotation.type === "citation"; +} +function _formatStandardCitations(annotations) { + function* iterateAnnotations() { + for (const annotation of annotations) if (_isStandardAnnotation(annotation)) { + if (annotation.source === "char") yield { + type: "char_location", + file_id: annotation.url ?? "", + start_char_index: annotation.startIndex ?? 0, + end_char_index: annotation.endIndex ?? 0, + document_title: annotation.title ?? null, + document_index: 0, + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "page") yield { + type: "page_location", + file_id: annotation.url ?? "", + start_page_number: annotation.startIndex ?? 0, + end_page_number: annotation.endIndex ?? 0, + document_title: annotation.title ?? null, + document_index: 0, + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "block") yield { + type: "content_block_location", + file_id: annotation.url ?? "", + start_block_index: annotation.startIndex ?? 0, + end_block_index: annotation.endIndex ?? 0, + document_title: annotation.title ?? null, + document_index: 0, + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "url") yield { + type: "web_search_result_location", + url: annotation.url ?? "", + title: annotation.title ?? null, + encrypted_index: String(annotation.startIndex ?? 0), + cited_text: annotation.citedText ?? "" + }; + else if (annotation.source === "search") yield { + type: "search_result_location", + title: annotation.title ?? null, + start_block_index: annotation.startIndex ?? 0, + end_block_index: annotation.endIndex ?? 0, + search_result_index: 0, + source: annotation.source ?? "", + cited_text: annotation.citedText ?? "" + }; + } + } + return Array.from(iterateAnnotations()); +} +function _formatBase64Data(data) { + if (typeof data === "string") return data; + else return _encodeUint8Array(data); +} +function _encodeUint8Array(data) { + const output = []; + for (let i = 0, { length } = data; i < length; i++) output.push(String.fromCharCode(data[i])); + return btoa(output.join("")); +} +function _normalizeMimeType(mimeType) { + return (mimeType ?? "").split(";")[0].toLowerCase(); +} +function _extractMetadataValue(metadata, key) { + if (metadata !== void 0 && metadata !== null && typeof metadata === "object" && key in metadata) return metadata[key]; + return void 0; +} +function _applyDocumentMetadata(block, metadata) { + const cacheControl = _extractMetadataValue(metadata, "cache_control"); + if (cacheControl !== void 0) block.cache_control = cacheControl; + const citations = _extractMetadataValue(metadata, "citations"); + if (citations !== void 0) block.citations = citations; + const context = _extractMetadataValue(metadata, "context"); + if (context !== void 0) block.context = context; + const title = _extractMetadataValue(metadata, "title"); + if (title !== void 0) block.title = title; + return block; +} +function _applyImageMetadata(block, metadata) { + const cacheControl = _extractMetadataValue(metadata, "cache_control"); + if (cacheControl !== void 0) block.cache_control = cacheControl; + return block; +} +function _hasAllowedImageMimeType(mimeType) { + const ALLOWED_IMAGE_MIME_TYPES = new Set([ + "image/jpeg", + "image/png", + "image/gif", + "image/webp" + ]); + return ALLOWED_IMAGE_MIME_TYPES.has(mimeType); +} +function _formatStandardContent(message) { + const result = []; + const responseMetadata = message.response_metadata; + const isAnthropicMessage = "model_provider" in responseMetadata && responseMetadata?.model_provider === "anthropic"; + for (const block of message.contentBlocks) if (block.type === "text") if (block.annotations) result.push({ + type: "text", + text: block.text, + citations: _formatStandardCitations(block.annotations) + }); + else result.push({ + type: "text", + text: block.text + }); + else if (block.type === "tool_call") result.push({ + type: "tool_use", + id: block.id ?? "", + name: block.name, + input: block.args + }); + else if (block.type === "tool_call_chunk") { + const input = dist_utils_iife(() => { + if (typeof block.args !== "string") return block.args; + try { + return JSON.parse(block.args); + } catch { + return {}; + } + }); + result.push({ + type: "tool_use", + id: block.id ?? "", + name: block.name ?? "", + input + }); + } else if (block.type === "reasoning" && isAnthropicMessage) result.push({ + type: "thinking", + thinking: block.reasoning, + signature: String(block.signature) + }); + else if (block.type === "server_tool_call" && isAnthropicMessage) { + if (block.name === "web_search") result.push({ + type: "server_tool_use", + name: block.name, + id: block.id ?? "", + input: block.args + }); + else if (block.name === "code_execution") result.push({ + type: "server_tool_use", + name: block.name, + id: block.id ?? "", + input: block.args + }); + } else if (block.type === "server_tool_call_result" && isAnthropicMessage) { + if (block.name === "web_search" && Array.isArray(block.output.urls)) { + const content = block.output.urls.map((url) => ({ + type: "web_search_result", + title: "", + encrypted_content: "", + url + })); + result.push({ + type: "web_search_tool_result", + tool_use_id: block.toolCallId ?? "", + content + }); + } else if (block.name === "code_execution") result.push({ + type: "code_execution_tool_result", + tool_use_id: block.toolCallId ?? "", + content: block.output + }); + else if (block.name === "mcp_tool_result") result.push({ + type: "mcp_tool_result", + tool_use_id: block.toolCallId ?? "", + content: block.output + }); + } else if (block.type === "audio") throw new Error("Anthropic does not support audio content blocks."); + else if (block.type === "file") { + const metadata = block.metadata; + if (block.fileId) { + result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "file", + file_id: block.fileId + } + }, metadata)); + continue; + } + if (block.url) { + const mimeType = _normalizeMimeType(block.mimeType); + if (mimeType === "application/pdf" || mimeType === "") { + result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "url", + url: block.url + } + }, metadata)); + continue; + } + } + if (block.data) { + const mimeType = _normalizeMimeType(block.mimeType); + if (mimeType === "" || mimeType === "application/pdf") result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "base64", + data: _formatBase64Data(block.data), + media_type: "application/pdf" + } + }, metadata)); + else if (mimeType === "text/plain") result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "text", + data: _formatBase64Data(block.data), + media_type: "text/plain" + } + }, metadata)); + else if (_hasAllowedImageMimeType(mimeType)) result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "content", + content: [{ + type: "image", + source: { + type: "base64", + data: _formatBase64Data(block.data), + media_type: mimeType + } + }] + } + }, metadata)); + else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${mimeType}`); + continue; + } + throw new Error("File content block must include a fileId, url, or data property."); + } else if (block.type === "image") { + const metadata = block.metadata; + if (block.fileId) { + result.push(_applyImageMetadata({ + type: "image", + source: { + type: "file", + file_id: block.fileId + } + }, metadata)); + continue; + } + if (block.url) { + result.push(_applyImageMetadata({ + type: "image", + source: { + type: "url", + url: block.url + } + }, metadata)); + continue; + } + if (block.data) { + const mimeType = _normalizeMimeType(block.mimeType) || "image/png"; + if (_hasAllowedImageMimeType(mimeType)) result.push(_applyImageMetadata({ + type: "image", + source: { + type: "base64", + data: _formatBase64Data(block.data), + media_type: mimeType + } + }, metadata)); + continue; + } + throw new Error("Image content block must include a fileId, url, or data property."); + } else if (block.type === "video") {} else if (block.type === "text-plain") { + if (block.data) result.push(_applyDocumentMetadata({ + type: "document", + source: { + type: "text", + data: _formatBase64Data(block.data), + media_type: "text/plain" + } + }, block.metadata)); + } else if (block.type === "non_standard" && isAnthropicMessage) result.push(block.value); + return result; +} + +//#endregion + +//# sourceMappingURL=standard.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/message_inputs.js + + + + +//#region src/utils/message_inputs.ts +function _formatImage(imageUrl) { + const parsed = parseBase64DataUrl({ dataUrl: imageUrl }); + if (parsed) return { + type: "base64", + media_type: parsed.mime_type, + data: parsed.data + }; + let parsedUrl; + try { + parsedUrl = new URL(imageUrl); + } catch { + throw new Error([ + `Malformed image URL: ${JSON.stringify(imageUrl)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`, + "Example: data:image/png;base64,/9j/4AAQSk...", + "Example: https://example.com/image.jpg" + ].join("\n\n")); + } + if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") return { + type: "url", + url: imageUrl + }; + throw new Error([ + `Invalid image URL protocol: ${JSON.stringify(parsedUrl.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`, + "Example: data:image/png;base64,/9j/4AAQSk...", + "Example: https://example.com/image.jpg" + ].join("\n\n")); +} +function _ensureMessageContents(messages) { + const updatedMsgs = []; + for (const message of messages) if (message._getType() === "tool") if (typeof message.content === "string") { + const previousMessage = updatedMsgs[updatedMsgs.length - 1]; + if (previousMessage?._getType() === "human" && Array.isArray(previousMessage.content) && "type" in previousMessage.content[0] && previousMessage.content[0].type === "tool_result") previousMessage.content.push({ + type: "tool_result", + content: message.content, + tool_use_id: message.tool_call_id + }); + else updatedMsgs.push(new HumanMessage({ content: [{ + type: "tool_result", + content: message.content, + tool_use_id: message.tool_call_id + }] })); + } else updatedMsgs.push(new HumanMessage({ content: [{ + type: "tool_result", + ...message.content != null ? { content: _formatContent(message) } : {}, + tool_use_id: message.tool_call_id + }] })); + else updatedMsgs.push(message); + return updatedMsgs; +} +function _convertLangChainToolCallToAnthropic(toolCall) { + if (toolCall.id === void 0) throw new Error(`Anthropic requires all tool calls to have an "id".`); + return { + type: "tool_use", + id: toolCall.id, + name: toolCall.name, + input: toolCall.args + }; +} +function* _formatContentBlocks(content) { + const toolTypes = [ + "bash_code_execution_tool_result", + "input_json_delta", + "server_tool_use", + "text_editor_code_execution_tool_result", + "tool_result", + "tool_use", + "web_search_result", + "web_search_tool_result" + ]; + const textTypes = ["text", "text_delta"]; + for (const contentPart of content) { + if (isDataContentBlock(contentPart)) yield convertToProviderContentBlock(contentPart, standardContentBlockConverter); + const cacheControl = "cache_control" in contentPart ? contentPart.cache_control : void 0; + if (contentPart.type === "image_url") { + let source; + if (typeof contentPart.image_url === "string") source = _formatImage(contentPart.image_url); + else if (typeof contentPart.image_url === "object" && contentPart.image_url !== null && "url" in contentPart.image_url && typeof contentPart.image_url.url === "string") source = _formatImage(contentPart.image_url.url); + if (source) yield { + type: "image", + source, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } else if (_isAnthropicImageBlockParam(contentPart)) return contentPart; + else if (contentPart.type === "document") yield { + ...contentPart, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + else if (_isAnthropicThinkingBlock(contentPart)) { + const block = { + type: "thinking", + thinking: contentPart.thinking, + signature: contentPart.signature, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + yield block; + } else if (_isAnthropicRedactedThinkingBlock(contentPart)) { + const block = { + type: "redacted_thinking", + data: contentPart.data, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + yield block; + } else if (_isAnthropicSearchResultBlock(contentPart)) { + const block = { + type: "search_result", + title: contentPart.title, + source: contentPart.source, + ..."cache_control" in contentPart && contentPart.cache_control ? { cache_control: contentPart.cache_control } : {}, + ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {}, + content: contentPart.content + }; + yield block; + } else if (textTypes.find((t) => t === contentPart.type) && "text" in contentPart) yield { + type: "text", + text: contentPart.text, + ...cacheControl ? { cache_control: cacheControl } : {}, + ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {} + }; + else if (toolTypes.find((t) => t === contentPart.type)) { + const contentPartCopy = { ...contentPart }; + if ("index" in contentPartCopy) delete contentPartCopy.index; + if (contentPartCopy.type === "input_json_delta") contentPartCopy.type = "tool_use"; + if ("input" in contentPartCopy) { + if (typeof contentPartCopy.input === "string") try { + contentPartCopy.input = JSON.parse(contentPartCopy.input); + } catch { + contentPartCopy.input = {}; + } + } + yield { + ...contentPartCopy, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } else if (contentPart.type === "container_upload") yield { + ...contentPart, + ...cacheControl ? { cache_control: cacheControl } : {} + }; + } +} +function _formatContent(message) { + const { content } = message; + if (typeof content === "string") return content; + else return Array.from(_formatContentBlocks(content)); +} +/** +* Formats messages as a prompt for the model. +* Used in LangSmith, export is important here. +* @param messages The base messages to format as a prompt. +* @returns The formatted prompt. +*/ +function message_inputs_convertMessagesToAnthropicPayload(messages) { + const mergedMessages = _ensureMessageContents(messages); + let system; + if (mergedMessages.length > 0 && mergedMessages[0]._getType() === "system") system = messages[0].content; + const conversationMessages = system !== void 0 ? mergedMessages.slice(1) : mergedMessages; + const formattedMessages = conversationMessages.map((message) => { + let role; + if (message._getType() === "human") role = "user"; + else if (message._getType() === "ai") role = "assistant"; + else if (message._getType() === "tool") role = "user"; + else if (message._getType() === "system") throw new Error("System messages are only permitted as the first passed message."); + else throw new Error(`Message type "${message.type}" is not supported.`); + if (isAIMessage(message) && message.response_metadata?.output_version === "v1") return { + role, + content: _formatStandardContent(message) + }; + if (isAIMessage(message) && !!message.tool_calls?.length) if (typeof message.content === "string") if (message.content === "") return { + role, + content: message.tool_calls.map(_convertLangChainToolCallToAnthropic) + }; + else return { + role, + content: [{ + type: "text", + text: message.content + }, ...message.tool_calls.map(_convertLangChainToolCallToAnthropic)] + }; + else { + const { content } = message; + const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) => content.find((contentPart) => (contentPart.type === "tool_use" || contentPart.type === "input_json_delta" || contentPart.type === "server_tool_use") && contentPart.id === toolCall.id)); + if (hasMismatchedToolCalls) console.warn(`The "tool_calls" field on a message is only respected if content is a string.`); + return { + role, + content: _formatContent(message) + }; + } + else return { + role, + content: _formatContent(message) + }; + }); + return { + messages: mergeMessages(formattedMessages), + system + }; +} +function mergeMessages(messages) { + if (!messages || messages.length <= 1) return messages; + const result = []; + let currentMessage = messages[0]; + const normalizeContent = (content) => { + if (typeof content === "string") return [{ + type: "text", + text: content + }]; + return content; + }; + const isToolResultMessage = (msg) => { + if (msg.role !== "user") return false; + if (typeof msg.content === "string") return false; + return Array.isArray(msg.content) && msg.content.every((item) => item.type === "tool_result"); + }; + for (let i = 1; i < messages.length; i += 1) { + const nextMessage = messages[i]; + if (isToolResultMessage(currentMessage) && isToolResultMessage(nextMessage)) currentMessage = { + ...currentMessage, + content: [...normalizeContent(currentMessage.content), ...normalizeContent(nextMessage.content)] + }; + else { + result.push(currentMessage); + currentMessage = nextMessage; + } + } + result.push(currentMessage); + return result; +} + +//#endregion + +//# sourceMappingURL=message_inputs.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/message_outputs.js + + + +//#region src/utils/message_outputs.ts +function _makeMessageChunkFromAnthropicEvent(data, fields) { + const response_metadata = { model_provider: "anthropic" }; + if (data.type === "message_start") { + const { content, usage,...additionalKwargs } = data.message; + const filteredAdditionalKwargs = {}; + for (const [key, value] of Object.entries(additionalKwargs)) if (value !== void 0 && value !== null) filteredAdditionalKwargs[key] = value; + const { input_tokens, output_tokens,...rest } = usage ?? {}; + const totalInputTokens = input_tokens + rest.cache_creation_input_tokens + rest.cache_read_input_tokens; + const usageMetadata = { + input_tokens: totalInputTokens, + output_tokens, + total_tokens: totalInputTokens + output_tokens, + input_token_details: { + cache_creation: rest.cache_creation_input_tokens, + cache_read: rest.cache_read_input_tokens + } + }; + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [], + additional_kwargs: filteredAdditionalKwargs, + usage_metadata: fields.streamUsage ? usageMetadata : void 0, + response_metadata: { + ...response_metadata, + usage: { ...rest } + }, + id: data.message.id + }) }; + } else if (data.type === "message_delta") { + const usageMetadata = { + input_tokens: 0, + output_tokens: data.usage.output_tokens, + total_tokens: data.usage.output_tokens, + input_token_details: { + cache_creation: data.usage.cache_creation_input_tokens, + cache_read: data.usage.cache_read_input_tokens + } + }; + const responseMetadata = "context_management" in data.delta ? { context_management: data.delta.context_management } : void 0; + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [], + response_metadata: responseMetadata, + additional_kwargs: { ...data.delta }, + usage_metadata: fields.streamUsage ? usageMetadata : void 0 + }) }; + } else if (data.type === "content_block_start" && [ + "tool_use", + "document", + "server_tool_use", + "web_search_tool_result" + ].includes(data.content_block.type)) { + const contentBlock = data.content_block; + let toolCallChunks; + if (contentBlock.type === "tool_use") toolCallChunks = [{ + id: contentBlock.id, + index: data.index, + name: contentBlock.name, + args: "" + }]; + else toolCallChunks = []; + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + ...data.content_block, + input: contentBlock.type === "server_tool_use" || contentBlock.type === "tool_use" ? "" : void 0 + }], + response_metadata, + additional_kwargs: {}, + tool_call_chunks: toolCallChunks + }) }; + } else if (data.type === "content_block_delta" && [ + "text_delta", + "citations_delta", + "thinking_delta", + "signature_delta" + ].includes(data.delta.type)) if (fields.coerceContentToString && "text" in data.delta) return { chunk: new AIMessageChunk({ content: data.delta.text }) }; + else { + const contentBlock = data.delta; + if ("citation" in contentBlock) { + contentBlock.citations = [contentBlock.citation]; + delete contentBlock.citation; + } + if (contentBlock.type === "thinking_delta" || contentBlock.type === "signature_delta") return { chunk: new AIMessageChunk({ + content: [{ + index: data.index, + ...contentBlock, + type: "thinking" + }], + response_metadata + }) }; + return { chunk: new AIMessageChunk({ + content: [{ + index: data.index, + ...contentBlock, + type: "text" + }], + response_metadata + }) }; + } + else if (data.type === "content_block_delta" && data.delta.type === "input_json_delta") return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + input: data.delta.partial_json, + type: data.delta.type + }], + response_metadata, + additional_kwargs: {}, + tool_call_chunks: [{ + index: data.index, + args: data.delta.partial_json + }] + }) }; + else if (data.type === "content_block_start" && data.content_block.type === "text") { + const content = data.content_block?.text; + if (content !== void 0) return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? content : [{ + index: data.index, + ...data.content_block + }], + response_metadata, + additional_kwargs: {} + }) }; + } else if (data.type === "content_block_start" && data.content_block.type === "redacted_thinking") return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? "" : [{ + index: data.index, + ...data.content_block + }], + response_metadata + }) }; + else if (data.type === "content_block_start" && data.content_block.type === "thinking") { + const content = data.content_block.thinking; + return { chunk: new AIMessageChunk({ + content: fields.coerceContentToString ? content : [{ + index: data.index, + ...data.content_block + }], + response_metadata + }) }; + } + return null; +} +function anthropicResponseToChatMessages(messages, additionalKwargs) { + const response_metadata = { + ...additionalKwargs, + model_provider: "anthropic" + }; + const usage = additionalKwargs.usage; + const usageMetadata = usage != null ? { + input_tokens: usage.input_tokens ?? 0, + output_tokens: usage.output_tokens ?? 0, + total_tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0), + input_token_details: { + cache_creation: usage.cache_creation_input_tokens, + cache_read: usage.cache_read_input_tokens + } + } : void 0; + if (messages.length === 1 && messages[0].type === "text") return [{ + text: messages[0].text, + message: new AIMessage({ + content: messages[0].text, + additional_kwargs: additionalKwargs, + usage_metadata: usageMetadata, + response_metadata, + id: additionalKwargs.id + }) + }]; + else { + const toolCalls = extractToolCalls(messages); + const generations = [{ + text: "", + message: new AIMessage({ + content: messages, + additional_kwargs: additionalKwargs, + tool_calls: toolCalls, + usage_metadata: usageMetadata, + response_metadata, + id: additionalKwargs.id + }) + }]; + return generations; + } +} + +//#endregion + +//# sourceMappingURL=message_outputs.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/errors.js +//#region src/utils/errors.ts +function errors_addLangChainErrorFields(error, lc_error_code) { + error.lc_error_code = lc_error_code; + error.message = `${error.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\n`; + return error; +} +function wrapAnthropicClientError(e) { + let error; + if (e.status === 400 && e.message.includes("tool")) error = errors_addLangChainErrorFields(e, "INVALID_TOOL_RESULTS"); + else if (e.status === 401) error = errors_addLangChainErrorFields(e, "MODEL_AUTHENTICATION"); + else if (e.status === 404) error = errors_addLangChainErrorFields(e, "MODEL_NOT_FOUND"); + else if (e.status === 429) error = errors_addLangChainErrorFields(e, "MODEL_RATE_LIMIT"); + else error = e; + return error; +} + +//#endregion + +//# sourceMappingURL=errors.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/profiles.js +//#region src/profiles.ts +const PROFILES = { + "claude-opus-4-0": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-5-sonnet-20241022": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-1": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-haiku-4-5": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-5-sonnet-20240620": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-5-haiku-latest": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-opus-20240229": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-4-5": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-4-5-20250929": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-4-20250514": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-20250514": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-5-haiku-20241022": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-haiku-20240307": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-7-sonnet-20250219": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-7-sonnet-latest": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-sonnet-4-0": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-opus-4-1-20250805": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-3-sonnet-20240229": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + }, + "claude-haiku-4-5-20251001": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 64e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true + } +}; +var profiles_default = PROFILES; + +//#endregion + +//# sourceMappingURL=profiles.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/tslib.mjs +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; +} +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + + +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * https://stackoverflow.com/a/2117523 + */ +let uuid_uuid4 = function () { + const { crypto } = globalThis; + if (crypto?.randomUUID) { + uuid_uuid4 = crypto.randomUUID.bind(crypto); + return crypto.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff; + return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16)); +}; +//# sourceMappingURL=uuid.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/errors.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function isAbortError(err) { + return (typeof err === 'object' && + err !== null && + // Spec-compliant fetch implementations + (('name' in err && err.name === 'AbortError') || + // Expo fetch + ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); +} +const castToError = (err) => { + if (err instanceof Error) + return err; + if (typeof err === 'object' && err !== null) { + try { + if (Object.prototype.toString.call(err) === '[object Error]') { + // @ts-ignore - not all envs have native support for cause yet + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + // @ts-ignore - not all envs have native support for cause yet + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } + catch { } + try { + return new Error(JSON.stringify(err)); + } + catch { } + } + return new Error(err); +}; +//# sourceMappingURL=errors.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/error.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class error_AnthropicError extends Error { +} +class APIError extends error_AnthropicError { + constructor(status, error, message, headers) { + super(`${APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get('request-id'); + this.error = error; + } + static makeMessage(status, error, message) { + const msg = error?.message ? + typeof error.message === 'string' ? + error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return '(no status code or body)'; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new APIConnectionError({ message, cause: castToError(errorResponse) }); + } + const error = errorResponse; + if (status === 400) { + return new BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new ConflictError(status, error, message, headers); + } + if (status === 422) { + return new UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new InternalServerError(status, error, message, headers); + } + return new APIError(status, error, message, headers); + } +} +class APIUserAbortError extends APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + } +} +class APIConnectionError extends APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) + this.cause = cause; + } +} +class APIConnectionTimeoutError extends APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? 'Request timed out.' }); + } +} +class BadRequestError extends APIError { +} +class AuthenticationError extends APIError { +} +class PermissionDeniedError extends APIError { +} +class NotFoundError extends APIError { +} +class ConflictError extends APIError { +} +class UnprocessableEntityError extends APIError { +} +class RateLimitError extends APIError { +} +class InternalServerError extends APIError { +} +//# sourceMappingURL=error.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +// https://url.spec.whatwg.org/#url-scheme-string +const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +const isAbsoluteURL = (url) => { + return startsWithSchemeRegexp.test(url); +}; +let values_isArray = (val) => ((values_isArray = Array.isArray), values_isArray(val)); +let isReadonlyArray = values_isArray; +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +function maybeObj(x) { + if (typeof x !== 'object') { + return {}; + } + return x ?? {}; +} +// https://stackoverflow.com/a/34491287 +function isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +// https://eslint.org/docs/latest/rules/no-prototype-builtins +function hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +const ensurePresent = (value) => { + if (value == null) { + throw new AnthropicError(`Expected a value to be given but received ${value} instead.`); + } + return value; +}; +const validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new error_AnthropicError(`${name} must be an integer`); + } + if (n < 0) { + throw new error_AnthropicError(`${name} must be a positive integer`); + } + return n; +}; +const coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +const coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +const coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +const maybeCoerceInteger = (value) => { + if (value == null) { + return undefined; + } + return coerceInteger(value); +}; +const maybeCoerceFloat = (value) => { + if (value == null) { + return undefined; + } + return coerceFloat(value); +}; +const maybeCoerceBoolean = (value) => { + if (value == null) { + return undefined; + } + return coerceBoolean(value); +}; +const safeJSON = (text) => { + try { + return JSON.parse(text); + } + catch (err) { + return undefined; + } +}; +// Gets a value from an object, deletes the key, and returns the value (or undefined if not found) +const pop = (obj, key) => { + const value = obj[key]; + delete obj[key]; + return value; +}; +//# sourceMappingURL=values.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +//# sourceMappingURL=sleep.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/version.mjs +const VERSION = '0.71.2'; // x-release-please-version +//# sourceMappingURL=version.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined'); +}; +/** + * Note this does not detect 'browser'; for that, use getBrowserInfo(). + */ +function getDetectedPlatform() { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return 'deno'; + } + if (typeof EdgeRuntime !== 'undefined') { + return 'edge'; + } + if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') { + return 'node'; + } + return 'unknown'; +} +const getPlatformProperties = () => { + const detectedPlatform = getDetectedPlatform(); + if (detectedPlatform === 'deno') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', + }; + } + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': globalThis.process.version, + }; + } + // Check if Node.js + if (detectedPlatform === 'node') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': normalizePlatform(globalThis.process.platform ?? 'unknown'), + 'X-Stainless-Arch': normalizeArch(globalThis.process.arch ?? 'unknown'), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown', + }; + } + const browserInfo = getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; + } + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function getBrowserInfo() { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +const normalizeArch = (arch) => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') + return 'x32'; + if (arch === 'x86_64' || arch === 'x64') + return 'x64'; + if (arch === 'arm') + return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') + return 'arm64'; + if (arch) + return `other:${arch}`; + return 'unknown'; +}; +const normalizePlatform = (platform) => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + platform = platform.toLowerCase(); + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) + return 'iOS'; + if (platform === 'android') + return 'Android'; + if (platform === 'darwin') + return 'MacOS'; + if (platform === 'win32') + return 'Windows'; + if (platform === 'freebsd') + return 'FreeBSD'; + if (platform === 'openbsd') + return 'OpenBSD'; + if (platform === 'linux') + return 'Linux'; + if (platform) + return `Other:${platform}`; + return 'Unknown'; +}; +let _platformHeaders; +const getPlatformHeaders = () => { + return (_platformHeaders ?? (_platformHeaders = getPlatformProperties())); +}; +//# sourceMappingURL=detect-platform.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/shims.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function getDefaultFetch() { + if (typeof fetch !== 'undefined') { + return fetch; + } + throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); +} +function makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === 'undefined') { + // Note: All of the platforms / runtimes we officially support already define + // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. + throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); + } + return new ReadableStream(...args); +} +function ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return makeReadableStream({ + start() { }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } + else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + }, + }); +} +/** + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +function ReadableStreamToAsyncIterable(stream) { + if (stream[Symbol.asyncIterator]) + return stream; + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); // release lock when stream becomes closed + return result; + } + catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; +} +/** + * Cancels a ReadableStream we don't need to consume. + * See https://undici.nodejs.org/#/?id=garbage-collection + */ +async function CancelReadableStream(stream) { + if (stream === null || typeof stream !== 'object') + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +//# sourceMappingURL=shims.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/request-options.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + 'content-type': 'application/json', + }, + body: JSON.stringify(body), + }; +}; +//# sourceMappingURL=request-options.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs +function concatBytes(buffers) { + let length = 0; + for (const buffer of buffers) { + length += buffer.length; + } + const output = new Uint8Array(length); + let index = 0; + for (const buffer of buffers) { + output.set(buffer, index); + index += buffer.length; + } + return output; +} +let encodeUTF8_; +function bytes_encodeUTF8(str) { + let encoder; + return (encodeUTF8_ ?? + ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str); +} +let decodeUTF8_; +function decodeUTF8(bytes) { + let decoder; + return (decodeUTF8_ ?? + ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); +} +//# sourceMappingURL=bytes.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs +var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex; + + +/** + * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally + * reading lines from text. + * + * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 + */ +class LineDecoder { + constructor() { + _LineDecoder_buffer.set(this, void 0); + _LineDecoder_carriageReturnIndex.set(this, void 0); + __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + decode(chunk) { + if (chunk == null) { + return []; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? bytes_encodeUTF8(chunk) + : chunk; + __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); + const lines = []; + let patternIndex; + while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { + if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { + // skip until we either get a corresponding `\n`, a new `\r` or nothing + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); + continue; + } + // we got double \r or \rtext\n + if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && + (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { + lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + continue; + } + const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); + lines.push(line); + __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); + __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); + } + return lines; + } + flush() { + if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) { + return []; + } + return this.decode('\n'); + } +} +_LineDecoder_buffer = new WeakMap(), _LineDecoder_carriageReturnIndex = new WeakMap(); +// prettier-ignore +LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); +LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; +/** + * This function searches the buffer for the end patterns, (\r or \n) + * and returns an object with the index preceding the matched newline and the + * index after the newline char. `null` is returned if no new line is found. + * + * ```ts + * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } + * ``` + */ +function findNewlineIndex(buffer, startIndex) { + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = startIndex ?? 0; i < buffer.length; i++) { + if (buffer[i] === newline) { + return { preceding: i, index: i + 1, carriage: false }; + } + if (buffer[i] === carriage) { + return { preceding: i, index: i + 1, carriage: true }; + } + } + return null; +} +function findDoubleNewlineIndex(buffer) { + // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) + // and returns the index right after the first occurrence of any pattern, + // or -1 if none of the patterns are found. + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = 0; i < buffer.length - 1; i++) { + if (buffer[i] === newline && buffer[i + 1] === newline) { + // \n\n + return i + 2; + } + if (buffer[i] === carriage && buffer[i + 1] === carriage) { + // \r\r + return i + 2; + } + if (buffer[i] === carriage && + buffer[i + 1] === newline && + i + 3 < buffer.length && + buffer[i + 2] === carriage && + buffer[i + 3] === newline) { + // \r\n\r\n + return i + 4; + } + } + return -1; +} +//# sourceMappingURL=line.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500, +}; +const parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return undefined; + } + if (hasOwn(levelNumbers, maybeLevel)) { + return maybeLevel; + } + loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); + return undefined; +}; +function noop() { } +function makeLogFn(fnLevel, logger, logLevel) { + if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { + return noop; + } + else { + // Don't wrap logger functions, we want the stacktrace intact! + return logger[fnLevel].bind(logger); + } +} +const noopLogger = { + error: noop, + warn: noop, + info: noop, + debug: noop, +}; +let cachedLoggers = /* @__PURE__ */ new WeakMap(); +function loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? 'off'; + if (!logger) { + return noopLogger; + } + const cachedLogger = cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: makeLogFn('error', logger, logLevel), + warn: makeLogFn('warn', logger, logLevel), + info: makeLogFn('info', logger, logLevel), + debug: makeLogFn('debug', logger, logLevel), + }; + cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +const formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options['headers']; // redundant + leaks internals + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + (name.toLowerCase() === 'x-api-key' || + name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie') ? + '***' + : value, + ])); + } + if ('retryOfRequestLogID' in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; +//# sourceMappingURL=log.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/streaming.mjs +var _Stream_client; + + + + + + + + + + +class Stream { + constructor(iterator, controller, client) { + this.iterator = iterator; + _Stream_client.set(this, void 0); + this.controller = controller; + __classPrivateFieldSet(this, _Stream_client, client, "f"); + } + static fromSSEResponse(response, controller, client) { + let consumed = false; + const logger = client ? loggerFor(client) : console; + async function* iterator() { + if (consumed) { + throw new error_AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const sse of _iterSSEMessages(response, controller)) { + if (sse.event === 'completion') { + try { + yield JSON.parse(sse.data); + } + catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + } + if (sse.event === 'message_start' || + sse.event === 'message_delta' || + sse.event === 'message_stop' || + sse.event === 'content_block_start' || + sse.event === 'content_block_delta' || + sse.event === 'content_block_stop') { + try { + yield JSON.parse(sse.data); + } + catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + } + if (sse.event === 'ping') { + continue; + } + if (sse.event === 'error') { + throw new APIError(undefined, safeJSON(sse.data) ?? sse.data, undefined, response.headers); + } + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (isAbortError(e)) + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller, client); + } + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream, controller, client) { + let consumed = false; + async function* iterLines() { + const lineDecoder = new LineDecoder(); + const iter = ReadableStreamToAsyncIterable(readableStream); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + yield line; + } + } + for (const line of lineDecoder.flush()) { + yield line; + } + } + async function* iterator() { + if (consumed) { + throw new error_AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) + continue; + if (line) + yield JSON.parse(line); + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (isAbortError(e)) + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new Stream(iterator, controller, client); + } + [(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { + return this.iterator(); + } + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { + next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + }, + }; + }; + return [ + new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), + new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), + ]; + } + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream() { + const self = this; + let iter; + return makeReadableStream({ + async start() { + iter = self[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) + return ctrl.close(); + const bytes = bytes_encodeUTF8(JSON.stringify(value) + '\n'); + ctrl.enqueue(bytes); + } + catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + }, + }); + } +} +async function* _iterSSEMessages(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== 'undefined' && + globalThis.navigator.product === 'ReactNative') { + throw new error_AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + } + throw new error_AnthropicError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new SSEDecoder(); + const lineDecoder = new LineDecoder(); + const iter = ReadableStreamToAsyncIterable(response.body); + for await (const sseChunk of iterSSEChunks(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } +} +/** + * Given an async iterable iterator, iterates over it and yields full + * SSE chunks, i.e. yields when a double new-line is encountered. + */ +async function* iterSSEChunks(iterator) { + let data = new Uint8Array(); + for await (const chunk of iterator) { + if (chunk == null) { + continue; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? bytes_encodeUTF8(chunk) + : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + if (data.length > 0) { + yield data; + } +} +class SSEDecoder { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith('\r')) { + line = line.substring(0, line.length - 1); + } + if (!line) { + // empty line and we didn't previously encounter any messages + if (!this.event && !this.data.length) + return null; + const sse = { + event: this.event, + data: this.data.join('\n'), + raw: this.chunks, + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; + } + this.chunks.push(line); + if (line.startsWith(':')) { + return null; + } + let [fieldname, _, value] = partition(line, ':'); + if (value.startsWith(' ')) { + value = value.substring(1); + } + if (fieldname === 'event') { + this.event = value; + } + else if (fieldname === 'data') { + this.data.push(value); + } + return null; + } +} +function partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; + } + return [str, '', '']; +} +//# sourceMappingURL=streaming.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/parse.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +async function defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (props.options.stream) { + loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller); + } + return Stream.fromSSEResponse(response, props.controller); + } + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get('content-type'); + const mediaType = contentType?.split(';')[0]?.trim(); + const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); + if (isJSON) { + const json = await response.json(); + return addRequestID(json, response); + } + const text = await response.text(); + return text; + })(); + loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime, + })); + return body; +} +function addRequestID(value, response) { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return value; + } + return Object.defineProperty(value, '_request_id', { + value: response.headers.get('request-id'), + enumerable: false, + }); +} +//# sourceMappingURL=parse.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/api-promise.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _APIPromise_client; + + +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +class APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = defaultParseResponse) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + _APIPromise_client.set(this, void 0); + __classPrivateFieldSet(this, _APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data, the raw `Response` instance and the ID of the request, + * returned via the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response, request_id: response.headers.get('request-id') }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +} +_APIPromise_client = new WeakMap(); +//# sourceMappingURL=api-promise.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/pagination.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _AbstractPage_client; + + + + + +class AbstractPage { + constructor(client, response, body, options) { + _AbstractPage_client.set(this, void 0); + __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new error_AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); + } + return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +} +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +class PagePromise extends APIPromise { + constructor(client, request, Page) { + super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +} +class Page extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.first_id = body.first_id || null; + this.last_id = body.last_id || null; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + if (this.options.query?.['before_id']) { + // in reverse + const first_id = this.first_id; + if (!first_id) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + before_id: first_id, + }, + }; + } + const cursor = this.last_id; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + after_id: cursor, + }, + }; + } +} +class TokenPage extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.next_page = body.next_page || null; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + const cursor = this.next_page; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + page_token: cursor, + }, + }; + } +} +class PageCursor extends AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.next_page = body.next_page || null; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + const cursor = this.next_page; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...maybeObj(this.options.query), + page: cursor, + }, + }; + } +} +//# sourceMappingURL=pagination.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/uploads.mjs + +const checkFileSupport = () => { + if (typeof File === 'undefined') { + const { process } = globalThis; + const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; + throw new Error('`File` is not defined as a global, which is required for file uploads.' + + (isOldNode ? + " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." + : '')); + } +}; +/** + * Construct a `File` instance. This is used to ensure a helpful error is thrown + * for environments that don't define a global `File` yet. + */ +function makeFile(fileBits, fileName, options) { + checkFileSupport(); + return new File(fileBits, fileName ?? 'unknown_file', options); +} +function getName(value) { + return (((typeof value === 'object' && + value !== null && + (('name' in value && value.name && String(value.name)) || + ('url' in value && value.url && String(value.url)) || + ('filename' in value && value.filename && String(value.filename)) || + ('path' in value && value.path && String(value.path)))) || + '') + .split(/[\\/]/) + .pop() || undefined); +} +const uploads_isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; +/** + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. + */ +const maybeMultipartFormRequestOptions = async (opts, fetch) => { + if (!hasUploadableValue(opts.body)) + return opts; + return { ...opts, body: await createForm(opts.body, fetch) }; +}; +const multipartFormRequestOptions = async (opts, fetch) => { + return { ...opts, body: await createForm(opts.body, fetch) }; +}; +const supportsFormDataMap = /* @__PURE__ */ new WeakMap(); +/** + * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending + * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". + * This function detects if the fetch function provided supports the global FormData object to avoid + * confusing error messages later on. + */ +function supportsFormData(fetchObject) { + const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; + const cached = supportsFormDataMap.get(fetch); + if (cached) + return cached; + const promise = (async () => { + try { + const FetchResponse = ('Response' in fetch ? + fetch.Response + : (await fetch('data:,')).constructor); + const data = new FormData(); + if (data.toString() === (await new FetchResponse(data).text())) { + return false; + } + return true; + } + catch { + // avoid false negatives + return true; + } + })(); + supportsFormDataMap.set(fetch, promise); + return promise; +} +const createForm = async (body, fetch) => { + if (!(await supportsFormData(fetch))) { + throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); + } + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); + return form; +}; +// We check for Blob not File because Bun.File doesn't inherit from File, +// but they both inherit from Blob and have a `name` property at runtime. +const isNamedBlob = (value) => value instanceof Blob && 'name' in value; +const isUploadable = (value) => typeof value === 'object' && + value !== null && + (value instanceof Response || uploads_isAsyncIterable(value) || isNamedBlob(value)); +const hasUploadableValue = (value) => { + if (isUploadable(value)) + return true; + if (Array.isArray(value)) + return value.some(hasUploadableValue); + if (value && typeof value === 'object') { + for (const k in value) { + if (hasUploadableValue(value[k])) + return true; + } + } + return false; +}; +const addFormValue = async (form, key, value) => { + if (value === undefined) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); + } + // TODO: make nested formats configurable + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + form.append(key, String(value)); + } + else if (value instanceof Response) { + let options = {}; + const contentType = value.headers.get('Content-Type'); + if (contentType) { + options = { type: contentType }; + } + form.append(key, makeFile([await value.blob()], getName(value), options)); + } + else if (uploads_isAsyncIterable(value)) { + form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value))); + } + else if (isNamedBlob(value)) { + form.append(key, makeFile([value], getName(value), { type: value.type })); + } + else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); + } + else if (typeof value === 'object') { + await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); + } + else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + } +}; +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/to-file.mjs + + +/** + * This check adds the arrayBuffer() method type because it is available and used at runtime + */ +const isBlobLike = (value) => value != null && + typeof value === 'object' && + typeof value.size === 'number' && + typeof value.type === 'string' && + typeof value.text === 'function' && + typeof value.slice === 'function' && + typeof value.arrayBuffer === 'function'; +/** + * This check adds the arrayBuffer() method type because it is available and used at runtime + */ +const isFileLike = (value) => value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + isBlobLike(value); +const isResponseLike = (value) => value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +async function toFile(value, name, options) { + checkFileSupport(); + // If it's a promise, resolve it. + value = await value; + name || (name = getName(value)); + // If we've been given a `File` we don't need to do anything if the name / options + // have not been customised. + if (isFileLike(value)) { + if (value instanceof File && name == null && options == null) { + return value; + } + return makeFile([await value.arrayBuffer()], name ?? value.name, { + type: value.type, + lastModified: value.lastModified, + ...options, + }); + } + if (isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return makeFile(await to_file_getBytes(blob), name, options); + } + const parts = await to_file_getBytes(value); + if (!options?.type) { + const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); + if (typeof type === 'string') { + options = { ...options, type }; + } + } + return makeFile(parts, name, options); +} +async function to_file_getBytes(value) { + let parts = []; + if (typeof value === 'string' || + ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } + else if (isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } + else if (uploads_isAsyncIterable(value) // includes Readable, ReadableStream, etc. + ) { + for await (const chunk of value) { + parts.push(...(await to_file_getBytes(chunk))); // TODO, consider validating? + } + } + else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`); + } + return parts; +} +function propsForError(value) { + if (typeof value !== 'object' || value === null) + return ''; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; +} +//# sourceMappingURL=to-file.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/uploads.mjs + +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/resource.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +class APIResource { + constructor(client) { + this._client = client; + } +} +//# sourceMappingURL=resource.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/headers.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); +function* iterateHeaders(headers) { + if (!headers) + return; + if (brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } + else if (isReadonlyArray(headers)) { + iter = headers; + } + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== 'string') + throw new TypeError('expected header name to be a string'); + const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === undefined) + continue; + // Objects keys always overwrite older headers, they never append. + // Yield a null to clear the header before adding the new values. + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +const buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = new Set(); + for (const headers of newHeaders) { + const seenHeaders = new Set(); + for (const [name, value] of iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } + else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; +const isEmptyHeaders = (headers) => { + for (const _ of iterateHeaders(headers)) + return false; + return true; +}; +//# sourceMappingURL=headers.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs + +/** + * Percent-encode everything that isn't safe to have in a path without encoding safe chars. + * + * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: + * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + */ +function encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { + // If there are no params, no processing is needed. + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); + if (index !== params.length && + (value == null || + (typeof value === 'object' && + // handle values from other realms + value.toString === + Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY) + ?.toString))) { + encoded = value + ''; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString + .call(value) + .slice(8, -1)} is not a valid path parameter`, + }); + } + return previousValue + currentValue + (index === params.length ? '' : encoded); + }, ''); + const pathOnly = path.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + // Find all invalid segments + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = ' '.repeat(segment.start - lastEnd); + const arrows = '^'.repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ''); + throw new error_AnthropicError(`Path parameters result in path with invalid segments:\n${invalidSegments + .map((e) => e.error) + .join('\n')}\n${path}\n${underline}`); + } + return path; +}; +/** + * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. + */ +const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); +//# sourceMappingURL=path.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class Files extends APIResource { + /** + * List Files + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fileMetadata of client.beta.files.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/files', (Page), { + query, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); + } + /** + * Delete File + * + * @example + * ```ts + * const deletedFile = await client.beta.files.delete( + * 'file_id', + * ); + * ``` + */ + delete(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path `/v1/files/${fileID}`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); + } + /** + * Download File + * + * @example + * ```ts + * const response = await client.beta.files.download( + * 'file_id', + * ); + * + * const content = await response.blob(); + * console.log(content); + * ``` + */ + download(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/files/${fileID}/content`, { + ...options, + headers: buildHeaders([ + { + 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString(), + Accept: 'application/binary', + }, + options?.headers, + ]), + __binaryResponse: true, + }); + } + /** + * Get File Metadata + * + * @example + * ```ts + * const fileMetadata = + * await client.beta.files.retrieveMetadata('file_id'); + * ``` + */ + retrieveMetadata(fileID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/files/${fileID}`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }); + } + /** + * Upload File + * + * @example + * ```ts + * const fileMetadata = await client.beta.files.upload({ + * file: fs.createReadStream('path/to/file'), + * }); + * ``` + */ + upload(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/files', multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, + options?.headers, + ]), + }, this._client)); + } +} +//# sourceMappingURL=files.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +class Models extends APIResource { + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific + * model or resolve a model alias to a model ID. + * + * @example + * ```ts + * const betaModelInfo = await client.beta.models.retrieve( + * 'model_id', + * ); + * ``` + */ + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/models/${modelID}?beta=true`, { + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } + /** + * List available models. + * + * The Models API response can be used to determine which models are available for + * use in the API. More recently released models are listed first. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaModelInfo of client.beta.models.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/models?beta=true', (Page), { + query, + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } +} +//# sourceMappingURL=models.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/constants.mjs +// File containing shared constants +/** + * Model-specific timeout constraints for non-streaming requests + */ +const MODEL_NONSTREAMING_TOKENS = { + 'claude-opus-4-20250514': 8192, + 'claude-opus-4-0': 8192, + 'claude-4-opus-20250514': 8192, + 'anthropic.claude-opus-4-20250514-v1:0': 8192, + 'claude-opus-4@20250514': 8192, + 'claude-opus-4-1-20250805': 8192, + 'anthropic.claude-opus-4-1-20250805-v1:0': 8192, + 'claude-opus-4-1@20250805': 8192, +}; +//# sourceMappingURL=constants.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs + +function maybeParseBetaMessage(message, params, opts) { + if (!params || !('parse' in (params.output_format ?? {}))) { + return { + ...message, + content: message.content.map((block) => { + if (block.type === 'text') { + const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', { + value: null, + enumerable: false, + }); + return Object.defineProperty(parsedBlock, 'parsed', { + get() { + opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.'); + return null; + }, + enumerable: false, + }); + } + return block; + }), + parsed_output: null, + }; + } + return parseBetaMessage(message, params, opts); +} +function parseBetaMessage(message, params, opts) { + let firstParsedOutput = null; + const content = message.content.map((block) => { + if (block.type === 'text') { + const parsedOutput = parseBetaOutputFormat(params, block.text); + if (firstParsedOutput === null) { + firstParsedOutput = parsedOutput; + } + const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', { + value: parsedOutput, + enumerable: false, + }); + return Object.defineProperty(parsedBlock, 'parsed', { + get() { + opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.'); + return parsedOutput; + }, + enumerable: false, + }); + } + return block; + }); + return { + ...message, + content, + parsed_output: firstParsedOutput, + }; +} +function parseBetaOutputFormat(params, content) { + if (params.output_format?.type !== 'json_schema') { + return null; + } + try { + if ('parse' in params.output_format) { + return params.output_format.parse(content); + } + return JSON.parse(content); + } + catch (error) { + throw new error_AnthropicError(`Failed to parse structured output: ${error}`); + } +} +//# sourceMappingURL=beta-parser.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs +const tokenize = (input) => { + let current = 0; + let tokens = []; + while (current < input.length) { + let char = input[current]; + if (char === '\\') { + current++; + continue; + } + if (char === '{') { + tokens.push({ + type: 'brace', + value: '{', + }); + current++; + continue; + } + if (char === '}') { + tokens.push({ + type: 'brace', + value: '}', + }); + current++; + continue; + } + if (char === '[') { + tokens.push({ + type: 'paren', + value: '[', + }); + current++; + continue; + } + if (char === ']') { + tokens.push({ + type: 'paren', + value: ']', + }); + current++; + continue; + } + if (char === ':') { + tokens.push({ + type: 'separator', + value: ':', + }); + current++; + continue; + } + if (char === ',') { + tokens.push({ + type: 'delimiter', + value: ',', + }); + current++; + continue; + } + if (char === '"') { + let value = ''; + let danglingQuote = false; + char = input[++current]; + while (char !== '"') { + if (current === input.length) { + danglingQuote = true; + break; + } + if (char === '\\') { + current++; + if (current === input.length) { + danglingQuote = true; + break; + } + value += char + input[current]; + char = input[++current]; + } + else { + value += char; + char = input[++current]; + } + } + char = input[++current]; + if (!danglingQuote) { + tokens.push({ + type: 'string', + value, + }); + } + continue; + } + let WHITESPACE = /\s/; + if (char && WHITESPACE.test(char)) { + current++; + continue; + } + let NUMBERS = /[0-9]/; + if ((char && NUMBERS.test(char)) || char === '-' || char === '.') { + let value = ''; + if (char === '-') { + value += char; + char = input[++current]; + } + while ((char && NUMBERS.test(char)) || char === '.') { + value += char; + char = input[++current]; + } + tokens.push({ + type: 'number', + value, + }); + continue; + } + let LETTERS = /[a-z]/i; + if (char && LETTERS.test(char)) { + let value = ''; + while (char && LETTERS.test(char)) { + if (current === input.length) { + break; + } + value += char; + char = input[++current]; + } + if (value == 'true' || value == 'false' || value === 'null') { + tokens.push({ + type: 'name', + value, + }); + } + else { + // unknown token, e.g. `nul` which isn't quite `null` + current++; + continue; + } + continue; + } + current++; + } + return tokens; +}, parser_strip = (tokens) => { + if (tokens.length === 0) { + return tokens; + } + let lastToken = tokens[tokens.length - 1]; + switch (lastToken.type) { + case 'separator': + tokens = tokens.slice(0, tokens.length - 1); + return parser_strip(tokens); + break; + case 'number': + let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1]; + if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') { + tokens = tokens.slice(0, tokens.length - 1); + return parser_strip(tokens); + } + case 'string': + let tokenBeforeTheLastToken = tokens[tokens.length - 2]; + if (tokenBeforeTheLastToken?.type === 'delimiter') { + tokens = tokens.slice(0, tokens.length - 1); + return parser_strip(tokens); + } + else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') { + tokens = tokens.slice(0, tokens.length - 1); + return parser_strip(tokens); + } + break; + case 'delimiter': + tokens = tokens.slice(0, tokens.length - 1); + return parser_strip(tokens); + break; + } + return tokens; +}, unstrip = (tokens) => { + let tail = []; + tokens.map((token) => { + if (token.type === 'brace') { + if (token.value === '{') { + tail.push('}'); + } + else { + tail.splice(tail.lastIndexOf('}'), 1); + } + } + if (token.type === 'paren') { + if (token.value === '[') { + tail.push(']'); + } + else { + tail.splice(tail.lastIndexOf(']'), 1); + } + } + }); + if (tail.length > 0) { + tail.reverse().map((item) => { + if (item === '}') { + tokens.push({ + type: 'brace', + value: '}', + }); + } + else if (item === ']') { + tokens.push({ + type: 'paren', + value: ']', + }); + } + }); + } + return tokens; +}, generate = (tokens) => { + let output = ''; + tokens.map((token) => { + switch (token.type) { + case 'string': + output += '"' + token.value + '"'; + break; + default: + output += token.value; + break; + } + }); + return output; +}, partialParse = (input) => JSON.parse(generate(unstrip(parser_strip(tokenize(input))))); + +//# sourceMappingURL=parser.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/error.mjs + +//# sourceMappingURL=error.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/streaming.mjs + +//# sourceMappingURL=streaming.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs +var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_params, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_logger, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage; + + + + + + +const JSON_BUF_PROPERTY = '__json_buf'; +function tracksToolInput(content) { + return content.type === 'tool_use' || content.type === 'server_tool_use' || content.type === 'mcp_tool_use'; +} +class BetaMessageStream { + constructor(params, opts) { + _BetaMessageStream_instances.add(this); + this.messages = []; + this.receivedMessages = []; + _BetaMessageStream_currentMessageSnapshot.set(this, void 0); + _BetaMessageStream_params.set(this, null); + this.controller = new AbortController(); + _BetaMessageStream_connectedPromise.set(this, void 0); + _BetaMessageStream_resolveConnectedPromise.set(this, () => { }); + _BetaMessageStream_rejectConnectedPromise.set(this, () => { }); + _BetaMessageStream_endPromise.set(this, void 0); + _BetaMessageStream_resolveEndPromise.set(this, () => { }); + _BetaMessageStream_rejectEndPromise.set(this, () => { }); + _BetaMessageStream_listeners.set(this, {}); + _BetaMessageStream_ended.set(this, false); + _BetaMessageStream_errored.set(this, false); + _BetaMessageStream_aborted.set(this, false); + _BetaMessageStream_catchingPromiseCreated.set(this, false); + _BetaMessageStream_response.set(this, void 0); + _BetaMessageStream_request_id.set(this, void 0); + _BetaMessageStream_logger.set(this, void 0); + _BetaMessageStream_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); + if (isAbortError(error)) { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof error_AnthropicError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const anthropicError = new error_AnthropicError(error.message); + // @ts-ignore + anthropicError.cause = error; + return this._emit('error', anthropicError); + } + return this._emit('error', new error_AnthropicError(String(error))); + }); + __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => { }); + __classPrivateFieldSet(this, _BetaMessageStream_params, params, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_logger, opts?.logger ?? console, "f"); + } + get response() { + return __classPrivateFieldGet(this, _BetaMessageStream_response, "f"); + } + get request_id() { + return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f"); + } + /** + * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, + * returned vie the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * This is the same as the `APIPromise.withResponse()` method. + * + * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` + * as no `Response` is available. + */ + async withResponse() { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f"); + if (!response) { + throw new Error('Could not resolve a `Response` object'); + } + return { + data: this, + response, + request_id: response.headers.get('request-id'), + }; + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new BetaMessageStream(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createMessage(messages, params, options, { logger } = {}) { + const runner = new BetaMessageStream(params, { logger }); + for (const message of params.messages) { + runner._addMessageParam(message); + } + __classPrivateFieldSet(runner, _BetaMessageStream_params, { ...params, stream: true }, "f"); + runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); + return runner; + } + _run(executor) { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f")); + } + _addMessageParam(message) { + this.messages.push(message); + } + _addMessage(message, emit = true) { + this.receivedMessages.push(message); + if (emit) { + this._emit('message', message); + } + } + async _createMessage(messages, params, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); + } + try { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + const { response, data: stream } = await messages + .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) + .withResponse(); + this._connected(response); + for await (const event of stream) { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } + } + } + _connected(response) { + if (this.ended) + return; + __classPrivateFieldSet(this, _BetaMessageStream_response, response, "f"); + __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get('request-id'), "f"); + __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response); + this._emit('connect'); + } + get ended() { + return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this MessageStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this MessageStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this MessageStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f"); + } + get currentMessage() { + return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + } + /** + * @returns a promise that resolves with the the final assistant Message response, + * or rejects if an error occurred or the stream ended prematurely without producing a Message. + * If structured outputs were used, this will be a ParsedMessage with a `parsed` field. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the the final assistant Message's text response, concatenated + * together if there are more than one text blocks. + * Rejects if an error occurred or the stream ended prematurely without producing a Message. + */ + async finalText() { + await this.done(); + return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this); + } + _emit(event, ...args) { + // make sure we don't emit any MessageStreamEvents after end + if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f")) + return; + if (event === 'end') { + __classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f"); + __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.final...() + // - etc. + Promise.reject(error); + } + __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + _emitFinal() { + const finalMessage = this.receivedMessages.at(-1); + if (finalMessage) { + this._emit('finalMessage', __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this)); + } + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); + } + try { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); + this._connected(null); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); + } + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } + } + } + [(_BetaMessageStream_currentMessageSnapshot = new WeakMap(), _BetaMessageStream_params = new WeakMap(), _BetaMessageStream_connectedPromise = new WeakMap(), _BetaMessageStream_resolveConnectedPromise = new WeakMap(), _BetaMessageStream_rejectConnectedPromise = new WeakMap(), _BetaMessageStream_endPromise = new WeakMap(), _BetaMessageStream_resolveEndPromise = new WeakMap(), _BetaMessageStream_rejectEndPromise = new WeakMap(), _BetaMessageStream_listeners = new WeakMap(), _BetaMessageStream_ended = new WeakMap(), _BetaMessageStream_errored = new WeakMap(), _BetaMessageStream_aborted = new WeakMap(), _BetaMessageStream_catchingPromiseCreated = new WeakMap(), _BetaMessageStream_response = new WeakMap(), _BetaMessageStream_request_id = new WeakMap(), _BetaMessageStream_logger = new WeakMap(), _BetaMessageStream_handleError = new WeakMap(), _BetaMessageStream_instances = new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() { + if (this.receivedMessages.length === 0) { + throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); + } + return this.receivedMessages.at(-1); + }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText() { + if (this.receivedMessages.length === 0) { + throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); + } + const textBlocks = this.receivedMessages + .at(-1) + .content.filter((block) => block.type === 'text') + .map((block) => block.text); + if (textBlocks.length === 0) { + throw new error_AnthropicError('stream ended without producing a content block with type=text'); + } + return textBlocks.join(' '); + }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest() { + if (this.ended) + return; + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); + }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent(event) { + if (this.ended) + return; + const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event); + this._emit('streamEvent', event, messageSnapshot); + switch (event.type) { + case 'content_block_delta': { + const content = messageSnapshot.content.at(-1); + switch (event.delta.type) { + case 'text_delta': { + if (content.type === 'text') { + this._emit('text', event.delta.text, content.text || ''); + } + break; + } + case 'citations_delta': { + if (content.type === 'text') { + this._emit('citation', event.delta.citation, content.citations ?? []); + } + break; + } + case 'input_json_delta': { + if (tracksToolInput(content) && content.input) { + this._emit('inputJson', event.delta.partial_json, content.input); + } + break; + } + case 'thinking_delta': { + if (content.type === 'thinking') { + this._emit('thinking', event.delta.thinking, content.thinking); + } + break; + } + case 'signature_delta': { + if (content.type === 'thinking') { + this._emit('signature', content.signature); + } + break; + } + default: + checkNever(event.delta); + } + break; + } + case 'message_stop': { + this._addMessageParam(messageSnapshot); + this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }), true); + break; + } + case 'content_block_stop': { + this._emit('contentBlock', messageSnapshot.content.at(-1)); + break; + } + case 'message_start': { + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f"); + break; + } + case 'content_block_start': + case 'message_delta': + break; + } + }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest() { + if (this.ended) { + throw new error_AnthropicError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (!snapshot) { + throw new error_AnthropicError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); + return maybeParseBetaMessage(snapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }); + }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage(event) { + let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); + if (event.type === 'message_start') { + if (snapshot) { + throw new error_AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + } + return event.message; + } + if (!snapshot) { + throw new error_AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + } + switch (event.type) { + case 'message_stop': + return snapshot; + case 'message_delta': + snapshot.container = event.delta.container; + snapshot.stop_reason = event.delta.stop_reason; + snapshot.stop_sequence = event.delta.stop_sequence; + snapshot.usage.output_tokens = event.usage.output_tokens; + snapshot.context_management = event.context_management; + if (event.usage.input_tokens != null) { + snapshot.usage.input_tokens = event.usage.input_tokens; + } + if (event.usage.cache_creation_input_tokens != null) { + snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; + } + if (event.usage.cache_read_input_tokens != null) { + snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; + } + if (event.usage.server_tool_use != null) { + snapshot.usage.server_tool_use = event.usage.server_tool_use; + } + return snapshot; + case 'content_block_start': + snapshot.content.push(event.content_block); + return snapshot; + case 'content_block_delta': { + const snapshotContent = snapshot.content.at(event.index); + switch (event.delta.type) { + case 'text_delta': { + if (snapshotContent?.type === 'text') { + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || '') + event.delta.text, + }; + } + break; + } + case 'citations_delta': { + if (snapshotContent?.type === 'text') { + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...(snapshotContent.citations ?? []), event.delta.citation], + }; + } + break; + } + case 'input_json_delta': { + if (snapshotContent && tracksToolInput(snapshotContent)) { + // we need to keep track of the raw JSON string as well so that we can + // re-parse it for each delta, for now we just store it as an untyped + // non-enumerable property on the snapshot + let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || ''; + jsonBuf += event.delta.partial_json; + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, JSON_BUF_PROPERTY, { + value: jsonBuf, + enumerable: false, + writable: true, + }); + if (jsonBuf) { + try { + newContent.input = partialParse(jsonBuf); + } + catch (err) { + const error = new error_AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); + __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error); + } + } + snapshot.content[event.index] = newContent; + } + break; + } + case 'thinking_delta': { + if (snapshotContent?.type === 'thinking') { + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking, + }; + } + break; + } + case 'signature_delta': { + if (snapshotContent?.type === 'thinking') { + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature, + }; + } + break; + } + default: + checkNever(event.delta); + } + return snapshot; + } + case 'content_block_stop': + return snapshot; + } + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('streamEvent', (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } + else { + pushQueue.push(event); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + toReadableStream() { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } +} +// used to ensure exhaustive case matching without throwing a runtime error +function checkNever(x) { } +//# sourceMappingURL=BetaMessageStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs +const DEFAULT_TOKEN_THRESHOLD = 100000; +const DEFAULT_SUMMARY_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include: +1. Task Overview +The user's core request and success criteria +Any clarifications or constraints they specified +2. Current State +What has been completed so far +Files created, modified, or analyzed (with paths if relevant) +Key outputs or artifacts produced +3. Important Discoveries +Technical constraints or requirements uncovered +Decisions made and their rationale +Errors encountered and how they were resolved +What approaches were tried that didn't work (and why) +4. Next Steps +Specific actions needed to complete the task +Any blockers or open questions to resolve +Priority order if multiple steps remain +5. Context to Preserve +User preferences or style requirements +Domain-specific details that aren't obvious +Any promises made to the user +Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task. +Wrap your summary in tags.`; +//# sourceMappingURL=CompactionControl.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs +var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_checkAndCompact, _BetaToolRunner_generateToolResponse; + + + + +/** + * Just Promise.withResolvers(), which is not available in all environments. + */ +function promiseWithResolvers() { + let resolve; + let reject; + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { promise, resolve: resolve, reject: reject }; +} +/** + * A ToolRunner handles the automatic conversation loop between the assistant and tools. + * + * A ToolRunner is an async iterable that yields either BetaMessage or BetaMessageStream objects + * depending on the streaming configuration. + */ +class BetaToolRunner { + constructor(client, params, options) { + _BetaToolRunner_instances.add(this); + this.client = client; + /** Whether the async iterator has been consumed */ + _BetaToolRunner_consumed.set(this, false); + /** Whether parameters have been mutated since the last API call */ + _BetaToolRunner_mutated.set(this, false); + /** Current state containing the request parameters */ + _BetaToolRunner_state.set(this, void 0); + _BetaToolRunner_options.set(this, void 0); + /** Promise for the last message received from the assistant */ + _BetaToolRunner_message.set(this, void 0); + /** Cached tool response to avoid redundant executions */ + _BetaToolRunner_toolResponse.set(this, void 0); + /** Promise resolvers for waiting on completion */ + _BetaToolRunner_completion.set(this, void 0); + /** Number of iterations (API requests) made so far */ + _BetaToolRunner_iterationCount.set(this, 0); + __classPrivateFieldSet(this, _BetaToolRunner_state, { + params: { + // You can't clone the entire params since there are functions as handlers. + // You also don't really need to clone params.messages, but it probably will prevent a foot gun + // somewhere. + ...params, + messages: structuredClone(params.messages), + }, + }, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_options, { + ...options, + headers: buildHeaders([{ 'x-stainless-helper': 'BetaToolRunner' }, options?.headers]), + }, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); + } + async *[(_BetaToolRunner_consumed = new WeakMap(), _BetaToolRunner_mutated = new WeakMap(), _BetaToolRunner_state = new WeakMap(), _BetaToolRunner_options = new WeakMap(), _BetaToolRunner_message = new WeakMap(), _BetaToolRunner_toolResponse = new WeakMap(), _BetaToolRunner_completion = new WeakMap(), _BetaToolRunner_iterationCount = new WeakMap(), _BetaToolRunner_instances = new WeakSet(), _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact() { + const compactionControl = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.compactionControl; + if (!compactionControl || !compactionControl.enabled) { + return false; + } + let tokensUsed = 0; + if (__classPrivateFieldGet(this, _BetaToolRunner_message, "f") !== undefined) { + try { + const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + const totalInputTokens = message.usage.input_tokens + + (message.usage.cache_creation_input_tokens ?? 0) + + (message.usage.cache_read_input_tokens ?? 0); + tokensUsed = totalInputTokens + message.usage.output_tokens; + } + catch { + // If we can't get the message, skip compaction + return false; + } + } + const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD; + if (tokensUsed < threshold) { + return false; + } + const model = compactionControl.model ?? __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.model; + const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT; + const messages = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages; + if (messages[messages.length - 1].role === 'assistant') { + // Remove tool_use blocks from the last message to avoid 400 error + // (tool_use requires tool_result, which we don't have yet) + const lastMessage = messages[messages.length - 1]; + if (Array.isArray(lastMessage.content)) { + const nonToolBlocks = lastMessage.content.filter((block) => block.type !== 'tool_use'); + if (nonToolBlocks.length === 0) { + // If all blocks were tool_use, just remove the message entirely + messages.pop(); + } + else { + lastMessage.content = nonToolBlocks; + } + } + } + const response = await this.client.beta.messages.create({ + model, + messages: [ + ...messages, + { + role: 'user', + content: [ + { + type: 'text', + text: summaryPrompt, + }, + ], + }, + ], + max_tokens: __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens, + }, { + headers: { 'x-stainless-helper': 'compaction' }, + }); + if (response.content[0]?.type !== 'text') { + throw new error_AnthropicError('Expected text response for compaction'); + } + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages = [ + { + role: 'user', + content: response.content, + }, + ]; + return true; + }, Symbol.asyncIterator)]() { + var _a; + if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { + throw new error_AnthropicError('Cannot iterate over a consumed stream'); + } + __classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); + try { + while (true) { + let stream; + try { + if (__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations && + __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) { + break; + } + __classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); + __classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a++, _a), "f"); + __classPrivateFieldSet(this, _BetaToolRunner_message, undefined, "f"); + const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; + if (params.stream) { + stream = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")); + __classPrivateFieldSet(this, _BetaToolRunner_message, stream.finalMessage(), "f"); + // Make sure that this promise doesn't throw before we get the option to do something about it. + // Error will be caught when we call await this.#message ultimately + __classPrivateFieldGet(this, _BetaToolRunner_message, "f").catch(() => { }); + yield stream; + } + else { + __classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); + yield __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + } + const isCompacted = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this); + if (!isCompacted) { + if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { + const { role, content } = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ role, content }); + } + const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1)); + if (toolMessage) { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage); + } + else if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { + break; + } + } + } + finally { + if (stream) { + stream.abort(); + } + } + } + if (!__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) { + throw new error_AnthropicError('ToolRunner concluded without a message from the server'); + } + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")); + } + catch (error) { + __classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f"); + // Silence unhandled promise errors + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => { }); + __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error); + __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); + throw error; + } + } + setMessagesParams(paramsOrMutator) { + if (typeof paramsOrMutator === 'function') { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params); + } + else { + __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator; + } + __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); + // Invalidate cached tool response since parameters changed + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); + } + /** + * Get the tool response for the last message from the assistant. + * Avoids redundant tool executions by caching results. + * + * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed + * + * @example + * const toolResponse = await runner.generateToolResponse(); + * if (toolResponse) { + * console.log('Tool results:', toolResponse.content); + * } + */ + async generateToolResponse() { + const message = (await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")) ?? this.params.messages.at(-1); + if (!message) { + return null; + } + return __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message); + } + /** + * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and + * will wait for an instance to start and go to completion. + * + * @returns A promise that resolves to the final BetaMessage when the iterator completes + * + * @example + * // Start consuming the iterator + * for await (const message of runner) { + * console.log('Message:', message.content); + * } + * + * // Meanwhile, wait for completion from another part of the code + * const finalMessage = await runner.done(); + * console.log('Final response:', finalMessage.content); + */ + done() { + return __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise; + } + /** + * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream: + * * If the iterator has not been consumed, consume the entire iterator and return the final message from the + * assistant. + * * If the iterator has been consumed, waits for it to complete and returns the final message. + * + * @returns A promise that resolves to the final BetaMessage from the conversation + * @throws {AnthropicError} If no messages were processed during the conversation + * + * @example + * const finalMessage = await runner.runUntilDone(); + * console.log('Final response:', finalMessage.content); + */ + async runUntilDone() { + // If not yet consumed, start consuming and wait for completion + if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { + for await (const _ of this) { + // Iterator naturally populates this.#message + } + } + // If consumed but not completed, wait for completion + return this.done(); + } + /** + * Get the current parameters being used by the ToolRunner. + * + * @returns A readonly view of the current ToolRunnerParams + * + * @example + * const currentParams = runner.params; + * console.log('Current model:', currentParams.model); + * console.log('Message count:', currentParams.messages.length); + */ + get params() { + return __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; + } + /** + * Add one or more messages to the conversation history. + * + * @param messages - One or more BetaMessageParam objects to add to the conversation + * + * @example + * runner.pushMessages( + * { role: 'user', content: 'Also, what about the weather in NYC?' } + * ); + * + * @example + * // Adding multiple messages + * runner.pushMessages( + * { role: 'user', content: 'What about NYC?' }, + * { role: 'user', content: 'And Boston?' } + * ); + */ + pushMessages(...messages) { + this.setMessagesParams((params) => ({ + ...params, + messages: [...params.messages, ...messages], + })); + } + /** + * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone() + * This allows using `await runner` instead of `await runner.runUntilDone()` + */ + then(onfulfilled, onrejected) { + return this.runUntilDone().then(onfulfilled, onrejected); + } +} +_BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse(lastMessage) { + if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== undefined) { + return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); + } + __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage), "f"); + return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); +}; +async function generateToolResponse(params, lastMessage = params.messages.at(-1)) { + // Only process if the last message is from the assistant and has tool use blocks + if (!lastMessage || + lastMessage.role !== 'assistant' || + !lastMessage.content || + typeof lastMessage.content === 'string') { + return null; + } + const toolUseBlocks = lastMessage.content.filter((content) => content.type === 'tool_use'); + if (toolUseBlocks.length === 0) { + return null; + } + const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => { + const tool = params.tools.find((t) => ('name' in t ? t.name : t.mcp_server_name) === toolUse.name); + if (!tool || !('run' in tool)) { + return { + type: 'tool_result', + tool_use_id: toolUse.id, + content: `Error: Tool '${toolUse.name}' not found`, + is_error: true, + }; + } + try { + let input = toolUse.input; + if ('parse' in tool && tool.parse) { + input = tool.parse(input); + } + const result = await tool.run(input); + return { + type: 'tool_result', + tool_use_id: toolUse.id, + content: result, + }; + } + catch (error) { + return { + type: 'tool_result', + tool_use_id: toolUse.id, + content: `Error: ${error instanceof Error ? error.message : String(error)}`, + is_error: true, + }; + } + })); + return { + role: 'user', + content: toolResults, + }; +} +//# sourceMappingURL=BetaToolRunner.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs + + + +class JSONLDecoder { + constructor(iterator, controller) { + this.iterator = iterator; + this.controller = controller; + } + async *decoder() { + const lineDecoder = new LineDecoder(); + for await (const chunk of this.iterator) { + for (const line of lineDecoder.decode(chunk)) { + yield JSON.parse(line); + } + } + for (const line of lineDecoder.flush()) { + yield JSON.parse(line); + } + } + [Symbol.asyncIterator]() { + return this.decoder(); + } + static fromResponse(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== 'undefined' && + globalThis.navigator.product === 'ReactNative') { + throw new error_AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + } + throw new error_AnthropicError(`Attempted to iterate over a response with no body`); + } + return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller); + } +} +//# sourceMappingURL=jsonl.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +class Batches extends APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-sonnet-4-5-20250929', + * }, + * }, + * ], + * }); + * ``` + */ + create(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/messages/batches?beta=true', { + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + /** + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` + */ + retrieve(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + /** + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const betaMessageBatch of client.beta.messages.batches.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/messages/batches?beta=true', (Page), { + query, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaDeletedMessageBatch = + * await client.beta.messages.batches.delete( + * 'message_batch_id', + * ); + * ``` + */ + delete(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path `/v1/messages/batches/${messageBatchID}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatch = + * await client.beta.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel(messageBatchID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, + options?.headers, + ]), + }); + } + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const betaMessageBatchIndividualResponse = + * await client.beta.messages.batches.results( + * 'message_batch_id', + * ); + * ``` + */ + async results(messageBatchID, params = {}, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new error_AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + } + const { betas } = params ?? {}; + return this._client + .get(batch.results_url, { + ...options, + headers: buildHeaders([ + { + 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(), + Accept: 'application/binary', + }, + options?.headers, + ]), + stream: true, + __binaryResponse: true, + }) + ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); + } +} +//# sourceMappingURL=batches.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + +const DEPRECATED_MODELS = { + 'claude-1.3': 'November 6th, 2024', + 'claude-1.3-100k': 'November 6th, 2024', + 'claude-instant-1.1': 'November 6th, 2024', + 'claude-instant-1.1-100k': 'November 6th, 2024', + 'claude-instant-1.2': 'November 6th, 2024', + 'claude-3-sonnet-20240229': 'July 21st, 2025', + 'claude-3-opus-20240229': 'January 5th, 2026', + 'claude-2.1': 'July 21st, 2025', + 'claude-2.0': 'July 21st, 2025', + 'claude-3-7-sonnet-latest': 'February 19th, 2026', + 'claude-3-7-sonnet-20250219': 'February 19th, 2026', +}; +class Messages extends APIResource { + constructor() { + super(...arguments); + this.batches = new Batches(this._client); + } + create(params, options) { + const { betas, ...body } = params; + if (body.model in DEPRECATED_MODELS) { + console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + return this._client.post('/v1/messages?beta=true', { + body, + timeout: timeout ?? 600000, + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + stream: params.stream ?? false, + }); + } + /** + * Send a structured list of input messages with text and/or image content, along with an expected `output_format` and + * the response will be automatically parsed and available in the `parsed_output` property of the message. + * + * @example + * ```ts + * const message = await client.beta.messages.parse({ + * model: 'claude-3-5-sonnet-20241022', + * max_tokens: 1024, + * messages: [{ role: 'user', content: 'What is 2+2?' }], + * output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'), + * }); + * + * console.log(message.parsed_output?.answer); // 4 + * ``` + */ + parse(params, options) { + options = { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(params.betas ?? []), 'structured-outputs-2025-11-13'].toString() }, + options?.headers, + ]), + }; + return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console })); + } + /** + * Create a Message stream + */ + stream(body, options) { + return BetaMessageStream.createMessage(this, body, options); + } + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, + * including tools, images, and documents, without creating it. + * + * Learn more about token counting in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) + * + * @example + * ```ts + * const betaMessageTokensCount = + * await client.beta.messages.countTokens({ + * messages: [{ content: 'string', role: 'user' }], + * model: 'claude-opus-4-5-20251101', + * }); + * ``` + */ + countTokens(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/messages/count_tokens?beta=true', { + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() }, + options?.headers, + ]), + }); + } + toolRunner(body, options) { + return new BetaToolRunner(this._client, body, options); + } +} + +Messages.Batches = Batches; +Messages.BetaToolRunner = BetaToolRunner; +//# sourceMappingURL=messages.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class Versions extends APIResource { + /** + * Create Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.create( + * 'skill_id', + * ); + * ``` + */ + create(skillID, params = {}, options) { + const { betas, ...body } = params ?? {}; + return this._client.post(path `/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }, this._client)); + } + /** + * Get Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.retrieve( + * 'version', + * { skill_id: 'skill_id' }, + * ); + * ``` + */ + retrieve(version, params, options) { + const { skill_id, betas } = params; + return this._client.get(path `/v1/skills/${skill_id}/versions/${version}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } + /** + * List Skill Versions + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const versionListResponse of client.beta.skills.versions.list( + * 'skill_id', + * )) { + * // ... + * } + * ``` + */ + list(skillID, params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList(path `/v1/skills/${skillID}/versions?beta=true`, (PageCursor), { + query, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } + /** + * Delete Skill Version + * + * @example + * ```ts + * const version = await client.beta.skills.versions.delete( + * 'version', + * { skill_id: 'skill_id' }, + * ); + * ``` + */ + delete(version, params, options) { + const { skill_id, betas } = params; + return this._client.delete(path `/v1/skills/${skill_id}/versions/${version}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } +} +//# sourceMappingURL=versions.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +class Skills extends APIResource { + constructor() { + super(...arguments); + this.versions = new Versions(this._client); + } + /** + * Create Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.create(); + * ``` + */ + create(params = {}, options) { + const { betas, ...body } = params ?? {}; + return this._client.post('/v1/skills?beta=true', multipartFormRequestOptions({ + body, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }, this._client)); + } + /** + * Get Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.retrieve('skill_id'); + * ``` + */ + retrieve(skillID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/skills/${skillID}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } + /** + * List Skills + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const skillListResponse of client.beta.skills.list()) { + * // ... + * } + * ``` + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/skills?beta=true', (PageCursor), { + query, + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } + /** + * Delete Skill + * + * @example + * ```ts + * const skill = await client.beta.skills.delete('skill_id'); + * ``` + */ + delete(skillID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.delete(path `/v1/skills/${skillID}?beta=true`, { + ...options, + headers: buildHeaders([ + { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, + options?.headers, + ]), + }); + } +} +Skills.Versions = Versions; +//# sourceMappingURL=skills.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + + +class Beta extends APIResource { + constructor() { + super(...arguments); + this.models = new Models(this._client); + this.messages = new Messages(this._client); + this.files = new Files(this._client); + this.skills = new Skills(this._client); + } +} +Beta.Models = Models; +Beta.Messages = Messages; +Beta.Files = Files; +Beta.Skills = Skills; +//# sourceMappingURL=beta.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/completions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Completions extends APIResource { + create(params, options) { + const { betas, ...body } = params; + return this._client.post('/v1/complete', { + body, + timeout: this._client._options.timeout ?? 600000, + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + stream: params.stream ?? false, + }); + } +} +//# sourceMappingURL=completions.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs +var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage; + + + + + +const MessageStream_JSON_BUF_PROPERTY = '__json_buf'; +function MessageStream_tracksToolInput(content) { + return content.type === 'tool_use' || content.type === 'server_tool_use'; +} +class MessageStream { + constructor() { + _MessageStream_instances.add(this); + this.messages = []; + this.receivedMessages = []; + _MessageStream_currentMessageSnapshot.set(this, void 0); + this.controller = new AbortController(); + _MessageStream_connectedPromise.set(this, void 0); + _MessageStream_resolveConnectedPromise.set(this, () => { }); + _MessageStream_rejectConnectedPromise.set(this, () => { }); + _MessageStream_endPromise.set(this, void 0); + _MessageStream_resolveEndPromise.set(this, () => { }); + _MessageStream_rejectEndPromise.set(this, () => { }); + _MessageStream_listeners.set(this, {}); + _MessageStream_ended.set(this, false); + _MessageStream_errored.set(this, false); + _MessageStream_aborted.set(this, false); + _MessageStream_catchingPromiseCreated.set(this, false); + _MessageStream_response.set(this, void 0); + _MessageStream_request_id.set(this, void 0); + _MessageStream_handleError.set(this, (error) => { + __classPrivateFieldSet(this, _MessageStream_errored, true, "f"); + if (isAbortError(error)) { + error = new APIUserAbortError(); + } + if (error instanceof APIUserAbortError) { + __classPrivateFieldSet(this, _MessageStream_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof error_AnthropicError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const anthropicError = new error_AnthropicError(error.message); + // @ts-ignore + anthropicError.cause = error; + return this._emit('error', anthropicError); + } + return this._emit('error', new error_AnthropicError(String(error))); + }); + __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f"); + __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f"); + }), "f"); + __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f"); + __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => { }); + __classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => { }); + } + get response() { + return __classPrivateFieldGet(this, _MessageStream_response, "f"); + } + get request_id() { + return __classPrivateFieldGet(this, _MessageStream_request_id, "f"); + } + /** + * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, + * returned vie the `request-id` header which is useful for debugging requests and resporting + * issues to Anthropic. + * + * This is the same as the `APIPromise.withResponse()` method. + * + * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` + * as no `Response` is available. + */ + async withResponse() { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f"); + if (!response) { + throw new Error('Could not resolve a `Response` object'); + } + return { + data: this, + response, + request_id: response.headers.get('request-id'), + }; + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new MessageStream(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createMessage(messages, params, options) { + const runner = new MessageStream(); + for (const message of params.messages) { + runner._addMessageParam(message); + } + runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); + return runner; + } + _run(executor) { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, __classPrivateFieldGet(this, _MessageStream_handleError, "f")); + } + _addMessageParam(message) { + this.messages.push(message); + } + _addMessage(message, emit = true) { + this.receivedMessages.push(message); + if (emit) { + this._emit('message', message); + } + } + async _createMessage(messages, params, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); + } + try { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + const { response, data: stream } = await messages + .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) + .withResponse(); + this._connected(response); + for await (const event of stream) { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); + } + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } + } + } + _connected(response) { + if (this.ended) + return; + __classPrivateFieldSet(this, _MessageStream_response, response, "f"); + __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get('request-id'), "f"); + __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response); + this._emit('connect'); + } + get ended() { + return __classPrivateFieldGet(this, _MessageStream_ended, "f"); + } + get errored() { + return __classPrivateFieldGet(this, _MessageStream_errored, "f"); + } + get aborted() { + return __classPrivateFieldGet(this, _MessageStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this MessageStream, so that calls can be chained + */ + on(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this MessageStream, so that calls can be chained + */ + off(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this MessageStream, so that calls can be chained + */ + once(event, listener) { + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); + }); + } + async done() { + __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); + await __classPrivateFieldGet(this, _MessageStream_endPromise, "f"); + } + get currentMessage() { + return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + } + /** + * @returns a promise that resolves with the the final assistant Message response, + * or rejects if an error occurred or the stream ended prematurely without producing a Message. + */ + async finalMessage() { + await this.done(); + return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the the final assistant Message's text response, concatenated + * together if there are more than one text blocks. + * Rejects if an error occurred or the stream ended prematurely without producing a Message. + */ + async finalText() { + await this.done(); + return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this); + } + _emit(event, ...args) { + // make sure we don't emit any MessageStreamEvents after end + if (__classPrivateFieldGet(this, _MessageStream_ended, "f")) + return; + if (event === 'end') { + __classPrivateFieldSet(this, _MessageStream_ended, true, "f"); + __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this); + } + const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; + if (listeners) { + __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.final...() + // - etc. + Promise.reject(error); + } + __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); + __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + _emitFinal() { + const finalMessage = this.receivedMessages.at(-1); + if (finalMessage) { + this._emit('finalMessage', __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this)); + } + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + let abortHandler; + if (signal) { + if (signal.aborted) + this.controller.abort(); + abortHandler = this.controller.abort.bind(this.controller); + signal.addEventListener('abort', abortHandler); + } + try { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); + this._connected(null); + const stream = Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new APIUserAbortError(); + } + __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); + } + finally { + if (signal && abortHandler) { + signal.removeEventListener('abort', abortHandler); + } + } + } + [(_MessageStream_currentMessageSnapshot = new WeakMap(), _MessageStream_connectedPromise = new WeakMap(), _MessageStream_resolveConnectedPromise = new WeakMap(), _MessageStream_rejectConnectedPromise = new WeakMap(), _MessageStream_endPromise = new WeakMap(), _MessageStream_resolveEndPromise = new WeakMap(), _MessageStream_rejectEndPromise = new WeakMap(), _MessageStream_listeners = new WeakMap(), _MessageStream_ended = new WeakMap(), _MessageStream_errored = new WeakMap(), _MessageStream_aborted = new WeakMap(), _MessageStream_catchingPromiseCreated = new WeakMap(), _MessageStream_response = new WeakMap(), _MessageStream_request_id = new WeakMap(), _MessageStream_handleError = new WeakMap(), _MessageStream_instances = new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() { + if (this.receivedMessages.length === 0) { + throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); + } + return this.receivedMessages.at(-1); + }, _MessageStream_getFinalText = function _MessageStream_getFinalText() { + if (this.receivedMessages.length === 0) { + throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); + } + const textBlocks = this.receivedMessages + .at(-1) + .content.filter((block) => block.type === 'text') + .map((block) => block.text); + if (textBlocks.length === 0) { + throw new error_AnthropicError('stream ended without producing a content block with type=text'); + } + return textBlocks.join(' '); + }, _MessageStream_beginRequest = function _MessageStream_beginRequest() { + if (this.ended) + return; + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); + }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) { + if (this.ended) + return; + const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event); + this._emit('streamEvent', event, messageSnapshot); + switch (event.type) { + case 'content_block_delta': { + const content = messageSnapshot.content.at(-1); + switch (event.delta.type) { + case 'text_delta': { + if (content.type === 'text') { + this._emit('text', event.delta.text, content.text || ''); + } + break; + } + case 'citations_delta': { + if (content.type === 'text') { + this._emit('citation', event.delta.citation, content.citations ?? []); + } + break; + } + case 'input_json_delta': { + if (MessageStream_tracksToolInput(content) && content.input) { + this._emit('inputJson', event.delta.partial_json, content.input); + } + break; + } + case 'thinking_delta': { + if (content.type === 'thinking') { + this._emit('thinking', event.delta.thinking, content.thinking); + } + break; + } + case 'signature_delta': { + if (content.type === 'thinking') { + this._emit('signature', content.signature); + } + break; + } + default: + MessageStream_checkNever(event.delta); + } + break; + } + case 'message_stop': { + this._addMessageParam(messageSnapshot); + this._addMessage(messageSnapshot, true); + break; + } + case 'content_block_stop': { + this._emit('contentBlock', messageSnapshot.content.at(-1)); + break; + } + case 'message_start': { + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f"); + break; + } + case 'content_block_start': + case 'message_delta': + break; + } + }, _MessageStream_endRequest = function _MessageStream_endRequest() { + if (this.ended) { + throw new error_AnthropicError(`stream has ended, this shouldn't happen`); + } + const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + if (!snapshot) { + throw new error_AnthropicError(`request ended without sending any chunks`); + } + __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); + return snapshot; + }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) { + let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); + if (event.type === 'message_start') { + if (snapshot) { + throw new error_AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); + } + return event.message; + } + if (!snapshot) { + throw new error_AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); + } + switch (event.type) { + case 'message_stop': + return snapshot; + case 'message_delta': + snapshot.stop_reason = event.delta.stop_reason; + snapshot.stop_sequence = event.delta.stop_sequence; + snapshot.usage.output_tokens = event.usage.output_tokens; + // Update other usage fields if they exist in the event + if (event.usage.input_tokens != null) { + snapshot.usage.input_tokens = event.usage.input_tokens; + } + if (event.usage.cache_creation_input_tokens != null) { + snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; + } + if (event.usage.cache_read_input_tokens != null) { + snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; + } + if (event.usage.server_tool_use != null) { + snapshot.usage.server_tool_use = event.usage.server_tool_use; + } + return snapshot; + case 'content_block_start': + snapshot.content.push({ ...event.content_block }); + return snapshot; + case 'content_block_delta': { + const snapshotContent = snapshot.content.at(event.index); + switch (event.delta.type) { + case 'text_delta': { + if (snapshotContent?.type === 'text') { + snapshot.content[event.index] = { + ...snapshotContent, + text: (snapshotContent.text || '') + event.delta.text, + }; + } + break; + } + case 'citations_delta': { + if (snapshotContent?.type === 'text') { + snapshot.content[event.index] = { + ...snapshotContent, + citations: [...(snapshotContent.citations ?? []), event.delta.citation], + }; + } + break; + } + case 'input_json_delta': { + if (snapshotContent && MessageStream_tracksToolInput(snapshotContent)) { + // we need to keep track of the raw JSON string as well so that we can + // re-parse it for each delta, for now we just store it as an untyped + // non-enumerable property on the snapshot + let jsonBuf = snapshotContent[MessageStream_JSON_BUF_PROPERTY] || ''; + jsonBuf += event.delta.partial_json; + const newContent = { ...snapshotContent }; + Object.defineProperty(newContent, MessageStream_JSON_BUF_PROPERTY, { + value: jsonBuf, + enumerable: false, + writable: true, + }); + if (jsonBuf) { + newContent.input = partialParse(jsonBuf); + } + snapshot.content[event.index] = newContent; + } + break; + } + case 'thinking_delta': { + if (snapshotContent?.type === 'thinking') { + snapshot.content[event.index] = { + ...snapshotContent, + thinking: snapshotContent.thinking + event.delta.thinking, + }; + } + break; + } + case 'signature_delta': { + if (snapshotContent?.type === 'thinking') { + snapshot.content[event.index] = { + ...snapshotContent, + signature: event.delta.signature, + }; + } + break; + } + default: + MessageStream_checkNever(event.delta); + } + return snapshot; + } + case 'content_block_stop': + return snapshot; + } + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('streamEvent', (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } + else { + pushQueue.push(event); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + toReadableStream() { + const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } +} +// used to ensure exhaustive case matching without throwing a runtime error +function MessageStream_checkNever(x) { } +//# sourceMappingURL=MessageStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +class batches_Batches extends APIResource { + /** + * Send a batch of Message creation requests. + * + * The Message Batches API can be used to process multiple Messages API requests at + * once. Once a Message Batch is created, it begins processing immediately. Batches + * can take up to 24 hours to complete. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.create({ + * requests: [ + * { + * custom_id: 'my-custom-id-1', + * params: { + * max_tokens: 1024, + * messages: [ + * { content: 'Hello, world', role: 'user' }, + * ], + * model: 'claude-sonnet-4-5-20250929', + * }, + * }, + * ], + * }); + * ``` + */ + create(body, options) { + return this._client.post('/v1/messages/batches', { body, ...options }); + } + /** + * This endpoint is idempotent and can be used to poll for Message Batch + * completion. To access the results of a Message Batch, make a request to the + * `results_url` field in the response. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.retrieve( + * 'message_batch_id', + * ); + * ``` + */ + retrieve(messageBatchID, options) { + return this._client.get(path `/v1/messages/batches/${messageBatchID}`, options); + } + /** + * List all Message Batches within a Workspace. Most recently created batches are + * returned first. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const messageBatch of client.messages.batches.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/v1/messages/batches', (Page), { query, ...options }); + } + /** + * Delete a Message Batch. + * + * Message Batches can only be deleted once they've finished processing. If you'd + * like to delete an in-progress batch, you must first cancel it. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const deletedMessageBatch = + * await client.messages.batches.delete('message_batch_id'); + * ``` + */ + delete(messageBatchID, options) { + return this._client.delete(path `/v1/messages/batches/${messageBatchID}`, options); + } + /** + * Batches may be canceled any time before processing ends. Once cancellation is + * initiated, the batch enters a `canceling` state, at which time the system may + * complete any in-progress, non-interruptible requests before finalizing + * cancellation. + * + * The number of canceled requests is specified in `request_counts`. To determine + * which requests were canceled, check the individual results within the batch. + * Note that cancellation may not result in any canceled requests if they were + * non-interruptible. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatch = await client.messages.batches.cancel( + * 'message_batch_id', + * ); + * ``` + */ + cancel(messageBatchID, options) { + return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel`, options); + } + /** + * Streams the results of a Message Batch as a `.jsonl` file. + * + * Each line in the file is a JSON object containing the result of a single request + * in the Message Batch. Results are not guaranteed to be in the same order as + * requests. Use the `custom_id` field to match results to requests. + * + * Learn more about the Message Batches API in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) + * + * @example + * ```ts + * const messageBatchIndividualResponse = + * await client.messages.batches.results('message_batch_id'); + * ``` + */ + async results(messageBatchID, options) { + const batch = await this.retrieve(messageBatchID); + if (!batch.results_url) { + throw new error_AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); + } + return this._client + .get(batch.results_url, { + ...options, + headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + stream: true, + __binaryResponse: true, + }) + ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); + } +} +//# sourceMappingURL=batches.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class messages_Messages extends APIResource { + constructor() { + super(...arguments); + this.batches = new batches_Batches(this._client); + } + create(body, options) { + if (body.model in messages_DEPRECATED_MODELS) { + console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${messages_DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); + } + let timeout = this._client._options.timeout; + if (!body.stream && timeout == null) { + const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; + timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); + } + return this._client.post('/v1/messages', { + body, + timeout: timeout ?? 600000, + ...options, + stream: body.stream ?? false, + }); + } + /** + * Create a Message stream + */ + stream(body, options) { + return MessageStream.createMessage(this, body, options); + } + /** + * Count the number of tokens in a Message. + * + * The Token Count API can be used to count the number of tokens in a Message, + * including tools, images, and documents, without creating it. + * + * Learn more about token counting in our + * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) + * + * @example + * ```ts + * const messageTokensCount = + * await client.messages.countTokens({ + * messages: [{ content: 'string', role: 'user' }], + * model: 'claude-opus-4-5-20251101', + * }); + * ``` + */ + countTokens(body, options) { + return this._client.post('/v1/messages/count_tokens', { body, ...options }); + } +} +const messages_DEPRECATED_MODELS = { + 'claude-1.3': 'November 6th, 2024', + 'claude-1.3-100k': 'November 6th, 2024', + 'claude-instant-1.1': 'November 6th, 2024', + 'claude-instant-1.1-100k': 'November 6th, 2024', + 'claude-instant-1.2': 'November 6th, 2024', + 'claude-3-sonnet-20240229': 'July 21st, 2025', + 'claude-3-opus-20240229': 'January 5th, 2026', + 'claude-2.1': 'July 21st, 2025', + 'claude-2.0': 'July 21st, 2025', + 'claude-3-7-sonnet-latest': 'February 19th, 2026', + 'claude-3-7-sonnet-20250219': 'February 19th, 2026', +}; +messages_Messages.Batches = batches_Batches; +//# sourceMappingURL=messages.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/models.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +class models_Models extends APIResource { + /** + * Get a specific model. + * + * The Models API response can be used to determine information about a specific + * model or resolve a model alias to a model ID. + */ + retrieve(modelID, params = {}, options) { + const { betas } = params ?? {}; + return this._client.get(path `/v1/models/${modelID}`, { + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } + /** + * List available models. + * + * The Models API response can be used to determine which models are available for + * use in the API. More recently released models are listed first. + */ + list(params = {}, options) { + const { betas, ...query } = params ?? {}; + return this._client.getAPIList('/v1/models', (Page), { + query, + ...options, + headers: buildHeaders([ + { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, + options?.headers, + ]), + }); + } +} +//# sourceMappingURL=models.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/index.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +const readEnv = (env) => { + if (typeof globalThis.process !== 'undefined') { + return globalThis.process.env?.[env]?.trim() ?? undefined; + } + if (typeof globalThis.Deno !== 'undefined') { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; +//# sourceMappingURL=env.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/client.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _BaseAnthropic_instances, client_a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden; + + + + + + + + + + + + + + + + + + + + + + + +const HUMAN_PROMPT = '\\n\\nHuman:'; +const AI_PROMPT = '\\n\\nAssistant:'; +/** + * Base class for Anthropic API clients. + */ +class BaseAnthropic { + /** + * API Client for interfacing with the Anthropic API. + * + * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null] + * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null] + * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = readEnv('ANTHROPIC_BASE_URL'), apiKey = readEnv('ANTHROPIC_API_KEY') ?? null, authToken = readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) { + _BaseAnthropic_instances.add(this); + _BaseAnthropic_encoder.set(this, void 0); + const options = { + apiKey, + authToken, + ...opts, + baseURL: baseURL || `https://api.anthropic.com`, + }; + if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { + throw new error_AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n"); + } + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? client_a.DEFAULT_TIMEOUT /* 10 minutes */; + this.logger = options.logger ?? console; + const defaultLogLevel = 'warn'; + // Set default logLevel early so that we can log a warning in parseLogLevel. + this.logLevel = defaultLogLevel; + this.logLevel = + parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? + parseLogLevel(readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ?? + defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? getDefaultFetch(); + __classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f"); + this._options = options; + this.apiKey = typeof apiKey === 'string' ? apiKey : null; + this.authToken = authToken; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + authToken: this.authToken, + ...options, + }); + return client; + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }) { + if (values.get('x-api-key') || values.get('authorization')) { + return; + } + if (this.apiKey && values.get('x-api-key')) { + return; + } + if (nulls.has('x-api-key')) { + return; + } + if (this.authToken && values.get('authorization')) { + return; + } + if (nulls.has('authorization')) { + return; + } + throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted'); + } + async authHeaders(opts) { + return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]); + } + async apiKeyAuth(opts) { + if (this.apiKey == null) { + return undefined; + } + return buildHeaders([{ 'X-Api-Key': this.apiKey }]); + } + async bearerAuth(opts) { + if (this.authToken == null) { + return undefined; + } + return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); + } + /** + * Basic re-implementation of `qs.stringify` for primitive types. + */ + stringifyQuery(query) { + return Object.entries(query) + .filter(([_, value]) => typeof value !== 'undefined') + .map(([key, value]) => { + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; + } + if (value === null) { + return `${encodeURIComponent(key)}=`; + } + throw new error_AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); + }) + .join('&'); + } + getUserAgent() { + return `${this.constructor.name}/JS ${VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${uuid_uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return APIError.generate(status, error, message, headers); + } + buildURL(path, query, defaultBaseURL) { + const baseURL = (!__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL; + const url = isAbsoluteURL(path) ? + new URL(path) + : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + if (!isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === 'object' && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + _calculateNonstreamingTimeout(maxTokens) { + const defaultTimeout = 10 * 60; + const expectedTimeout = (60 * 60 * maxTokens) / 128000; + if (expectedTimeout > defaultTimeout) { + throw new error_AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' + + 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details'); + } + return defaultTimeout * 1000; + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { } + get(path, opts) { + return this.methodRequest('get', path, opts); + } + post(path, opts) { + return this.methodRequest('post', path, opts); + } + patch(path, opts) { + return this.methodRequest('patch', path, opts); + } + put(path, opts) { + return this.methodRequest('put', path, opts); + } + delete(path, opts) { + return this.methodRequest('delete', path, opts); + } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => { + return { method, path, ...opts }; + })); + } + request(options, remainingRetries = null) { + return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining, + }); + await this.prepareRequest(req, { url, options }); + /** Not an API request ID, just for correlating local log entries. */ + const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); + const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers, + })); + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new APIUserAbortError(); + } + // detect native connection timeout errors + // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" + // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" + // others do not provide enough information to distinguish timeouts from other connection errors + const isTimeout = isAbortError(response) || + /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); + if (retriesRemaining) { + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); + loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + if (isTimeout) { + throw new APIConnectionTimeoutError(); + } + throw new APIConnectionError({ cause: response }); + } + const specialHeaders = [...response.headers.entries()] + .filter(([name]) => name === 'request-id') + .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value)) + .join(''); + const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + // We don't need the body of this response. + await CancelReadableStream(response.body); + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err) => castToError(err).message); + const errJSON = safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime, + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + loggerFor(this).info(responseInfo); + loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null, undefined); + return new PagePromise(this, request, Page); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + if (signal) + signal.addEventListener('abort', () => controller.abort()); + const timeout = setTimeout(() => controller.abort(), ms); + const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) || + (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); + const fetchOptions = { + signal: controller.signal, + ...(isReadableBody ? { duplex: 'half' } : {}), + method: 'GET', + ...options, + }; + if (method) { + // Custom methods like 'patch' need to be uppercased + // See https://github.com/nodejs/undici/issues/2294 + fetchOptions.method = method.toUpperCase(); + } + try { + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare + return await this.fetch.call(undefined, url, fetchOptions); + } + finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') + return true; + if (shouldRetryHeader === 'false') + return false; + // Retry on request timeouts. + if (response.status === 408) + return true; + // Retry on lock timeouts. + if (response.status === 409) + return true; + // Retry on rate limits. + if (response.status === 429) + return true; + // Retry internal errors. + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. + const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + const retryAfterHeader = responseHeaders?.get('retry-after'); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; + } + else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says, but otherwise calculate a default + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8.0; + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + // Apply some jitter, take up to at most 25 percent of the retry time. + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1000; + } + calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) { + const maxTime = 60 * 60 * 1000; // 60 minutes + const defaultTime = 60 * 10 * 1000; // 10 minutes + const expectedTime = (maxTime * maxTokens) / 128000; + if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) { + throw new error_AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details'); + } + return defaultTime; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path, query, defaultBaseURL } = options; + const url = this.buildURL(path, query, defaultBaseURL); + if ('timeout' in options) + validatePositiveInteger('timeout', options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...(options.signal && { signal: options.signal }), + ...(globalThis.ReadableStream && + body instanceof globalThis.ReadableStream && { duplex: 'half' }), + ...(body && { body }), + ...(this.fetchOptions ?? {}), + ...(options.fetchOptions ?? {}), + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount, }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = buildHeaders([ + idempotencyHeaders, + { + Accept: 'application/json', + 'User-Agent': this.getUserAgent(), + 'X-Stainless-Retry-Count': String(retryCount), + ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), + ...getPlatformHeaders(), + ...(this._options.dangerouslyAllowBrowser ? + { 'anthropic-dangerous-direct-browser-access': 'true' } + : undefined), + 'anthropic-version': '2023-06-01', + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers, + ]); + this.validateHeaders(headers); + return headers.values; + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: undefined, body: undefined }; + } + const headers = buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || + body instanceof ArrayBuffer || + body instanceof DataView || + (typeof body === 'string' && + // Preserve legacy string encoding behavior for now + headers.values.has('content-type')) || + // `Blob` is superset of `File` + (globalThis.Blob && body instanceof globalThis.Blob) || + // `FormData` -> `multipart/form-data` + body instanceof FormData || + // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || + // Send chunked stream (each chunk has own `length`) + (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) { + return { bodyHeaders: undefined, body: body }; + } + else if (typeof body === 'object' && + (Symbol.asyncIterator in body || + (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { + return { bodyHeaders: undefined, body: ReadableStreamFrom(body) }; + } + else { + return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers }); + } + } +} +client_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() { + return this.baseURL !== 'https://api.anthropic.com'; +}; +BaseAnthropic.Anthropic = client_a; +BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT; +BaseAnthropic.AI_PROMPT = AI_PROMPT; +BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes +BaseAnthropic.AnthropicError = error_AnthropicError; +BaseAnthropic.APIError = APIError; +BaseAnthropic.APIConnectionError = APIConnectionError; +BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError; +BaseAnthropic.APIUserAbortError = APIUserAbortError; +BaseAnthropic.NotFoundError = NotFoundError; +BaseAnthropic.ConflictError = ConflictError; +BaseAnthropic.RateLimitError = RateLimitError; +BaseAnthropic.BadRequestError = BadRequestError; +BaseAnthropic.AuthenticationError = AuthenticationError; +BaseAnthropic.InternalServerError = InternalServerError; +BaseAnthropic.PermissionDeniedError = PermissionDeniedError; +BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError; +BaseAnthropic.toFile = toFile; +/** + * API Client for interfacing with the Anthropic API. + */ +class Anthropic extends BaseAnthropic { + constructor() { + super(...arguments); + this.completions = new Completions(this); + this.messages = new messages_Messages(this); + this.models = new models_Models(this); + this.beta = new Beta(this); + } +} +Anthropic.Completions = Completions; +Anthropic.Messages = messages_Messages; +Anthropic.Models = models_Models; +Anthropic.Beta = Beta; +//# sourceMappingURL=client.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/index.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +const toBase64 = (data) => { + if (!data) + return ''; + if (typeof globalThis.Buffer !== 'undefined') { + return globalThis.Buffer.from(data).toString('base64'); + } + if (typeof data === 'string') { + data = encodeUTF8(data); + } + if (typeof btoa !== 'undefined') { + return btoa(String.fromCharCode.apply(null, data)); + } + throw new AnthropicError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined'); +}; +const fromBase64 = (str) => { + if (typeof globalThis.Buffer !== 'undefined') { + const buf = globalThis.Buffer.from(str, 'base64'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + if (typeof atob !== 'undefined') { + const bstr = atob(str); + const buf = new Uint8Array(bstr.length); + for (let i = 0; i < bstr.length; i++) { + buf[i] = bstr.charCodeAt(i); + } + return buf; + } + throw new AnthropicError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined'); +}; +//# sourceMappingURL=base64.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +//# sourceMappingURL=utils.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/transform-json-schema.mjs + +// Supported string formats +const SUPPORTED_STRING_FORMATS = new Set([ + 'date-time', + 'time', + 'date', + 'duration', + 'email', + 'hostname', + 'uri', + 'ipv4', + 'ipv6', + 'uuid', +]); +function transform_json_schema_deepClone(obj) { + return JSON.parse(JSON.stringify(obj)); +} +function transformJSONSchema(jsonSchema) { + const workingCopy = transform_json_schema_deepClone(jsonSchema); + return _transformJSONSchema(workingCopy); +} +function _transformJSONSchema(jsonSchema) { + const strictSchema = {}; + const ref = pop(jsonSchema, '$ref'); + if (ref !== undefined) { + strictSchema['$ref'] = ref; + return strictSchema; + } + const defs = pop(jsonSchema, '$defs'); + if (defs !== undefined) { + const strictDefs = {}; + strictSchema['$defs'] = strictDefs; + for (const [name, defSchema] of Object.entries(defs)) { + strictDefs[name] = _transformJSONSchema(defSchema); + } + } + const type = pop(jsonSchema, 'type'); + const anyOf = pop(jsonSchema, 'anyOf'); + const oneOf = pop(jsonSchema, 'oneOf'); + const allOf = pop(jsonSchema, 'allOf'); + if (Array.isArray(anyOf)) { + strictSchema['anyOf'] = anyOf.map((variant) => _transformJSONSchema(variant)); + } + else if (Array.isArray(oneOf)) { + strictSchema['anyOf'] = oneOf.map((variant) => _transformJSONSchema(variant)); + } + else if (Array.isArray(allOf)) { + strictSchema['allOf'] = allOf.map((entry) => _transformJSONSchema(entry)); + } + else { + if (type === undefined) { + throw new Error('JSON schema must have a type defined if anyOf/oneOf/allOf are not used'); + } + strictSchema['type'] = type; + } + const description = pop(jsonSchema, 'description'); + if (description !== undefined) { + strictSchema['description'] = description; + } + const title = pop(jsonSchema, 'title'); + if (title !== undefined) { + strictSchema['title'] = title; + } + if (type === 'object') { + const properties = pop(jsonSchema, 'properties') || {}; + strictSchema['properties'] = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [ + key, + _transformJSONSchema(propSchema), + ])); + pop(jsonSchema, 'additionalProperties'); + strictSchema['additionalProperties'] = false; + const required = pop(jsonSchema, 'required'); + if (required !== undefined) { + strictSchema['required'] = required; + } + } + else if (type === 'string') { + const format = pop(jsonSchema, 'format'); + if (format !== undefined && SUPPORTED_STRING_FORMATS.has(format)) { + strictSchema['format'] = format; + } + else if (format !== undefined) { + jsonSchema['format'] = format; + } + } + else if (type === 'array') { + const items = pop(jsonSchema, 'items'); + if (items !== undefined) { + strictSchema['items'] = _transformJSONSchema(items); + } + const minItems = pop(jsonSchema, 'minItems'); + if (minItems !== undefined && (minItems === 0 || minItems === 1)) { + strictSchema['minItems'] = minItems; + } + else if (minItems !== undefined) { + jsonSchema['minItems'] = minItems; + } + } + if (Object.keys(jsonSchema).length > 0) { + const existingDescription = strictSchema['description']; + strictSchema['description'] = + (existingDescription ? existingDescription + '\n\n' : '') + + '{' + + Object.entries(jsonSchema) + .map(([key, value]) => `${key}: ${JSON.stringify(value)}`) + .join(', ') + + '}'; + } + return strictSchema; +} +//# sourceMappingURL=transform-json-schema.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/chat_models.js + + + + + + + + + + + + + + + + + + + +//#region src/chat_models.ts +const MODEL_DEFAULT_MAX_OUTPUT_TOKENS = { + "claude-opus-4-1": 8192, + "claude-opus-4": 8192, + "claude-sonnet-4": 8192, + "claude-sonnet-3-7-sonnet": 8192, + "claude-3-5-sonnet": 4096, + "claude-3-5-haiku": 4096, + "claude-3-haiku": 2048 +}; +const FALLBACK_MAX_OUTPUT_TOKENS = 2048; +function defaultMaxOutputTokensForModel(model) { + if (!model) return FALLBACK_MAX_OUTPUT_TOKENS; + const maxTokens = Object.entries(MODEL_DEFAULT_MAX_OUTPUT_TOKENS).find(([key]) => model.startsWith(key))?.[1]; + return maxTokens ?? FALLBACK_MAX_OUTPUT_TOKENS; +} +function _toolsInParams(params) { + return !!(params.tools && params.tools.length > 0); +} +function _documentsInParams(params) { + for (const message of params.messages ?? []) { + if (typeof message.content === "string") continue; + for (const block of message.content ?? []) if (typeof block === "object" && block != null && block.type === "document" && typeof block.citations === "object" && block.citations?.enabled) return true; + } + return false; +} +function _thinkingInParams(params) { + return !!(params.thinking && params.thinking.type === "enabled"); +} +function isAnthropicTool(tool) { + return "input_schema" in tool; +} +function isBuiltinTool(tool) { + const builtInToolPrefixes = [ + "text_editor_", + "computer_", + "bash_", + "web_search_", + "web_fetch_", + "str_replace_editor_", + "str_replace_based_edit_tool_", + "code_execution_", + "memory_", + "tool_search_", + "mcp_toolset" + ]; + return typeof tool === "object" && tool !== null && "type" in tool && ("name" in tool || "mcp_server_name" in tool) && typeof tool.type === "string" && builtInToolPrefixes.some((prefix) => typeof tool.type === "string" && tool.type.startsWith(prefix)); +} +function _combineBetas(a, b, ...rest) { + return Array.from(new Set([ + ...a ?? [], + ...b ?? [], + ...rest.flatMap((x) => Array.from(x)) + ])); +} +function extractToken(chunk) { + if (typeof chunk.content === "string") return chunk.content; + else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "input" in chunk.content[0]) return typeof chunk.content[0].input === "string" ? chunk.content[0].input : JSON.stringify(chunk.content[0].input); + else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "text" in chunk.content[0] && typeof chunk.content[0].text === "string") return chunk.content[0].text; + return void 0; +} +/** +* Anthropic chat model integration. +* +* Setup: +* Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`. +* +* ```bash +* npm install @langchain/anthropic +* export ANTHROPIC_API_KEY="your-api-key" +* ``` +* +* ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor) +* +* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html) +* +* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. +* They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below: +* +* ```typescript +* // When calling `.bind`, call options should be passed via the first argument +* const llmWithArgsBound = llm.bindTools([...]).withConfig({ +* stop: ["\n"], +* }); +* +* // When calling `.bindTools`, call options should be passed via the second argument +* const llmWithTools = llm.bindTools( +* [...], +* { +* tool_choice: "auto", +* } +* ); +* ``` +* +* ## Examples +* +*
+* Instantiate +* +* ```typescript +* import { ChatAnthropic } from '@langchain/anthropic'; +* +* const llm = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* temperature: 0, +* maxTokens: undefined, +* maxRetries: 2, +* // apiKey: "...", +* // baseUrl: "...", +* // other params... +* }); +* ``` +*
+* +*
+* +*
+* Invoking +* +* ```typescript +* const input = `Translate "I love programming" into French.`; +* +* // Models also accept a list of chat messages or a formatted prompt +* const result = await llm.invoke(input); +* console.log(result); +* ``` +* +* ```txt +* AIMessage { +* "id": "msg_01QDpd78JUHpRP6bRRNyzbW3", +* "content": "Here's the translation to French:\n\nJ'adore la programmation.", +* "response_metadata": { +* "id": "msg_01QDpd78JUHpRP6bRRNyzbW3", +* "model": "claude-sonnet-4-5-20250929", +* "stop_reason": "end_turn", +* "stop_sequence": null, +* "usage": { +* "input_tokens": 25, +* "output_tokens": 19 +* }, +* "type": "message", +* "role": "assistant" +* }, +* "usage_metadata": { +* "input_tokens": 25, +* "output_tokens": 19, +* "total_tokens": 44 +* } +* } +* ``` +*
+* +*
+* +*
+* Streaming Chunks +* +* ```typescript +* for await (const chunk of await llm.stream(input)) { +* console.log(chunk); +* } +* ``` +* +* ```txt +* AIMessageChunk { +* "id": "msg_01N8MwoYxiKo9w4chE4gXUs4", +* "content": "", +* "additional_kwargs": { +* "id": "msg_01N8MwoYxiKo9w4chE4gXUs4", +* "type": "message", +* "role": "assistant", +* "model": "claude-sonnet-4-5-20250929" +* }, +* "usage_metadata": { +* "input_tokens": 25, +* "output_tokens": 1, +* "total_tokens": 26 +* } +* } +* AIMessageChunk { +* "content": "", +* } +* AIMessageChunk { +* "content": "Here", +* } +* AIMessageChunk { +* "content": "'s", +* } +* AIMessageChunk { +* "content": " the translation to", +* } +* AIMessageChunk { +* "content": " French:\n\nJ", +* } +* AIMessageChunk { +* "content": "'adore la programmation", +* } +* AIMessageChunk { +* "content": ".", +* } +* AIMessageChunk { +* "content": "", +* "additional_kwargs": { +* "stop_reason": "end_turn", +* "stop_sequence": null +* }, +* "usage_metadata": { +* "input_tokens": 0, +* "output_tokens": 19, +* "total_tokens": 19 +* } +* } +* ``` +*
+* +*
+* +*
+* Aggregate Streamed Chunks +* +* ```typescript +* import { AIMessageChunk } from '@langchain/core/messages'; +* import { concat } from '@langchain/core/utils/stream'; +* +* const stream = await llm.stream(input); +* let full: AIMessageChunk | undefined; +* for await (const chunk of stream) { +* full = !full ? chunk : concat(full, chunk); +* } +* console.log(full); +* ``` +* +* ```txt +* AIMessageChunk { +* "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA", +* "content": "Here's the translation to French:\n\nJ'adore la programmation.", +* "additional_kwargs": { +* "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA", +* "type": "message", +* "role": "assistant", +* "model": "claude-sonnet-4-5-20250929", +* "stop_reason": "end_turn", +* "stop_sequence": null +* }, +* "usage_metadata": { +* "input_tokens": 25, +* "output_tokens": 20, +* "total_tokens": 45 +* } +* } +* ``` +*
+* +*
+* +*
+* Bind tools +* +* ```typescript +* import { z } from 'zod'; +* +* const GetWeather = { +* name: "GetWeather", +* description: "Get the current weather in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const GetPopulation = { +* name: "GetPopulation", +* description: "Get the current population in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); +* const aiMsg = await llmWithTools.invoke( +* "Which city is hotter today and which is bigger: LA or NY?" +* ); +* console.log(aiMsg.tool_calls); +* ``` +* +* ```txt +* [ +* { +* name: 'GetWeather', +* args: { location: 'Los Angeles, CA' }, +* id: 'toolu_01WjW3Dann6BPJVtLhovdBD5', +* type: 'tool_call' +* }, +* { +* name: 'GetWeather', +* args: { location: 'New York, NY' }, +* id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe', +* type: 'tool_call' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'Los Angeles, CA' }, +* id: 'toolu_0165qYWBA2VFyUst5RA18zew', +* type: 'tool_call' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'New York, NY' }, +* id: 'toolu_01PGNyP33vxr13tGqr7i3rDo', +* type: 'tool_call' +* } +* ] +* ``` +*
+* +*
+* +*
+* Tool Search +* +* Tool search enables Claude to dynamically discover and load tools on-demand +* instead of loading all tool definitions upfront. This is useful when you have +* many tools but want to avoid the overhead of sending all definitions with every request. +* +* ```typescript +* import { ChatAnthropic } from "@langchain/anthropic"; +* +* const model = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* }); +* +* const tools = [ +* // Tool search server tool +* { +* type: "tool_search_tool_regex_20251119", +* name: "tool_search_tool_regex", +* }, +* // Tools with defer_loading are loaded on-demand +* { +* name: "get_weather", +* description: "Get the current weather for a location", +* input_schema: { +* type: "object", +* properties: { +* location: { type: "string", description: "City name" }, +* unit: { +* type: "string", +* enum: ["celsius", "fahrenheit"], +* }, +* }, +* required: ["location"], +* }, +* defer_loading: true, // Tool is loaded on-demand +* }, +* { +* name: "search_files", +* description: "Search through files in the workspace", +* input_schema: { +* type: "object", +* properties: { +* query: { type: "string" }, +* }, +* required: ["query"], +* }, +* defer_loading: true, // Tool is loaded on-demand +* }, +* ]; +* +* const modelWithTools = model.bindTools(tools); +* const response = await modelWithTools.invoke("What's the weather in San Francisco?"); +* ``` +* +* You can also use the `tool()` helper with the `extras` field: +* +* ```typescript +* import { tool } from "@langchain/core/tools"; +* import { z } from "zod"; +* +* const getWeather = tool( +* async (input) => `Weather in ${input.location}`, +* { +* name: "get_weather", +* description: "Get weather for a location", +* schema: z.object({ location: z.string() }), +* extras: { defer_loading: true }, +* } +* ); +* ``` +* +* **Note:** The required `advanced-tool-use-2025-11-20` beta header is automatically +* appended to the request when using tool search tools. +* +* **Best practices:** +* - Tools with `defer_loading: true` are only loaded when Claude discovers them via search +* - Keep your 3-5 most frequently used tools as non-deferred for optimal performance +* - Both regex and bm25 variants search tool names, descriptions, and argument info +* +* See the {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool | Claude docs} +* for more information. +*
+* +*
+* +*
+* Structured Output +* +* ChatAnthropic supports structured output through two main approaches: +* +* 1. **Function Calling with `withStructuredOutput()`**: Uses Anthropic's tool calling +* under the hood to constrain outputs to a specific schema. +* 2. **JSON Schema Mode**: Uses Anthropic's native JSON schema support for direct +* structured output without tool calling overhead. +* +* **Using withStructuredOutput (Function Calling)** +* +* This method leverages Anthropic's tool calling capabilities to ensure the model +* returns data matching your schema: +* +* ```typescript +* import { z } from 'zod'; +* +* const Joke = z.object({ +* setup: z.string().describe("The setup of the joke"), +* punchline: z.string().describe("The punchline to the joke"), +* rating: z.number().optional().describe("How funny the joke is, from 1 to 10") +* }).describe('Joke to tell user.'); +* +* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); +* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); +* console.log(jokeResult); +* ``` +* +* ```txt +* { +* setup: "Why don't cats play poker in the jungle?", +* punchline: 'Too many cheetahs!', +* rating: 7 +* } +* ``` +* +* **Using JSON Schema Mode** +* +* For more direct control, you can use Anthropic's native JSON schema support by +* passing `method: "jsonSchema"`: +* +* ```typescript +* import { z } from 'zod'; +* +* const RecipeSchema = z.object({ +* recipeName: z.string().describe("Name of the recipe"), +* ingredients: z.array(z.string()).describe("List of ingredients needed"), +* steps: z.array(z.string()).describe("Cooking steps in order"), +* prepTime: z.number().describe("Preparation time in minutes") +* }); +* +* const structuredLlm = llm.withStructuredOutput(RecipeSchema, { +* method: "jsonSchema" +* }); +* +* const recipe = await structuredLlm.invoke( +* "Give me a simple recipe for chocolate chip cookies" +* ); +* console.log(recipe); +* ``` +* +* ```txt +* { +* recipeName: 'Classic Chocolate Chip Cookies', +* ingredients: [ +* '2 1/4 cups all-purpose flour', +* '1 cup butter, softened', +* ... +* ], +* steps: [ +* 'Preheat oven to 375°F', +* 'Mix butter and sugars until creamy', +* ... +* ], +* prepTime: 15 +* } +* ``` +*
+* +*
+* +*
+* Multimodal +* +* ```typescript +* import { HumanMessage } from '@langchain/core/messages'; +* +* const imageUrl = "https://example.com/image.jpg"; +* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); +* const base64Image = Buffer.from(imageData).toString('base64'); +* +* const message = new HumanMessage({ +* content: [ +* { type: "text", text: "describe the weather in this image" }, +* { +* type: "image_url", +* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, +* }, +* ] +* }); +* +* const imageDescriptionAiMsg = await llm.invoke([message]); +* console.log(imageDescriptionAiMsg.content); +* ``` +* +* ```txt +* The weather in this image appears to be beautiful and clear. The sky is a vibrant blue with scattered white clouds, suggesting a sunny and pleasant day. The clouds are wispy and light, indicating calm conditions without any signs of storms or heavy weather. The bright green grass on the rolling hills looks lush and well-watered, which could mean recent rainfall or good growing conditions. Overall, the scene depicts a perfect spring or early summer day with mild temperatures, plenty of sunshine, and gentle breezes - ideal weather for enjoying the outdoors or for plant growth. +* ``` +*
+* +*
+* +*
+* Usage Metadata +* +* ```typescript +* const aiMsgForMetadata = await llm.invoke(input); +* console.log(aiMsgForMetadata.usage_metadata); +* ``` +* +* ```txt +* { input_tokens: 25, output_tokens: 19, total_tokens: 44 } +* ``` +*
+* +*
+* +*
+* Stream Usage Metadata +* +* ```typescript +* const streamForMetadata = await llm.stream( +* input, +* { +* streamUsage: true +* } +* ); +* let fullForMetadata: AIMessageChunk | undefined; +* for await (const chunk of streamForMetadata) { +* fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk); +* } +* console.log(fullForMetadata?.usage_metadata); +* ``` +* +* ```txt +* { input_tokens: 25, output_tokens: 20, total_tokens: 45 } +* ``` +*
+* +*
+* +*
+* Response Metadata +* +* ```typescript +* const aiMsgForResponseMetadata = await llm.invoke(input); +* console.log(aiMsgForResponseMetadata.response_metadata); +* ``` +* +* ```txt +* { +* id: 'msg_01STxeQxJmp4sCSpioD6vK3L', +* model: 'claude-sonnet-4-5-20250929', +* stop_reason: 'end_turn', +* stop_sequence: null, +* usage: { input_tokens: 25, output_tokens: 19 }, +* type: 'message', +* role: 'assistant' +* } +* ``` +*
+* +*
+*/ +var ChatAnthropicMessages = class extends BaseChatModel { + static lc_name() { + return "ChatAnthropic"; + } + get lc_secrets() { + return { + anthropicApiKey: "ANTHROPIC_API_KEY", + apiKey: "ANTHROPIC_API_KEY" + }; + } + get lc_aliases() { + return { modelName: "model" }; + } + lc_serializable = true; + anthropicApiKey; + apiKey; + apiUrl; + temperature; + topK; + topP; + maxTokens; + modelName = "claude-3-5-sonnet-latest"; + model = "claude-3-5-sonnet-latest"; + invocationKwargs; + stopSequences; + streaming = false; + clientOptions; + thinking = { type: "disabled" }; + contextManagement; + batchClient; + streamingClient; + streamUsage = true; + betas; + /** + * Optional method that returns an initialized underlying Anthropic client. + * Useful for accessing Anthropic models hosted on other cloud services + * such as Google Vertex. + */ + createClient; + constructor(fields) { + super(fields ?? {}); + this.anthropicApiKey = fields?.apiKey ?? fields?.anthropicApiKey ?? getEnvironmentVariable("ANTHROPIC_API_KEY"); + if (!this.anthropicApiKey && !fields?.createClient) throw new Error("Anthropic API key not found"); + this.clientOptions = fields?.clientOptions ?? {}; + /** Keep anthropicApiKey for backwards compatibility */ + this.apiKey = this.anthropicApiKey; + this.apiUrl = fields?.anthropicApiUrl; + /** Keep modelName for backwards compatibility */ + this.modelName = fields?.model ?? fields?.modelName ?? this.model; + this.model = this.modelName; + this.invocationKwargs = fields?.invocationKwargs ?? {}; + this.topP = fields?.topP ?? this.topP; + this.temperature = fields?.temperature ?? this.temperature; + this.topK = fields?.topK ?? this.topK; + this.maxTokens = fields?.maxTokens ?? defaultMaxOutputTokensForModel(this.model); + this.stopSequences = fields?.stopSequences ?? this.stopSequences; + this.streaming = fields?.streaming ?? false; + this.streamUsage = fields?.streamUsage ?? this.streamUsage; + this.thinking = fields?.thinking ?? this.thinking; + this.contextManagement = fields?.contextManagement ?? this.contextManagement; + this.betas = fields?.betas ?? this.betas; + this.createClient = fields?.createClient ?? ((options) => new Anthropic(options)); + } + getLsParams(options) { + const params = this.invocationParams(options); + return { + ls_provider: "anthropic", + ls_model_name: this.model, + ls_model_type: "chat", + ls_temperature: params.temperature ?? void 0, + ls_max_tokens: params.max_tokens ?? void 0, + ls_stop: options.stop + }; + } + /** + * Formats LangChain StructuredTools to AnthropicTools. + * + * @param {ChatAnthropicCallOptions["tools"]} tools The tools to format + * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed. + */ + formatStructuredToolToAnthropic(tools) { + if (!tools) return void 0; + return tools.map((tool) => { + if (isLangChainTool(tool) && tool.extras?.providerToolDefinition) return tool.extras.providerToolDefinition; + if (isBuiltinTool(tool)) return tool; + if (isAnthropicTool(tool)) return tool; + if (isOpenAITool(tool)) return { + name: tool.function.name, + description: tool.function.description, + input_schema: tool.function.parameters + }; + if (isLangChainTool(tool)) return { + name: tool.name, + description: tool.description, + input_schema: isInteropZodSchema(tool.schema) ? toJsonSchema(tool.schema) : tool.schema, + ...tool.extras ? AnthropicToolExtrasSchema.parse(tool.extras) : {} + }; + throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(tool, null, 2)}`); + }); + } + bindTools(tools, kwargs) { + return this.withConfig({ + tools: this.formatStructuredToolToAnthropic(tools), + ...kwargs + }); + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(options) { + const tool_choice = handleToolChoice(options?.tool_choice); + const toolBetas = options?.tools?.reduce((acc, tool) => { + if (typeof tool === "object" && "type" in tool && tool.type in ANTHROPIC_TOOL_BETAS) { + const beta = ANTHROPIC_TOOL_BETAS[tool.type]; + if (!acc.includes(beta)) return [...acc, beta]; + } + return acc; + }, []); + const output = { + model: this.model, + stop_sequences: options?.stop ?? this.stopSequences, + stream: this.streaming, + max_tokens: this.maxTokens, + tools: this.formatStructuredToolToAnthropic(options?.tools), + tool_choice, + thinking: this.thinking, + context_management: this.contextManagement, + ...this.invocationKwargs, + container: options?.container, + betas: _combineBetas(this.betas, options?.betas, toolBetas ?? []), + output_format: options?.output_format, + mcp_servers: options?.mcp_servers + }; + if (this.thinking.type === "enabled") { + if (this.topP !== void 0 && this.topK !== -1) throw new Error("topK is not supported when thinking is enabled"); + if (this.temperature !== void 0 && this.temperature !== 1) throw new Error("temperature is not supported when thinking is enabled"); + } else { + output.temperature = this.temperature; + output.top_k = this.topK; + output.top_p = this.topP; + } + return output; + } + /** @ignore */ + _identifyingParams() { + return { + model_name: this.model, + ...this.invocationParams() + }; + } + /** + * Get the identifying parameters for the model + */ + identifyingParams() { + return { + model_name: this.model, + ...this.invocationParams() + }; + } + async *_streamResponseChunks(messages, options, runManager) { + const params = this.invocationParams(options); + const formattedMessages = message_inputs_convertMessagesToAnthropicPayload(messages); + const payload = { + ...params, + ...formattedMessages, + stream: true + }; + const coerceContentToString = !_toolsInParams(payload) && !_documentsInParams(payload) && !_thinkingInParams(payload); + const stream = await this.createStreamWithRetry(payload, { headers: options.headers }); + for await (const data of stream) { + if (options.signal?.aborted) { + stream.controller.abort(); + throw new Error("AbortError: User aborted the request."); + } + const shouldStreamUsage = this.streamUsage ?? options.streamUsage; + const result = _makeMessageChunkFromAnthropicEvent(data, { + streamUsage: shouldStreamUsage, + coerceContentToString + }); + if (!result) continue; + const { chunk } = result; + const token = extractToken(chunk); + const generationChunk = new ChatGenerationChunk({ + message: new AIMessageChunk({ + content: chunk.content, + additional_kwargs: chunk.additional_kwargs, + tool_call_chunks: chunk.tool_call_chunks, + usage_metadata: shouldStreamUsage ? chunk.usage_metadata : void 0, + response_metadata: chunk.response_metadata, + id: chunk.id + }), + text: token ?? "" + }); + yield generationChunk; + await runManager?.handleLLMNewToken(token ?? "", void 0, void 0, void 0, void 0, { chunk: generationChunk }); + } + } + /** @ignore */ + async _generateNonStreaming(messages, params, requestOptions) { + const response = await this.completionWithRetry({ + ...params, + stream: false, + ...message_inputs_convertMessagesToAnthropicPayload(messages) + }, requestOptions); + const { content,...additionalKwargs } = response; + const generations = anthropicResponseToChatMessages(content, additionalKwargs); + const { role: _role, type: _type,...rest } = additionalKwargs; + return { + generations, + llmOutput: rest + }; + } + /** @ignore */ + async _generate(messages, options, runManager) { + if (this.stopSequences && options.stop) throw new Error(`"stopSequence" parameter found in input and default params`); + const params = this.invocationParams(options); + if (params.stream) { + let finalChunk; + const stream = this._streamResponseChunks(messages, options, runManager); + for await (const chunk of stream) if (finalChunk === void 0) finalChunk = chunk; + else finalChunk = finalChunk.concat(chunk); + if (finalChunk === void 0) throw new Error("No chunks returned from Anthropic API."); + return { generations: [{ + text: finalChunk.text, + message: finalChunk.message + }] }; + } else return this._generateNonStreaming(messages, params, { + signal: options.signal, + headers: options.headers + }); + } + /** + * Creates a streaming request with retry. + * @param request The parameters for creating a completion. + * @param options + * @returns A streaming request. + */ + async createStreamWithRetry(request, options) { + if (!this.streamingClient) { + const options_ = this.apiUrl ? { baseURL: this.apiUrl } : void 0; + this.streamingClient = this.createClient({ + dangerouslyAllowBrowser: true, + ...this.clientOptions, + ...options_, + apiKey: this.apiKey, + maxRetries: 0 + }); + } + const { betas,...rest } = request; + const makeCompletionRequest = async () => { + try { + if (request?.betas?.length) { + const stream = await this.streamingClient.beta.messages.create({ + ...rest, + betas, + ...this.invocationKwargs, + stream: true + }, options); + return stream; + } + return await this.streamingClient.messages.create({ + ...rest, + ...this.invocationKwargs, + stream: true + }, options); + } catch (e) { + const error = wrapAnthropicClientError(e); + throw error; + } + }; + return this.caller.call(makeCompletionRequest); + } + /** @ignore */ + async completionWithRetry(request, options) { + if (!this.batchClient) { + const options$1 = this.apiUrl ? { baseURL: this.apiUrl } : void 0; + this.batchClient = this.createClient({ + dangerouslyAllowBrowser: true, + ...this.clientOptions, + ...options$1, + apiKey: this.apiKey, + maxRetries: 0 + }); + } + const { betas,...rest } = request; + const makeCompletionRequest = async () => { + try { + if (request?.betas?.length) { + const response = await this.batchClient.beta.messages.create({ + ...rest, + ...this.invocationKwargs, + betas + }, options); + return response; + } + return await this.batchClient.messages.create({ + ...rest, + ...this.invocationKwargs + }, options); + } catch (e) { + const error = wrapAnthropicClientError(e); + throw error; + } + }; + return this.caller.callWithOptions({ signal: options.signal ?? void 0 }, makeCompletionRequest); + } + _llmType() { + return "anthropic"; + } + /** + * Return profiling information for the model. + * + * Provides information about the model's capabilities and constraints, + * including token limits, multimodal support, and advanced features like + * tool calling and structured output. + * + * @returns {ModelProfile} An object describing the model's capabilities and constraints + * + * @example + * ```typescript + * const model = new ChatAnthropic({ model: "claude-opus-4-0" }); + * const profile = model.profile; + * console.log(profile.maxInputTokens); // 200000 + * console.log(profile.imageInputs); // true + * ``` + */ + get profile() { + return profiles_default[this.model] ?? {}; + } + withStructuredOutput(outputSchema, config) { + let llm; + let outputParser; + const { schema, name, includeRaw } = { + ...config, + schema: outputSchema + }; + let method = config?.method ?? "functionCalling"; + if (method === "jsonMode") { + console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`); + method = "jsonSchema"; + } + if (method === "jsonSchema") { + outputParser = isInteropZodSchema(schema) ? StructuredOutputParser.fromZodSchema(schema) : new JsonOutputParser(); + const jsonSchema = transformJSONSchema(toJsonSchema(schema)); + llm = this.withConfig({ + outputVersion: "v0", + output_format: { + type: "json_schema", + schema: jsonSchema + }, + betas: ["structured-outputs-2025-11-13"], + ls_structured_output_format: { + kwargs: { method: "json_schema" }, + schema: jsonSchema + } + }); + } else if (method === "functionCalling") { + let functionName = name ?? "extract"; + let tools; + if (isInteropZodSchema(schema)) { + const jsonSchema = toJsonSchema(schema); + tools = [{ + name: functionName, + description: jsonSchema.description ?? "A function available to call.", + input_schema: jsonSchema + }]; + outputParser = new AnthropicToolsOutputParser({ + returnSingle: true, + keyName: functionName, + zodSchema: schema + }); + } else { + let anthropicTools; + if (typeof schema.name === "string" && typeof schema.description === "string" && typeof schema.input_schema === "object" && schema.input_schema != null) { + anthropicTools = schema; + functionName = schema.name; + } else anthropicTools = { + name: functionName, + description: schema.description ?? "", + input_schema: schema + }; + tools = [anthropicTools]; + outputParser = new AnthropicToolsOutputParser({ + returnSingle: true, + keyName: functionName + }); + } + if (this.thinking?.type === "enabled") { + const thinkingAdmonition = "Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called."; + console.warn(thinkingAdmonition); + llm = this.withConfig({ + outputVersion: "v0", + tools, + ls_structured_output_format: { + kwargs: { method: "functionCalling" }, + schema: toJsonSchema(schema) + } + }); + const raiseIfNoToolCalls = (message) => { + if (!message.tool_calls || message.tool_calls.length === 0) throw new Error(thinkingAdmonition); + return message; + }; + llm = llm.pipe(raiseIfNoToolCalls); + } else llm = this.withConfig({ + outputVersion: "v0", + tools, + tool_choice: { + type: "tool", + name: functionName + }, + ls_structured_output_format: { + kwargs: { method: "functionCalling" }, + schema: toJsonSchema(schema) + } + }); + } else throw new TypeError(`Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`); + if (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: "ChatAnthropicStructuredOutput" }); + const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); + const parserNone = RunnablePassthrough.assign({ parsed: () => null }); + const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); + return RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" }); + } +}; +var ChatAnthropic = class extends ChatAnthropicMessages {}; + +//#endregion + +//# sourceMappingURL=chat_models.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/prompts.js + + +//#region src/utils/prompts.ts +/** +* Convert a formatted LangChain prompt (e.g. pulled from the hub) into +* a format expected by Anthropic's JS SDK. +* +* Requires the "@langchain/anthropic" package to be installed in addition +* to the Anthropic SDK. +* +* @example +* ```ts +* import { convertPromptToAnthropic } from "langsmith/utils/hub/anthropic"; +* import { pull } from "langchain/hub"; +* +* import Anthropic from '@anthropic-ai/sdk'; +* +* const prompt = await pull("jacob/joke-generator"); +* const formattedPrompt = await prompt.invoke({ +* topic: "cats", +* }); +* +* const { system, messages } = convertPromptToAnthropic(formattedPrompt); +* +* const anthropicClient = new Anthropic({ +* apiKey: 'your_api_key', +* }); +* +* const anthropicResponse = await anthropicClient.messages.create({ +* model: "claude-sonnet-4-5-20250929", +* max_tokens: 1024, +* stream: false, +* system, +* messages, +* }); +* ``` +* @param formattedPrompt +* @returns A partial Anthropic payload. +*/ +function convertPromptToAnthropic(formattedPrompt) { + const messages = formattedPrompt.toChatMessages(); + const anthropicBody = _convertMessagesToAnthropicPayload(messages); + if (anthropicBody.messages === void 0) anthropicBody.messages = []; + return anthropicBody; +} + +//#endregion + +//# sourceMappingURL=prompts.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/types.js + + +//#region src/tools/types.ts +/** +* Memory tool command types as defined by Anthropic's memory tool API. +* @beta +* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/memory-tool +*/ +const Memory20250818ViewCommandSchema = object({ + command: literal("view"), + path: schemas_string() +}); +const Memory20250818CreateCommandSchema = object({ + command: literal("create"), + path: schemas_string(), + file_text: schemas_string() +}); +const Memory20250818StrReplaceCommandSchema = object({ + command: literal("str_replace"), + path: schemas_string(), + old_str: schemas_string(), + new_str: schemas_string() +}); +const Memory20250818InsertCommandSchema = object({ + command: literal("insert"), + path: schemas_string(), + insert_line: schemas_number(), + insert_text: schemas_string() +}); +const Memory20250818DeleteCommandSchema = object({ + command: literal("delete"), + path: schemas_string() +}); +const Memory20250818RenameCommandSchema = object({ + command: literal("rename"), + old_path: schemas_string(), + new_path: schemas_string() +}); +const Memory20250818CommandSchema = discriminatedUnion("command", [ + Memory20250818ViewCommandSchema, + Memory20250818CreateCommandSchema, + Memory20250818StrReplaceCommandSchema, + Memory20250818InsertCommandSchema, + Memory20250818DeleteCommandSchema, + Memory20250818RenameCommandSchema +]); +/** +* Text editor tool command types for Claude 4.x models. +* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/text-editor-tool +*/ +const TextEditor20250728ViewCommandSchema = object({ + command: literal("view"), + path: schemas_string(), + view_range: tuple([schemas_number(), schemas_number()]).optional() +}); +const TextEditor20250728StrReplaceCommandSchema = object({ + command: literal("str_replace"), + path: schemas_string(), + old_str: schemas_string(), + new_str: schemas_string() +}); +const TextEditor20250728CreateCommandSchema = object({ + command: literal("create"), + path: schemas_string(), + file_text: schemas_string() +}); +const TextEditor20250728InsertCommandSchema = object({ + command: literal("insert"), + path: schemas_string(), + insert_line: schemas_number(), + new_str: schemas_string() +}); +const TextEditor20250728CommandSchema = discriminatedUnion("command", [ + TextEditor20250728ViewCommandSchema, + TextEditor20250728StrReplaceCommandSchema, + TextEditor20250728CreateCommandSchema, + TextEditor20250728InsertCommandSchema +]); +const coordinateSchema = tuple([schemas_number(), schemas_number()]); +const ComputerScreenshotActionSchema = object({ action: literal("screenshot") }); +const ComputerLeftClickActionSchema = object({ + action: literal("left_click"), + coordinate: coordinateSchema +}); +const ComputerRightClickActionSchema = object({ + action: literal("right_click"), + coordinate: coordinateSchema +}); +const ComputerMiddleClickActionSchema = object({ + action: literal("middle_click"), + coordinate: coordinateSchema +}); +const ComputerDoubleClickActionSchema = object({ + action: literal("double_click"), + coordinate: coordinateSchema +}); +const ComputerTripleClickActionSchema = object({ + action: literal("triple_click"), + coordinate: coordinateSchema +}); +const ComputerLeftClickDragActionSchema = object({ + action: literal("left_click_drag"), + start_coordinate: coordinateSchema, + end_coordinate: coordinateSchema +}); +const ComputerLeftMouseDownActionSchema = object({ + action: literal("left_mouse_down"), + coordinate: coordinateSchema +}); +const ComputerLeftMouseUpActionSchema = object({ + action: literal("left_mouse_up"), + coordinate: coordinateSchema +}); +const ComputerScrollActionSchema = object({ + action: literal("scroll"), + coordinate: coordinateSchema, + scroll_direction: schemas_enum([ + "up", + "down", + "left", + "right" + ]), + scroll_amount: schemas_number() +}); +const ComputerTypeActionSchema = object({ + action: literal("type"), + text: schemas_string() +}); +const ComputerKeyActionSchema = object({ + action: literal("key"), + key: schemas_string() +}); +const ComputerMouseMoveActionSchema = object({ + action: literal("mouse_move"), + coordinate: coordinateSchema +}); +const ComputerHoldKeyActionSchema = object({ + action: literal("hold_key"), + key: schemas_string() +}); +const ComputerWaitActionSchema = object({ + action: literal("wait"), + duration: schemas_number().optional() +}); +const ComputerZoomActionSchema = object({ + action: literal("zoom"), + region: tuple([ + schemas_number(), + schemas_number(), + schemas_number(), + schemas_number() + ]) +}); +const Computer20250124ActionSchema = discriminatedUnion("action", [ + ComputerScreenshotActionSchema, + ComputerLeftClickActionSchema, + ComputerRightClickActionSchema, + ComputerMiddleClickActionSchema, + ComputerDoubleClickActionSchema, + ComputerTripleClickActionSchema, + ComputerLeftClickDragActionSchema, + ComputerLeftMouseDownActionSchema, + ComputerLeftMouseUpActionSchema, + ComputerScrollActionSchema, + ComputerTypeActionSchema, + ComputerKeyActionSchema, + ComputerMouseMoveActionSchema, + ComputerHoldKeyActionSchema, + ComputerWaitActionSchema +]); +const Computer20251124ActionSchema = discriminatedUnion("action", [ + ComputerScreenshotActionSchema, + ComputerLeftClickActionSchema, + ComputerRightClickActionSchema, + ComputerMiddleClickActionSchema, + ComputerDoubleClickActionSchema, + ComputerTripleClickActionSchema, + ComputerLeftClickDragActionSchema, + ComputerLeftMouseDownActionSchema, + ComputerLeftMouseUpActionSchema, + ComputerScrollActionSchema, + ComputerTypeActionSchema, + ComputerKeyActionSchema, + ComputerMouseMoveActionSchema, + ComputerHoldKeyActionSchema, + ComputerWaitActionSchema, + ComputerZoomActionSchema +]); +/** +* Bash tool command types for Claude 4 models and Claude 3.7. +* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/bash-tool +*/ +const Bash20250124ExecuteCommandSchema = object({ command: schemas_string().describe("The bash command to run") }); +const Bash20250124RestartCommandSchema = object({ restart: literal(true).describe("Set to true to restart the bash session") }); +const Bash20250124CommandSchema = union([Bash20250124ExecuteCommandSchema, Bash20250124RestartCommandSchema]); + +//#endregion + +//# sourceMappingURL=types.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/memory.js + + + +//#region src/tools/memory.ts +/** +* Creates an Anthropic memory tool that can be used with ChatAnthropic. +* +* The memory tool enables Claude to store and retrieve information across conversations +* through a memory file directory. Claude can create, read, update, and delete files that +* persist between sessions, allowing it to build knowledge over time without keeping +* everything in the context window. +* +* @example +* ```typescript +* import { ChatAnthropic, memory_20250818 } from "@langchain/anthropic"; +* +* const llm = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929" +* }); +* +* const memory = memory_20250818({ +* execute: async (args) => { +* // handle memory command execution +* // ... +* }, +* }); +* const llmWithMemory = llm.bindTools([memory]); +* +* const response = await llmWithMemory.invoke("Remember that I like Python"); +* ``` +* +* @param options - Optional configuration for the memory tool (currently unused) +* @param options.execute - Optional execute function that handles memory command execution. +* @returns The memory tool object that can be passed to `bindTools` +* +* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/memory-tool +*/ +function memory_20250818(options) { + const memoryTool = tool(options?.execute, { + name: "memory", + schema: Memory20250818CommandSchema + }); + memoryTool.extras = { + ...memoryTool.extras ?? {}, + providerToolDefinition: { + type: "memory_20250818", + name: "memory" + } + }; + return memoryTool; +} + +//#endregion + +//# sourceMappingURL=memory.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/webSearch.js +//#region src/tools/webSearch.ts +/** +* Creates a web search tool that gives Claude direct access to real-time web content, +* allowing it to answer questions with up-to-date information beyond its knowledge cutoff. +* Claude automatically cites sources from search results as part of its answer. +* +* @see {@link https://docs.anthropic.com/en/docs/build-with-claude/tool-use/web-search-tool | Anthropic Web Search Documentation} +* @param options - Configuration options for the web search tool +* @returns A web search tool definition to be passed to the Anthropic API +* +* @example +* ```typescript +* import { ChatAnthropic, tools } from "@langchain/anthropic"; +* +* const model = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* }); +* +* // Basic usage +* const response = await model.invoke("What is the weather in NYC?", { +* tools: [tools.webSearch_20250305()], +* }); +* +* // With options +* const responseWithOptions = await model.invoke("Latest news about AI?", { +* tools: [tools.webSearch_20250305({ +* maxUses: 5, +* allowedDomains: ["reuters.com", "bbc.com"], +* userLocation: { +* type: "approximate", +* city: "San Francisco", +* region: "California", +* country: "US", +* timezone: "America/Los_Angeles", +* }, +* })], +* }); +* ``` +*/ +function webSearch_20250305(options) { + return { + type: "web_search_20250305", + name: "web_search", + max_uses: options?.maxUses, + allowed_domains: options?.allowedDomains, + blocked_domains: options?.blockedDomains, + cache_control: options?.cacheControl, + defer_loading: options?.deferLoading, + strict: options?.strict, + user_location: options?.userLocation + }; +} + +//#endregion + +//# sourceMappingURL=webSearch.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/webFetch.js +//#region src/tools/webFetch.ts +/** +* Creates a web fetch tool that allows Claude to retrieve full content from specified +* web pages and PDF documents. Claude can only fetch URLs that have been explicitly +* provided by the user or that come from previous web search or web fetch results. +* +* @warning Enabling the web fetch tool in environments where Claude processes untrusted +* input alongside sensitive data poses data exfiltration risks. We recommend only using +* this tool in trusted environments or when handling non-sensitive data. +* +* @see {@link https://docs.anthropic.com/en/docs/build-with-claude/tool-use/web-fetch-tool | Anthropic Web Fetch Documentation} +* @param options - Configuration options for the web fetch tool +* @returns A web fetch tool definition to be passed to the Anthropic API +* +* @example +* ```typescript +* import { ChatAnthropic, tools } from "@langchain/anthropic"; +* +* const model = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* }); +* +* // Basic usage - fetch content from a URL +* const response = await model.invoke( +* "Please analyze the content at https://example.com/article", +* { tools: [tools.webFetch_20250910()] } +* ); +* +* // With options +* const responseWithOptions = await model.invoke( +* "Summarize this research paper: https://arxiv.org/abs/2024.12345", +* { +* tools: [tools.webFetch_20250910({ +* maxUses: 5, +* allowedDomains: ["arxiv.org", "example.com"], +* citations: { enabled: true }, +* maxContentTokens: 50000, +* })], +* } +* ); +* +* // Combined with web search for comprehensive information gathering +* const combinedResponse = await model.invoke( +* "Find recent articles about quantum computing and analyze the most relevant one", +* { +* tools: [ +* tools.webSearch_20250305({ maxUses: 3 }), +* tools.webFetch_20250910({ maxUses: 5, citations: { enabled: true } }), +* ], +* } +* ); +* ``` +*/ +function webFetch_20250910(options) { + return { + type: "web_fetch_20250910", + name: "web_fetch", + max_uses: options?.maxUses, + allowed_domains: options?.allowedDomains, + blocked_domains: options?.blockedDomains, + cache_control: options?.cacheControl, + citations: options?.citations, + max_content_tokens: options?.maxContentTokens + }; +} + +//#endregion + +//# sourceMappingURL=webFetch.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/toolSearch.js +//#region src/tools/toolSearch.ts +/** +* Creates a regex-based tool search tool that enables Claude to work with hundreds +* or thousands of tools by dynamically discovering and loading them on-demand. +* Claude constructs regex patterns (using Python's `re.search()` syntax) to search +* for tools by name, description, argument names, and argument descriptions. +* +* @note This tool requires the beta header `advanced-tool-use-2025-11-20` in API requests. +* +* @see {@link https://docs.anthropic.com/en/docs/build-with-claude/tool-use/tool-search-tool | Anthropic Tool Search Documentation} +* @param options - Configuration options for the tool search tool +* @returns A tool search tool definition to be passed to the Anthropic API +* +* @example +* ```typescript +* import { ChatAnthropic, tools } from "@langchain/anthropic"; +* +* const model = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* }); +* +* const getWeather = tool( +* async (input: { location: string }) => { +* return `Weather in ${input.location}`; +* }, +* { +* name: "get_weather", +* description: "Get the weather at a specific location", +* schema: z.object({ +* location: z.string(), +* }), +* extras: { defer_loading: true }, +* }, +* ); +* +* // Use with deferred tools - Claude will search and discover tools as needed +* const response = await model.invoke("What is the weather in San Francisco?", { +* tools: [ +* tools.toolSearchRegex_20251119(), +* getWeather, +* ], +* }); +* ``` +*/ +function toolSearchRegex_20251119(options) { + return { + type: "tool_search_tool_regex_20251119", + name: "tool_search_tool_regex", + cache_control: options?.cacheControl + }; +} +/** +* Creates a BM25-based tool search tool that enables Claude to work with hundreds +* or thousands of tools by dynamically discovering and loading them on-demand. +* Claude uses natural language queries to search for tools by name, description, +* argument names, and argument descriptions. +* +* @note This tool requires the beta header `advanced-tool-use-2025-11-20` in API requests. +* +* @see {@link https://docs.anthropic.com/en/docs/build-with-claude/tool-use/tool-search-tool | Anthropic Tool Search Documentation} +* @param options - Configuration options for the tool search tool +* @returns A tool search tool definition to be passed to the Anthropic API +* +* @example +* ```typescript +* import { ChatAnthropic, tools } from "@langchain/anthropic"; +* +* const model = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* clientOptions: { +* defaultHeaders: { "anthropic-beta": "advanced-tool-use-2025-11-20" }, +* }, +* }); +* +* const getWeather = tool( +* async (input: { location: string }) => { +* return `Weather in ${input.location}`; +* }, +* { +* name: "get_weather", +* description: "Get the weather at a specific location", +* schema: z.object({ +* location: z.string(), +* }), +* extras: { defer_loading: true }, +* }, +* ); +* +* // Use with deferred tools - Claude will search using natural language +* const response = await model.invoke("What is the weather in San Francisco?", { +* tools: [ +* tools.toolSearchBM25_20251119(), +* getWeather, +* ], +* }); +* ``` +*/ +function toolSearchBM25_20251119(options) { + return { + type: "tool_search_tool_bm25_20251119", + name: "tool_search_tool_bm25", + cache_control: options?.cacheControl + }; +} + +//#endregion + +//# sourceMappingURL=toolSearch.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/textEditor.js + + + +//#region src/tools/textEditor.ts +/** +* Creates an Anthropic text editor tool for Claude 4.x models that can view and modify text files. +* +* The text editor tool enables Claude to view and modify text files, helping debug, fix, +* and improve code or other text documents. Claude can directly interact with files, +* providing hands-on assistance rather than just suggesting changes. +* +* Available commands: +* - `view`: Examine file contents or list directory contents +* - `str_replace`: Replace specific text in a file +* - `create`: Create a new file with specified content +* - `insert`: Insert text at a specific line number +* +* @example +* ```typescript +* import { ChatAnthropic, tools } from "@langchain/anthropic"; +* import * as fs from "fs"; +* +* const llm = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* }); +* +* const textEditor = tools.textEditor_20250728({ +* execute: async (args) => { +* if (args.command === "view") { +* const content = fs.readFileSync(args.path, "utf-8"); +* return content.split("\n").map((line, i) => `${i + 1}: ${line}`).join("\n"); +* } +* if (args.command === "str_replace") { +* let content = fs.readFileSync(args.path, "utf-8"); +* content = content.replace(args.old_str!, args.new_str!); +* fs.writeFileSync(args.path, content); +* return "Successfully replaced text."; +* } +* // Handle other commands... +* return "Command executed"; +* }, +* maxCharacters: 10000, +* }); +* +* const llmWithEditor = llm.bindTools([textEditor]); +* const response = await llmWithEditor.invoke( +* "There's a syntax error in my primes.py file. Can you help me fix it?" +* ); +* ``` +* +* @param options - Configuration options for the text editor tool +* @param options.execute - Function that handles text editor command execution +* @param options.maxCharacters - Maximum characters to return when viewing files +* @returns The text editor tool object that can be passed to `bindTools` +* +* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/text-editor-tool +*/ +function textEditor_20250728(options) { + const name = "str_replace_based_edit_tool"; + const textEditorTool = tool(options?.execute, { + name, + description: "A tool for editing text files", + schema: TextEditor20250728CommandSchema + }); + textEditorTool.extras = { + ...textEditorTool.extras ?? {}, + providerToolDefinition: { + type: "text_editor_20250728", + name, + ...options?.maxCharacters !== void 0 && { max_characters: options.maxCharacters } + } + }; + return textEditorTool; +} + +//#endregion + +//# sourceMappingURL=textEditor.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/computer.js + + + +//#region src/tools/computer.ts +const TOOL_NAME = "computer"; +/** +* Creates an Anthropic computer use tool for Claude Opus 4.5 that provides +* screenshot capabilities and mouse/keyboard control for autonomous desktop interaction. +* +* The computer use tool enables Claude to interact with desktop environments through: +* - **Screenshot capture**: See what's currently displayed on screen +* - **Mouse control**: Click, drag, and move the cursor +* - **Keyboard input**: Type text and use keyboard shortcuts +* - **Zoom**: View specific screen regions at full resolution (when enabled) +* +* @warning Computer use is a beta feature with unique risks. Use a dedicated virtual machine +* or container with minimal privileges. Avoid giving access to sensitive data. +* +* @see {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool | Anthropic Computer Use Documentation} +* +* @example +* ```typescript +* import { ChatAnthropic, tools } from "@langchain/anthropic"; +* +* const llm = new ChatAnthropic({ +* model: "claude-opus-4-5-20251101", +* clientOptions: { +* defaultHeaders: { +* "anthropic-beta": "computer-use-2025-11-24", +* }, +* }, +* }); +* +* const computer = tools.computer_20251124({ +* displayWidthPx: 1024, +* displayHeightPx: 768, +* displayNumber: 1, +* enableZoom: true, +* execute: async (action) => { +* if (action.action === "screenshot") { +* // Capture and return base64-encoded screenshot +* return captureScreenshot(); +* } +* if (action.action === "left_click") { +* // Click at the specified coordinates +* await click(action.coordinate[0], action.coordinate[1]); +* return captureScreenshot(); +* } +* // Handle other actions... +* }, +* }); +* +* const llmWithComputer = llm.bindTools([computer]); +* const response = await llmWithComputer.invoke( +* "Save a picture of a cat to my desktop." +* ); +* ``` +* +* @param options - Configuration options for the computer use tool +* @returns The computer use tool object that can be passed to `bindTools` +*/ +function computer_20251124(options) { + const name = TOOL_NAME; + const computerTool = tool(options.execute, { + name, + schema: Computer20251124ActionSchema + }); + computerTool.extras = { + ...computerTool.extras ?? {}, + providerToolDefinition: { + type: "computer_20251124", + name, + display_width_px: options.displayWidthPx, + display_height_px: options.displayHeightPx, + ...options.displayNumber !== void 0 && { display_number: options.displayNumber }, + ...options.enableZoom !== void 0 && { enable_zoom: options.enableZoom } + } + }; + return computerTool; +} +/** +* Creates an Anthropic computer use tool that provides screenshot capabilities and mouse/keyboard control +* for autonomous desktop interaction. +* +* Supported models: Claude Sonnet 4.5, Haiku 4.5, Opus 4.1, Sonnet 4, Opus 4, and Sonnet 3.7 versions. +* +* The computer use tool enables Claude to interact with desktop environments through: +* - **Screenshot capture**: See what's currently displayed on screen +* - **Mouse control**: Click, drag, and move the cursor +* - **Keyboard input**: Type text and use keyboard shortcuts +* +* @warning Computer use is a beta feature with unique risks. Use a dedicated virtual machine +* or container with minimal privileges. Avoid giving access to sensitive data. +* +* @see {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool | Anthropic Computer Use Documentation} +* +* @example +* ```typescript +* import { ChatAnthropic, tools } from "@langchain/anthropic"; +* +* const llm = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* clientOptions: { +* defaultHeaders: { +* "anthropic-beta": "computer-use-2025-01-24", +* }, +* }, +* }); +* +* const computer = tools.computer_20250124({ +* displayWidthPx: 1024, +* displayHeightPx: 768, +* displayNumber: 1, +* execute: async (action) => { +* if (action.action === "screenshot") { +* // Capture and return base64-encoded screenshot +* return captureScreenshot(); +* } +* if (action.action === "left_click") { +* // Click at the specified coordinates +* await click(action.coordinate[0], action.coordinate[1]); +* return captureScreenshot(); +* } +* // Handle other actions... +* }, +* }); +* +* const llmWithComputer = llm.bindTools([computer]); +* const response = await llmWithComputer.invoke( +* "Save a picture of a cat to my desktop." +* ); +* ``` +* +* @param options - Configuration options for the computer use tool +* @returns The computer use tool object that can be passed to `bindTools` +*/ +function computer_20250124(options) { + const name = TOOL_NAME; + const computerTool = tool(options.execute, { + name, + description: "A tool for interacting with the computer", + schema: Computer20250124ActionSchema + }); + computerTool.extras = { + ...computerTool.extras ?? {}, + providerToolDefinition: { + type: "computer_20250124", + name, + display_width_px: options.displayWidthPx, + display_height_px: options.displayHeightPx, + ...options.displayNumber !== void 0 && { display_number: options.displayNumber } + } + }; + return computerTool; +} + +//#endregion + +//# sourceMappingURL=computer.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/codeExecution.js +//#region src/tools/codeExecution.ts +/** +* Creates a code execution tool that allows Claude to run Bash commands and manipulate files +* in a secure, sandboxed environment. Claude can analyze data, create visualizations, +* perform calculations, and process files. +* +* When this tool is provided, Claude automatically gains access to: +* - **Bash commands**: Execute shell commands for system operations +* - **File operations**: Create, view, and edit files directly +* +* @note This tool requires the beta header `code-execution-2025-08-25` in API requests. +* +* @see {@link https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/code-execution-tool | Anthropic Code Execution Documentation} +* @param options - Configuration options for the code execution tool +* @returns A code execution tool definition to be passed to the Anthropic API +* +* @example +* ```typescript +* import { ChatAnthropic, tools } from "@langchain/anthropic"; +* +* const model = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* }); +* +* // Basic usage - calculations and data analysis +* const response = await model.invoke( +* "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", +* { tools: [tools.codeExecution_20250825()] } +* ); +* +* // File operations and visualization +* const response2 = await model.invoke( +* "Create a matplotlib visualization of sales data and save it as chart.png", +* { tools: [tools.codeExecution_20250825()] } +* ); +* ``` +* +* @example Container reuse +* ```typescript +* // First request - creates a container +* const response1 = await model.invoke( +* "Write a random number to /tmp/number.txt", +* { tools: [tools.codeExecution_20250825()] } +* ); +* +* // Extract container ID from response for reuse +* const containerId = response1.response_metadata?.container?.id; +* +* // Second request - reuse container to access the file +* const response2 = await model.invoke( +* "Read /tmp/number.txt and calculate its square", +* { +* tools: [tools.codeExecution_20250825()], +* // Pass container ID to reuse the same environment +* } +* ); +* ``` +*/ +function codeExecution_20250825(options) { + return { + type: "code_execution_20250825", + name: "code_execution", + cache_control: options?.cacheControl + }; +} + +//#endregion + +//# sourceMappingURL=codeExecution.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/bash.js + + + +//#region src/tools/bash.ts +/** +* Creates an Anthropic bash tool for Claude 4 models and Claude 3.7 that enables +* shell command execution in a persistent bash session. +* +* The bash tool provides Claude with: +* - **Persistent bash session**: Maintains state between commands +* - **Shell command execution**: Run any shell command +* - **Environment access**: Access to environment variables and working directory +* - **Command chaining**: Support for pipes, redirects, and scripting +* +* Available commands: +* - Execute a command: `{ command: "ls -la" }` +* - Restart the session: `{ restart: true }` +* +* @warning The bash tool provides direct system access. Implement safety measures +* such as running in isolated environments (Docker/VM), command filtering, +* and resource limits. +* +* @example +* ```typescript +* import { ChatAnthropic, tools } from "@langchain/anthropic"; +* import { execSync } from "child_process"; +* +* const llm = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* }); +* +* const bash = tools.bash_20250124({ +* execute: async (args) => { +* if (args.restart) { +* // Reset session state +* return "Bash session restarted"; +* } +* try { +* const output = execSync(args.command!, { +* encoding: "utf-8", +* timeout: 30000, +* }); +* return output; +* } catch (error) { +* return `Error: ${error.message}`; +* } +* }, +* }); +* +* const llmWithBash = llm.bindTools([bash]); +* const response = await llmWithBash.invoke( +* "List all Python files in the current directory" +* ); +* +* // Outputs: "bash" +* console.log(response.tool_calls[0].name); +* // Outputs: "ls -la *.py 2>/dev/null || echo \"No Python files found in the current directory\" +* console.log(response.tool_calls[0].args.command); +* ``` +* +* @example Multi-step automation +* ```typescript +* // Claude can chain commands in a persistent session: +* // 1. cd /tmp +* // 2. echo "Hello" > test.txt +* // 3. cat test.txt // Works because we're still in /tmp +* ``` +* +* @param options - Configuration options for the bash tool +* @param options.execute - Function that handles bash command execution +* @returns The bash tool object that can be passed to `bindTools` +* +* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/bash-tool +*/ +function bash_20250124(options) { + const name = "bash"; + const bashTool = tool(options?.execute, { + name, + description: "A tool for executing bash commands", + schema: Bash20250124CommandSchema + }); + bashTool.extras = { + ...bashTool.extras ?? {}, + providerToolDefinition: { + type: "bash_20250124", + name + } + }; + return bashTool; +} + +//#endregion + +//# sourceMappingURL=bash.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/mcpToolset.js +//#region src/tools/mcpToolset.ts +/** +* Creates an MCP toolset that connects to a remote MCP server to access its tools. +* This enables Claude to use tools from MCP servers without implementing a separate MCP client. +* +* @note This tool requires the beta header `mcp-client-2025-11-20` in API requests. +* The header is automatically added when using this tool. +* +* @see {@link https://docs.anthropic.com/en/docs/agents-and-tools/mcp-connector | Anthropic MCP Connector Documentation} +* @param options - Configuration options for the MCP toolset +* @returns An MCP toolset definition to be passed to the Anthropic API tools array +* +* @example +* ```typescript +* import { ChatAnthropic, tools } from "@langchain/anthropic"; +* +* const model = new ChatAnthropic({ +* model: "claude-sonnet-4-5-20250929", +* }); +* +* // Basic usage - enable all tools from an MCP server +* const response = await model.invoke("What tools do you have available?", { +* mcp_servers: [{ +* type: "url", +* url: "https://example-server.modelcontextprotocol.io/sse", +* name: "example-mcp", +* authorization_token: "YOUR_TOKEN", +* }], +* tools: [ +* tools.mcpToolset_20251120({ serverName: "example-mcp" }), +* ], +* }); +* +* // Allowlist pattern - enable only specific tools +* const responseAllowlist = await model.invoke("Search for events", { +* mcp_servers: [{ +* type: "url", +* url: "https://calendar.example.com/sse", +* name: "google-calendar-mcp", +* authorization_token: "YOUR_TOKEN", +* }], +* tools: [ +* tools.mcpToolset_20251120({ +* serverName: "google-calendar-mcp", +* defaultConfig: { enabled: false }, +* configs: { +* search_events: { enabled: true }, +* create_event: { enabled: true }, +* }, +* }), +* ], +* }); +* +* // Denylist pattern - disable specific tools +* const responseDenylist = await model.invoke("List my events", { +* mcp_servers: [{ +* type: "url", +* url: "https://calendar.example.com/sse", +* name: "google-calendar-mcp", +* authorization_token: "YOUR_TOKEN", +* }], +* tools: [ +* tools.mcpToolset_20251120({ +* serverName: "google-calendar-mcp", +* configs: { +* delete_all_events: { enabled: false }, +* share_calendar_publicly: { enabled: false }, +* }, +* }), +* ], +* }); +* +* // With deferred loading for use with Tool Search Tool +* const responseDeferred = await model.invoke("Search for tools", { +* mcp_servers: [{ +* type: "url", +* url: "https://example.com/sse", +* name: "example-mcp", +* }], +* tools: [ +* tools.toolSearchRegex_20251119(), +* tools.mcpToolset_20251120({ +* serverName: "example-mcp", +* defaultConfig: { deferLoading: true }, +* }), +* ], +* }); +* ``` +*/ +function mcpToolset_20251120(options) { + const defaultConfig = options.defaultConfig?.enabled !== void 0 || options.defaultConfig?.deferLoading !== void 0 ? { + enabled: options.defaultConfig?.enabled, + defer_loading: options.defaultConfig?.deferLoading + } : void 0; + const configs = options.configs ? Object.fromEntries(Object.entries(options.configs).map(([toolName, config]) => [toolName, { + enabled: config.enabled, + defer_loading: config.deferLoading + }])) : void 0; + return { + type: "mcp_toolset", + mcp_server_name: options.serverName, + default_config: defaultConfig, + configs, + cache_control: options.cacheControl + }; +} + +//#endregion + +//# sourceMappingURL=mcpToolset.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/index.js + + + + + + + + + + +//#region src/tools/index.ts +const tools = { + memory_20250818: memory_20250818, + webSearch_20250305: webSearch_20250305, + webFetch_20250910: webFetch_20250910, + toolSearchRegex_20251119: toolSearchRegex_20251119, + toolSearchBM25_20251119: toolSearchBM25_20251119, + textEditor_20250728: textEditor_20250728, + computer_20251124: computer_20251124, + computer_20250124: computer_20250124, + codeExecution_20250825: codeExecution_20250825, + bash_20250124: bash_20250124, + mcpToolset_20251120: mcpToolset_20251120 +}; + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/index.js + + + + + +;// CONCATENATED MODULE: ./src/providers/anthropic.provider.ts + +/** + * Anthropic Claude provider implementation + */ +class AnthropicProvider { + name = 'anthropic'; + apiKey; + constructor(apiKey) { + this.apiKey = apiKey || process.env.ANTHROPIC_API_KEY || ''; + } + isConfigured() { + return !!this.apiKey; + } + getDefaultModel() { + return 'claude-sonnet-4-5-20250929'; + } + getChatModel(config = {}) { + if (!this.isConfigured()) { + throw new Error('Anthropic API key is not configured'); + } + return new ChatAnthropic({ + apiKey: this.apiKey, + modelName: config.model || this.getDefaultModel(), + temperature: config.temperature ?? 0.2, + maxTokens: config.maxTokens ?? 4000, + }); + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/errors.js +//#region src/utils/errors.ts +function utils_errors_addLangChainErrorFields(error, lc_error_code) { + error.lc_error_code = lc_error_code; + error.message = `${error.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\n`; + return error; +} + +//#endregion + +//# sourceMappingURL=errors.js.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/tslib.mjs +function tslib_classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") + throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; +} +function tslib_classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) + throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) + throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + + +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/uuid.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * https://stackoverflow.com/a/2117523 + */ +let utils_uuid_uuid4 = function () { + const { crypto } = globalThis; + if (crypto?.randomUUID) { + utils_uuid_uuid4 = crypto.randomUUID.bind(crypto); + return crypto.randomUUID(); + } + const u8 = new Uint8Array(1); + const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff; + return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16)); +}; +//# sourceMappingURL=uuid.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/errors.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function errors_isAbortError(err) { + return (typeof err === 'object' && + err !== null && + // Spec-compliant fetch implementations + (('name' in err && err.name === 'AbortError') || + // Expo fetch + ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); +} +const errors_castToError = (err) => { + if (err instanceof Error) + return err; + if (typeof err === 'object' && err !== null) { + try { + if (Object.prototype.toString.call(err) === '[object Error]') { + // @ts-ignore - not all envs have native support for cause yet + const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); + if (err.stack) + error.stack = err.stack; + // @ts-ignore - not all envs have native support for cause yet + if (err.cause && !error.cause) + error.cause = err.cause; + if (err.name) + error.name = err.name; + return error; + } + } + catch { } + try { + return new Error(JSON.stringify(err)); + } + catch { } + } + return new Error(err); +}; +//# sourceMappingURL=errors.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/error.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class error_OpenAIError extends Error { +} +class error_APIError extends error_OpenAIError { + constructor(status, error, message, headers) { + super(`${error_APIError.makeMessage(status, error, message)}`); + this.status = status; + this.headers = headers; + this.requestID = headers?.get('x-request-id'); + this.error = error; + const data = error; + this.code = data?.['code']; + this.param = data?.['param']; + this.type = data?.['type']; + } + static makeMessage(status, error, message) { + const msg = error?.message ? + typeof error.message === 'string' ? + error.message + : JSON.stringify(error.message) + : error ? JSON.stringify(error) + : message; + if (status && msg) { + return `${status} ${msg}`; + } + if (status) { + return `${status} status code (no body)`; + } + if (msg) { + return msg; + } + return '(no status code or body)'; + } + static generate(status, errorResponse, message, headers) { + if (!status || !headers) { + return new error_APIConnectionError({ message, cause: errors_castToError(errorResponse) }); + } + const error = errorResponse?.['error']; + if (status === 400) { + return new error_BadRequestError(status, error, message, headers); + } + if (status === 401) { + return new error_AuthenticationError(status, error, message, headers); + } + if (status === 403) { + return new error_PermissionDeniedError(status, error, message, headers); + } + if (status === 404) { + return new error_NotFoundError(status, error, message, headers); + } + if (status === 409) { + return new error_ConflictError(status, error, message, headers); + } + if (status === 422) { + return new error_UnprocessableEntityError(status, error, message, headers); + } + if (status === 429) { + return new error_RateLimitError(status, error, message, headers); + } + if (status >= 500) { + return new error_InternalServerError(status, error, message, headers); + } + return new error_APIError(status, error, message, headers); + } +} +class error_APIUserAbortError extends error_APIError { + constructor({ message } = {}) { + super(undefined, undefined, message || 'Request was aborted.', undefined); + } +} +class error_APIConnectionError extends error_APIError { + constructor({ message, cause }) { + super(undefined, undefined, message || 'Connection error.', undefined); + // in some environments the 'cause' property is already declared + // @ts-ignore + if (cause) + this.cause = cause; + } +} +class error_APIConnectionTimeoutError extends error_APIConnectionError { + constructor({ message } = {}) { + super({ message: message ?? 'Request timed out.' }); + } +} +class error_BadRequestError extends error_APIError { +} +class error_AuthenticationError extends error_APIError { +} +class error_PermissionDeniedError extends error_APIError { +} +class error_NotFoundError extends error_APIError { +} +class error_ConflictError extends error_APIError { +} +class error_UnprocessableEntityError extends error_APIError { +} +class error_RateLimitError extends error_APIError { +} +class error_InternalServerError extends error_APIError { +} +class LengthFinishReasonError extends error_OpenAIError { + constructor() { + super(`Could not parse response content as the length limit was reached`); + } +} +class ContentFilterFinishReasonError extends error_OpenAIError { + constructor() { + super(`Could not parse response content as the request was rejected by the content filter`); + } +} +class InvalidWebhookSignatureError extends Error { + constructor(message) { + super(message); + } +} +//# sourceMappingURL=error.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/values.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +// https://url.spec.whatwg.org/#url-scheme-string +const values_startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; +const values_isAbsoluteURL = (url) => { + return values_startsWithSchemeRegexp.test(url); +}; +let utils_values_isArray = (val) => ((utils_values_isArray = Array.isArray), utils_values_isArray(val)); +let values_isReadonlyArray = utils_values_isArray; +/** Returns an object if the given value isn't an object, otherwise returns as-is */ +function values_maybeObj(x) { + if (typeof x !== 'object') { + return {}; + } + return x ?? {}; +} +// https://stackoverflow.com/a/34491287 +function values_isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +// https://eslint.org/docs/latest/rules/no-prototype-builtins +function values_hasOwn(obj, key) { + return Object.prototype.hasOwnProperty.call(obj, key); +} +function values_isObj(obj) { + return obj != null && typeof obj === 'object' && !Array.isArray(obj); +} +const values_ensurePresent = (value) => { + if (value == null) { + throw new OpenAIError(`Expected a value to be given but received ${value} instead.`); + } + return value; +}; +const values_validatePositiveInteger = (name, n) => { + if (typeof n !== 'number' || !Number.isInteger(n)) { + throw new error_OpenAIError(`${name} must be an integer`); + } + if (n < 0) { + throw new error_OpenAIError(`${name} must be a positive integer`); + } + return n; +}; +const values_coerceInteger = (value) => { + if (typeof value === 'number') + return Math.round(value); + if (typeof value === 'string') + return parseInt(value, 10); + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +const values_coerceFloat = (value) => { + if (typeof value === 'number') + return value; + if (typeof value === 'string') + return parseFloat(value); + throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); +}; +const values_coerceBoolean = (value) => { + if (typeof value === 'boolean') + return value; + if (typeof value === 'string') + return value === 'true'; + return Boolean(value); +}; +const values_maybeCoerceInteger = (value) => { + if (value == null) { + return undefined; + } + return values_coerceInteger(value); +}; +const values_maybeCoerceFloat = (value) => { + if (value == null) { + return undefined; + } + return values_coerceFloat(value); +}; +const values_maybeCoerceBoolean = (value) => { + if (value == null) { + return undefined; + } + return values_coerceBoolean(value); +}; +const values_safeJSON = (text) => { + try { + return JSON.parse(text); + } + catch (err) { + return undefined; + } +}; +//# sourceMappingURL=values.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/sleep.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const sleep_sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); +//# sourceMappingURL=sleep.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/version.mjs +const version_VERSION = '6.15.0'; // x-release-please-version +//# sourceMappingURL=version.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/detect-platform.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const detect_platform_isRunningInBrowser = () => { + return ( + // @ts-ignore + typeof window !== 'undefined' && + // @ts-ignore + typeof window.document !== 'undefined' && + // @ts-ignore + typeof navigator !== 'undefined'); +}; +/** + * Note this does not detect 'browser'; for that, use getBrowserInfo(). + */ +function detect_platform_getDetectedPlatform() { + if (typeof Deno !== 'undefined' && Deno.build != null) { + return 'deno'; + } + if (typeof EdgeRuntime !== 'undefined') { + return 'edge'; + } + if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') { + return 'node'; + } + return 'unknown'; +} +const detect_platform_getPlatformProperties = () => { + const detectedPlatform = detect_platform_getDetectedPlatform(); + if (detectedPlatform === 'deno') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_VERSION, + 'X-Stainless-OS': detect_platform_normalizePlatform(Deno.build.os), + 'X-Stainless-Arch': detect_platform_normalizeArch(Deno.build.arch), + 'X-Stainless-Runtime': 'deno', + 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', + }; + } + if (typeof EdgeRuntime !== 'undefined') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': `other:${EdgeRuntime}`, + 'X-Stainless-Runtime': 'edge', + 'X-Stainless-Runtime-Version': globalThis.process.version, + }; + } + // Check if Node.js + if (detectedPlatform === 'node') { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_VERSION, + 'X-Stainless-OS': detect_platform_normalizePlatform(globalThis.process.platform ?? 'unknown'), + 'X-Stainless-Arch': detect_platform_normalizeArch(globalThis.process.arch ?? 'unknown'), + 'X-Stainless-Runtime': 'node', + 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown', + }; + } + const browserInfo = detect_platform_getBrowserInfo(); + if (browserInfo) { + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, + 'X-Stainless-Runtime-Version': browserInfo.version, + }; + } + // TODO add support for Cloudflare workers, etc. + return { + 'X-Stainless-Lang': 'js', + 'X-Stainless-Package-Version': version_VERSION, + 'X-Stainless-OS': 'Unknown', + 'X-Stainless-Arch': 'unknown', + 'X-Stainless-Runtime': 'unknown', + 'X-Stainless-Runtime-Version': 'unknown', + }; +}; +// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts +function detect_platform_getBrowserInfo() { + if (typeof navigator === 'undefined' || !navigator) { + return null; + } + // NOTE: The order matters here! + const browserPatterns = [ + { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, + { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, + ]; + // Find the FIRST matching browser + for (const { key, pattern } of browserPatterns) { + const match = pattern.exec(navigator.userAgent); + if (match) { + const major = match[1] || 0; + const minor = match[2] || 0; + const patch = match[3] || 0; + return { browser: key, version: `${major}.${minor}.${patch}` }; + } + } + return null; +} +const detect_platform_normalizeArch = (arch) => { + // Node docs: + // - https://nodejs.org/api/process.html#processarch + // Deno docs: + // - https://doc.deno.land/deno/stable/~/Deno.build + if (arch === 'x32') + return 'x32'; + if (arch === 'x86_64' || arch === 'x64') + return 'x64'; + if (arch === 'arm') + return 'arm'; + if (arch === 'aarch64' || arch === 'arm64') + return 'arm64'; + if (arch) + return `other:${arch}`; + return 'unknown'; +}; +const detect_platform_normalizePlatform = (platform) => { + // Node platforms: + // - https://nodejs.org/api/process.html#processplatform + // Deno platforms: + // - https://doc.deno.land/deno/stable/~/Deno.build + // - https://github.com/denoland/deno/issues/14799 + platform = platform.toLowerCase(); + // NOTE: this iOS check is untested and may not work + // Node does not work natively on IOS, there is a fork at + // https://github.com/nodejs-mobile/nodejs-mobile + // however it is unknown at the time of writing how to detect if it is running + if (platform.includes('ios')) + return 'iOS'; + if (platform === 'android') + return 'Android'; + if (platform === 'darwin') + return 'MacOS'; + if (platform === 'win32') + return 'Windows'; + if (platform === 'freebsd') + return 'FreeBSD'; + if (platform === 'openbsd') + return 'OpenBSD'; + if (platform === 'linux') + return 'Linux'; + if (platform) + return `Other:${platform}`; + return 'Unknown'; +}; +let detect_platform_platformHeaders; +const detect_platform_getPlatformHeaders = () => { + return (detect_platform_platformHeaders ?? (detect_platform_platformHeaders = detect_platform_getPlatformProperties())); +}; +//# sourceMappingURL=detect-platform.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/shims.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +function shims_getDefaultFetch() { + if (typeof fetch !== 'undefined') { + return fetch; + } + throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); +} +function shims_makeReadableStream(...args) { + const ReadableStream = globalThis.ReadableStream; + if (typeof ReadableStream === 'undefined') { + // Note: All of the platforms / runtimes we officially support already define + // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. + throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); + } + return new ReadableStream(...args); +} +function shims_ReadableStreamFrom(iterable) { + let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); + return shims_makeReadableStream({ + start() { }, + async pull(controller) { + const { done, value } = await iter.next(); + if (done) { + controller.close(); + } + else { + controller.enqueue(value); + } + }, + async cancel() { + await iter.return?.(); + }, + }); +} +/** + * Most browsers don't yet have async iterable support for ReadableStream, + * and Node has a very different way of reading bytes from its "ReadableStream". + * + * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 + */ +function shims_ReadableStreamToAsyncIterable(stream) { + if (stream[Symbol.asyncIterator]) + return stream; + const reader = stream.getReader(); + return { + async next() { + try { + const result = await reader.read(); + if (result?.done) + reader.releaseLock(); // release lock when stream becomes closed + return result; + } + catch (e) { + reader.releaseLock(); // release lock when stream becomes errored + throw e; + } + }, + async return() { + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; + return { done: true, value: undefined }; + }, + [Symbol.asyncIterator]() { + return this; + }, + }; +} +/** + * Cancels a ReadableStream we don't need to consume. + * See https://undici.nodejs.org/#/?id=garbage-collection + */ +async function shims_CancelReadableStream(stream) { + if (stream === null || typeof stream !== 'object') + return; + if (stream[Symbol.asyncIterator]) { + await stream[Symbol.asyncIterator]().return?.(); + return; + } + const reader = stream.getReader(); + const cancelPromise = reader.cancel(); + reader.releaseLock(); + await cancelPromise; +} +//# sourceMappingURL=shims.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/request-options.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +const request_options_FallbackEncoder = ({ headers, body }) => { + return { + bodyHeaders: { + 'content-type': 'application/json', + }, + body: JSON.stringify(body), + }; +}; +//# sourceMappingURL=request-options.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/formats.mjs +const default_format = 'RFC3986'; +const default_formatter = (v) => String(v); +const formatters = { + RFC1738: (v) => String(v).replace(/%20/g, '+'), + RFC3986: default_formatter, +}; +const RFC1738 = 'RFC1738'; +const RFC3986 = 'RFC3986'; +//# sourceMappingURL=formats.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/utils.mjs + + +let has = (obj, key) => ((has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty)), + has(obj, key)); +const hex_table = /* @__PURE__ */ (() => { + const array = []; + for (let i = 0; i < 256; ++i) { + array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); + } + return array; +})(); +function compact_queue(queue) { + while (queue.length > 1) { + const item = queue.pop(); + if (!item) + continue; + const obj = item.obj[item.prop]; + if (isArray(obj)) { + const compacted = []; + for (let j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted.push(obj[j]); + } + } + // @ts-ignore + item.obj[item.prop] = compacted; + } + } +} +function array_to_object(source, options) { + const obj = options && options.plainObjects ? Object.create(null) : {}; + for (let i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + return obj; +} +function utils_merge(target, source, options = {}) { + if (!source) { + return target; + } + if (typeof source !== 'object') { + if (isArray(target)) { + target.push(source); + } + else if (target && typeof target === 'object') { + if ((options && (options.plainObjects || options.allowPrototypes)) || !has(Object.prototype, source)) { + target[source] = true; + } + } + else { + return [target, source]; + } + return target; + } + if (!target || typeof target !== 'object') { + return [target].concat(source); + } + let mergeTarget = target; + if (isArray(target) && !isArray(source)) { + // @ts-ignore + mergeTarget = array_to_object(target, options); + } + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has(target, i)) { + const targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = utils_merge(targetItem, item, options); + } + else { + target.push(item); + } + } + else { + target[i] = item; + } + }); + return target; + } + return Object.keys(source).reduce(function (acc, key) { + const value = source[key]; + if (has(acc, key)) { + acc[key] = utils_merge(acc[key], value, options); + } + else { + acc[key] = value; + } + return acc; + }, mergeTarget); +} +function assign_single_source(target, source) { + return Object.keys(source).reduce(function (acc, key) { + acc[key] = source[key]; + return acc; + }, target); +} +function utils_decode(str, _, charset) { + const strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } + catch (e) { + return strWithoutPlus; + } +} +const limit = 1024; +const utils_encode = (str, _defaultEncoder, charset, _kind, format) => { + // This code was originally written by Brian White for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + let string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } + else if (typeof str !== 'string') { + string = String(str); + } + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + let out = ''; + for (let j = 0; j < string.length; j += limit) { + const segment = string.length >= limit ? string.slice(j, j + limit) : string; + const arr = []; + for (let i = 0; i < segment.length; ++i) { + let c = segment.charCodeAt(i); + if (c === 0x2d || // - + c === 0x2e || // . + c === 0x5f || // _ + c === 0x7e || // ~ + (c >= 0x30 && c <= 0x39) || // 0-9 + (c >= 0x41 && c <= 0x5a) || // a-z + (c >= 0x61 && c <= 0x7a) || // A-Z + (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + arr[arr.length] = segment.charAt(i); + continue; + } + if (c < 0x80) { + arr[arr.length] = hex_table[c]; + continue; + } + if (c < 0x800) { + arr[arr.length] = hex_table[0xc0 | (c >> 6)] + hex_table[0x80 | (c & 0x3f)]; + continue; + } + if (c < 0xd800 || c >= 0xe000) { + arr[arr.length] = + hex_table[0xe0 | (c >> 12)] + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)]; + continue; + } + i += 1; + c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff)); + arr[arr.length] = + hex_table[0xf0 | (c >> 18)] + + hex_table[0x80 | ((c >> 12) & 0x3f)] + + hex_table[0x80 | ((c >> 6) & 0x3f)] + + hex_table[0x80 | (c & 0x3f)]; + } + out += arr.join(''); + } + return out; +}; +function compact(value) { + const queue = [{ obj: { o: value }, prop: 'o' }]; + const refs = []; + for (let i = 0; i < queue.length; ++i) { + const item = queue[i]; + // @ts-ignore + const obj = item.obj[item.prop]; + const keys = Object.keys(obj); + for (let j = 0; j < keys.length; ++j) { + const key = keys[j]; + const val = obj[key]; + if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { + queue.push({ obj: obj, prop: key }); + refs.push(val); + } + } + } + compact_queue(queue); + return value; +} +function is_regexp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; +} +function is_buffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); +} +function combine(a, b) { + return [].concat(a, b); +} +function maybe_map(val, fn) { + if (utils_values_isArray(val)) { + const mapped = []; + for (let i = 0; i < val.length; i += 1) { + mapped.push(fn(val[i])); + } + return mapped; + } + return fn(val); +} +//# sourceMappingURL=utils.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/stringify.mjs + + + +const array_prefix_generators = { + brackets(prefix) { + return String(prefix) + '[]'; + }, + comma: 'comma', + indices(prefix, key) { + return String(prefix) + '[' + key + ']'; + }, + repeat(prefix) { + return String(prefix); + }, +}; +const push_to_array = function (arr, value_or_array) { + Array.prototype.push.apply(arr, utils_values_isArray(value_or_array) ? value_or_array : [value_or_array]); +}; +let toISOString; +const defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: 'indices', + charset: 'utf-8', + charsetSentinel: false, + delimiter: '&', + encode: true, + encodeDotInKeys: false, + encoder: utils_encode, + encodeValuesOnly: false, + format: default_format, + formatter: default_formatter, + /** @deprecated */ + indices: false, + serializeDate(date) { + return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); + }, + skipNulls: false, + strictNullHandling: false, +}; +function is_non_nullish_primitive(v) { + return (typeof v === 'string' || + typeof v === 'number' || + typeof v === 'boolean' || + typeof v === 'symbol' || + typeof v === 'bigint'); +} +const sentinel = {}; +function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { + let obj = object; + let tmp_sc = sideChannel; + let step = 0; + let find_flag = false; + while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) { + // Where object last appeared in the ref tree + const pos = tmp_sc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } + else { + find_flag = true; // Break while + } + } + if (typeof tmp_sc.get(sentinel) === 'undefined') { + step = 0; + } + } + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } + else if (obj instanceof Date) { + obj = serializeDate?.(obj); + } + else if (generateArrayPrefix === 'comma' && utils_values_isArray(obj)) { + obj = maybe_map(obj, function (value) { + if (value instanceof Date) { + return serializeDate?.(value); + } + return value; + }); + } + if (obj === null) { + if (strictNullHandling) { + return encoder && !encodeValuesOnly ? + // @ts-expect-error + encoder(prefix, defaults.encoder, charset, 'key', format) + : prefix; + } + obj = ''; + } + if (is_non_nullish_primitive(obj) || is_buffer(obj)) { + if (encoder) { + const key_value = encodeValuesOnly ? prefix + // @ts-expect-error + : encoder(prefix, defaults.encoder, charset, 'key', format); + return [ + formatter?.(key_value) + + '=' + + // @ts-expect-error + formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)), + ]; + } + return [formatter?.(prefix) + '=' + formatter?.(String(obj))]; + } + const values = []; + if (typeof obj === 'undefined') { + return values; + } + let obj_keys; + if (generateArrayPrefix === 'comma' && utils_values_isArray(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + // @ts-expect-error values only + obj = maybe_map(obj, encoder); + } + obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } + else if (utils_values_isArray(filter)) { + obj_keys = filter; + } + else { + const keys = Object.keys(obj); + obj_keys = sort ? keys.sort(sort) : keys; + } + const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); + const adjusted_prefix = commaRoundTrip && utils_values_isArray(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; + if (allowEmptyArrays && utils_values_isArray(obj) && obj.length === 0) { + return adjusted_prefix + '[]'; + } + for (let j = 0; j < obj_keys.length; ++j) { + const key = obj_keys[j]; + const value = + // @ts-ignore + typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; + if (skipNulls && value === null) { + continue; + } + // @ts-ignore + const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, '%2E') : key; + const key_prefix = utils_values_isArray(obj) ? + typeof generateArrayPrefix === 'function' ? + generateArrayPrefix(adjusted_prefix, encoded_key) + : adjusted_prefix + : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']'); + sideChannel.set(object, step); + const valueSideChannel = new WeakMap(); + valueSideChannel.set(sentinel, sideChannel); + push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, + // @ts-ignore + generateArrayPrefix === 'comma' && encodeValuesOnly && utils_values_isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); + } + return values; +} +function normalize_stringify_options(opts = defaults) { + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { + throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); + } + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + const charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + let format = default_format; + if (typeof opts.format !== 'undefined') { + if (!has(formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + const formatter = formatters[format]; + let filter = defaults.filter; + if (typeof opts.filter === 'function' || utils_values_isArray(opts.filter)) { + filter = opts.filter; + } + let arrayFormat; + if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { + arrayFormat = opts.arrayFormat; + } + else if ('indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } + else { + arrayFormat = defaults.arrayFormat; + } + if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + const allowDots = typeof opts.allowDots === 'undefined' ? + !!opts.encodeDotInKeys === true ? + true + : defaults.allowDots + : !!opts.allowDots; + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + // @ts-ignore + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat: arrayFormat, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + // @ts-ignore + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, + }; +} +function stringify_stringify(object, opts = {}) { + let obj = object; + const options = normalize_stringify_options(opts); + let obj_keys; + let filter; + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } + else if (utils_values_isArray(options.filter)) { + filter = options.filter; + obj_keys = filter; + } + const keys = []; + if (typeof obj !== 'object' || obj === null) { + return ''; + } + const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; + const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; + if (!obj_keys) { + obj_keys = Object.keys(obj); + } + if (options.sort) { + obj_keys.sort(options.sort); + } + const sideChannel = new WeakMap(); + for (let i = 0; i < obj_keys.length; ++i) { + const key = obj_keys[i]; + if (options.skipNulls && obj[key] === null) { + continue; + } + push_to_array(keys, inner_stringify(obj[key], key, + // @ts-expect-error + generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); + } + const joined = keys.join(options.delimiter); + let prefix = options.addQueryPrefix === true ? '?' : ''; + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B&'; + } + else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93&'; + } + } + return joined.length > 0 ? prefix + joined : ''; +} +//# sourceMappingURL=stringify.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/index.mjs + +const formats = { + formatters: formatters, + RFC1738: RFC1738, + RFC3986: RFC3986, + default: default_format, +}; + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/bytes.mjs +function bytes_concatBytes(buffers) { + let length = 0; + for (const buffer of buffers) { + length += buffer.length; + } + const output = new Uint8Array(length); + let index = 0; + for (const buffer of buffers) { + output.set(buffer, index); + index += buffer.length; + } + return output; +} +let bytes_encodeUTF8_; +function utils_bytes_encodeUTF8(str) { + let encoder; + return (bytes_encodeUTF8_ ?? + ((encoder = new globalThis.TextEncoder()), (bytes_encodeUTF8_ = encoder.encode.bind(encoder))))(str); +} +let bytes_decodeUTF8_; +function bytes_decodeUTF8(bytes) { + let decoder; + return (bytes_decodeUTF8_ ?? + ((decoder = new globalThis.TextDecoder()), (bytes_decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); +} +//# sourceMappingURL=bytes.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/decoders/line.mjs +var line_LineDecoder_buffer, line_LineDecoder_carriageReturnIndex; + + +/** + * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally + * reading lines from text. + * + * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 + */ +class line_LineDecoder { + constructor() { + line_LineDecoder_buffer.set(this, void 0); + line_LineDecoder_carriageReturnIndex.set(this, void 0); + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, new Uint8Array(), "f"); + tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); + } + decode(chunk) { + if (chunk == null) { + return []; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? utils_bytes_encodeUTF8(chunk) + : chunk; + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, bytes_concatBytes([tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f"), binaryChunk]), "f"); + const lines = []; + let patternIndex; + while ((patternIndex = line_findNewlineIndex(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f"), tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f"))) != null) { + if (patternIndex.carriage && tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") == null) { + // skip until we either get a corresponding `\n`, a new `\r` or nothing + tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, patternIndex.index, "f"); + continue; + } + // we got double \r or \rtext\n + if (tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") != null && + (patternIndex.index !== tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { + lines.push(bytes_decodeUTF8(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(0, tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") - 1))); + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f")), "f"); + tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); + continue; + } + const endIndex = tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; + const line = bytes_decodeUTF8(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(0, endIndex)); + lines.push(line); + tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); + tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); + } + return lines; + } + flush() { + if (!tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").length) { + return []; + } + return this.decode('\n'); + } +} +line_LineDecoder_buffer = new WeakMap(), line_LineDecoder_carriageReturnIndex = new WeakMap(); +// prettier-ignore +line_LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); +line_LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; +/** + * This function searches the buffer for the end patterns, (\r or \n) + * and returns an object with the index preceding the matched newline and the + * index after the newline char. `null` is returned if no new line is found. + * + * ```ts + * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } + * ``` + */ +function line_findNewlineIndex(buffer, startIndex) { + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = startIndex ?? 0; i < buffer.length; i++) { + if (buffer[i] === newline) { + return { preceding: i, index: i + 1, carriage: false }; + } + if (buffer[i] === carriage) { + return { preceding: i, index: i + 1, carriage: true }; + } + } + return null; +} +function line_findDoubleNewlineIndex(buffer) { + // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) + // and returns the index right after the first occurrence of any pattern, + // or -1 if none of the patterns are found. + const newline = 0x0a; // \n + const carriage = 0x0d; // \r + for (let i = 0; i < buffer.length - 1; i++) { + if (buffer[i] === newline && buffer[i + 1] === newline) { + // \n\n + return i + 2; + } + if (buffer[i] === carriage && buffer[i + 1] === carriage) { + // \r\r + return i + 2; + } + if (buffer[i] === carriage && + buffer[i + 1] === newline && + i + 3 < buffer.length && + buffer[i + 2] === carriage && + buffer[i + 3] === newline) { + // \r\n\r\n + return i + 4; + } + } + return -1; +} +//# sourceMappingURL=line.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/log.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const log_levelNumbers = { + off: 0, + error: 200, + warn: 300, + info: 400, + debug: 500, +}; +const log_parseLogLevel = (maybeLevel, sourceName, client) => { + if (!maybeLevel) { + return undefined; + } + if (values_hasOwn(log_levelNumbers, maybeLevel)) { + return maybeLevel; + } + log_loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(log_levelNumbers))}`); + return undefined; +}; +function log_noop() { } +function log_makeLogFn(fnLevel, logger, logLevel) { + if (!logger || log_levelNumbers[fnLevel] > log_levelNumbers[logLevel]) { + return log_noop; + } + else { + // Don't wrap logger functions, we want the stacktrace intact! + return logger[fnLevel].bind(logger); + } +} +const log_noopLogger = { + error: log_noop, + warn: log_noop, + info: log_noop, + debug: log_noop, +}; +let log_cachedLoggers = /* @__PURE__ */ new WeakMap(); +function log_loggerFor(client) { + const logger = client.logger; + const logLevel = client.logLevel ?? 'off'; + if (!logger) { + return log_noopLogger; + } + const cachedLogger = log_cachedLoggers.get(logger); + if (cachedLogger && cachedLogger[0] === logLevel) { + return cachedLogger[1]; + } + const levelLogger = { + error: log_makeLogFn('error', logger, logLevel), + warn: log_makeLogFn('warn', logger, logLevel), + info: log_makeLogFn('info', logger, logLevel), + debug: log_makeLogFn('debug', logger, logLevel), + }; + log_cachedLoggers.set(logger, [logLevel, levelLogger]); + return levelLogger; +} +const log_formatRequestDetails = (details) => { + if (details.options) { + details.options = { ...details.options }; + delete details.options['headers']; // redundant + leaks internals + } + if (details.headers) { + details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ + name, + (name.toLowerCase() === 'authorization' || + name.toLowerCase() === 'cookie' || + name.toLowerCase() === 'set-cookie') ? + '***' + : value, + ])); + } + if ('retryOfRequestLogID' in details) { + if (details.retryOfRequestLogID) { + details.retryOf = details.retryOfRequestLogID; + } + delete details.retryOfRequestLogID; + } + return details; +}; +//# sourceMappingURL=log.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/streaming.mjs +var streaming_Stream_client; + + + + + + + + + +class streaming_Stream { + constructor(iterator, controller, client) { + this.iterator = iterator; + streaming_Stream_client.set(this, void 0); + this.controller = controller; + tslib_classPrivateFieldSet(this, streaming_Stream_client, client, "f"); + } + static fromSSEResponse(response, controller, client) { + let consumed = false; + const logger = client ? log_loggerFor(client) : console; + async function* iterator() { + if (consumed) { + throw new error_OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const sse of streaming_iterSSEMessages(response, controller)) { + if (done) + continue; + if (sse.data.startsWith('[DONE]')) { + done = true; + continue; + } + if (sse.event === null || !sse.event.startsWith('thread.')) { + let data; + try { + data = JSON.parse(sse.data); + } + catch (e) { + logger.error(`Could not parse message into JSON:`, sse.data); + logger.error(`From chunk:`, sse.raw); + throw e; + } + if (data && data.error) { + throw new error_APIError(undefined, data.error, undefined, response.headers); + } + yield data; + } + else { + let data; + try { + data = JSON.parse(sse.data); + } + catch (e) { + console.error(`Could not parse message into JSON:`, sse.data); + console.error(`From chunk:`, sse.raw); + throw e; + } + // TODO: Is this where the error should be thrown? + if (sse.event == 'error') { + throw new error_APIError(undefined, data.error, data.message, undefined); + } + yield { event: sse.event, data: data }; + } + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (errors_isAbortError(e)) + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new streaming_Stream(iterator, controller, client); + } + /** + * Generates a Stream from a newline-separated ReadableStream + * where each item is a JSON value. + */ + static fromReadableStream(readableStream, controller, client) { + let consumed = false; + async function* iterLines() { + const lineDecoder = new line_LineDecoder(); + const iter = shims_ReadableStreamToAsyncIterable(readableStream); + for await (const chunk of iter) { + for (const line of lineDecoder.decode(chunk)) { + yield line; + } + } + for (const line of lineDecoder.flush()) { + yield line; + } + } + async function* iterator() { + if (consumed) { + throw new error_OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); + } + consumed = true; + let done = false; + try { + for await (const line of iterLines()) { + if (done) + continue; + if (line) + yield JSON.parse(line); + } + done = true; + } + catch (e) { + // If the user calls `stream.controller.abort()`, we should exit without throwing. + if (errors_isAbortError(e)) + return; + throw e; + } + finally { + // If the user `break`s, abort the ongoing request. + if (!done) + controller.abort(); + } + } + return new streaming_Stream(iterator, controller, client); + } + [(streaming_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { + return this.iterator(); + } + /** + * Splits the stream into two streams which can be + * independently read from at different speeds. + */ + tee() { + const left = []; + const right = []; + const iterator = this.iterator(); + const teeIterator = (queue) => { + return { + next: () => { + if (queue.length === 0) { + const result = iterator.next(); + left.push(result); + right.push(result); + } + return queue.shift(); + }, + }; + }; + return [ + new streaming_Stream(() => teeIterator(left), this.controller, tslib_classPrivateFieldGet(this, streaming_Stream_client, "f")), + new streaming_Stream(() => teeIterator(right), this.controller, tslib_classPrivateFieldGet(this, streaming_Stream_client, "f")), + ]; + } + /** + * Converts this stream to a newline-separated ReadableStream of + * JSON stringified values in the stream + * which can be turned back into a Stream with `Stream.fromReadableStream()`. + */ + toReadableStream() { + const self = this; + let iter; + return shims_makeReadableStream({ + async start() { + iter = self[Symbol.asyncIterator](); + }, + async pull(ctrl) { + try { + const { value, done } = await iter.next(); + if (done) + return ctrl.close(); + const bytes = utils_bytes_encodeUTF8(JSON.stringify(value) + '\n'); + ctrl.enqueue(bytes); + } + catch (err) { + ctrl.error(err); + } + }, + async cancel() { + await iter.return?.(); + }, + }); + } +} +async function* streaming_iterSSEMessages(response, controller) { + if (!response.body) { + controller.abort(); + if (typeof globalThis.navigator !== 'undefined' && + globalThis.navigator.product === 'ReactNative') { + throw new error_OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); + } + throw new error_OpenAIError(`Attempted to iterate over a response with no body`); + } + const sseDecoder = new streaming_SSEDecoder(); + const lineDecoder = new line_LineDecoder(); + const iter = shims_ReadableStreamToAsyncIterable(response.body); + for await (const sseChunk of streaming_iterSSEChunks(iter)) { + for (const line of lineDecoder.decode(sseChunk)) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } + } + for (const line of lineDecoder.flush()) { + const sse = sseDecoder.decode(line); + if (sse) + yield sse; + } +} +/** + * Given an async iterable iterator, iterates over it and yields full + * SSE chunks, i.e. yields when a double new-line is encountered. + */ +async function* streaming_iterSSEChunks(iterator) { + let data = new Uint8Array(); + for await (const chunk of iterator) { + if (chunk == null) { + continue; + } + const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) + : typeof chunk === 'string' ? utils_bytes_encodeUTF8(chunk) + : chunk; + let newData = new Uint8Array(data.length + binaryChunk.length); + newData.set(data); + newData.set(binaryChunk, data.length); + data = newData; + let patternIndex; + while ((patternIndex = line_findDoubleNewlineIndex(data)) !== -1) { + yield data.slice(0, patternIndex); + data = data.slice(patternIndex); + } + } + if (data.length > 0) { + yield data; + } +} +class streaming_SSEDecoder { + constructor() { + this.event = null; + this.data = []; + this.chunks = []; + } + decode(line) { + if (line.endsWith('\r')) { + line = line.substring(0, line.length - 1); + } + if (!line) { + // empty line and we didn't previously encounter any messages + if (!this.event && !this.data.length) + return null; + const sse = { + event: this.event, + data: this.data.join('\n'), + raw: this.chunks, + }; + this.event = null; + this.data = []; + this.chunks = []; + return sse; + } + this.chunks.push(line); + if (line.startsWith(':')) { + return null; + } + let [fieldname, _, value] = streaming_partition(line, ':'); + if (value.startsWith(' ')) { + value = value.substring(1); + } + if (fieldname === 'event') { + this.event = value; + } + else if (fieldname === 'data') { + this.data.push(value); + } + return null; + } +} +function streaming_partition(str, delimiter) { + const index = str.indexOf(delimiter); + if (index !== -1) { + return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; + } + return [str, '', '']; +} +//# sourceMappingURL=streaming.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/parse.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +async function parse_defaultParseResponse(client, props) { + const { response, requestLogID, retryOfRequestLogID, startTime } = props; + const body = await (async () => { + if (props.options.stream) { + log_loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); + // Note: there is an invariant here that isn't represented in the type system + // that if you set `stream: true` the response type must also be `Stream` + if (props.options.__streamClass) { + return props.options.__streamClass.fromSSEResponse(response, props.controller, client); + } + return streaming_Stream.fromSSEResponse(response, props.controller, client); + } + // fetch refuses to read the body when the status code is 204. + if (response.status === 204) { + return null; + } + if (props.options.__binaryResponse) { + return response; + } + const contentType = response.headers.get('content-type'); + const mediaType = contentType?.split(';')[0]?.trim(); + const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); + if (isJSON) { + const json = await response.json(); + return parse_addRequestID(json, response); + } + const text = await response.text(); + return text; + })(); + log_loggerFor(client).debug(`[${requestLogID}] response parsed`, log_formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + body, + durationMs: Date.now() - startTime, + })); + return body; +} +function parse_addRequestID(value, response) { + if (!value || typeof value !== 'object' || Array.isArray(value)) { + return value; + } + return Object.defineProperty(value, '_request_id', { + value: response.headers.get('x-request-id'), + enumerable: false, + }); +} +//# sourceMappingURL=parse.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/api-promise.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var api_promise_APIPromise_client; + + +/** + * A subclass of `Promise` providing additional helper methods + * for interacting with the SDK. + */ +class api_promise_APIPromise extends Promise { + constructor(client, responsePromise, parseResponse = parse_defaultParseResponse) { + super((resolve) => { + // this is maybe a bit weird but this has to be a no-op to not implicitly + // parse the response body; instead .then, .catch, .finally are overridden + // to parse the response + resolve(null); + }); + this.responsePromise = responsePromise; + this.parseResponse = parseResponse; + api_promise_APIPromise_client.set(this, void 0); + tslib_classPrivateFieldSet(this, api_promise_APIPromise_client, client, "f"); + } + _thenUnwrap(transform) { + return new api_promise_APIPromise(tslib_classPrivateFieldGet(this, api_promise_APIPromise_client, "f"), this.responsePromise, async (client, props) => parse_addRequestID(transform(await this.parseResponse(client, props), props), props.response)); + } + /** + * Gets the raw `Response` instance instead of parsing the response + * data. + * + * If you want to parse the response body but still get the `Response` + * instance, you can use {@link withResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + asResponse() { + return this.responsePromise.then((p) => p.response); + } + /** + * Gets the parsed response data, the raw `Response` instance and the ID of the request, + * returned via the X-Request-ID header which is useful for debugging requests and reporting + * issues to OpenAI. + * + * If you just want to get the raw `Response` instance without parsing it, + * you can use {@link asResponse()}. + * + * 👋 Getting the wrong TypeScript type for `Response`? + * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` + * to your `tsconfig.json`. + */ + async withResponse() { + const [data, response] = await Promise.all([this.parse(), this.asResponse()]); + return { data, response, request_id: response.headers.get('x-request-id') }; + } + parse() { + if (!this.parsedPromise) { + this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(tslib_classPrivateFieldGet(this, api_promise_APIPromise_client, "f"), data)); + } + return this.parsedPromise; + } + then(onfulfilled, onrejected) { + return this.parse().then(onfulfilled, onrejected); + } + catch(onrejected) { + return this.parse().catch(onrejected); + } + finally(onfinally) { + return this.parse().finally(onfinally); + } +} +api_promise_APIPromise_client = new WeakMap(); +//# sourceMappingURL=api-promise.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/pagination.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var pagination_AbstractPage_client; + + + + + +class pagination_AbstractPage { + constructor(client, response, body, options) { + pagination_AbstractPage_client.set(this, void 0); + tslib_classPrivateFieldSet(this, pagination_AbstractPage_client, client, "f"); + this.options = options; + this.response = response; + this.body = body; + } + hasNextPage() { + const items = this.getPaginatedItems(); + if (!items.length) + return false; + return this.nextPageRequestOptions() != null; + } + async getNextPage() { + const nextOptions = this.nextPageRequestOptions(); + if (!nextOptions) { + throw new error_OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); + } + return await tslib_classPrivateFieldGet(this, pagination_AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); + } + async *iterPages() { + let page = this; + yield page; + while (page.hasNextPage()) { + page = await page.getNextPage(); + yield page; + } + } + async *[(pagination_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { + for await (const page of this.iterPages()) { + for (const item of page.getPaginatedItems()) { + yield item; + } + } + } +} +/** + * This subclass of Promise will resolve to an instantiated Page once the request completes. + * + * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ +class pagination_PagePromise extends api_promise_APIPromise { + constructor(client, request, Page) { + super(client, request, async (client, props) => new Page(client, props.response, await parse_defaultParseResponse(client, props), props.options)); + } + /** + * Allow auto-paginating iteration on an unawaited list call, eg: + * + * for await (const item of client.items.list()) { + * console.log(item) + * } + */ + async *[Symbol.asyncIterator]() { + const page = await this; + for await (const item of page) { + yield item; + } + } +} +/** + * Note: no pagination actually occurs yet, this is for forwards-compatibility. + */ +class pagination_Page extends pagination_AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.object = body.object; + } + getPaginatedItems() { + return this.data ?? []; + } + nextPageRequestOptions() { + return null; + } +} +class CursorPage extends pagination_AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + const data = this.getPaginatedItems(); + const id = data[data.length - 1]?.id; + if (!id) { + return null; + } + return { + ...this.options, + query: { + ...values_maybeObj(this.options.query), + after: id, + }, + }; + } +} +class ConversationCursorPage extends pagination_AbstractPage { + constructor(client, response, body, options) { + super(client, response, body, options); + this.data = body.data || []; + this.has_more = body.has_more || false; + this.last_id = body.last_id || ''; + } + getPaginatedItems() { + return this.data ?? []; + } + hasNextPage() { + if (this.has_more === false) { + return false; + } + return super.hasNextPage(); + } + nextPageRequestOptions() { + const cursor = this.last_id; + if (!cursor) { + return null; + } + return { + ...this.options, + query: { + ...values_maybeObj(this.options.query), + after: cursor, + }, + }; + } +} +//# sourceMappingURL=pagination.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/uploads.mjs + +const uploads_checkFileSupport = () => { + if (typeof File === 'undefined') { + const { process } = globalThis; + const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; + throw new Error('`File` is not defined as a global, which is required for file uploads.' + + (isOldNode ? + " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." + : '')); + } +}; +/** + * Construct a `File` instance. This is used to ensure a helpful error is thrown + * for environments that don't define a global `File` yet. + */ +function uploads_makeFile(fileBits, fileName, options) { + uploads_checkFileSupport(); + return new File(fileBits, fileName ?? 'unknown_file', options); +} +function uploads_getName(value) { + return (((typeof value === 'object' && + value !== null && + (('name' in value && value.name && String(value.name)) || + ('url' in value && value.url && String(value.url)) || + ('filename' in value && value.filename && String(value.filename)) || + ('path' in value && value.path && String(value.path)))) || + '') + .split(/[\\/]/) + .pop() || undefined); +} +const internal_uploads_isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; +/** + * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. + * Otherwise returns the request as is. + */ +const uploads_maybeMultipartFormRequestOptions = async (opts, fetch) => { + if (!uploads_hasUploadableValue(opts.body)) + return opts; + return { ...opts, body: await uploads_createForm(opts.body, fetch) }; +}; +const uploads_multipartFormRequestOptions = async (opts, fetch) => { + return { ...opts, body: await uploads_createForm(opts.body, fetch) }; +}; +const uploads_supportsFormDataMap = /* @__PURE__ */ new WeakMap(); +/** + * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending + * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". + * This function detects if the fetch function provided supports the global FormData object to avoid + * confusing error messages later on. + */ +function uploads_supportsFormData(fetchObject) { + const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; + const cached = uploads_supportsFormDataMap.get(fetch); + if (cached) + return cached; + const promise = (async () => { + try { + const FetchResponse = ('Response' in fetch ? + fetch.Response + : (await fetch('data:,')).constructor); + const data = new FormData(); + if (data.toString() === (await new FetchResponse(data).text())) { + return false; + } + return true; + } + catch { + // avoid false negatives + return true; + } + })(); + uploads_supportsFormDataMap.set(fetch, promise); + return promise; +} +const uploads_createForm = async (body, fetch) => { + if (!(await uploads_supportsFormData(fetch))) { + throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); + } + const form = new FormData(); + await Promise.all(Object.entries(body || {}).map(([key, value]) => uploads_addFormValue(form, key, value))); + return form; +}; +// We check for Blob not File because Bun.File doesn't inherit from File, +// but they both inherit from Blob and have a `name` property at runtime. +const uploads_isNamedBlob = (value) => value instanceof Blob && 'name' in value; +const uploads_isUploadable = (value) => typeof value === 'object' && + value !== null && + (value instanceof Response || internal_uploads_isAsyncIterable(value) || uploads_isNamedBlob(value)); +const uploads_hasUploadableValue = (value) => { + if (uploads_isUploadable(value)) + return true; + if (Array.isArray(value)) + return value.some(uploads_hasUploadableValue); + if (value && typeof value === 'object') { + for (const k in value) { + if (uploads_hasUploadableValue(value[k])) + return true; + } + } + return false; +}; +const uploads_addFormValue = async (form, key, value) => { + if (value === undefined) + return; + if (value == null) { + throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); + } + // TODO: make nested formats configurable + if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { + form.append(key, String(value)); + } + else if (value instanceof Response) { + form.append(key, uploads_makeFile([await value.blob()], uploads_getName(value))); + } + else if (internal_uploads_isAsyncIterable(value)) { + form.append(key, uploads_makeFile([await new Response(shims_ReadableStreamFrom(value)).blob()], uploads_getName(value))); + } + else if (uploads_isNamedBlob(value)) { + form.append(key, value, uploads_getName(value)); + } + else if (Array.isArray(value)) { + await Promise.all(value.map((entry) => uploads_addFormValue(form, key + '[]', entry))); + } + else if (typeof value === 'object') { + await Promise.all(Object.entries(value).map(([name, prop]) => uploads_addFormValue(form, `${key}[${name}]`, prop))); + } + else { + throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); + } +}; +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/to-file.mjs + + +/** + * This check adds the arrayBuffer() method type because it is available and used at runtime + */ +const to_file_isBlobLike = (value) => value != null && + typeof value === 'object' && + typeof value.size === 'number' && + typeof value.type === 'string' && + typeof value.text === 'function' && + typeof value.slice === 'function' && + typeof value.arrayBuffer === 'function'; +/** + * This check adds the arrayBuffer() method type because it is available and used at runtime + */ +const to_file_isFileLike = (value) => value != null && + typeof value === 'object' && + typeof value.name === 'string' && + typeof value.lastModified === 'number' && + to_file_isBlobLike(value); +const to_file_isResponseLike = (value) => value != null && + typeof value === 'object' && + typeof value.url === 'string' && + typeof value.blob === 'function'; +/** + * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats + * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts + * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible + * @param {Object=} options additional properties + * @param {string=} options.type the MIME type of the content + * @param {number=} options.lastModified the last modified timestamp + * @returns a {@link File} with the given properties + */ +async function to_file_toFile(value, name, options) { + uploads_checkFileSupport(); + // If it's a promise, resolve it. + value = await value; + // If we've been given a `File` we don't need to do anything + if (to_file_isFileLike(value)) { + if (value instanceof File) { + return value; + } + return uploads_makeFile([await value.arrayBuffer()], value.name); + } + if (to_file_isResponseLike(value)) { + const blob = await value.blob(); + name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); + return uploads_makeFile(await internal_to_file_getBytes(blob), name, options); + } + const parts = await internal_to_file_getBytes(value); + name || (name = uploads_getName(value)); + if (!options?.type) { + const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); + if (typeof type === 'string') { + options = { ...options, type }; + } + } + return uploads_makeFile(parts, name, options); +} +async function internal_to_file_getBytes(value) { + let parts = []; + if (typeof value === 'string' || + ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. + value instanceof ArrayBuffer) { + parts.push(value); + } + else if (to_file_isBlobLike(value)) { + parts.push(value instanceof Blob ? value : await value.arrayBuffer()); + } + else if (internal_uploads_isAsyncIterable(value) // includes Readable, ReadableStream, etc. + ) { + for await (const chunk of value) { + parts.push(...(await internal_to_file_getBytes(chunk))); // TODO, consider validating? + } + } + else { + const constructor = value?.constructor?.name; + throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${to_file_propsForError(value)}`); + } + return parts; +} +function to_file_propsForError(value) { + if (typeof value !== 'object' || value === null) + return ''; + const props = Object.getOwnPropertyNames(value); + return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; +} +//# sourceMappingURL=to-file.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/uploads.mjs + +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/core/resource.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +class resource_APIResource { + constructor(client) { + this._client = client; + } +} +//# sourceMappingURL=resource.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/path.mjs + +/** + * Percent-encode everything that isn't safe to have in a path without encoding safe chars. + * + * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: + * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" + * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" + * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" + */ +function path_encodeURIPath(str) { + return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); +} +const path_EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); +const path_createPathTagFunction = (pathEncoder = path_encodeURIPath) => function path(statics, ...params) { + // If there are no params, no processing is needed. + if (statics.length === 1) + return statics[0]; + let postPath = false; + const invalidSegments = []; + const path = statics.reduce((previousValue, currentValue, index) => { + if (/[?#]/.test(currentValue)) { + postPath = true; + } + const value = params[index]; + let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); + if (index !== params.length && + (value == null || + (typeof value === 'object' && + // handle values from other realms + value.toString === + Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? path_EMPTY) ?? path_EMPTY) + ?.toString))) { + encoded = value + ''; + invalidSegments.push({ + start: previousValue.length + currentValue.length, + length: encoded.length, + error: `Value of type ${Object.prototype.toString + .call(value) + .slice(8, -1)} is not a valid path parameter`, + }); + } + return previousValue + currentValue + (index === params.length ? '' : encoded); + }, ''); + const pathOnly = path.split(/[?#]/, 1)[0]; + const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; + let match; + // Find all invalid segments + while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { + invalidSegments.push({ + start: match.index, + length: match[0].length, + error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, + }); + } + invalidSegments.sort((a, b) => a.start - b.start); + if (invalidSegments.length > 0) { + let lastEnd = 0; + const underline = invalidSegments.reduce((acc, segment) => { + const spaces = ' '.repeat(segment.start - lastEnd); + const arrows = '^'.repeat(segment.length); + lastEnd = segment.start + segment.length; + return acc + spaces + arrows; + }, ''); + throw new error_OpenAIError(`Path parameters result in path with invalid segments:\n${invalidSegments + .map((e) => e.error) + .join('\n')}\n${path}\n${underline}`); + } + return path; +}; +/** + * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. + */ +const path_path = /* @__PURE__ */ path_createPathTagFunction(path_encodeURIPath); +//# sourceMappingURL=path.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/messages.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class completions_messages_Messages extends resource_APIResource { + /** + * Get the messages in a stored chat completion. Only Chat Completions that have + * been created with the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list( + * 'completion_id', + * )) { + * // ... + * } + * ``` + */ + list(completionID, query = {}, options) { + return this._client.getAPIList(path_path `/chat/completions/${completionID}/messages`, (CursorPage), { query, ...options }); + } +} +//# sourceMappingURL=messages.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/error.mjs + +//# sourceMappingURL=error.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/parser.mjs + +function isChatCompletionFunctionTool(tool) { + return tool !== undefined && 'function' in tool && tool.function !== undefined; +} +function makeParseableResponseFormat(response_format, parser) { + const obj = { ...response_format }; + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-response-format', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + }); + return obj; +} +function parser_makeParseableTextFormat(response_format, parser) { + const obj = { ...response_format }; + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-response-format', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + }); + return obj; +} +function isAutoParsableResponseFormat(response_format) { + return response_format?.['$brand'] === 'auto-parseable-response-format'; +} +function parser_makeParseableTool(tool, { parser, callback, }) { + const obj = { ...tool }; + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-tool', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + $callback: { + value: callback, + enumerable: false, + }, + }); + return obj; +} +function isAutoParsableTool(tool) { + return tool?.['$brand'] === 'auto-parseable-tool'; +} +function maybeParseChatCompletion(completion, params) { + if (!params || !hasAutoParseableInput(params)) { + return { + ...completion, + choices: completion.choices.map((choice) => { + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + return { + ...choice, + message: { + ...choice.message, + parsed: null, + ...(choice.message.tool_calls ? + { + tool_calls: choice.message.tool_calls, + } + : undefined), + }, + }; + }), + }; + } + return parseChatCompletion(completion, params); +} +function parseChatCompletion(completion, params) { + const choices = completion.choices.map((choice) => { + if (choice.finish_reason === 'length') { + throw new LengthFinishReasonError(); + } + if (choice.finish_reason === 'content_filter') { + throw new ContentFilterFinishReasonError(); + } + assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); + return { + ...choice, + message: { + ...choice.message, + ...(choice.message.tool_calls ? + { + tool_calls: choice.message.tool_calls?.map((toolCall) => parser_parseToolCall(params, toolCall)) ?? undefined, + } + : undefined), + parsed: choice.message.content && !choice.message.refusal ? + parseResponseFormat(params, choice.message.content) + : null, + }, + }; + }); + return { ...completion, choices }; +} +function parseResponseFormat(params, content) { + if (params.response_format?.type !== 'json_schema') { + return null; + } + if (params.response_format?.type === 'json_schema') { + if ('$parseRaw' in params.response_format) { + const response_format = params.response_format; + return response_format.$parseRaw(content); + } + return JSON.parse(content); + } + return null; +} +function parser_parseToolCall(params, toolCall) { + const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); // TS doesn't narrow based on isChatCompletionTool + return { + ...toolCall, + function: { + ...toolCall.function, + parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) + : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) + : null, + }, + }; +} +function shouldParseToolCall(params, toolCall) { + if (!params || !('tools' in params) || !params.tools) { + return false; + } + const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); + return (isChatCompletionFunctionTool(inputTool) && + (isAutoParsableTool(inputTool) || inputTool?.function.strict || false)); +} +function hasAutoParseableInput(params) { + if (isAutoParsableResponseFormat(params.response_format)) { + return true; + } + return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false); +} +function assertToolCallsAreChatCompletionFunctionToolCalls(toolCalls) { + for (const toolCall of toolCalls || []) { + if (toolCall.type !== 'function') { + throw new error_OpenAIError(`Currently only \`function\` tool calls are supported; Received \`${toolCall.type}\``); + } + } +} +function validateInputTools(tools) { + for (const tool of tools ?? []) { + if (tool.type !== 'function') { + throw new error_OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); + } + if (tool.function.strict !== true) { + throw new error_OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); + } + } +} +//# sourceMappingURL=parser.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/chatCompletionUtils.mjs +const isAssistantMessage = (message) => { + return message?.role === 'assistant'; +}; +const chatCompletionUtils_isToolMessage = (message) => { + return message?.role === 'tool'; +}; +function isPresent(obj) { + return obj != null; +} +//# sourceMappingURL=chatCompletionUtils.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/EventStream.mjs +var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError; + + +class EventStream { + constructor() { + _EventStream_instances.add(this); + this.controller = new AbortController(); + _EventStream_connectedPromise.set(this, void 0); + _EventStream_resolveConnectedPromise.set(this, () => { }); + _EventStream_rejectConnectedPromise.set(this, () => { }); + _EventStream_endPromise.set(this, void 0); + _EventStream_resolveEndPromise.set(this, () => { }); + _EventStream_rejectEndPromise.set(this, () => { }); + _EventStream_listeners.set(this, {}); + _EventStream_ended.set(this, false); + _EventStream_errored.set(this, false); + _EventStream_aborted.set(this, false); + _EventStream_catchingPromiseCreated.set(this, false); + tslib_classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => { + tslib_classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, "f"); + tslib_classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f"); + }), "f"); + tslib_classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => { + tslib_classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, "f"); + tslib_classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f"); + }), "f"); + // Don't let these promises cause unhandled rejection errors. + // we will manually cause an unhandled rejection error later + // if the user hasn't registered any error listener or called + // any promise-returning method. + tslib_classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => { }); + tslib_classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => { }); + } + _run(executor) { + // Unfortunately if we call `executor()` immediately we get runtime errors about + // references to `this` before the `super()` constructor call returns. + setTimeout(() => { + executor().then(() => { + this._emitFinal(); + this._emit('end'); + }, tslib_classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this)); + }, 0); + } + _connected() { + if (this.ended) + return; + tslib_classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this); + this._emit('connect'); + } + get ended() { + return tslib_classPrivateFieldGet(this, _EventStream_ended, "f"); + } + get errored() { + return tslib_classPrivateFieldGet(this, _EventStream_errored, "f"); + } + get aborted() { + return tslib_classPrivateFieldGet(this, _EventStream_aborted, "f"); + } + abort() { + this.controller.abort(); + } + /** + * Adds the listener function to the end of the listeners array for the event. + * No checks are made to see if the listener has already been added. Multiple calls passing + * the same combination of event and listener will result in the listener being added, and + * called, multiple times. + * @returns this ChatCompletionStream, so that calls can be chained + */ + on(event, listener) { + const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); + listeners.push({ listener }); + return this; + } + /** + * Removes the specified listener from the listener array for the event. + * off() will remove, at most, one instance of a listener from the listener array. If any single + * listener has been added multiple times to the listener array for the specified event, then + * off() must be called multiple times to remove each instance. + * @returns this ChatCompletionStream, so that calls can be chained + */ + off(event, listener) { + const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; + if (!listeners) + return this; + const index = listeners.findIndex((l) => l.listener === listener); + if (index >= 0) + listeners.splice(index, 1); + return this; + } + /** + * Adds a one-time listener function for the event. The next time the event is triggered, + * this listener is removed and then invoked. + * @returns this ChatCompletionStream, so that calls can be chained + */ + once(event, listener) { + const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); + listeners.push({ listener, once: true }); + return this; + } + /** + * This is similar to `.once()`, but returns a Promise that resolves the next time + * the event is triggered, instead of calling a listener callback. + * @returns a Promise that resolves the next time given event is triggered, + * or rejects if an error is emitted. (If you request the 'error' event, + * returns a promise that resolves with the error). + * + * Example: + * + * const message = await stream.emitted('message') // rejects if the stream errors + */ + emitted(event) { + return new Promise((resolve, reject) => { + tslib_classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); + if (event !== 'error') + this.once('error', reject); + this.once(event, resolve); + }); + } + async done() { + tslib_classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); + await tslib_classPrivateFieldGet(this, _EventStream_endPromise, "f"); + } + _emit(event, ...args) { + // make sure we don't emit any events after end + if (tslib_classPrivateFieldGet(this, _EventStream_ended, "f")) { + return; + } + if (event === 'end') { + tslib_classPrivateFieldSet(this, _EventStream_ended, true, "f"); + tslib_classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this); + } + const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; + if (listeners) { + tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once); + listeners.forEach(({ listener }) => listener(...args)); + } + if (event === 'abort') { + const error = args[0]; + if (!tslib_classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { + Promise.reject(error); + } + tslib_classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); + tslib_classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + return; + } + if (event === 'error') { + // NOTE: _emit('error', error) should only be called from #handleError(). + const error = args[0]; + if (!tslib_classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { + // Trigger an unhandled rejection if the user hasn't registered any error handlers. + // If you are seeing stack traces here, make sure to handle errors via either: + // - runner.on('error', () => ...) + // - await runner.done() + // - await runner.finalChatCompletion() + // - etc. + Promise.reject(error); + } + tslib_classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); + tslib_classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); + this._emit('end'); + } + } + _emitFinal() { } +} +_EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedPromise = new WeakMap(), _EventStream_rejectConnectedPromise = new WeakMap(), _EventStream_endPromise = new WeakMap(), _EventStream_resolveEndPromise = new WeakMap(), _EventStream_rejectEndPromise = new WeakMap(), _EventStream_listeners = new WeakMap(), _EventStream_ended = new WeakMap(), _EventStream_errored = new WeakMap(), _EventStream_aborted = new WeakMap(), _EventStream_catchingPromiseCreated = new WeakMap(), _EventStream_instances = new WeakSet(), _EventStream_handleError = function _EventStream_handleError(error) { + tslib_classPrivateFieldSet(this, _EventStream_errored, true, "f"); + if (error instanceof Error && error.name === 'AbortError') { + error = new error_APIUserAbortError(); + } + if (error instanceof error_APIUserAbortError) { + tslib_classPrivateFieldSet(this, _EventStream_aborted, true, "f"); + return this._emit('abort', error); + } + if (error instanceof error_OpenAIError) { + return this._emit('error', error); + } + if (error instanceof Error) { + const openAIError = new error_OpenAIError(error.message); + // @ts-ignore + openAIError.cause = error; + return this._emit('error', openAIError); + } + return this._emit('error', new error_OpenAIError(String(error))); +}; +//# sourceMappingURL=EventStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/RunnableFunction.mjs +function isRunnableFunctionWithParse(fn) { + return typeof fn.parse === 'function'; +} +/** + * This is helper class for passing a `function` and `parse` where the `function` + * argument type matches the `parse` return type. + */ +class ParsingToolFunction { + constructor(input) { + this.type = 'function'; + this.function = input; + } +} +//# sourceMappingURL=RunnableFunction.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/AbstractChatCompletionRunner.mjs +var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; + + + + + + +const DEFAULT_MAX_CHAT_COMPLETIONS = 10; +class AbstractChatCompletionRunner extends EventStream { + constructor() { + super(...arguments); + _AbstractChatCompletionRunner_instances.add(this); + this._chatCompletions = []; + this.messages = []; + } + _addChatCompletion(chatCompletion) { + this._chatCompletions.push(chatCompletion); + this._emit('chatCompletion', chatCompletion); + const message = chatCompletion.choices[0]?.message; + if (message) + this._addMessage(message); + return chatCompletion; + } + _addMessage(message, emit = true) { + if (!('content' in message)) + message.content = null; + this.messages.push(message); + if (emit) { + this._emit('message', message); + if (chatCompletionUtils_isToolMessage(message) && message.content) { + // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. + this._emit('functionToolCallResult', message.content); + } + else if (isAssistantMessage(message) && message.tool_calls) { + for (const tool_call of message.tool_calls) { + if (tool_call.type === 'function') { + this._emit('functionToolCall', tool_call.function); + } + } + } + } + } + /** + * @returns a promise that resolves with the final ChatCompletion, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletion. + */ + async finalChatCompletion() { + await this.done(); + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (!completion) + throw new error_OpenAIError('stream ended without producing a ChatCompletion'); + return completion; + } + /** + * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalContent() { + await this.done(); + return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + } + /** + * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, + * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalMessage() { + await this.done(); + return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + } + /** + * @returns a promise that resolves with the content of the final FunctionCall, or rejects + * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. + */ + async finalFunctionToolCall() { + await this.done(); + return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); + } + async finalFunctionToolCallResult() { + await this.done(); + return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); + } + async totalUsage() { + await this.done(); + return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); + } + allChatCompletions() { + return [...this._chatCompletions]; + } + _emitFinal() { + const completion = this._chatCompletions[this._chatCompletions.length - 1]; + if (completion) + this._emit('finalChatCompletion', completion); + const finalMessage = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); + if (finalMessage) + this._emit('finalMessage', finalMessage); + const finalContent = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); + if (finalContent) + this._emit('finalContent', finalContent); + const finalFunctionCall = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); + if (finalFunctionCall) + this._emit('finalFunctionToolCall', finalFunctionCall); + const finalFunctionCallResult = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); + if (finalFunctionCallResult != null) + this._emit('finalFunctionToolCallResult', finalFunctionCallResult); + if (this._chatCompletions.some((c) => c.usage)) { + this._emit('totalUsage', tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); + } + } + async _createChatCompletion(client, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); + const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); + this._connected(); + return this._addChatCompletion(parseChatCompletion(chatCompletion, params)); + } + async _runChatCompletion(client, params, options) { + for (const message of params.messages) { + this._addMessage(message, false); + } + return await this._createChatCompletion(client, params, options); + } + async _runTools(client, params, options) { + const role = 'tool'; + const { tool_choice = 'auto', stream, ...restParams } = params; + const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice.type === 'function' && tool_choice?.function?.name; + const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; + // TODO(someday): clean this logic up + const inputTools = params.tools.map((tool) => { + if (isAutoParsableTool(tool)) { + if (!tool.$callback) { + throw new error_OpenAIError('Tool given to `.runTools()` that does not have an associated function'); + } + return { + type: 'function', + function: { + function: tool.$callback, + name: tool.function.name, + description: tool.function.description || '', + parameters: tool.function.parameters, + parse: tool.$parseRaw, + strict: true, + }, + }; + } + return tool; + }); + const functionsByName = {}; + for (const f of inputTools) { + if (f.type === 'function') { + functionsByName[f.function.name || f.function.function.name] = f.function; + } + } + const tools = 'tools' in params ? + inputTools.map((t) => t.type === 'function' ? + { + type: 'function', + function: { + name: t.function.name || t.function.function.name, + parameters: t.function.parameters, + description: t.function.description, + strict: t.function.strict, + }, + } + : t) + : undefined; + for (const message of params.messages) { + this._addMessage(message, false); + } + for (let i = 0; i < maxChatCompletions; ++i) { + const chatCompletion = await this._createChatCompletion(client, { + ...restParams, + tool_choice, + tools, + messages: [...this.messages], + }, options); + const message = chatCompletion.choices[0]?.message; + if (!message) { + throw new error_OpenAIError(`missing message in ChatCompletion response`); + } + if (!message.tool_calls?.length) { + return; + } + for (const tool_call of message.tool_calls) { + if (tool_call.type !== 'function') + continue; + const tool_call_id = tool_call.id; + const { name, arguments: args } = tool_call.function; + const fn = functionsByName[name]; + if (!fn) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName) + .map((name) => JSON.stringify(name)) + .join(', ')}. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + else if (singleFunctionToCall && singleFunctionToCall !== name) { + const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; + this._addMessage({ role, tool_call_id, content }); + continue; + } + let parsed; + try { + parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; + } + catch (error) { + const content = error instanceof Error ? error.message : String(error); + this._addMessage({ role, tool_call_id, content }); + continue; + } + // @ts-expect-error it can't rule out `never` type. + const rawContent = await fn.function(parsed, this); + const content = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); + this._addMessage({ role, tool_call_id, content }); + if (singleFunctionToCall) { + return; + } + } + } + return; + } +} +_AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { + return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; +}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() { + let i = this.messages.length; + while (i-- > 0) { + const message = this.messages[i]; + if (isAssistantMessage(message)) { + // TODO: support audio here + const ret = { + ...message, + content: message.content ?? null, + refusal: message.refusal ?? null, + }; + return ret; + } + } + throw new error_OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); +}, _AbstractChatCompletionRunner_getFinalFunctionToolCall = function _AbstractChatCompletionRunner_getFinalFunctionToolCall() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (isAssistantMessage(message) && message?.tool_calls?.length) { + return message.tool_calls.filter((x) => x.type === 'function').at(-1)?.function; + } + } + return; +}, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult() { + for (let i = this.messages.length - 1; i >= 0; i--) { + const message = this.messages[i]; + if (chatCompletionUtils_isToolMessage(message) && + message.content != null && + typeof message.content === 'string' && + this.messages.some((x) => x.role === 'assistant' && + x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) { + return message.content; + } + } + return; +}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() { + const total = { + completion_tokens: 0, + prompt_tokens: 0, + total_tokens: 0, + }; + for (const { usage } of this._chatCompletions) { + if (usage) { + total.completion_tokens += usage.completion_tokens; + total.prompt_tokens += usage.prompt_tokens; + total.total_tokens += usage.total_tokens; + } + } + return total; +}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) { + if (params.n != null && params.n > 1) { + throw new error_OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.'); + } +}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) { + return (typeof rawContent === 'string' ? rawContent + : rawContent === undefined ? 'undefined' + : JSON.stringify(rawContent)); +}; +//# sourceMappingURL=AbstractChatCompletionRunner.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionRunner.mjs + + +class ChatCompletionRunner extends AbstractChatCompletionRunner { + static runTools(client, params, options) { + const runner = new ChatCompletionRunner(); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(client, params, opts)); + return runner; + } + _addMessage(message, emit = true) { + super._addMessage(message, emit); + if (isAssistantMessage(message) && message.content) { + this._emit('content', message.content); + } + } +} +//# sourceMappingURL=ChatCompletionRunner.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/partial-json-parser/parser.mjs +const STR = 0b000000001; +const NUM = 0b000000010; +const ARR = 0b000000100; +const OBJ = 0b000001000; +const NULL = 0b000010000; +const BOOL = 0b000100000; +const NAN = 0b001000000; +const INFINITY = 0b010000000; +const MINUS_INFINITY = 0b100000000; +const INF = INFINITY | MINUS_INFINITY; +const SPECIAL = NULL | BOOL | INF | NAN; +const ATOM = STR | NUM | SPECIAL; +const COLLECTION = ARR | OBJ; +const ALL = ATOM | COLLECTION; +const Allow = { + STR, + NUM, + ARR, + OBJ, + NULL, + BOOL, + NAN, + INFINITY, + MINUS_INFINITY, + INF, + SPECIAL, + ATOM, + COLLECTION, + ALL, +}; +// The JSON string segment was unable to be parsed completely +class PartialJSON extends Error { +} +class MalformedJSON extends Error { +} +/** + * Parse incomplete JSON + * @param {string} jsonString Partial JSON to be parsed + * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details + * @returns The parsed JSON + * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter) + * @throws {MalformedJSON} If the JSON is malformed + */ +function parseJSON(jsonString, allowPartial = Allow.ALL) { + if (typeof jsonString !== 'string') { + throw new TypeError(`expecting str, got ${typeof jsonString}`); + } + if (!jsonString.trim()) { + throw new Error(`${jsonString} is empty`); + } + return _parseJSON(jsonString.trim(), allowPartial); +} +const _parseJSON = (jsonString, allow) => { + const length = jsonString.length; + let index = 0; + const markPartialJSON = (msg) => { + throw new PartialJSON(`${msg} at position ${index}`); + }; + const throwMalformedError = (msg) => { + throw new MalformedJSON(`${msg} at position ${index}`); + }; + const parseAny = () => { + skipBlank(); + if (index >= length) + markPartialJSON('Unexpected end of input'); + if (jsonString[index] === '"') + return parseStr(); + if (jsonString[index] === '{') + return parseObj(); + if (jsonString[index] === '[') + return parseArr(); + if (jsonString.substring(index, index + 4) === 'null' || + (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))) { + index += 4; + return null; + } + if (jsonString.substring(index, index + 4) === 'true' || + (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))) { + index += 4; + return true; + } + if (jsonString.substring(index, index + 5) === 'false' || + (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))) { + index += 5; + return false; + } + if (jsonString.substring(index, index + 8) === 'Infinity' || + (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))) { + index += 8; + return Infinity; + } + if (jsonString.substring(index, index + 9) === '-Infinity' || + (Allow.MINUS_INFINITY & allow && + 1 < length - index && + length - index < 9 && + '-Infinity'.startsWith(jsonString.substring(index)))) { + index += 9; + return -Infinity; + } + if (jsonString.substring(index, index + 3) === 'NaN' || + (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))) { + index += 3; + return NaN; + } + return parseNum(); + }; + const parseStr = () => { + const start = index; + let escape = false; + index++; // skip initial quote + while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === '\\'))) { + escape = jsonString[index] === '\\' ? !escape : false; + index++; + } + if (jsonString.charAt(index) == '"') { + try { + return JSON.parse(jsonString.substring(start, ++index - Number(escape))); + } + catch (e) { + throwMalformedError(String(e)); + } + } + else if (Allow.STR & allow) { + try { + return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"'); + } + catch (e) { + // SyntaxError: Invalid escape sequence + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\')) + '"'); + } + } + markPartialJSON('Unterminated string literal'); + }; + const parseObj = () => { + index++; // skip initial brace + skipBlank(); + const obj = {}; + try { + while (jsonString[index] !== '}') { + skipBlank(); + if (index >= length && Allow.OBJ & allow) + return obj; + const key = parseStr(); + skipBlank(); + index++; // skip colon + try { + const value = parseAny(); + Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); + } + catch (e) { + if (Allow.OBJ & allow) + return obj; + else + throw e; + } + skipBlank(); + if (jsonString[index] === ',') + index++; // skip comma + } + } + catch (e) { + if (Allow.OBJ & allow) + return obj; + else + markPartialJSON("Expected '}' at end of object"); + } + index++; // skip final brace + return obj; + }; + const parseArr = () => { + index++; // skip initial bracket + const arr = []; + try { + while (jsonString[index] !== ']') { + arr.push(parseAny()); + skipBlank(); + if (jsonString[index] === ',') { + index++; // skip comma + } + } + } + catch (e) { + if (Allow.ARR & allow) { + return arr; + } + markPartialJSON("Expected ']' at end of array"); + } + index++; // skip final bracket + return arr; + }; + const parseNum = () => { + if (index === 0) { + if (jsonString === '-' && Allow.NUM & allow) + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString); + } + catch (e) { + if (Allow.NUM & allow) { + try { + if ('.' === jsonString[jsonString.length - 1]) + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.'))); + return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e'))); + } + catch (e) { } + } + throwMalformedError(String(e)); + } + } + const start = index; + if (jsonString[index] === '-') + index++; + while (jsonString[index] && !',]}'.includes(jsonString[index])) + index++; + if (index == length && !(Allow.NUM & allow)) + markPartialJSON('Unterminated number literal'); + try { + return JSON.parse(jsonString.substring(start, index)); + } + catch (e) { + if (jsonString.substring(start, index) === '-' && Allow.NUM & allow) + markPartialJSON("Not sure what '-' is"); + try { + return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e'))); + } + catch (e) { + throwMalformedError(String(e)); + } + } + }; + const skipBlank = () => { + while (index < length && ' \n\r\t'.includes(jsonString[index])) { + index++; + } + }; + return parseAny(); +}; +// using this function with malformed JSON is undefined behavior +const parser_partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); + +//# sourceMappingURL=parser.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/streaming.mjs + +//# sourceMappingURL=streaming.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStream.mjs +var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion; + + + + + + +class ChatCompletionStream extends AbstractChatCompletionRunner { + constructor(params) { + super(); + _ChatCompletionStream_instances.add(this); + _ChatCompletionStream_params.set(this, void 0); + _ChatCompletionStream_choiceEventStates.set(this, void 0); + _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); + tslib_classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f"); + tslib_classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); + } + get currentChatCompletionSnapshot() { + return tslib_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + } + /** + * Intended for use on the frontend, consuming a stream produced with + * `.toReadableStream()` on the backend. + * + * Note that messages sent to the model do not appear in `.on('message')` + * in this context. + */ + static fromReadableStream(stream) { + const runner = new ChatCompletionStream(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static createChatCompletion(client, params, options) { + const runner = new ChatCompletionStream(params); + runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); + return runner; + } + async _createChatCompletion(client, params, options) { + super._createChatCompletion; + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const chunk of stream) { + tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + return this._addChatCompletion(tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); + this._connected(); + const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); + let chatId; + for await (const chunk of stream) { + if (chatId && chatId !== chunk.id) { + // A new request has been made. + this._addChatCompletion(tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); + chatId = chunk.id; + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + return this._addChatCompletion(tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); + } + [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { + if (this.ended) + return; + tslib_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) { + let state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index]; + if (state) { + return state; + } + state = { + content_done: false, + refusal_done: false, + logprobs_content_done: false, + logprobs_refusal_done: false, + done_tool_calls: new Set(), + current_tool_call_index: null, + }; + tslib_classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state; + return state; + }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { + if (this.ended) + return; + const completion = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); + this._emit('chunk', chunk, completion); + for (const choice of chunk.choices) { + const choiceSnapshot = completion.choices[choice.index]; + if (choice.delta.content != null && + choiceSnapshot.message?.role === 'assistant' && + choiceSnapshot.message?.content) { + this._emit('content', choice.delta.content, choiceSnapshot.message.content); + this._emit('content.delta', { + delta: choice.delta.content, + snapshot: choiceSnapshot.message.content, + parsed: choiceSnapshot.message.parsed, + }); + } + if (choice.delta.refusal != null && + choiceSnapshot.message?.role === 'assistant' && + choiceSnapshot.message?.refusal) { + this._emit('refusal.delta', { + delta: choice.delta.refusal, + snapshot: choiceSnapshot.message.refusal, + }); + } + if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') { + this._emit('logprobs.content.delta', { + content: choice.logprobs?.content, + snapshot: choiceSnapshot.logprobs?.content ?? [], + }); + } + if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') { + this._emit('logprobs.refusal.delta', { + refusal: choice.logprobs?.refusal, + snapshot: choiceSnapshot.logprobs?.refusal ?? [], + }); + } + const state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + if (choiceSnapshot.finish_reason) { + tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); + if (state.current_tool_call_index != null) { + tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); + } + } + for (const toolCall of choice.delta.tool_calls ?? []) { + if (state.current_tool_call_index !== toolCall.index) { + tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); + // new tool call started, the previous one is done + if (state.current_tool_call_index != null) { + tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); + } + } + state.current_tool_call_index = toolCall.index; + } + for (const toolCallDelta of choice.delta.tool_calls ?? []) { + const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index]; + if (!toolCallSnapshot?.type) { + continue; + } + if (toolCallSnapshot?.type === 'function') { + this._emit('tool_calls.function.arguments.delta', { + name: toolCallSnapshot.function?.name, + index: toolCallDelta.index, + arguments: toolCallSnapshot.function.arguments, + parsed_arguments: toolCallSnapshot.function.parsed_arguments, + arguments_delta: toolCallDelta.function?.arguments ?? '', + }); + } + else { + ChatCompletionStream_assertNever(toolCallSnapshot?.type); + } + } + } + }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) { + const state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + if (state.done_tool_calls.has(toolCallIndex)) { + // we've already fired the done event + return; + } + const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex]; + if (!toolCallSnapshot) { + throw new Error('no tool call snapshot'); + } + if (!toolCallSnapshot.type) { + throw new Error('tool call snapshot missing `type`'); + } + if (toolCallSnapshot.type === 'function') { + const inputTool = tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name); // TS doesn't narrow based on isChatCompletionTool + this._emit('tool_calls.function.arguments.done', { + name: toolCallSnapshot.function.name, + index: toolCallIndex, + arguments: toolCallSnapshot.function.arguments, + parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) + : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) + : null, + }); + } + else { + ChatCompletionStream_assertNever(toolCallSnapshot.type); + } + }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) { + const state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); + if (choiceSnapshot.message.content && !state.content_done) { + state.content_done = true; + const responseFormat = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this); + this._emit('content.done', { + content: choiceSnapshot.message.content, + parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null, + }); + } + if (choiceSnapshot.message.refusal && !state.refusal_done) { + state.refusal_done = true; + this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal }); + } + if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) { + state.logprobs_content_done = true; + this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content }); + } + if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) { + state.logprobs_refusal_done = true; + this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal }); + } + }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() { + if (this.ended) { + throw new error_OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = tslib_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + if (!snapshot) { + throw new error_OpenAIError(`request ended without sending any chunks`); + } + tslib_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); + tslib_classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); + return finalizeChatCompletion(snapshot, tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")); + }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() { + const responseFormat = tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format; + if (isAutoParsableResponseFormat(responseFormat)) { + return responseFormat; + } + return null; + }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { + var _a, _b, _c, _d; + let snapshot = tslib_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); + const { choices, ...rest } = chunk; + if (!snapshot) { + snapshot = tslib_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { + ...rest, + choices: [], + }, "f"); + } + else { + Object.assign(snapshot, rest); + } + for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { + let choice = snapshot.choices[index]; + if (!choice) { + choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; + } + if (logprobs) { + if (!choice.logprobs) { + choice.logprobs = Object.assign({}, logprobs); + } + else { + const { content, refusal, ...rest } = logprobs; + assertIsEmpty(rest); + Object.assign(choice.logprobs, rest); + if (content) { + (_a = choice.logprobs).content ?? (_a.content = []); + choice.logprobs.content.push(...content); + } + if (refusal) { + (_b = choice.logprobs).refusal ?? (_b.refusal = []); + choice.logprobs.refusal.push(...refusal); + } + } + } + if (finish_reason) { + choice.finish_reason = finish_reason; + if (tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f"))) { + if (finish_reason === 'length') { + throw new LengthFinishReasonError(); + } + if (finish_reason === 'content_filter') { + throw new ContentFilterFinishReasonError(); + } + } + } + Object.assign(choice, other); + if (!delta) + continue; // Shouldn't happen; just in case. + const { content, refusal, function_call, role, tool_calls, ...rest } = delta; + assertIsEmpty(rest); + Object.assign(choice.message, rest); + if (refusal) { + choice.message.refusal = (choice.message.refusal || '') + refusal; + } + if (role) + choice.message.role = role; + if (function_call) { + if (!choice.message.function_call) { + choice.message.function_call = function_call; + } + else { + if (function_call.name) + choice.message.function_call.name = function_call.name; + if (function_call.arguments) { + (_c = choice.message.function_call).arguments ?? (_c.arguments = ''); + choice.message.function_call.arguments += function_call.arguments; + } + } + } + if (content) { + choice.message.content = (choice.message.content || '') + content; + if (!choice.message.refusal && tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) { + choice.message.parsed = parser_partialParse(choice.message.content); + } + } + if (tool_calls) { + if (!choice.message.tool_calls) + choice.message.tool_calls = []; + for (const { index, id, type, function: fn, ...rest } of tool_calls) { + const tool_call = ((_d = choice.message.tool_calls)[index] ?? (_d[index] = {})); + Object.assign(tool_call, rest); + if (id) + tool_call.id = id; + if (type) + tool_call.type = type; + if (fn) + tool_call.function ?? (tool_call.function = { name: fn.name ?? '', arguments: '' }); + if (fn?.name) + tool_call.function.name = fn.name; + if (fn?.arguments) { + tool_call.function.arguments += fn.arguments; + if (shouldParseToolCall(tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), tool_call)) { + tool_call.function.parsed_arguments = parser_partialParse(tool_call.function.arguments); + } + } + } + } + } + return snapshot; + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('chunk', (chunk) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(chunk); + } + else { + pushQueue.push(chunk); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + toReadableStream() { + const stream = new streaming_Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } +} +function finalizeChatCompletion(snapshot, params) { + const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; + const completion = { + ...rest, + id, + choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => { + if (!finish_reason) { + throw new error_OpenAIError(`missing finish_reason for choice ${index}`); + } + const { content = null, function_call, tool_calls, ...messageRest } = message; + const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. + if (!role) { + throw new error_OpenAIError(`missing role for choice ${index}`); + } + if (function_call) { + const { arguments: args, name } = function_call; + if (args == null) { + throw new error_OpenAIError(`missing function_call.arguments for choice ${index}`); + } + if (!name) { + throw new error_OpenAIError(`missing function_call.name for choice ${index}`); + } + return { + ...choiceRest, + message: { + content, + function_call: { arguments: args, name }, + role, + refusal: message.refusal ?? null, + }, + finish_reason, + index, + logprobs, + }; + } + if (tool_calls) { + return { + ...choiceRest, + index, + finish_reason, + logprobs, + message: { + ...messageRest, + role, + content, + refusal: message.refusal ?? null, + tool_calls: tool_calls.map((tool_call, i) => { + const { function: fn, type, id, ...toolRest } = tool_call; + const { arguments: args, name, ...fnRest } = fn || {}; + if (id == null) { + throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); + } + if (type == null) { + throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); + } + if (name == null) { + throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`); + } + if (args == null) { + throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`); + } + return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; + }), + }, + }; + } + return { + ...choiceRest, + message: { ...messageRest, content, role, refusal: message.refusal ?? null }, + finish_reason, + index, + logprobs, + }; + }), + created, + model, + object: 'chat.completion', + ...(system_fingerprint ? { system_fingerprint } : {}), + }; + return maybeParseChatCompletion(completion, params); +} +function str(x) { + return JSON.stringify(x); +} +/** + * Ensures the given argument is an empty object, useful for + * asserting that all known properties on an object have been + * destructured. + */ +function assertIsEmpty(obj) { + return; +} +function ChatCompletionStream_assertNever(_x) { } +//# sourceMappingURL=ChatCompletionStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStreamingRunner.mjs + +class ChatCompletionStreamingRunner extends ChatCompletionStream { + static fromReadableStream(stream) { + const runner = new ChatCompletionStreamingRunner(null); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + static runTools(client, params, options) { + const runner = new ChatCompletionStreamingRunner( + // @ts-expect-error TODO these types are incompatible + params); + const opts = { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, + }; + runner._run(() => runner._runTools(client, params, opts)); + return runner; + } +} +//# sourceMappingURL=ChatCompletionStreamingRunner.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/completions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + + +class completions_Completions extends resource_APIResource { + constructor() { + super(...arguments); + this.messages = new completions_messages_Messages(this._client); + } + create(body, options) { + return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }); + } + /** + * Get a stored chat completion. Only Chat Completions that have been created with + * the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * const chatCompletion = + * await client.chat.completions.retrieve('completion_id'); + * ``` + */ + retrieve(completionID, options) { + return this._client.get(path_path `/chat/completions/${completionID}`, options); + } + /** + * Modify a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be modified. Currently, the only + * supported modification is to update the `metadata` field. + * + * @example + * ```ts + * const chatCompletion = await client.chat.completions.update( + * 'completion_id', + * { metadata: { foo: 'string' } }, + * ); + * ``` + */ + update(completionID, body, options) { + return this._client.post(path_path `/chat/completions/${completionID}`, { body, ...options }); + } + /** + * List stored Chat Completions. Only Chat Completions that have been stored with + * the `store` parameter set to `true` will be returned. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatCompletion of client.chat.completions.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/chat/completions', (CursorPage), { query, ...options }); + } + /** + * Delete a stored chat completion. Only Chat Completions that have been created + * with the `store` parameter set to `true` can be deleted. + * + * @example + * ```ts + * const chatCompletionDeleted = + * await client.chat.completions.delete('completion_id'); + * ``` + */ + delete(completionID, options) { + return this._client.delete(path_path `/chat/completions/${completionID}`, options); + } + parse(body, options) { + validateInputTools(body.tools); + return this._client.chat.completions + .create(body, { + ...options, + headers: { + ...options?.headers, + 'X-Stainless-Helper-Method': 'chat.completions.parse', + }, + }) + ._thenUnwrap((completion) => parseChatCompletion(completion, body)); + } + runTools(body, options) { + if (body.stream) { + return ChatCompletionStreamingRunner.runTools(this._client, body, options); + } + return ChatCompletionRunner.runTools(this._client, body, options); + } + /** + * Creates a chat completion stream + */ + stream(body, options) { + return ChatCompletionStream.createChatCompletion(this._client, body, options); + } +} + + + + +completions_Completions.Messages = completions_messages_Messages; +//# sourceMappingURL=completions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/chat.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Chat extends resource_APIResource { + constructor() { + super(...arguments); + this.completions = new completions_Completions(this._client); + } +} +Chat.Completions = completions_Completions; +//# sourceMappingURL=chat.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/index.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/index.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/headers.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +const headers_brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders'); +function* headers_iterateHeaders(headers) { + if (!headers) + return; + if (headers_brand_privateNullableHeaders in headers) { + const { values, nulls } = headers; + yield* values.entries(); + for (const name of nulls) { + yield [name, null]; + } + return; + } + let shouldClear = false; + let iter; + if (headers instanceof Headers) { + iter = headers.entries(); + } + else if (values_isReadonlyArray(headers)) { + iter = headers; + } + else { + shouldClear = true; + iter = Object.entries(headers ?? {}); + } + for (let row of iter) { + const name = row[0]; + if (typeof name !== 'string') + throw new TypeError('expected header name to be a string'); + const values = values_isReadonlyArray(row[1]) ? row[1] : [row[1]]; + let didClear = false; + for (const value of values) { + if (value === undefined) + continue; + // Objects keys always overwrite older headers, they never append. + // Yield a null to clear the header before adding the new values. + if (shouldClear && !didClear) { + didClear = true; + yield [name, null]; + } + yield [name, value]; + } + } +} +const headers_buildHeaders = (newHeaders) => { + const targetHeaders = new Headers(); + const nullHeaders = new Set(); + for (const headers of newHeaders) { + const seenHeaders = new Set(); + for (const [name, value] of headers_iterateHeaders(headers)) { + const lowerName = name.toLowerCase(); + if (!seenHeaders.has(lowerName)) { + targetHeaders.delete(name); + seenHeaders.add(lowerName); + } + if (value === null) { + targetHeaders.delete(name); + nullHeaders.add(lowerName); + } + else { + targetHeaders.append(name, value); + nullHeaders.delete(lowerName); + } + } + } + return { [headers_brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; +}; +const headers_isEmptyHeaders = (headers) => { + for (const _ of headers_iterateHeaders(headers)) + return false; + return true; +}; +//# sourceMappingURL=headers.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/speech.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Speech extends resource_APIResource { + /** + * Generates audio from the input text. + * + * @example + * ```ts + * const speech = await client.audio.speech.create({ + * input: 'input', + * model: 'string', + * voice: 'ash', + * }); + * + * const content = await speech.blob(); + * console.log(content); + * ``` + */ + create(body, options) { + return this._client.post('/audio/speech', { + body, + ...options, + headers: headers_buildHeaders([{ Accept: 'application/octet-stream' }, options?.headers]), + __binaryResponse: true, + }); + } +} +//# sourceMappingURL=speech.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/transcriptions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Transcriptions extends resource_APIResource { + create(body, options) { + return this._client.post('/audio/transcriptions', uploads_multipartFormRequestOptions({ + body, + ...options, + stream: body.stream ?? false, + __metadata: { model: body.model }, + }, this._client)); + } +} +//# sourceMappingURL=transcriptions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/translations.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Translations extends resource_APIResource { + create(body, options) { + return this._client.post('/audio/translations', uploads_multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }, this._client)); + } +} +//# sourceMappingURL=translations.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/audio.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +class Audio extends resource_APIResource { + constructor() { + super(...arguments); + this.transcriptions = new Transcriptions(this._client); + this.translations = new Translations(this._client); + this.speech = new Speech(this._client); + } +} +Audio.Transcriptions = Transcriptions; +Audio.Translations = Translations; +Audio.Speech = Speech; +//# sourceMappingURL=audio.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/batches.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class resources_batches_Batches extends resource_APIResource { + /** + * Creates and executes a batch from an uploaded file of requests + */ + create(body, options) { + return this._client.post('/batches', { body, ...options }); + } + /** + * Retrieves a batch. + */ + retrieve(batchID, options) { + return this._client.get(path_path `/batches/${batchID}`, options); + } + /** + * List your organization's batches. + */ + list(query = {}, options) { + return this._client.getAPIList('/batches', (CursorPage), { query, ...options }); + } + /** + * Cancels an in-progress batch. The batch will be in status `cancelling` for up to + * 10 minutes, before changing to `cancelled`, where it will have partial results + * (if any) available in the output file. + */ + cancel(batchID, options) { + return this._client.post(path_path `/batches/${batchID}/cancel`, options); + } +} +//# sourceMappingURL=batches.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/assistants.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +class Assistants extends resource_APIResource { + /** + * Create an assistant with a model and instructions. + * + * @example + * ```ts + * const assistant = await client.beta.assistants.create({ + * model: 'gpt-4o', + * }); + * ``` + */ + create(body, options) { + return this._client.post('/assistants', { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieves an assistant. + * + * @example + * ```ts + * const assistant = await client.beta.assistants.retrieve( + * 'assistant_id', + * ); + * ``` + */ + retrieve(assistantID, options) { + return this._client.get(path_path `/assistants/${assistantID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Modifies an assistant. + * + * @example + * ```ts + * const assistant = await client.beta.assistants.update( + * 'assistant_id', + * ); + * ``` + */ + update(assistantID, body, options) { + return this._client.post(path_path `/assistants/${assistantID}`, { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of assistants. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const assistant of client.beta.assistants.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/assistants', (CursorPage), { + query, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Delete an assistant. + * + * @example + * ```ts + * const assistantDeleted = + * await client.beta.assistants.delete('assistant_id'); + * ``` + */ + delete(assistantID, options) { + return this._client.delete(path_path `/assistants/${assistantID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} +//# sourceMappingURL=assistants.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/sessions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Sessions extends resource_APIResource { + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API. Can be configured with the same session parameters as the + * `session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains a + * usable ephemeral API token that can be used to authenticate browser clients for + * the Realtime API. + * + * @example + * ```ts + * const session = + * await client.beta.realtime.sessions.create(); + * ``` + */ + create(body, options) { + return this._client.post('/realtime/sessions', { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} +//# sourceMappingURL=sessions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/transcription-sessions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class TranscriptionSessions extends resource_APIResource { + /** + * Create an ephemeral API token for use in client-side applications with the + * Realtime API specifically for realtime transcriptions. Can be configured with + * the same session parameters as the `transcription_session.update` client event. + * + * It responds with a session object, plus a `client_secret` key which contains a + * usable ephemeral API token that can be used to authenticate browser clients for + * the Realtime API. + * + * @example + * ```ts + * const transcriptionSession = + * await client.beta.realtime.transcriptionSessions.create(); + * ``` + */ + create(body, options) { + return this._client.post('/realtime/transcription_sessions', { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} +//# sourceMappingURL=transcription-sessions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/realtime.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +/** + * @deprecated Realtime has now launched and is generally available. The old beta API is now deprecated. + */ +class Realtime extends resource_APIResource { + constructor() { + super(...arguments); + this.sessions = new Sessions(this._client); + this.transcriptionSessions = new TranscriptionSessions(this._client); + } +} +Realtime.Sessions = Sessions; +Realtime.TranscriptionSessions = TranscriptionSessions; +//# sourceMappingURL=realtime.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chatkit/sessions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class sessions_Sessions extends resource_APIResource { + /** + * Create a ChatKit session + * + * @example + * ```ts + * const chatSession = + * await client.beta.chatkit.sessions.create({ + * user: 'x', + * workflow: { id: 'id' }, + * }); + * ``` + */ + create(body, options) { + return this._client.post('/chatkit/sessions', { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), + }); + } + /** + * Cancel a ChatKit session + * + * @example + * ```ts + * const chatSession = + * await client.beta.chatkit.sessions.cancel('cksess_123'); + * ``` + */ + cancel(sessionID, options) { + return this._client.post(path_path `/chatkit/sessions/${sessionID}/cancel`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), + }); + } +} +//# sourceMappingURL=sessions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chatkit/threads.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +class Threads extends resource_APIResource { + /** + * Retrieve a ChatKit thread + * + * @example + * ```ts + * const chatkitThread = + * await client.beta.chatkit.threads.retrieve('cthr_123'); + * ``` + */ + retrieve(threadID, options) { + return this._client.get(path_path `/chatkit/threads/${threadID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), + }); + } + /** + * List ChatKit threads + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const chatkitThread of client.beta.chatkit.threads.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/chatkit/threads', (ConversationCursorPage), { + query, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), + }); + } + /** + * Delete a ChatKit thread + * + * @example + * ```ts + * const thread = await client.beta.chatkit.threads.delete( + * 'cthr_123', + * ); + * ``` + */ + delete(threadID, options) { + return this._client.delete(path_path `/chatkit/threads/${threadID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), + }); + } + /** + * List ChatKit thread items + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const thread of client.beta.chatkit.threads.listItems( + * 'cthr_123', + * )) { + * // ... + * } + * ``` + */ + listItems(threadID, query = {}, options) { + return this._client.getAPIList(path_path `/chatkit/threads/${threadID}/items`, (ConversationCursorPage), { query, ...options, headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]) }); + } +} +//# sourceMappingURL=threads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chatkit/chatkit.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class ChatKit extends resource_APIResource { + constructor() { + super(...arguments); + this.sessions = new sessions_Sessions(this._client); + this.threads = new Threads(this._client); + } +} +ChatKit.Sessions = sessions_Sessions; +ChatKit.Threads = Threads; +//# sourceMappingURL=chatkit.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/messages.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class threads_messages_Messages extends resource_APIResource { + /** + * Create a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(threadID, body, options) { + return this._client.post(path_path `/threads/${threadID}/messages`, { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieve a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(messageID, params, options) { + const { thread_id } = params; + return this._client.get(path_path `/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Modifies a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(messageID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path_path `/threads/${thread_id}/messages/${messageID}`, { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of messages for a given thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(threadID, query = {}, options) { + return this._client.getAPIList(path_path `/threads/${threadID}/messages`, (CursorPage), { + query, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Deletes a message. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + delete(messageID, params, options) { + const { thread_id } = params; + return this._client.delete(path_path `/threads/${thread_id}/messages/${messageID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} +//# sourceMappingURL=messages.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/steps.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class Steps extends resource_APIResource { + /** + * Retrieves a run step. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(stepID, params, options) { + const { thread_id, run_id, ...query } = params; + return this._client.get(path_path `/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, { + query, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of run steps belonging to a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(runID, params, options) { + const { thread_id, ...query } = params; + return this._client.getAPIList(path_path `/threads/${thread_id}/runs/${runID}/steps`, (CursorPage), { + query, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} +//# sourceMappingURL=steps.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/base64.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +const base64_toBase64 = (data) => { + if (!data) + return ''; + if (typeof globalThis.Buffer !== 'undefined') { + return globalThis.Buffer.from(data).toString('base64'); + } + if (typeof data === 'string') { + data = encodeUTF8(data); + } + if (typeof btoa !== 'undefined') { + return btoa(String.fromCharCode.apply(null, data)); + } + throw new OpenAIError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined'); +}; +const base64_fromBase64 = (str) => { + if (typeof globalThis.Buffer !== 'undefined') { + const buf = globalThis.Buffer.from(str, 'base64'); + return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + } + if (typeof atob !== 'undefined') { + const bstr = atob(str); + const buf = new Uint8Array(bstr.length); + for (let i = 0; i < bstr.length; i++) { + buf[i] = bstr.charCodeAt(i); + } + return buf; + } + throw new OpenAIError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined'); +}; +/** + * Converts a Base64 encoded string to a Float32Array. + * @param base64Str - The Base64 encoded string. + * @returns An Array of numbers interpreted as Float32 values. + */ +const toFloat32Array = (base64Str) => { + if (typeof Buffer !== 'undefined') { + // for Node.js environment + const buf = Buffer.from(base64Str, 'base64'); + return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT)); + } + else { + // for legacy web platform APIs + const binaryStr = atob(base64Str); + const len = binaryStr.length; + const bytes = new Uint8Array(len); + for (let i = 0; i < len; i++) { + bytes[i] = binaryStr.charCodeAt(i); + } + return Array.from(new Float32Array(bytes.buffer)); + } +}; +//# sourceMappingURL=base64.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/env.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +/** + * Read an environment variable. + * + * Trims beginning and trailing whitespace. + * + * Will return undefined if the environment variable doesn't exist or cannot be accessed. + */ +const env_readEnv = (env) => { + if (typeof globalThis.process !== 'undefined') { + return globalThis.process.env?.[env]?.trim() ?? undefined; + } + if (typeof globalThis.Deno !== 'undefined') { + return globalThis.Deno.env?.get?.(env)?.trim(); + } + return undefined; +}; +//# sourceMappingURL=env.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/internal/utils.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +//# sourceMappingURL=utils.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/AssistantStream.mjs +var _AssistantStream_instances, AssistantStream_a, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun; + + + + + +class AssistantStream extends EventStream { + constructor() { + super(...arguments); + _AssistantStream_instances.add(this); + //Track all events in a single list for reference + _AssistantStream_events.set(this, []); + //Used to accumulate deltas + //We are accumulating many types so the value here is not strict + _AssistantStream_runStepSnapshots.set(this, {}); + _AssistantStream_messageSnapshots.set(this, {}); + _AssistantStream_messageSnapshot.set(this, void 0); + _AssistantStream_finalRun.set(this, void 0); + _AssistantStream_currentContentIndex.set(this, void 0); + _AssistantStream_currentContent.set(this, void 0); + _AssistantStream_currentToolCallIndex.set(this, void 0); + _AssistantStream_currentToolCall.set(this, void 0); + //For current snapshot methods + _AssistantStream_currentEvent.set(this, void 0); + _AssistantStream_currentRunSnapshot.set(this, void 0); + _AssistantStream_currentRunStepSnapshot.set(this, void 0); + } + [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + //Catch all for passing along all events + this.on('event', (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } + else { + pushQueue.push(event); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); + } + const chunk = pushQueue.shift(); + return { value: chunk, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + static fromReadableStream(stream) { + const runner = new AssistantStream_a(); + runner._run(() => runner._fromReadableStream(stream)); + return runner; + } + async _fromReadableStream(readableStream, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + this._connected(); + const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + toReadableStream() { + const stream = new streaming_Stream(this[Symbol.asyncIterator].bind(this), this.controller); + return stream.toReadableStream(); + } + static createToolAssistantStream(runId, runs, params, options) { + const runner = new AssistantStream_a(); + runner._run(() => runner._runToolAssistantStream(runId, runs, params, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; + } + async _createToolAssistantStream(run, runId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream = await run.submitToolOutputs(runId, body, { + ...options, + signal: this.controller.signal, + }); + this._connected(); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + static createThreadAssistantStream(params, thread, options) { + const runner = new AssistantStream_a(); + runner._run(() => runner._threadAssistantStream(params, thread, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; + } + static createAssistantStream(threadId, runs, params, options) { + const runner = new AssistantStream_a(); + runner._run(() => runner._runAssistantStream(threadId, runs, params, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; + } + currentEvent() { + return tslib_classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"); + } + currentRun() { + return tslib_classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"); + } + currentMessageSnapshot() { + return tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"); + } + currentRunStepSnapshot() { + return tslib_classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"); + } + async finalRunSteps() { + await this.done(); + return Object.values(tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")); + } + async finalMessages() { + await this.done(); + return Object.values(tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")); + } + async finalRun() { + await this.done(); + if (!tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) + throw Error('Final run was not received.'); + return tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); + } + async _createThreadAssistantStream(thread, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + async _createAssistantStream(run, threadId, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + const body = { ...params, stream: true }; + const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); + this._connected(); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); + } + static accumulateDelta(acc, delta) { + for (const [key, deltaValue] of Object.entries(delta)) { + if (!acc.hasOwnProperty(key)) { + acc[key] = deltaValue; + continue; + } + let accValue = acc[key]; + if (accValue === null || accValue === undefined) { + acc[key] = deltaValue; + continue; + } + // We don't accumulate these special properties + if (key === 'index' || key === 'type') { + acc[key] = deltaValue; + continue; + } + // Type-specific accumulation logic + if (typeof accValue === 'string' && typeof deltaValue === 'string') { + accValue += deltaValue; + } + else if (typeof accValue === 'number' && typeof deltaValue === 'number') { + accValue += deltaValue; + } + else if (values_isObj(accValue) && values_isObj(deltaValue)) { + accValue = this.accumulateDelta(accValue, deltaValue); + } + else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { + if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) { + accValue.push(...deltaValue); // Use spread syntax for efficient addition + continue; + } + for (const deltaEntry of deltaValue) { + if (!values_isObj(deltaEntry)) { + throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`); + } + const index = deltaEntry['index']; + if (index == null) { + console.error(deltaEntry); + throw new Error('Expected array delta entry to have an `index` property'); + } + if (typeof index !== 'number') { + throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`); + } + const accEntry = accValue[index]; + if (accEntry == null) { + accValue.push(deltaEntry); + } + else { + accValue[index] = this.accumulateDelta(accEntry, deltaEntry); + } + } + continue; + } + else { + throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); + } + acc[key] = accValue; + } + return acc; + } + _addRun(run) { + return run; + } + async _threadAssistantStream(params, thread, options) { + return await this._createThreadAssistantStream(thread, params, options); + } + async _runAssistantStream(threadId, runs, params, options) { + return await this._createAssistantStream(runs, threadId, params, options); + } + async _runToolAssistantStream(runId, runs, params, options) { + return await this._createToolAssistantStream(runs, runId, params, options); + } +} +AssistantStream_a = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { + if (this.ended) + return; + tslib_classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f"); + tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); + switch (event.event) { + case 'thread.created': + //No action on this event. + break; + case 'thread.run.created': + case 'thread.run.queued': + case 'thread.run.in_progress': + case 'thread.run.requires_action': + case 'thread.run.completed': + case 'thread.run.incomplete': + case 'thread.run.failed': + case 'thread.run.cancelling': + case 'thread.run.cancelled': + case 'thread.run.expired': + tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); + break; + case 'thread.run.step.created': + case 'thread.run.step.in_progress': + case 'thread.run.step.delta': + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); + break; + case 'thread.message.created': + case 'thread.message.in_progress': + case 'thread.message.delta': + case 'thread.message.completed': + case 'thread.message.incomplete': + tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); + break; + case 'error': + //This is included for completeness, but errors are processed in the SSE event processing so this should not occur + throw new Error('Encountered an error event in event processing - errors should be processed earlier'); + default: + AssistantStream_assertNever(event); + } +}, _AssistantStream_endRequest = function _AssistantStream_endRequest() { + if (this.ended) { + throw new error_OpenAIError(`stream has ended, this shouldn't happen`); + } + if (!tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) + throw Error('Final run has not been received'); + return tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); +}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) { + const [accumulatedMessage, newContent] = tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + tslib_classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); + tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; + for (const content of newContent) { + const snapshotContent = accumulatedMessage.content[content.index]; + if (snapshotContent?.type == 'text') { + this._emit('textCreated', snapshotContent.text); + } + } + switch (event.event) { + case 'thread.message.created': + this._emit('messageCreated', event.data); + break; + case 'thread.message.in_progress': + break; + case 'thread.message.delta': + this._emit('messageDelta', event.data.delta, accumulatedMessage); + if (event.data.delta.content) { + for (const content of event.data.delta.content) { + //If it is text delta, emit a text delta event + if (content.type == 'text' && content.text) { + let textDelta = content.text; + let snapshot = accumulatedMessage.content[content.index]; + if (snapshot && snapshot.type == 'text') { + this._emit('textDelta', textDelta, snapshot.text); + } + else { + throw Error('The snapshot associated with this text delta is not text or missing'); + } + } + if (content.index != tslib_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) { + //See if we have in progress content + if (tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) { + switch (tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) { + case 'text': + this._emit('textDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + case 'image_file': + this._emit('imageFileDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + } + } + tslib_classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f"); + } + tslib_classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); + } + } + break; + case 'thread.message.completed': + case 'thread.message.incomplete': + //We emit the latest content we were working on on completion (including incomplete) + if (tslib_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== undefined) { + const currentContent = event.data.content[tslib_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")]; + if (currentContent) { + switch (currentContent.type) { + case 'image_file': + this._emit('imageFileDone', currentContent.image_file, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + case 'text': + this._emit('textDone', currentContent.text, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); + break; + } + } + } + if (tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) { + this._emit('messageDone', event.data); + } + tslib_classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, "f"); + } +}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) { + const accumulatedRunStep = tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); + tslib_classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); + switch (event.event) { + case 'thread.run.step.created': + this._emit('runStepCreated', event.data); + break; + case 'thread.run.step.delta': + const delta = event.data.delta; + if (delta.step_details && + delta.step_details.type == 'tool_calls' && + delta.step_details.tool_calls && + accumulatedRunStep.step_details.type == 'tool_calls') { + for (const toolCall of delta.step_details.tool_calls) { + if (toolCall.index == tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) { + this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); + } + else { + if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + } + tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); + tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); + if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) + this._emit('toolCallCreated', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + } + } + } + this._emit('runStepDelta', event.data.delta, accumulatedRunStep); + break; + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + tslib_classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, "f"); + const details = event.data.step_details; + if (details.type == 'tool_calls') { + if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); + } + } + this._emit('runStepDone', event.data, accumulatedRunStep); + break; + case 'thread.run.step.in_progress': + break; + } +}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) { + tslib_classPrivateFieldGet(this, _AssistantStream_events, "f").push(event); + this._emit('event', event); +}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) { + switch (event.event) { + case 'thread.run.step.created': + tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + return event.data; + case 'thread.run.step.delta': + let snapshot = tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + if (!snapshot) { + throw Error('Received a RunStepDelta before creation of a snapshot'); + } + let data = event.data; + if (data.delta) { + const accumulated = AssistantStream_a.accumulateDelta(snapshot, data.delta); + tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; + } + return tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + case 'thread.run.step.completed': + case 'thread.run.step.failed': + case 'thread.run.step.cancelled': + case 'thread.run.step.expired': + case 'thread.run.step.in_progress': + tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; + break; + } + if (tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) + return tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; + throw new Error('No snapshot available'); +}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) { + let newContent = []; + switch (event.event) { + case 'thread.message.created': + //On creation the snapshot is just the initial message + return [event.data, newContent]; + case 'thread.message.delta': + if (!snapshot) { + throw Error('Received a delta with no existing snapshot (there should be one from message creation)'); + } + let data = event.data; + //If this delta does not have content, nothing to process + if (data.delta.content) { + for (const contentElement of data.delta.content) { + if (contentElement.index in snapshot.content) { + let currentContent = snapshot.content[contentElement.index]; + snapshot.content[contentElement.index] = tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); + } + else { + snapshot.content[contentElement.index] = contentElement; + // This is a new element + newContent.push(contentElement); + } + } + } + return [snapshot, newContent]; + case 'thread.message.in_progress': + case 'thread.message.completed': + case 'thread.message.incomplete': + //No changes on other thread events + if (snapshot) { + return [snapshot, newContent]; + } + else { + throw Error('Received thread message event with no existing snapshot'); + } + } + throw Error('Tried to accumulate a non-message event'); +}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) { + return AssistantStream_a.accumulateDelta(currentContent, contentElement); +}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) { + tslib_classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f"); + switch (event.event) { + case 'thread.run.created': + break; + case 'thread.run.queued': + break; + case 'thread.run.in_progress': + break; + case 'thread.run.requires_action': + case 'thread.run.cancelled': + case 'thread.run.failed': + case 'thread.run.completed': + case 'thread.run.expired': + case 'thread.run.incomplete': + tslib_classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f"); + if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { + this._emit('toolCallDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); + tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); + } + break; + case 'thread.run.cancelling': + break; + } +}; +function AssistantStream_assertNever(_x) { } +//# sourceMappingURL=AssistantStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/runs.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class Runs extends resource_APIResource { + constructor() { + super(...arguments); + this.steps = new Steps(this._client); + } + create(threadID, params, options) { + const { include, ...body } = params; + return this._client.post(path_path `/threads/${threadID}/runs`, { + query: { include }, + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: params.stream ?? false, + }); + } + /** + * Retrieves a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(runID, params, options) { + const { thread_id } = params; + return this._client.get(path_path `/threads/${thread_id}/runs/${runID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Modifies a run. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(runID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path_path `/threads/${thread_id}/runs/${runID}`, { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of runs belonging to a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + list(threadID, query = {}, options) { + return this._client.getAPIList(path_path `/threads/${threadID}/runs`, (CursorPage), { + query, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Cancels a run that is `in_progress`. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + cancel(runID, params, options) { + const { thread_id } = params; + return this._client.post(path_path `/threads/${thread_id}/runs/${runID}/cancel`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * A helper to create a run an poll for a terminal state. More information on Run + * lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndPoll(threadId, body, options) { + const run = await this.create(threadId, body, options); + return await this.poll(run.id, { thread_id: threadId }, options); + } + /** + * Create a Run stream + * + * @deprecated use `stream` instead + */ + createAndStream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + /** + * A helper to poll a run status until it reaches a terminal state. More + * information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async poll(runId, params, options) { + const headers = headers_buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + while (true) { + const { data: run, response } = await this.retrieve(runId, params, { + ...options, + headers: { ...options?.headers, ...headers }, + }).withResponse(); + switch (run.status) { + //If we are in any sort of intermediate state we poll + case 'queued': + case 'in_progress': + case 'cancelling': + let sleepInterval = 5000; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } + else { + const headerInterval = response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep_sleep(sleepInterval); + break; + //We return the run in any terminal state. + case 'requires_action': + case 'incomplete': + case 'cancelled': + case 'completed': + case 'failed': + case 'expired': + return run; + } + } + } + /** + * Create a Run stream + */ + stream(threadId, body, options) { + return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); + } + submitToolOutputs(runID, params, options) { + const { thread_id, ...body } = params; + return this._client.post(path_path `/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: params.stream ?? false, + }); + } + /** + * A helper to submit a tool output to a run and poll for a terminal run state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async submitToolOutputsAndPoll(runId, params, options) { + const run = await this.submitToolOutputs(runId, params, options); + return await this.poll(run.id, params, options); + } + /** + * Submit the tool outputs from a previous run and stream the run to a terminal + * state. More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + submitToolOutputsStream(runId, params, options) { + return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options); + } +} +Runs.Steps = Steps; +//# sourceMappingURL=runs.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/threads.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + +/** + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ +class threads_Threads extends resource_APIResource { + constructor() { + super(...arguments); + this.runs = new Runs(this._client); + this.messages = new threads_messages_Messages(this._client); + } + /** + * Create a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + create(body = {}, options) { + return this._client.post('/threads', { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieves a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + retrieve(threadID, options) { + return this._client.get(path_path `/threads/${threadID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Modifies a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + update(threadID, body, options) { + return this._client.post(path_path `/threads/${threadID}`, { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Delete a thread. + * + * @deprecated The Assistants API is deprecated in favor of the Responses API + */ + delete(threadID, options) { + return this._client.delete(path_path `/threads/${threadID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + createAndRun(body, options) { + return this._client.post('/threads/runs', { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + stream: body.stream ?? false, + }); + } + /** + * A helper to create a thread, start a run and then poll for a terminal state. + * More information on Run lifecycles can be found here: + * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps + */ + async createAndRunPoll(body, options) { + const run = await this.createAndRun(body, options); + return await this.runs.poll(run.id, { thread_id: run.thread_id }, options); + } + /** + * Create a thread and stream the run back + */ + createAndRunStream(body, options) { + return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); + } +} +threads_Threads.Runs = Runs; +threads_Threads.Messages = threads_messages_Messages; +//# sourceMappingURL=threads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/beta.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + + +class beta_Beta extends resource_APIResource { + constructor() { + super(...arguments); + this.realtime = new Realtime(this._client); + this.chatkit = new ChatKit(this._client); + this.assistants = new Assistants(this._client); + this.threads = new threads_Threads(this._client); + } +} +beta_Beta.Realtime = Realtime; +beta_Beta.ChatKit = ChatKit; +beta_Beta.Assistants = Assistants; +beta_Beta.Threads = threads_Threads; +//# sourceMappingURL=beta.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/completions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class resources_completions_Completions extends resource_APIResource { + create(body, options) { + return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }); + } +} +//# sourceMappingURL=completions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/files/content.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Content extends resource_APIResource { + /** + * Retrieve Container File Content + */ + retrieve(fileID, params, options) { + const { container_id } = params; + return this._client.get(path_path `/containers/${container_id}/files/${fileID}/content`, { + ...options, + headers: headers_buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + __binaryResponse: true, + }); + } +} +//# sourceMappingURL=content.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/files/files.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +class files_Files extends resource_APIResource { + constructor() { + super(...arguments); + this.content = new Content(this._client); + } + /** + * Create a Container File + * + * You can send either a multipart/form-data request with the raw file content, or + * a JSON request with a file ID. + */ + create(containerID, body, options) { + return this._client.post(path_path `/containers/${containerID}/files`, uploads_multipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Retrieve Container File + */ + retrieve(fileID, params, options) { + const { container_id } = params; + return this._client.get(path_path `/containers/${container_id}/files/${fileID}`, options); + } + /** + * List Container files + */ + list(containerID, query = {}, options) { + return this._client.getAPIList(path_path `/containers/${containerID}/files`, (CursorPage), { + query, + ...options, + }); + } + /** + * Delete Container File + */ + delete(fileID, params, options) { + const { container_id } = params; + return this._client.delete(path_path `/containers/${container_id}/files/${fileID}`, { + ...options, + headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } +} +files_Files.Content = Content; +//# sourceMappingURL=files.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/containers.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +class Containers extends resource_APIResource { + constructor() { + super(...arguments); + this.files = new files_Files(this._client); + } + /** + * Create Container + */ + create(body, options) { + return this._client.post('/containers', { body, ...options }); + } + /** + * Retrieve Container + */ + retrieve(containerID, options) { + return this._client.get(path_path `/containers/${containerID}`, options); + } + /** + * List Containers + */ + list(query = {}, options) { + return this._client.getAPIList('/containers', (CursorPage), { query, ...options }); + } + /** + * Delete Container + */ + delete(containerID, options) { + return this._client.delete(path_path `/containers/${containerID}`, { + ...options, + headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } +} +Containers.Files = files_Files; +//# sourceMappingURL=containers.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/conversations/items.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Items extends resource_APIResource { + /** + * Create items in a conversation with the given ID. + */ + create(conversationID, params, options) { + const { include, ...body } = params; + return this._client.post(path_path `/conversations/${conversationID}/items`, { + query: { include }, + body, + ...options, + }); + } + /** + * Get a single item from a conversation with the given IDs. + */ + retrieve(itemID, params, options) { + const { conversation_id, ...query } = params; + return this._client.get(path_path `/conversations/${conversation_id}/items/${itemID}`, { query, ...options }); + } + /** + * List all items for a conversation with the given ID. + */ + list(conversationID, query = {}, options) { + return this._client.getAPIList(path_path `/conversations/${conversationID}/items`, (ConversationCursorPage), { query, ...options }); + } + /** + * Delete an item from a conversation with the given IDs. + */ + delete(itemID, params, options) { + const { conversation_id } = params; + return this._client.delete(path_path `/conversations/${conversation_id}/items/${itemID}`, options); + } +} +//# sourceMappingURL=items.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/conversations/conversations.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +class Conversations extends resource_APIResource { + constructor() { + super(...arguments); + this.items = new Items(this._client); + } + /** + * Create a conversation. + */ + create(body = {}, options) { + return this._client.post('/conversations', { body, ...options }); + } + /** + * Get a conversation + */ + retrieve(conversationID, options) { + return this._client.get(path_path `/conversations/${conversationID}`, options); + } + /** + * Update a conversation + */ + update(conversationID, body, options) { + return this._client.post(path_path `/conversations/${conversationID}`, { body, ...options }); + } + /** + * Delete a conversation. Items in the conversation will not be deleted. + */ + delete(conversationID, options) { + return this._client.delete(path_path `/conversations/${conversationID}`, options); + } +} +Conversations.Items = Items; +//# sourceMappingURL=conversations.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/embeddings.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class embeddings_Embeddings extends resource_APIResource { + /** + * Creates an embedding vector representing the input text. + * + * @example + * ```ts + * const createEmbeddingResponse = + * await client.embeddings.create({ + * input: 'The quick brown fox jumped over the lazy dog', + * model: 'text-embedding-3-small', + * }); + * ``` + */ + create(body, options) { + const hasUserProvidedEncodingFormat = !!body.encoding_format; + // No encoding_format specified, defaulting to base64 for performance reasons + // See https://github.com/openai/openai-node/pull/1312 + let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : 'base64'; + if (hasUserProvidedEncodingFormat) { + log_loggerFor(this._client).debug('embeddings/user defined encoding_format:', body.encoding_format); + } + const response = this._client.post('/embeddings', { + body: { + ...body, + encoding_format: encoding_format, + }, + ...options, + }); + // if the user specified an encoding_format, return the response as-is + if (hasUserProvidedEncodingFormat) { + return response; + } + // in this stage, we are sure the user did not specify an encoding_format + // and we defaulted to base64 for performance reasons + // we are sure then that the response is base64 encoded, let's decode it + // the returned result will be a float32 array since this is OpenAI API's default encoding + log_loggerFor(this._client).debug('embeddings/decoding base64 embeddings from base64'); + return response._thenUnwrap((response) => { + if (response && response.data) { + response.data.forEach((embeddingBase64Obj) => { + const embeddingBase64Str = embeddingBase64Obj.embedding; + embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str); + }); + } + return response; + }); + } +} +//# sourceMappingURL=embeddings.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/output-items.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class OutputItems extends resource_APIResource { + /** + * Get an evaluation run output item by ID. + */ + retrieve(outputItemID, params, options) { + const { eval_id, run_id } = params; + return this._client.get(path_path `/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, options); + } + /** + * Get a list of output items for an evaluation run. + */ + list(runID, params, options) { + const { eval_id, ...query } = params; + return this._client.getAPIList(path_path `/evals/${eval_id}/runs/${runID}/output_items`, (CursorPage), { query, ...options }); + } +} +//# sourceMappingURL=output-items.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/runs.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class runs_Runs extends resource_APIResource { + constructor() { + super(...arguments); + this.outputItems = new OutputItems(this._client); + } + /** + * Kicks off a new run for a given evaluation, specifying the data source, and what + * model configuration to use to test. The datasource will be validated against the + * schema specified in the config of the evaluation. + */ + create(evalID, body, options) { + return this._client.post(path_path `/evals/${evalID}/runs`, { body, ...options }); + } + /** + * Get an evaluation run by ID. + */ + retrieve(runID, params, options) { + const { eval_id } = params; + return this._client.get(path_path `/evals/${eval_id}/runs/${runID}`, options); + } + /** + * Get a list of runs for an evaluation. + */ + list(evalID, query = {}, options) { + return this._client.getAPIList(path_path `/evals/${evalID}/runs`, (CursorPage), { + query, + ...options, + }); + } + /** + * Delete an eval run. + */ + delete(runID, params, options) { + const { eval_id } = params; + return this._client.delete(path_path `/evals/${eval_id}/runs/${runID}`, options); + } + /** + * Cancel an ongoing evaluation run. + */ + cancel(runID, params, options) { + const { eval_id } = params; + return this._client.post(path_path `/evals/${eval_id}/runs/${runID}`, options); + } +} +runs_Runs.OutputItems = OutputItems; +//# sourceMappingURL=runs.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/evals.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class Evals extends resource_APIResource { + constructor() { + super(...arguments); + this.runs = new runs_Runs(this._client); + } + /** + * Create the structure of an evaluation that can be used to test a model's + * performance. An evaluation is a set of testing criteria and the config for a + * data source, which dictates the schema of the data used in the evaluation. After + * creating an evaluation, you can run it on different models and model parameters. + * We support several types of graders and datasources. For more information, see + * the [Evals guide](https://platform.openai.com/docs/guides/evals). + */ + create(body, options) { + return this._client.post('/evals', { body, ...options }); + } + /** + * Get an evaluation by ID. + */ + retrieve(evalID, options) { + return this._client.get(path_path `/evals/${evalID}`, options); + } + /** + * Update certain properties of an evaluation. + */ + update(evalID, body, options) { + return this._client.post(path_path `/evals/${evalID}`, { body, ...options }); + } + /** + * List evaluations for a project. + */ + list(query = {}, options) { + return this._client.getAPIList('/evals', (CursorPage), { query, ...options }); + } + /** + * Delete an evaluation. + */ + delete(evalID, options) { + return this._client.delete(path_path `/evals/${evalID}`, options); + } +} +Evals.Runs = runs_Runs; +//# sourceMappingURL=evals.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/files.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +class resources_files_Files extends resource_APIResource { + /** + * Upload a file that can be used across various endpoints. Individual files can be + * up to 512 MB, and the size of all files uploaded by one organization can be up + * to 1 TB. + * + * - The Assistants API supports files up to 2 million tokens and of specific file + * types. See the + * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) + * for details. + * - The Fine-tuning API only supports `.jsonl` files. The input also has certain + * required formats for fine-tuning + * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) + * or + * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) + * models. + * - The Batch API only supports `.jsonl` files up to 200 MB in size. The input + * also has a specific required + * [format](https://platform.openai.com/docs/api-reference/batch/request-input). + * + * Please [contact us](https://help.openai.com/) if you need to increase these + * storage limits. + */ + create(body, options) { + return this._client.post('/files', uploads_multipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Returns information about a specific file. + */ + retrieve(fileID, options) { + return this._client.get(path_path `/files/${fileID}`, options); + } + /** + * Returns a list of files. + */ + list(query = {}, options) { + return this._client.getAPIList('/files', (CursorPage), { query, ...options }); + } + /** + * Delete a file and remove it from all vector stores. + */ + delete(fileID, options) { + return this._client.delete(path_path `/files/${fileID}`, options); + } + /** + * Returns the contents of the specified file. + */ + content(fileID, options) { + return this._client.get(path_path `/files/${fileID}/content`, { + ...options, + headers: headers_buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + __binaryResponse: true, + }); + } + /** + * Waits for the given file to be processed, default timeout is 30 mins. + */ + async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) { + const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); + const start = Date.now(); + let file = await this.retrieve(id); + while (!file.status || !TERMINAL_STATES.has(file.status)) { + await sleep_sleep(pollInterval); + file = await this.retrieve(id); + if (Date.now() - start > maxWait) { + throw new error_APIConnectionTimeoutError({ + message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, + }); + } + } + return file; + } +} +//# sourceMappingURL=files.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/methods.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class Methods extends resource_APIResource { +} +//# sourceMappingURL=methods.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/graders.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class Graders extends resource_APIResource { + /** + * Run a grader. + * + * @example + * ```ts + * const response = await client.fineTuning.alpha.graders.run({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * model_sample: 'model_sample', + * }); + * ``` + */ + run(body, options) { + return this._client.post('/fine_tuning/alpha/graders/run', { body, ...options }); + } + /** + * Validate a grader. + * + * @example + * ```ts + * const response = + * await client.fineTuning.alpha.graders.validate({ + * grader: { + * input: 'input', + * name: 'name', + * operation: 'eq', + * reference: 'reference', + * type: 'string_check', + * }, + * }); + * ``` + */ + validate(body, options) { + return this._client.post('/fine_tuning/alpha/graders/validate', { body, ...options }); + } +} +//# sourceMappingURL=graders.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/alpha.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Alpha extends resource_APIResource { + constructor() { + super(...arguments); + this.graders = new Graders(this._client); + } +} +Alpha.Graders = Graders; +//# sourceMappingURL=alpha.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Permissions extends resource_APIResource { + /** + * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). + * + * This enables organization owners to share fine-tuned models with other projects + * in their organization. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * { project_ids: ['string'] }, + * )) { + * // ... + * } + * ``` + */ + create(fineTunedModelCheckpoint, body, options) { + return this._client.getAPIList(path_path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, (pagination_Page), { body, method: 'post', ...options }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to view all permissions for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTunedModelCheckpoint, query = {}, options) { + return this._client.get(path_path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { + query, + ...options, + }); + } + /** + * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). + * + * Organization owners can use this endpoint to delete a permission for a + * fine-tuned model checkpoint. + * + * @example + * ```ts + * const permission = + * await client.fineTuning.checkpoints.permissions.delete( + * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', + * { + * fine_tuned_model_checkpoint: + * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', + * }, + * ); + * ``` + */ + delete(permissionID, params, options) { + const { fine_tuned_model_checkpoint } = params; + return this._client.delete(path_path `/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, options); + } +} +//# sourceMappingURL=permissions.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Checkpoints extends resource_APIResource { + constructor() { + super(...arguments); + this.permissions = new Permissions(this._client); + } +} +Checkpoints.Permissions = Permissions; +//# sourceMappingURL=checkpoints.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class checkpoints_Checkpoints extends resource_APIResource { + /** + * List checkpoints for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + list(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path_path `/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, (CursorPage), { query, ...options }); + } +} +//# sourceMappingURL=checkpoints.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/jobs.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class Jobs extends resource_APIResource { + constructor() { + super(...arguments); + this.checkpoints = new checkpoints_Checkpoints(this._client); + } + /** + * Creates a fine-tuning job which begins the process of creating a new model from + * a given dataset. + * + * Response includes details of the enqueued job including job status and the name + * of the fine-tuned models once complete. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.create({ + * model: 'gpt-4o-mini', + * training_file: 'file-abc123', + * }); + * ``` + */ + create(body, options) { + return this._client.post('/fine_tuning/jobs', { body, ...options }); + } + /** + * Get info about a fine-tuning job. + * + * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.retrieve( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + retrieve(fineTuningJobID, options) { + return this._client.get(path_path `/fine_tuning/jobs/${fineTuningJobID}`, options); + } + /** + * List your organization's fine-tuning jobs + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJob of client.fineTuning.jobs.list()) { + * // ... + * } + * ``` + */ + list(query = {}, options) { + return this._client.getAPIList('/fine_tuning/jobs', (CursorPage), { query, ...options }); + } + /** + * Immediately cancel a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.cancel( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + cancel(fineTuningJobID, options) { + return this._client.post(path_path `/fine_tuning/jobs/${fineTuningJobID}/cancel`, options); + } + /** + * Get status updates for a fine-tuning job. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * )) { + * // ... + * } + * ``` + */ + listEvents(fineTuningJobID, query = {}, options) { + return this._client.getAPIList(path_path `/fine_tuning/jobs/${fineTuningJobID}/events`, (CursorPage), { query, ...options }); + } + /** + * Pause a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.pause( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + pause(fineTuningJobID, options) { + return this._client.post(path_path `/fine_tuning/jobs/${fineTuningJobID}/pause`, options); + } + /** + * Resume a fine-tune job. + * + * @example + * ```ts + * const fineTuningJob = await client.fineTuning.jobs.resume( + * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', + * ); + * ``` + */ + resume(fineTuningJobID, options) { + return this._client.post(path_path `/fine_tuning/jobs/${fineTuningJobID}/resume`, options); + } +} +Jobs.Checkpoints = checkpoints_Checkpoints; +//# sourceMappingURL=jobs.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/fine-tuning.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + + +class FineTuning extends resource_APIResource { + constructor() { + super(...arguments); + this.methods = new Methods(this._client); + this.jobs = new Jobs(this._client); + this.checkpoints = new Checkpoints(this._client); + this.alpha = new Alpha(this._client); + } +} +FineTuning.Methods = Methods; +FineTuning.Jobs = Jobs; +FineTuning.Checkpoints = Checkpoints; +FineTuning.Alpha = Alpha; +//# sourceMappingURL=fine-tuning.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/grader-models.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class GraderModels extends resource_APIResource { +} +//# sourceMappingURL=grader-models.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/graders.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class graders_Graders extends resource_APIResource { + constructor() { + super(...arguments); + this.graderModels = new GraderModels(this._client); + } +} +graders_Graders.GraderModels = GraderModels; +//# sourceMappingURL=graders.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/images.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + +class Images extends resource_APIResource { + /** + * Creates a variation of a given image. This endpoint only supports `dall-e-2`. + * + * @example + * ```ts + * const imagesResponse = await client.images.createVariation({ + * image: fs.createReadStream('otter.png'), + * }); + * ``` + */ + createVariation(body, options) { + return this._client.post('/images/variations', uploads_multipartFormRequestOptions({ body, ...options }, this._client)); + } + edit(body, options) { + return this._client.post('/images/edits', uploads_multipartFormRequestOptions({ body, ...options, stream: body.stream ?? false }, this._client)); + } + generate(body, options) { + return this._client.post('/images/generations', { body, ...options, stream: body.stream ?? false }); + } +} +//# sourceMappingURL=images.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/models.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class resources_models_Models extends resource_APIResource { + /** + * Retrieves a model instance, providing basic information about the model such as + * the owner and permissioning. + */ + retrieve(model, options) { + return this._client.get(path_path `/models/${model}`, options); + } + /** + * Lists the currently available models, and provides basic information about each + * one such as the owner and availability. + */ + list(options) { + return this._client.getAPIList('/models', (pagination_Page), options); + } + /** + * Delete a fine-tuned model. You must have the Owner role in your organization to + * delete a model. + */ + delete(model, options) { + return this._client.delete(path_path `/models/${model}`, options); + } +} +//# sourceMappingURL=models.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/moderations.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class Moderations extends resource_APIResource { + /** + * Classifies if text and/or image inputs are potentially harmful. Learn more in + * the [moderation guide](https://platform.openai.com/docs/guides/moderation). + */ + create(body, options) { + return this._client.post('/moderations', { body, ...options }); + } +} +//# sourceMappingURL=moderations.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/realtime/calls.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Calls extends resource_APIResource { + /** + * Accept an incoming SIP call and configure the realtime session that will handle + * it. + * + * @example + * ```ts + * await client.realtime.calls.accept('call_id', { + * type: 'realtime', + * }); + * ``` + */ + accept(callID, body, options) { + return this._client.post(path_path `/realtime/calls/${callID}/accept`, { + body, + ...options, + headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } + /** + * End an active Realtime API call, whether it was initiated over SIP or WebRTC. + * + * @example + * ```ts + * await client.realtime.calls.hangup('call_id'); + * ``` + */ + hangup(callID, options) { + return this._client.post(path_path `/realtime/calls/${callID}/hangup`, { + ...options, + headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } + /** + * Transfer an active SIP call to a new destination using the SIP REFER verb. + * + * @example + * ```ts + * await client.realtime.calls.refer('call_id', { + * target_uri: 'tel:+14155550123', + * }); + * ``` + */ + refer(callID, body, options) { + return this._client.post(path_path `/realtime/calls/${callID}/refer`, { + body, + ...options, + headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } + /** + * Decline an incoming SIP call by returning a SIP status code to the caller. + * + * @example + * ```ts + * await client.realtime.calls.reject('call_id'); + * ``` + */ + reject(callID, body = {}, options) { + return this._client.post(path_path `/realtime/calls/${callID}/reject`, { + body, + ...options, + headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } +} +//# sourceMappingURL=calls.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/realtime/client-secrets.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class ClientSecrets extends resource_APIResource { + /** + * Create a Realtime client secret with an associated session configuration. + * + * @example + * ```ts + * const clientSecret = + * await client.realtime.clientSecrets.create(); + * ``` + */ + create(body, options) { + return this._client.post('/realtime/client_secrets', { body, ...options }); + } +} +//# sourceMappingURL=client-secrets.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/realtime/realtime.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class realtime_Realtime extends resource_APIResource { + constructor() { + super(...arguments); + this.clientSecrets = new ClientSecrets(this._client); + this.calls = new Calls(this._client); + } +} +realtime_Realtime.ClientSecrets = ClientSecrets; +realtime_Realtime.Calls = Calls; +//# sourceMappingURL=realtime.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/ResponsesParser.mjs + + +function maybeParseResponse(response, params) { + if (!params || !ResponsesParser_hasAutoParseableInput(params)) { + return { + ...response, + output_parsed: null, + output: response.output.map((item) => { + if (item.type === 'function_call') { + return { + ...item, + parsed_arguments: null, + }; + } + if (item.type === 'message') { + return { + ...item, + content: item.content.map((content) => ({ + ...content, + parsed: null, + })), + }; + } + else { + return item; + } + }), + }; + } + return parseResponse(response, params); +} +function parseResponse(response, params) { + const output = response.output.map((item) => { + if (item.type === 'function_call') { + return { + ...item, + parsed_arguments: ResponsesParser_parseToolCall(params, item), + }; + } + if (item.type === 'message') { + const content = item.content.map((content) => { + if (content.type === 'output_text') { + return { + ...content, + parsed: parseTextFormat(params, content.text), + }; + } + return content; + }); + return { + ...item, + content, + }; + } + return item; + }); + const parsed = Object.assign({}, response, { output }); + if (!Object.getOwnPropertyDescriptor(response, 'output_text')) { + addOutputText(parsed); + } + Object.defineProperty(parsed, 'output_parsed', { + enumerable: true, + get() { + for (const output of parsed.output) { + if (output.type !== 'message') { + continue; + } + for (const content of output.content) { + if (content.type === 'output_text' && content.parsed !== null) { + return content.parsed; + } + } + } + return null; + }, + }); + return parsed; +} +function parseTextFormat(params, content) { + if (params.text?.format?.type !== 'json_schema') { + return null; + } + if ('$parseRaw' in params.text?.format) { + const text_format = params.text?.format; + return text_format.$parseRaw(content); + } + return JSON.parse(content); +} +function ResponsesParser_hasAutoParseableInput(params) { + if (isAutoParsableResponseFormat(params.text?.format)) { + return true; + } + return false; +} +function ResponsesParser_makeParseableResponseTool(tool, { parser, callback, }) { + const obj = { ...tool }; + Object.defineProperties(obj, { + $brand: { + value: 'auto-parseable-tool', + enumerable: false, + }, + $parseRaw: { + value: parser, + enumerable: false, + }, + $callback: { + value: callback, + enumerable: false, + }, + }); + return obj; +} +function ResponsesParser_isAutoParsableTool(tool) { + return tool?.['$brand'] === 'auto-parseable-tool'; +} +function getInputToolByName(input_tools, name) { + return input_tools.find((tool) => tool.type === 'function' && tool.name === name); +} +function ResponsesParser_parseToolCall(params, toolCall) { + const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); + return { + ...toolCall, + ...toolCall, + parsed_arguments: ResponsesParser_isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.arguments) + : inputTool?.strict ? JSON.parse(toolCall.arguments) + : null, + }; +} +function ResponsesParser_shouldParseToolCall(params, toolCall) { + if (!params) { + return false; + } + const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); + return ResponsesParser_isAutoParsableTool(inputTool) || inputTool?.strict || false; +} +function ResponsesParser_validateInputTools(tools) { + for (const tool of tools ?? []) { + if (tool.type !== 'function') { + throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); + } + if (tool.function.strict !== true) { + throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); + } + } +} +function addOutputText(rsp) { + const texts = []; + for (const output of rsp.output) { + if (output.type !== 'message') { + continue; + } + for (const content of output.content) { + if (content.type === 'output_text') { + texts.push(content.text); + } + } + } + rsp.output_text = texts.join(''); +} +//# sourceMappingURL=ResponsesParser.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/responses/ResponseStream.mjs +var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse; + + + + +class ResponseStream extends EventStream { + constructor(params) { + super(); + _ResponseStream_instances.add(this); + _ResponseStream_params.set(this, void 0); + _ResponseStream_currentResponseSnapshot.set(this, void 0); + _ResponseStream_finalResponse.set(this, void 0); + tslib_classPrivateFieldSet(this, _ResponseStream_params, params, "f"); + } + static createResponse(client, params, options) { + const runner = new ResponseStream(params); + runner._run(() => runner._createOrRetrieveResponse(client, params, { + ...options, + headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, + })); + return runner; + } + async _createOrRetrieveResponse(client, params, options) { + const signal = options?.signal; + if (signal) { + if (signal.aborted) + this.controller.abort(); + signal.addEventListener('abort', () => this.controller.abort()); + } + tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this); + let stream; + let starting_after = null; + if ('response_id' in params) { + stream = await client.responses.retrieve(params.response_id, { stream: true }, { ...options, signal: this.controller.signal, stream: true }); + starting_after = params.starting_after ?? null; + } + else { + stream = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); + } + this._connected(); + for await (const event of stream) { + tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after); + } + if (stream.controller.signal?.aborted) { + throw new error_APIUserAbortError(); + } + return tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this); + } + [(_ResponseStream_params = new WeakMap(), _ResponseStream_currentResponseSnapshot = new WeakMap(), _ResponseStream_finalResponse = new WeakMap(), _ResponseStream_instances = new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest() { + if (this.ended) + return; + tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); + }, _ResponseStream_addEvent = function _ResponseStream_addEvent(event, starting_after) { + if (this.ended) + return; + const maybeEmit = (name, event) => { + if (starting_after == null || event.sequence_number > starting_after) { + this._emit(name, event); + } + }; + const response = tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event); + maybeEmit('event', event); + switch (event.type) { + case 'response.output_text.delta': { + const output = response.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'message') { + const content = output.content[event.content_index]; + if (!content) { + throw new error_OpenAIError(`missing content at index ${event.content_index}`); + } + if (content.type !== 'output_text') { + throw new error_OpenAIError(`expected content to be 'output_text', got ${content.type}`); + } + maybeEmit('response.output_text.delta', { + ...event, + snapshot: content.text, + }); + } + break; + } + case 'response.function_call_arguments.delta': { + const output = response.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'function_call') { + maybeEmit('response.function_call_arguments.delta', { + ...event, + snapshot: output.arguments, + }); + } + break; + } + default: + maybeEmit(event.type, event); + break; + } + }, _ResponseStream_endRequest = function _ResponseStream_endRequest() { + if (this.ended) { + throw new error_OpenAIError(`stream has ended, this shouldn't happen`); + } + const snapshot = tslib_classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); + if (!snapshot) { + throw new error_OpenAIError(`request ended without sending any events`); + } + tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); + const parsedResponse = finalizeResponse(snapshot, tslib_classPrivateFieldGet(this, _ResponseStream_params, "f")); + tslib_classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f"); + return parsedResponse; + }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse(event) { + let snapshot = tslib_classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); + if (!snapshot) { + if (event.type !== 'response.created') { + throw new error_OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`); + } + snapshot = tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); + return snapshot; + } + switch (event.type) { + case 'response.output_item.added': { + snapshot.output.push(event.item); + break; + } + case 'response.content_part.added': { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + const type = output.type; + const part = event.part; + if (type === 'message' && part.type !== 'reasoning_text') { + output.content.push(part); + } + else if (type === 'reasoning' && part.type === 'reasoning_text') { + if (!output.content) { + output.content = []; + } + output.content.push(part); + } + break; + } + case 'response.output_text.delta': { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'message') { + const content = output.content[event.content_index]; + if (!content) { + throw new error_OpenAIError(`missing content at index ${event.content_index}`); + } + if (content.type !== 'output_text') { + throw new error_OpenAIError(`expected content to be 'output_text', got ${content.type}`); + } + content.text += event.delta; + } + break; + } + case 'response.function_call_arguments.delta': { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'function_call') { + output.arguments += event.delta; + } + break; + } + case 'response.reasoning_text.delta': { + const output = snapshot.output[event.output_index]; + if (!output) { + throw new error_OpenAIError(`missing output at index ${event.output_index}`); + } + if (output.type === 'reasoning') { + const content = output.content?.[event.content_index]; + if (!content) { + throw new error_OpenAIError(`missing content at index ${event.content_index}`); + } + if (content.type !== 'reasoning_text') { + throw new error_OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`); + } + content.text += event.delta; + } + break; + } + case 'response.completed': { + tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); + break; + } + } + return snapshot; + }, Symbol.asyncIterator)]() { + const pushQueue = []; + const readQueue = []; + let done = false; + this.on('event', (event) => { + const reader = readQueue.shift(); + if (reader) { + reader.resolve(event); + } + else { + pushQueue.push(event); + } + }); + this.on('end', () => { + done = true; + for (const reader of readQueue) { + reader.resolve(undefined); + } + readQueue.length = 0; + }); + this.on('abort', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + this.on('error', (err) => { + done = true; + for (const reader of readQueue) { + reader.reject(err); + } + readQueue.length = 0; + }); + return { + next: async () => { + if (!pushQueue.length) { + if (done) { + return { value: undefined, done: true }; + } + return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event) => (event ? { value: event, done: false } : { value: undefined, done: true })); + } + const event = pushQueue.shift(); + return { value: event, done: false }; + }, + return: async () => { + this.abort(); + return { value: undefined, done: true }; + }, + }; + } + /** + * @returns a promise that resolves with the final Response, or rejects + * if an error occurred or the stream ended prematurely without producing a REsponse. + */ + async finalResponse() { + await this.done(); + const response = tslib_classPrivateFieldGet(this, _ResponseStream_finalResponse, "f"); + if (!response) + throw new error_OpenAIError('stream ended without producing a ChatCompletion'); + return response; + } +} +function finalizeResponse(snapshot, params) { + return maybeParseResponse(snapshot, params); +} +//# sourceMappingURL=ResponseStream.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/input-items.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class InputItems extends resource_APIResource { + /** + * Returns a list of input items for a given response. + * + * @example + * ```ts + * // Automatically fetches more pages as needed. + * for await (const responseItem of client.responses.inputItems.list( + * 'response_id', + * )) { + * // ... + * } + * ``` + */ + list(responseID, query = {}, options) { + return this._client.getAPIList(path_path `/responses/${responseID}/input_items`, (CursorPage), { query, ...options }); + } +} +//# sourceMappingURL=input-items.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/input-tokens.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + +class InputTokens extends resource_APIResource { + /** + * Get input token counts + * + * @example + * ```ts + * const response = await client.responses.inputTokens.count(); + * ``` + */ + count(body = {}, options) { + return this._client.post('/responses/input_tokens', { body, ...options }); + } +} +//# sourceMappingURL=input-tokens.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/responses.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + + +class Responses extends resource_APIResource { + constructor() { + super(...arguments); + this.inputItems = new InputItems(this._client); + this.inputTokens = new InputTokens(this._client); + } + create(body, options) { + return this._client.post('/responses', { body, ...options, stream: body.stream ?? false })._thenUnwrap((rsp) => { + if ('object' in rsp && rsp.object === 'response') { + addOutputText(rsp); + } + return rsp; + }); + } + retrieve(responseID, query = {}, options) { + return this._client.get(path_path `/responses/${responseID}`, { + query, + ...options, + stream: query?.stream ?? false, + })._thenUnwrap((rsp) => { + if ('object' in rsp && rsp.object === 'response') { + addOutputText(rsp); + } + return rsp; + }); + } + /** + * Deletes a model response with the given ID. + * + * @example + * ```ts + * await client.responses.delete( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + delete(responseID, options) { + return this._client.delete(path_path `/responses/${responseID}`, { + ...options, + headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), + }); + } + parse(body, options) { + return this._client.responses + .create(body, options) + ._thenUnwrap((response) => parseResponse(response, body)); + } + /** + * Creates a model response stream + */ + stream(body, options) { + return ResponseStream.createResponse(this._client, body, options); + } + /** + * Cancels a model response with the given ID. Only responses created with the + * `background` parameter set to `true` can be cancelled. + * [Learn more](https://platform.openai.com/docs/guides/background). + * + * @example + * ```ts + * const response = await client.responses.cancel( + * 'resp_677efb5139a88190b512bc3fef8e535d', + * ); + * ``` + */ + cancel(responseID, options) { + return this._client.post(path_path `/responses/${responseID}/cancel`, options); + } + /** + * Compact conversation + * + * @example + * ```ts + * const compactedResponse = await client.responses.compact({ + * model: 'gpt-5.2', + * }); + * ``` + */ + compact(body, options) { + return this._client.post('/responses/compact', { body, ...options }); + } +} +Responses.InputItems = InputItems; +Responses.InputTokens = InputTokens; +//# sourceMappingURL=responses.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/parts.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + +class Parts extends resource_APIResource { + /** + * Adds a + * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. + * A Part represents a chunk of bytes from the file you are trying to upload. + * + * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload + * maximum of 8 GB. + * + * It is possible to add multiple Parts in parallel. You can decide the intended + * order of the Parts when you + * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). + */ + create(uploadID, body, options) { + return this._client.post(path_path `/uploads/${uploadID}/parts`, uploads_multipartFormRequestOptions({ body, ...options }, this._client)); + } +} +//# sourceMappingURL=parts.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/uploads.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + +class Uploads extends resource_APIResource { + constructor() { + super(...arguments); + this.parts = new Parts(this._client); + } + /** + * Creates an intermediate + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object + * that you can add + * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. + * Currently, an Upload can accept at most 8 GB in total and expires after an hour + * after you create it. + * + * Once you complete the Upload, we will create a + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * contains all the parts you uploaded. This File is usable in the rest of our + * platform as a regular File object. + * + * For certain `purpose` values, the correct `mime_type` must be specified. Please + * refer to documentation for the + * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). + * + * For guidance on the proper filename extensions for each purpose, please follow + * the documentation on + * [creating a File](https://platform.openai.com/docs/api-reference/files/create). + */ + create(body, options) { + return this._client.post('/uploads', { body, ...options }); + } + /** + * Cancels the Upload. No Parts may be added after an Upload is cancelled. + */ + cancel(uploadID, options) { + return this._client.post(path_path `/uploads/${uploadID}/cancel`, options); + } + /** + * Completes the + * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). + * + * Within the returned Upload object, there is a nested + * [File](https://platform.openai.com/docs/api-reference/files/object) object that + * is ready to use in the rest of the platform. + * + * You can specify the order of the Parts by passing in an ordered list of the Part + * IDs. + * + * The number of bytes uploaded upon completion must match the number of bytes + * initially specified when creating the Upload object. No Parts may be added after + * an Upload is completed. + */ + complete(uploadID, body, options) { + return this._client.post(path_path `/uploads/${uploadID}/complete`, { body, ...options }); + } +} +Uploads.Parts = Parts; +//# sourceMappingURL=uploads.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/Util.mjs +/** + * Like `Promise.allSettled()` but throws an error if any promises are rejected. + */ +const allSettledWithThrow = async (promises) => { + const results = await Promise.allSettled(promises); + const rejected = results.filter((result) => result.status === 'rejected'); + if (rejected.length) { + for (const result of rejected) { + console.error(result.reason); + } + throw new Error(`${rejected.length} promise(s) failed - see the above errors`); + } + // Note: TS was complaining about using `.filter().map()` here for some reason + const values = []; + for (const result of results) { + if (result.status === 'fulfilled') { + values.push(result.value); + } + } + return values; +}; +//# sourceMappingURL=Util.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/file-batches.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + +class FileBatches extends resource_APIResource { + /** + * Create a vector store file batch. + */ + create(vectorStoreID, body, options) { + return this._client.post(path_path `/vector_stores/${vectorStoreID}/file_batches`, { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieves a vector store file batch. + */ + retrieve(batchID, params, options) { + const { vector_store_id } = params; + return this._client.get(path_path `/vector_stores/${vector_store_id}/file_batches/${batchID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Cancel a vector store file batch. This attempts to cancel the processing of + * files in this batch as soon as possible. + */ + cancel(batchID, params, options) { + const { vector_store_id } = params; + return this._client.post(path_path `/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Create a vector store batch and poll until all files have been processed. + */ + async createAndPoll(vectorStoreId, body, options) { + const batch = await this.create(vectorStoreId, body); + return await this.poll(vectorStoreId, batch.id, options); + } + /** + * Returns a list of vector store files in a batch. + */ + listFiles(batchID, params, options) { + const { vector_store_id, ...query } = params; + return this._client.getAPIList(path_path `/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, (CursorPage), { query, ...options, headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }); + } + /** + * Wait for the given file batch to be processed. + * + * Note: this will return even if one of the files failed to process, you need to + * check batch.file_counts.failed_count to handle this case. + */ + async poll(vectorStoreID, batchID, options) { + const headers = headers_buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + while (true) { + const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, { + ...options, + headers, + }).withResponse(); + switch (batch.status) { + case 'in_progress': + let sleepInterval = 5000; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } + else { + const headerInterval = response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep_sleep(sleepInterval); + break; + case 'failed': + case 'cancelled': + case 'completed': + return batch; + } + } + } + /** + * Uploads the given files concurrently and then creates a vector store file batch. + * + * The concurrency limit is configurable using the `maxConcurrency` parameter. + */ + async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) { + if (files == null || files.length == 0) { + throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`); + } + const configuredConcurrency = options?.maxConcurrency ?? 5; + // We cap the number of workers at the number of files (so we don't start any unnecessary workers) + const concurrencyLimit = Math.min(configuredConcurrency, files.length); + const client = this._client; + const fileIterator = files.values(); + const allFileIds = [...fileIds]; + // This code is based on this design. The libraries don't accommodate our environment limits. + // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all + async function processFiles(iterator) { + for (let item of iterator) { + const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options); + allFileIds.push(fileObj.id); + } + } + // Start workers to process results + const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles); + // Wait for all processing to complete. + await allSettledWithThrow(workers); + return await this.createAndPoll(vectorStoreId, { + file_ids: allFileIds, + }); + } +} +//# sourceMappingURL=file-batches.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/files.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class vector_stores_files_Files extends resource_APIResource { + /** + * Create a vector store file by attaching a + * [File](https://platform.openai.com/docs/api-reference/files) to a + * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). + */ + create(vectorStoreID, body, options) { + return this._client.post(path_path `/vector_stores/${vectorStoreID}/files`, { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieves a vector store file. + */ + retrieve(fileID, params, options) { + const { vector_store_id } = params; + return this._client.get(path_path `/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Update attributes on a vector store file. + */ + update(fileID, params, options) { + const { vector_store_id, ...body } = params; + return this._client.post(path_path `/vector_stores/${vector_store_id}/files/${fileID}`, { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of vector store files. + */ + list(vectorStoreID, query = {}, options) { + return this._client.getAPIList(path_path `/vector_stores/${vectorStoreID}/files`, (CursorPage), { + query, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Delete a vector store file. This will remove the file from the vector store but + * the file itself will not be deleted. To delete the file, use the + * [delete file](https://platform.openai.com/docs/api-reference/files/delete) + * endpoint. + */ + delete(fileID, params, options) { + const { vector_store_id } = params; + return this._client.delete(path_path `/vector_stores/${vector_store_id}/files/${fileID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Attach a file to the given vector store and wait for it to be processed. + */ + async createAndPoll(vectorStoreId, body, options) { + const file = await this.create(vectorStoreId, body, options); + return await this.poll(vectorStoreId, file.id, options); + } + /** + * Wait for the vector store file to finish processing. + * + * Note: this will return even if the file failed to process, you need to check + * file.last_error and file.status to handle these cases + */ + async poll(vectorStoreID, fileID, options) { + const headers = headers_buildHeaders([ + options?.headers, + { + 'X-Stainless-Poll-Helper': 'true', + 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, + }, + ]); + while (true) { + const fileResponse = await this.retrieve(fileID, { + vector_store_id: vectorStoreID, + }, { ...options, headers }).withResponse(); + const file = fileResponse.data; + switch (file.status) { + case 'in_progress': + let sleepInterval = 5000; + if (options?.pollIntervalMs) { + sleepInterval = options.pollIntervalMs; + } + else { + const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms'); + if (headerInterval) { + const headerIntervalMs = parseInt(headerInterval); + if (!isNaN(headerIntervalMs)) { + sleepInterval = headerIntervalMs; + } + } + } + await sleep_sleep(sleepInterval); + break; + case 'failed': + case 'completed': + return file; + } + } + } + /** + * Upload a file to the `files` API and then attach it to the given vector store. + * + * Note the file will be asynchronously processed (you can use the alternative + * polling helper method to wait for processing to complete). + */ + async upload(vectorStoreId, file, options) { + const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options); + return this.create(vectorStoreId, { file_id: fileInfo.id }, options); + } + /** + * Add a file to a vector store and poll until processing is complete. + */ + async uploadAndPoll(vectorStoreId, file, options) { + const fileInfo = await this.upload(vectorStoreId, file, options); + return await this.poll(vectorStoreId, fileInfo.id, options); + } + /** + * Retrieve the parsed contents of a vector store file. + */ + content(fileID, params, options) { + const { vector_store_id } = params; + return this._client.getAPIList(path_path `/vector_stores/${vector_store_id}/files/${fileID}/content`, (pagination_Page), { ...options, headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }); + } +} +//# sourceMappingURL=files.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/vector-stores.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + +class VectorStores extends resource_APIResource { + constructor() { + super(...arguments); + this.files = new vector_stores_files_Files(this._client); + this.fileBatches = new FileBatches(this._client); + } + /** + * Create a vector store. + */ + create(body, options) { + return this._client.post('/vector_stores', { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Retrieves a vector store. + */ + retrieve(vectorStoreID, options) { + return this._client.get(path_path `/vector_stores/${vectorStoreID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Modifies a vector store. + */ + update(vectorStoreID, body, options) { + return this._client.post(path_path `/vector_stores/${vectorStoreID}`, { + body, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Returns a list of vector stores. + */ + list(query = {}, options) { + return this._client.getAPIList('/vector_stores', (CursorPage), { + query, + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Delete a vector store. + */ + delete(vectorStoreID, options) { + return this._client.delete(path_path `/vector_stores/${vectorStoreID}`, { + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } + /** + * Search a vector store for relevant chunks based on a query and file attributes + * filter. + */ + search(vectorStoreID, body, options) { + return this._client.getAPIList(path_path `/vector_stores/${vectorStoreID}/search`, (pagination_Page), { + body, + method: 'post', + ...options, + headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), + }); + } +} +VectorStores.Files = vector_stores_files_Files; +VectorStores.FileBatches = FileBatches; +//# sourceMappingURL=vector-stores.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/videos.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + +class Videos extends resource_APIResource { + /** + * Create a video + */ + create(body, options) { + return this._client.post('/videos', uploads_maybeMultipartFormRequestOptions({ body, ...options }, this._client)); + } + /** + * Retrieve a video + */ + retrieve(videoID, options) { + return this._client.get(path_path `/videos/${videoID}`, options); + } + /** + * List videos + */ + list(query = {}, options) { + return this._client.getAPIList('/videos', (ConversationCursorPage), { query, ...options }); + } + /** + * Delete a video + */ + delete(videoID, options) { + return this._client.delete(path_path `/videos/${videoID}`, options); + } + /** + * Download video content + */ + downloadContent(videoID, query = {}, options) { + return this._client.get(path_path `/videos/${videoID}/content`, { + query, + ...options, + headers: headers_buildHeaders([{ Accept: 'application/binary' }, options?.headers]), + __binaryResponse: true, + }); + } + /** + * Create a video remix + */ + remix(videoID, body, options) { + return this._client.post(path_path `/videos/${videoID}/remix`, uploads_maybeMultipartFormRequestOptions({ body, ...options }, this._client)); + } +} +//# sourceMappingURL=videos.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/webhooks.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader; + + + + +class Webhooks extends resource_APIResource { + constructor() { + super(...arguments); + _Webhooks_instances.add(this); + } + /** + * Validates that the given payload was sent by OpenAI and parses the payload. + */ + async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { + await this.verifySignature(payload, headers, secret, tolerance); + return JSON.parse(payload); + } + /** + * Validates whether or not the webhook payload was sent by OpenAI. + * + * An error will be raised if the webhook payload was not sent by OpenAI. + * + * @param payload - The webhook payload + * @param headers - The webhook headers + * @param secret - The webhook secret (optional, will use client secret if not provided) + * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes) + */ + async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { + if (typeof crypto === 'undefined' || + typeof crypto.subtle.importKey !== 'function' || + typeof crypto.subtle.verify !== 'function') { + throw new Error('Webhook signature verification is only supported when the `crypto` global is defined'); + } + tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret); + const headersObj = headers_buildHeaders([headers]).values; + const signatureHeader = tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-signature'); + const timestamp = tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-timestamp'); + const webhookId = tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-id'); + // Validate timestamp to prevent replay attacks + const timestampSeconds = parseInt(timestamp, 10); + if (isNaN(timestampSeconds)) { + throw new InvalidWebhookSignatureError('Invalid webhook timestamp format'); + } + const nowSeconds = Math.floor(Date.now() / 1000); + if (nowSeconds - timestampSeconds > tolerance) { + throw new InvalidWebhookSignatureError('Webhook timestamp is too old'); + } + if (timestampSeconds > nowSeconds + tolerance) { + throw new InvalidWebhookSignatureError('Webhook timestamp is too new'); + } + // Extract signatures from v1, format + // The signature header can have multiple values, separated by spaces. + // Each value is in the format v1,. We should accept if any match. + const signatures = signatureHeader + .split(' ') + .map((part) => (part.startsWith('v1,') ? part.substring(3) : part)); + // Decode the secret if it starts with whsec_ + const decodedSecret = secret.startsWith('whsec_') ? + Buffer.from(secret.replace('whsec_', ''), 'base64') + : Buffer.from(secret, 'utf-8'); + // Create the signed payload: {webhook_id}.{timestamp}.{payload} + const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`; + // Import the secret as a cryptographic key for HMAC + const key = await crypto.subtle.importKey('raw', decodedSecret, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']); + // Check if any signature matches using timing-safe WebCrypto verify + for (const signature of signatures) { + try { + const signatureBytes = Buffer.from(signature, 'base64'); + const isValid = await crypto.subtle.verify('HMAC', key, signatureBytes, new TextEncoder().encode(signedPayload)); + if (isValid) { + return; // Valid signature found + } + } + catch { + // Invalid base64 or signature format, continue to next signature + continue; + } + } + throw new InvalidWebhookSignatureError('The given webhook signature does not match the expected signature'); + } +} +_Webhooks_instances = new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret(secret) { + if (typeof secret !== 'string' || secret.length === 0) { + throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`); + } +}, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader(headers, name) { + if (!headers) { + throw new Error(`Headers are required`); + } + const value = headers.get(name); + if (value === null || value === undefined) { + throw new Error(`Missing required header: ${name}`); + } + return value; +}; +//# sourceMappingURL=webhooks.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/resources/index.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + + + + + + + + + + + + + + + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/client.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. +var _OpenAI_instances, openai_client_a, _OpenAI_encoder, _OpenAI_baseURLOverridden; + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/** + * API Client for interfacing with the OpenAI API. + */ +class OpenAI { + /** + * API Client for interfacing with the OpenAI API. + * + * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null] + * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = env_readEnv('OPENAI_BASE_URL'), apiKey = env_readEnv('OPENAI_API_KEY'), organization = env_readEnv('OPENAI_ORG_ID') ?? null, project = env_readEnv('OPENAI_PROJECT_ID') ?? null, webhookSecret = env_readEnv('OPENAI_WEBHOOK_SECRET') ?? null, ...opts } = {}) { + _OpenAI_instances.add(this); + _OpenAI_encoder.set(this, void 0); + this.completions = new resources_completions_Completions(this); + this.chat = new Chat(this); + this.embeddings = new embeddings_Embeddings(this); + this.files = new resources_files_Files(this); + this.images = new Images(this); + this.audio = new Audio(this); + this.moderations = new Moderations(this); + this.models = new resources_models_Models(this); + this.fineTuning = new FineTuning(this); + this.graders = new graders_Graders(this); + this.vectorStores = new VectorStores(this); + this.webhooks = new Webhooks(this); + this.beta = new beta_Beta(this); + this.batches = new resources_batches_Batches(this); + this.uploads = new Uploads(this); + this.responses = new Responses(this); + this.realtime = new realtime_Realtime(this); + this.conversations = new Conversations(this); + this.evals = new Evals(this); + this.containers = new Containers(this); + this.videos = new Videos(this); + if (apiKey === undefined) { + throw new error_OpenAIError('Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.'); + } + const options = { + apiKey, + organization, + project, + webhookSecret, + ...opts, + baseURL: baseURL || `https://api.openai.com/v1`, + }; + if (!options.dangerouslyAllowBrowser && detect_platform_isRunningInBrowser()) { + throw new error_OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); + } + this.baseURL = options.baseURL; + this.timeout = options.timeout ?? openai_client_a.DEFAULT_TIMEOUT /* 10 minutes */; + this.logger = options.logger ?? console; + const defaultLogLevel = 'warn'; + // Set default logLevel early so that we can log a warning in parseLogLevel. + this.logLevel = defaultLogLevel; + this.logLevel = + log_parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? + log_parseLogLevel(env_readEnv('OPENAI_LOG'), "process.env['OPENAI_LOG']", this) ?? + defaultLogLevel; + this.fetchOptions = options.fetchOptions; + this.maxRetries = options.maxRetries ?? 2; + this.fetch = options.fetch ?? shims_getDefaultFetch(); + tslib_classPrivateFieldSet(this, _OpenAI_encoder, request_options_FallbackEncoder, "f"); + this._options = options; + this.apiKey = typeof apiKey === 'string' ? apiKey : 'Missing Key'; + this.organization = organization; + this.project = project; + this.webhookSecret = webhookSecret; + } + /** + * Create a new client instance re-using the same options given to the current client with optional overriding. + */ + withOptions(options) { + const client = new this.constructor({ + ...this._options, + baseURL: this.baseURL, + maxRetries: this.maxRetries, + timeout: this.timeout, + logger: this.logger, + logLevel: this.logLevel, + fetch: this.fetch, + fetchOptions: this.fetchOptions, + apiKey: this.apiKey, + organization: this.organization, + project: this.project, + webhookSecret: this.webhookSecret, + ...options, + }); + return client; + } + defaultQuery() { + return this._options.defaultQuery; + } + validateHeaders({ values, nulls }) { + return; + } + async authHeaders(opts) { + return headers_buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); + } + stringifyQuery(query) { + return stringify_stringify(query, { arrayFormat: 'brackets' }); + } + getUserAgent() { + return `${this.constructor.name}/JS ${version_VERSION}`; + } + defaultIdempotencyKey() { + return `stainless-node-retry-${utils_uuid_uuid4()}`; + } + makeStatusError(status, error, message, headers) { + return error_APIError.generate(status, error, message, headers); + } + async _callApiKey() { + const apiKey = this._options.apiKey; + if (typeof apiKey !== 'function') + return false; + let token; + try { + token = await apiKey(); + } + catch (err) { + if (err instanceof error_OpenAIError) + throw err; + throw new error_OpenAIError(`Failed to get token from 'apiKey' function: ${err.message}`, + // @ts-ignore + { cause: err }); + } + if (typeof token !== 'string' || !token) { + throw new error_OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`); + } + this.apiKey = token; + return true; + } + buildURL(path, query, defaultBaseURL) { + const baseURL = (!tslib_classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL; + const url = values_isAbsoluteURL(path) ? + new URL(path) + : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); + const defaultQuery = this.defaultQuery(); + if (!values_isEmptyObj(defaultQuery)) { + query = { ...defaultQuery, ...query }; + } + if (typeof query === 'object' && query && !Array.isArray(query)) { + url.search = this.stringifyQuery(query); + } + return url.toString(); + } + /** + * Used as a callback for mutating the given `FinalRequestOptions` object. + */ + async prepareOptions(options) { + await this._callApiKey(); + } + /** + * Used as a callback for mutating the given `RequestInit` object. + * + * This is useful for cases where you want to add certain headers based off of + * the request properties, e.g. `method` or `url`. + */ + async prepareRequest(request, { url, options }) { } + get(path, opts) { + return this.methodRequest('get', path, opts); + } + post(path, opts) { + return this.methodRequest('post', path, opts); + } + patch(path, opts) { + return this.methodRequest('patch', path, opts); + } + put(path, opts) { + return this.methodRequest('put', path, opts); + } + delete(path, opts) { + return this.methodRequest('delete', path, opts); + } + methodRequest(method, path, opts) { + return this.request(Promise.resolve(opts).then((opts) => { + return { method, path, ...opts }; + })); + } + request(options, remainingRetries = null) { + return new api_promise_APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); + } + async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { + const options = await optionsInput; + const maxRetries = options.maxRetries ?? this.maxRetries; + if (retriesRemaining == null) { + retriesRemaining = maxRetries; + } + await this.prepareOptions(options); + const { req, url, timeout } = await this.buildRequest(options, { + retryCount: maxRetries - retriesRemaining, + }); + await this.prepareRequest(req, { url, options }); + /** Not an API request ID, just for correlating local log entries. */ + const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); + const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; + const startTime = Date.now(); + log_loggerFor(this).debug(`[${requestLogID}] sending request`, log_formatRequestDetails({ + retryOfRequestLogID, + method: options.method, + url, + options, + headers: req.headers, + })); + if (options.signal?.aborted) { + throw new error_APIUserAbortError(); + } + const controller = new AbortController(); + const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(errors_castToError); + const headersTime = Date.now(); + if (response instanceof globalThis.Error) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + if (options.signal?.aborted) { + throw new error_APIUserAbortError(); + } + // detect native connection timeout errors + // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" + // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" + // others do not provide enough information to distinguish timeouts from other connection errors + const isTimeout = errors_isAbortError(response) || + /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); + if (retriesRemaining) { + log_loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); + log_loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, log_formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); + } + log_loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); + log_loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, log_formatRequestDetails({ + retryOfRequestLogID, + url, + durationMs: headersTime - startTime, + message: response.message, + })); + if (isTimeout) { + throw new error_APIConnectionTimeoutError(); + } + throw new error_APIConnectionError({ cause: response }); + } + const specialHeaders = [...response.headers.entries()] + .filter(([name]) => name === 'x-request-id') + .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value)) + .join(''); + const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; + if (!response.ok) { + const shouldRetry = await this.shouldRetry(response); + if (retriesRemaining && shouldRetry) { + const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; + // We don't need the body of this response. + await shims_CancelReadableStream(response.body); + log_loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + log_loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, log_formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); + } + const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; + log_loggerFor(this).info(`${responseInfo} - ${retryMessage}`); + const errText = await response.text().catch((err) => errors_castToError(err).message); + const errJSON = values_safeJSON(errText); + const errMessage = errJSON ? undefined : errText; + log_loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, log_formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + message: errMessage, + durationMs: Date.now() - startTime, + })); + const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); + throw err; + } + log_loggerFor(this).info(responseInfo); + log_loggerFor(this).debug(`[${requestLogID}] response start`, log_formatRequestDetails({ + retryOfRequestLogID, + url: response.url, + status: response.status, + headers: response.headers, + durationMs: headersTime - startTime, + })); + return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; + } + getAPIList(path, Page, opts) { + return this.requestAPIList(Page, { method: 'get', path, ...opts }); + } + requestAPIList(Page, options) { + const request = this.makeRequest(options, null, undefined); + return new pagination_PagePromise(this, request, Page); + } + async fetchWithTimeout(url, init, ms, controller) { + const { signal, method, ...options } = init || {}; + if (signal) + signal.addEventListener('abort', () => controller.abort()); + const timeout = setTimeout(() => controller.abort(), ms); + const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) || + (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); + const fetchOptions = { + signal: controller.signal, + ...(isReadableBody ? { duplex: 'half' } : {}), + method: 'GET', + ...options, + }; + if (method) { + // Custom methods like 'patch' need to be uppercased + // See https://github.com/nodejs/undici/issues/2294 + fetchOptions.method = method.toUpperCase(); + } + try { + // use undefined this binding; fetch errors if bound to something else in browser/cloudflare + return await this.fetch.call(undefined, url, fetchOptions); + } + finally { + clearTimeout(timeout); + } + } + async shouldRetry(response) { + // Note this is not a standard header. + const shouldRetryHeader = response.headers.get('x-should-retry'); + // If the server explicitly says whether or not to retry, obey. + if (shouldRetryHeader === 'true') + return true; + if (shouldRetryHeader === 'false') + return false; + // Retry on request timeouts. + if (response.status === 408) + return true; + // Retry on lock timeouts. + if (response.status === 409) + return true; + // Retry on rate limits. + if (response.status === 429) + return true; + // Retry internal errors. + if (response.status >= 500) + return true; + return false; + } + async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { + let timeoutMillis; + // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. + const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); + if (retryAfterMillisHeader) { + const timeoutMs = parseFloat(retryAfterMillisHeader); + if (!Number.isNaN(timeoutMs)) { + timeoutMillis = timeoutMs; + } + } + // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After + const retryAfterHeader = responseHeaders?.get('retry-after'); + if (retryAfterHeader && !timeoutMillis) { + const timeoutSeconds = parseFloat(retryAfterHeader); + if (!Number.isNaN(timeoutSeconds)) { + timeoutMillis = timeoutSeconds * 1000; + } + else { + timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); + } + } + // If the API asks us to wait a certain amount of time (and it's a reasonable amount), + // just do what it says, but otherwise calculate a default + if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { + const maxRetries = options.maxRetries ?? this.maxRetries; + timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); + } + await sleep_sleep(timeoutMillis); + return this.makeRequest(options, retriesRemaining - 1, requestLogID); + } + calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { + const initialRetryDelay = 0.5; + const maxRetryDelay = 8.0; + const numRetries = maxRetries - retriesRemaining; + // Apply exponential backoff, but not more than the max. + const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); + // Apply some jitter, take up to at most 25 percent of the retry time. + const jitter = 1 - Math.random() * 0.25; + return sleepSeconds * jitter * 1000; + } + async buildRequest(inputOptions, { retryCount = 0 } = {}) { + const options = { ...inputOptions }; + const { method, path, query, defaultBaseURL } = options; + const url = this.buildURL(path, query, defaultBaseURL); + if ('timeout' in options) + values_validatePositiveInteger('timeout', options.timeout); + options.timeout = options.timeout ?? this.timeout; + const { bodyHeaders, body } = this.buildBody({ options }); + const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); + const req = { + method, + headers: reqHeaders, + ...(options.signal && { signal: options.signal }), + ...(globalThis.ReadableStream && + body instanceof globalThis.ReadableStream && { duplex: 'half' }), + ...(body && { body }), + ...(this.fetchOptions ?? {}), + ...(options.fetchOptions ?? {}), + }; + return { req, url, timeout: options.timeout }; + } + async buildHeaders({ options, method, bodyHeaders, retryCount, }) { + let idempotencyHeaders = {}; + if (this.idempotencyHeader && method !== 'get') { + if (!options.idempotencyKey) + options.idempotencyKey = this.defaultIdempotencyKey(); + idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; + } + const headers = headers_buildHeaders([ + idempotencyHeaders, + { + Accept: 'application/json', + 'User-Agent': this.getUserAgent(), + 'X-Stainless-Retry-Count': String(retryCount), + ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), + ...detect_platform_getPlatformHeaders(), + 'OpenAI-Organization': this.organization, + 'OpenAI-Project': this.project, + }, + await this.authHeaders(options), + this._options.defaultHeaders, + bodyHeaders, + options.headers, + ]); + this.validateHeaders(headers); + return headers.values; + } + buildBody({ options: { body, headers: rawHeaders } }) { + if (!body) { + return { bodyHeaders: undefined, body: undefined }; + } + const headers = headers_buildHeaders([rawHeaders]); + if ( + // Pass raw type verbatim + ArrayBuffer.isView(body) || + body instanceof ArrayBuffer || + body instanceof DataView || + (typeof body === 'string' && + // Preserve legacy string encoding behavior for now + headers.values.has('content-type')) || + // `Blob` is superset of `File` + (globalThis.Blob && body instanceof globalThis.Blob) || + // `FormData` -> `multipart/form-data` + body instanceof FormData || + // `URLSearchParams` -> `application/x-www-form-urlencoded` + body instanceof URLSearchParams || + // Send chunked stream (each chunk has own `length`) + (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) { + return { bodyHeaders: undefined, body: body }; + } + else if (typeof body === 'object' && + (Symbol.asyncIterator in body || + (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { + return { bodyHeaders: undefined, body: shims_ReadableStreamFrom(body) }; + } + else { + return tslib_classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers }); + } + } +} +openai_client_a = OpenAI, _OpenAI_encoder = new WeakMap(), _OpenAI_instances = new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() { + return this.baseURL !== 'https://api.openai.com/v1'; +}; +OpenAI.OpenAI = openai_client_a; +OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes +OpenAI.OpenAIError = error_OpenAIError; +OpenAI.APIError = error_APIError; +OpenAI.APIConnectionError = error_APIConnectionError; +OpenAI.APIConnectionTimeoutError = error_APIConnectionTimeoutError; +OpenAI.APIUserAbortError = error_APIUserAbortError; +OpenAI.NotFoundError = error_NotFoundError; +OpenAI.ConflictError = error_ConflictError; +OpenAI.RateLimitError = error_RateLimitError; +OpenAI.BadRequestError = error_BadRequestError; +OpenAI.AuthenticationError = error_AuthenticationError; +OpenAI.InternalServerError = error_InternalServerError; +OpenAI.PermissionDeniedError = error_PermissionDeniedError; +OpenAI.UnprocessableEntityError = error_UnprocessableEntityError; +OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError; +OpenAI.toFile = to_file_toFile; +OpenAI.Completions = resources_completions_Completions; +OpenAI.Chat = Chat; +OpenAI.Embeddings = embeddings_Embeddings; +OpenAI.Files = resources_files_Files; +OpenAI.Images = Images; +OpenAI.Audio = Audio; +OpenAI.Moderations = Moderations; +OpenAI.Models = resources_models_Models; +OpenAI.FineTuning = FineTuning; +OpenAI.Graders = graders_Graders; +OpenAI.VectorStores = VectorStores; +OpenAI.Webhooks = Webhooks; +OpenAI.Beta = beta_Beta; +OpenAI.Batches = resources_batches_Batches; +OpenAI.Uploads = Uploads; +OpenAI.Responses = Responses; +OpenAI.Realtime = realtime_Realtime; +OpenAI.Conversations = Conversations; +OpenAI.Evals = Evals; +OpenAI.Containers = Containers; +OpenAI.Videos = Videos; +//# sourceMappingURL=client.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/azure.mjs + + + + +/** API Client for interfacing with the Azure OpenAI API. */ +class AzureOpenAI extends OpenAI { + /** + * API Client for interfacing with the Azure OpenAI API. + * + * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined] + * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` + * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined] + * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. + * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] + * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`. + * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. + * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. + * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. + * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. + * @param {Headers} opts.defaultHeaders - Default headers to include with every request to the API. + * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. + * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. + */ + constructor({ baseURL = env_readEnv('OPENAI_BASE_URL'), apiKey = env_readEnv('AZURE_OPENAI_API_KEY'), apiVersion = env_readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) { + if (!apiVersion) { + throw new error_OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' })."); + } + if (typeof azureADTokenProvider === 'function') { + dangerouslyAllowBrowser = true; + } + if (!azureADTokenProvider && !apiKey) { + throw new error_OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.'); + } + if (azureADTokenProvider && apiKey) { + throw new error_OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.'); + } + opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion }; + if (!baseURL) { + if (!endpoint) { + endpoint = process.env['AZURE_OPENAI_ENDPOINT']; + } + if (!endpoint) { + throw new error_OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable'); + } + baseURL = `${endpoint}/openai`; + } + else { + if (endpoint) { + throw new error_OpenAIError('baseURL and endpoint are mutually exclusive'); + } + } + super({ + apiKey: azureADTokenProvider ?? apiKey, + baseURL, + ...opts, + ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}), + }); + this.apiVersion = ''; + this.apiVersion = apiVersion; + this.deploymentName = deployment; + } + async buildRequest(options, props = {}) { + if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) { + if (!values_isObj(options.body)) { + throw new Error('Expected request body to be an object'); + } + const model = this.deploymentName || options.body['model'] || options.__metadata?.['model']; + if (model !== undefined && !this.baseURL.includes('/deployments')) { + options.path = `/deployments/${model}${options.path}`; + } + } + return super.buildRequest(options, props); + } + async authHeaders(opts) { + if (typeof this._options.apiKey === 'string') { + return headers_buildHeaders([{ 'api-key': this.apiKey }]); + } + return super.authHeaders(opts); + } +} +const _deployments_endpoints = new Set([ + '/completions', + '/chat/completions', + '/embeddings', + '/audio/transcriptions', + '/audio/translations', + '/audio/speech', + '/images/generations', + '/batches', + '/images/edits', +]); +//# sourceMappingURL=azure.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/index.mjs +// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. + + + + + + + +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/client.js + + + +//#region src/utils/client.ts +function wrapOpenAIClientError(e) { + if (!e || typeof e !== "object") return e; + let error; + if (e.constructor.name === error_APIConnectionTimeoutError.name && "message" in e && typeof e.message === "string") { + error = new Error(e.message); + error.name = "TimeoutError"; + } else if (e.constructor.name === error_APIUserAbortError.name && "message" in e && typeof e.message === "string") { + error = new Error(e.message); + error.name = "AbortError"; + } else if ("status" in e && e.status === 400 && "message" in e && typeof e.message === "string" && e.message.includes("tool_calls")) error = utils_errors_addLangChainErrorFields(e, "INVALID_TOOL_RESULTS"); + else if ("status" in e && e.status === 401) error = utils_errors_addLangChainErrorFields(e, "MODEL_AUTHENTICATION"); + else if ("status" in e && e.status === 429) error = utils_errors_addLangChainErrorFields(e, "MODEL_RATE_LIMIT"); + else if ("status" in e && e.status === 404) error = utils_errors_addLangChainErrorFields(e, "MODEL_NOT_FOUND"); + else error = e; + return error; +} + +//#endregion + +//# sourceMappingURL=client.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/misc.js + + +//#region src/utils/misc.ts +const iife$1 = (fn) => fn(); +function isReasoningModel(model) { + if (!model) return false; + if (/^o\d/.test(model ?? "")) return true; + if (model.startsWith("gpt-5") && !model.startsWith("gpt-5-chat")) return true; + return false; +} +function extractGenericMessageCustomRole(message) { + if (message.role !== "system" && message.role !== "developer" && message.role !== "assistant" && message.role !== "user" && message.role !== "function" && message.role !== "tool") console.warn(`Unknown message role: ${message.role}`); + return message.role; +} +function getRequiredFilenameFromMetadata(block) { + const filename = block.metadata?.filename ?? block.metadata?.name ?? block.metadata?.title; + if (!filename) throw new Error("a filename or name or title is needed via meta-data for OpenAI when working with multimodal blocks"); + return filename; +} +function messageToOpenAIRole(message) { + const type = message._getType(); + switch (type) { + case "system": return "system"; + case "ai": return "assistant"; + case "human": return "user"; + case "function": return "function"; + case "tool": return "tool"; + case "generic": + if (!ChatMessage.isInstance(message)) throw new Error("Invalid generic chat message"); + return extractGenericMessageCustomRole(message); + default: throw new Error(`Unknown message type: ${type}`); + } +} +function _modelPrefersResponsesAPI(model) { + return model.includes("gpt-5.2-pro"); +} + +//#endregion + +//# sourceMappingURL=misc.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/azure.js + + + +//#region src/utils/azure.ts +/** +* This function generates an endpoint URL for (Azure) OpenAI +* based on the configuration parameters provided. +* +* @param {OpenAIEndpointConfig} config - The configuration object for the (Azure) endpoint. +* +* @property {string} config.azureOpenAIApiDeploymentName - The deployment name of Azure OpenAI. +* @property {string} config.azureOpenAIApiInstanceName - The instance name of Azure OpenAI, e.g. `example-resource`. +* @property {string} config.azureOpenAIApiKey - The API Key for Azure OpenAI. +* @property {string} config.azureOpenAIBasePath - The base path for Azure OpenAI, e.g. `https://example-resource.azure.openai.com/openai/deployments/`. +* @property {string} config.baseURL - Some other custom base path URL. +* @property {string} config.azureOpenAIEndpoint - The endpoint for the Azure OpenAI instance, e.g. `https://example-resource.azure.openai.com/`. +* +* The function operates as follows: +* - If both `azureOpenAIBasePath` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`). +* - If both `azureOpenAIEndpoint` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`). +* - If `azureOpenAIApiKey` is provided, it checks for `azureOpenAIApiInstanceName` and `azureOpenAIApiDeploymentName` and throws an error if any of these is missing. If both are provided, it generates an URL incorporating these parameters. +* - If none of the above conditions are met, return any custom `baseURL`. +* - The function returns the generated URL as a string, or undefined if no custom paths are specified. +* +* @throws Will throw an error if the necessary parameters for generating the URL are missing. +* +* @returns {string | undefined} The generated (Azure) OpenAI endpoint URL. +*/ +function getEndpoint(config) { + const { azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName, azureOpenAIApiKey, azureOpenAIBasePath, baseURL, azureADTokenProvider, azureOpenAIEndpoint } = config; + if ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIBasePath && azureOpenAIApiDeploymentName) return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`; + if ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIEndpoint && azureOpenAIApiDeploymentName) return `${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`; + if (azureOpenAIApiKey || azureADTokenProvider) { + if (!azureOpenAIApiInstanceName) throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey"); + if (!azureOpenAIApiDeploymentName) throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey"); + return `https://${azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${azureOpenAIApiDeploymentName}`; + } + return baseURL; +} +function isHeaders(headers) { + return typeof Headers !== "undefined" && headers !== null && typeof headers === "object" && Object.prototype.toString.call(headers) === "[object Headers]"; +} +/** +* Normalizes various header formats into a consistent Record format. +* +* This function accepts headers in multiple formats and converts them to a +* Record for consistent handling. +* +* @param headers - The headers to normalize. Can be: +* - A Headers instance +* - An array of [key, value] pairs +* - A plain object with string keys +* - A NullableHeaders-like object with a 'values' property containing Headers +* - null or undefined +* @returns A normalized Record containing the header key-value pairs +* +* @example +* ```ts +* // With Headers instance +* const headers1 = new Headers([['content-type', 'application/json']]); +* const normalized1 = normalizeHeaders(headers1); +* +* // With plain object +* const headers2 = { 'content-type': 'application/json' }; +* const normalized2 = normalizeHeaders(headers2); +* +* // With array of pairs +* const headers3 = [['content-type', 'application/json']]; +* const normalized3 = normalizeHeaders(headers3); +* ``` +*/ +function normalizeHeaders(headers) { + const output = iife$1(() => { + if (isHeaders(headers)) return headers; + else if (Array.isArray(headers)) return new Headers(headers); + else if (typeof headers === "object" && headers !== null && "values" in headers && isHeaders(headers.values)) return headers.values; + else if (typeof headers === "object" && headers !== null) { + const entries = Object.entries(headers).filter(([, v]) => typeof v === "string").map(([k, v]) => [k, v]); + return new Headers(entries); + } + return new Headers(); + }); + return Object.fromEntries(output.entries()); +} +function getFormattedEnv() { + let env = getEnv(); + if (env === "node" || env === "deno") env = `(${env}/${process.version}; ${process.platform}; ${process.arch})`; + return env; +} +function getHeadersWithUserAgent(headers, isAzure = false, version = "1.0.0") { + const normalizedHeaders = normalizeHeaders(headers); + const env = getFormattedEnv(); + const library = `langchainjs${isAzure ? "-azure" : ""}-openai`; + return { + ...normalizedHeaders, + "User-Agent": normalizedHeaders["User-Agent"] ? `${library}/${version} (${env})${normalizedHeaders["User-Agent"]}` : `${library}/${version} (${env})` + }; +} + +//#endregion + +//# sourceMappingURL=azure.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/tools.js + + + + +//#region src/utils/tools.ts +/** +* Formats a tool in either OpenAI format, or LangChain structured tool format +* into an OpenAI tool format. If the tool is already in OpenAI format, return without +* any changes. If it is in LangChain structured tool format, convert it to OpenAI tool format +* using OpenAI's `zodFunction` util, falling back to `convertToOpenAIFunction` if the parameters +* returned from the `zodFunction` util are not defined. +* +* @param {BindToolsInput} tool The tool to convert to an OpenAI tool. +* @param {Object} [fields] Additional fields to add to the OpenAI tool. +* @returns {ToolDefinition} The inputted tool in OpenAI tool format. +*/ +function _convertToOpenAITool(tool, fields) { + let toolDef; + if (isLangChainTool(tool)) toolDef = convertToOpenAITool(tool); + else toolDef = tool; + if (fields?.strict !== void 0) toolDef.function.strict = fields.strict; + return toolDef; +} +function isAnyOfProp(prop) { + return prop.anyOf !== void 0 && Array.isArray(prop.anyOf); +} +function formatFunctionDefinitions(functions) { + const lines = ["namespace functions {", ""]; + for (const f of functions) { + if (f.description) lines.push(`// ${f.description}`); + if (Object.keys(f.parameters.properties ?? {}).length > 0) { + lines.push(`type ${f.name} = (_: {`); + lines.push(formatObjectProperties(f.parameters, 0)); + lines.push("}) => any;"); + } else lines.push(`type ${f.name} = () => any;`); + lines.push(""); + } + lines.push("} // namespace functions"); + return lines.join("\n"); +} +function formatObjectProperties(obj, indent) { + const lines = []; + for (const [name, param] of Object.entries(obj.properties ?? {})) { + if (param.description && indent < 2) lines.push(`// ${param.description}`); + if (obj.required?.includes(name)) lines.push(`${name}: ${formatType(param, indent)},`); + else lines.push(`${name}?: ${formatType(param, indent)},`); + } + return lines.map((line) => " ".repeat(indent) + line).join("\n"); +} +function formatType(param, indent) { + if (isAnyOfProp(param)) return param.anyOf.map((v) => formatType(v, indent)).join(" | "); + switch (param.type) { + case "string": + if (param.enum) return param.enum.map((v) => `"${v}"`).join(" | "); + return "string"; + case "number": + if (param.enum) return param.enum.map((v) => `${v}`).join(" | "); + return "number"; + case "integer": + if (param.enum) return param.enum.map((v) => `${v}`).join(" | "); + return "number"; + case "boolean": return "boolean"; + case "null": return "null"; + case "object": return [ + "{", + formatObjectProperties(param, indent + 2), + "}" + ].join("\n"); + case "array": + if (param.items) return `${formatType(param.items, indent)}[]`; + return "any[]"; + default: return ""; + } +} +function formatToOpenAIToolChoice(toolChoice) { + if (!toolChoice) return void 0; + else if (toolChoice === "any" || toolChoice === "required") return "required"; + else if (toolChoice === "auto") return "auto"; + else if (toolChoice === "none") return "none"; + else if (typeof toolChoice === "string") return { + type: "function", + function: { name: toolChoice } + }; + else return toolChoice; +} +function isBuiltInTool(tool) { + return "type" in tool && tool.type !== "function"; +} +/** +* Checks if a tool has a provider-specific tool definition in extras.providerToolDefinition. +* This is used for tools like localShell, shell, computerUse, and applyPatch +* that need to be sent as built-in tool types to the OpenAI API. +*/ +function hasProviderToolDefinition(tool) { + return typeof tool === "object" && tool !== null && "extras" in tool && typeof tool.extras === "object" && tool.extras !== null && "providerToolDefinition" in tool.extras && typeof tool.extras.providerToolDefinition === "object" && tool.extras.providerToolDefinition !== null; +} +function isBuiltInToolChoice(tool_choice) { + return tool_choice != null && typeof tool_choice === "object" && "type" in tool_choice && tool_choice.type !== "function"; +} +function isCustomTool(tool) { + return typeof tool === "object" && tool !== null && "metadata" in tool && typeof tool.metadata === "object" && tool.metadata !== null && "customTool" in tool.metadata && typeof tool.metadata.customTool === "object" && tool.metadata.customTool !== null; +} +function isOpenAICustomTool(tool) { + return "type" in tool && tool.type === "custom" && "custom" in tool && typeof tool.custom === "object" && tool.custom !== null; +} +function parseCustomToolCall(rawToolCall) { + if (rawToolCall.type !== "custom_tool_call") return void 0; + return { + ...rawToolCall, + type: "tool_call", + call_id: rawToolCall.id, + id: rawToolCall.call_id, + name: rawToolCall.name, + isCustomTool: true, + args: { input: rawToolCall.input } + }; +} +/** +* Parses a computer_call output item from the OpenAI Responses API +* into a ToolCall format that can be processed by the ToolNode. +* +* @param rawToolCall - The raw computer_call output item from the API +* @returns A ComputerToolCall object if valid, undefined otherwise +*/ +function parseComputerCall(rawToolCall) { + if (rawToolCall.type !== "computer_call") return void 0; + return { + ...rawToolCall, + type: "tool_call", + call_id: rawToolCall.id, + id: rawToolCall.call_id, + name: "computer_use", + isComputerTool: true, + args: { action: rawToolCall.action } + }; +} +/** +* Checks if a tool call is a computer tool call. +* @param toolCall - The tool call to check. +* @returns True if the tool call is a computer tool call, false otherwise. +*/ +function isComputerToolCall(toolCall) { + return typeof toolCall === "object" && toolCall !== null && "type" in toolCall && toolCall.type === "tool_call" && "isComputerTool" in toolCall && toolCall.isComputerTool === true; +} +function isCustomToolCall(toolCall) { + return typeof toolCall === "object" && toolCall !== null && "type" in toolCall && toolCall.type === "tool_call" && "isCustomTool" in toolCall && toolCall.isCustomTool === true; +} +function convertCompletionsCustomTool(tool) { + const getFormat = () => { + if (!tool.custom.format) return void 0; + if (tool.custom.format.type === "grammar") return { + type: "grammar", + definition: tool.custom.format.grammar.definition, + syntax: tool.custom.format.grammar.syntax + }; + if (tool.custom.format.type === "text") return { type: "text" }; + return void 0; + }; + return { + type: "custom", + name: tool.custom.name, + description: tool.custom.description, + format: getFormat() + }; +} +function convertResponsesCustomTool(tool) { + const getFormat = () => { + if (!tool.format) return void 0; + if (tool.format.type === "grammar") return { + type: "grammar", + grammar: { + definition: tool.format.definition, + syntax: tool.format.syntax + } + }; + if (tool.format.type === "text") return { type: "text" }; + return void 0; + }; + return { + type: "custom", + custom: { + name: tool.name, + description: tool.description, + format: getFormat() + } + }; +} + +//#endregion + +//# sourceMappingURL=tools.js.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/Options.mjs +const Options_ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use'); +const zod_to_json_schema_Options_defaultOptions = { + name: undefined, + $refStrategy: 'root', + effectStrategy: 'input', + pipeStrategy: 'all', + dateStrategy: 'format:date-time', + mapStrategy: 'entries', + nullableStrategy: 'from-target', + removeAdditionalStrategy: 'passthrough', + definitionPath: 'definitions', + target: 'jsonSchema7', + strictUnions: false, + errorMessages: false, + markdownDescription: false, + patternStrategy: 'escape', + applyRegexFlags: false, + emailStrategy: 'format:email', + base64Strategy: 'contentEncoding:base64', + nameStrategy: 'ref', +}; +const Options_getDefaultOptions = (options) => { + // We need to add `definitions` here as we may mutate it + return (typeof options === 'string' ? + { + ...zod_to_json_schema_Options_defaultOptions, + basePath: ['#'], + definitions: {}, + name: options, + } + : { + ...zod_to_json_schema_Options_defaultOptions, + basePath: ['#'], + definitions: {}, + ...options, + }); +}; +//# sourceMappingURL=Options.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/util.mjs +const zodDef = (zodSchema) => { + return '_def' in zodSchema ? zodSchema._def : zodSchema; +}; +function util_isEmptyObj(obj) { + if (!obj) + return true; + for (const _k in obj) + return false; + return true; +} +//# sourceMappingURL=util.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs + + +const Refs_getRefs = (options) => { + const _options = Options_getDefaultOptions(options); + const currentPath = _options.name !== undefined ? + [..._options.basePath, _options.definitionPath, _options.name] + : _options.basePath; + return { + ..._options, + currentPath: currentPath, + propertyPath: undefined, + seenRefs: new Set(), + seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ + zodDef(def), + { + def: zodDef(def), + path: [..._options.basePath, _options.definitionPath, name], + // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. + jsonSchema: undefined, + }, + ])), + }; +}; +//# sourceMappingURL=Refs.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs +function any_parseAnyDef() { + return {}; +} +//# sourceMappingURL=any.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs +function errorMessages_addErrorMessage(res, key, errorMessage, refs) { + if (!refs?.errorMessages) + return; + if (errorMessage) { + res.errorMessage = { + ...res.errorMessage, + [key]: errorMessage, + }; + } +} +function errorMessages_setResponseValueAndErrors(res, key, value, errorMessage, refs) { + res[key] = value; + errorMessages_addErrorMessage(res, key, errorMessage, refs); +} +//# sourceMappingURL=errorMessages.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs + + + +function array_parseArrayDef(def, refs) { + const res = { + type: 'array', + }; + if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { + res.items = parseDef_parseDef(def.type._def, { + ...refs, + currentPath: [...refs.currentPath, 'items'], + }); + } + if (def.minLength) { + errorMessages_setResponseValueAndErrors(res, 'minItems', def.minLength.value, def.minLength.message, refs); + } + if (def.maxLength) { + errorMessages_setResponseValueAndErrors(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs); + } + if (def.exactLength) { + errorMessages_setResponseValueAndErrors(res, 'minItems', def.exactLength.value, def.exactLength.message, refs); + errorMessages_setResponseValueAndErrors(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs); + } + return res; +} +//# sourceMappingURL=array.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs + +function bigint_parseBigintDef(def, refs) { + const res = { + type: 'integer', + format: 'int64', + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case 'min': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } + else { + errorMessages_setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } + break; + case 'max': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } + else { + errorMessages_setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } + break; + case 'multipleOf': + errorMessages_setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs); + break; + } + } + return res; +} +//# sourceMappingURL=bigint.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs +function boolean_parseBooleanDef() { + return { + type: 'boolean', + }; +} +//# sourceMappingURL=boolean.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs + +function branded_parseBrandedDef(_def, refs) { + return parseDef_parseDef(_def.type._def, refs); +} +//# sourceMappingURL=branded.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs + +const catch_parseCatchDef = (def, refs) => { + return parseDef_parseDef(def.innerType._def, refs); +}; +//# sourceMappingURL=catch.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs + +function date_parseDateDef(def, refs, overrideDateStrategy) { + const strategy = overrideDateStrategy ?? refs.dateStrategy; + if (Array.isArray(strategy)) { + return { + anyOf: strategy.map((item, i) => date_parseDateDef(def, refs, item)), + }; + } + switch (strategy) { + case 'string': + case 'format:date-time': + return { + type: 'string', + format: 'date-time', + }; + case 'format:date': + return { + type: 'string', + format: 'date', + }; + case 'integer': + return date_integerDateParser(def, refs); + } +} +const date_integerDateParser = (def, refs) => { + const res = { + type: 'integer', + format: 'unix-time', + }; + if (refs.target === 'openApi3') { + return res; + } + for (const check of def.checks) { + switch (check.kind) { + case 'min': + errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, // This is in milliseconds + check.message, refs); + break; + case 'max': + errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, // This is in milliseconds + check.message, refs); + break; + } + } + return res; +}; +//# sourceMappingURL=date.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs + +function default_parseDefaultDef(_def, refs) { + return { + ...parseDef_parseDef(_def.innerType._def, refs), + default: _def.defaultValue(), + }; +} +//# sourceMappingURL=default.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs + +function effects_parseEffectsDef(_def, refs, forceResolution) { + return refs.effectStrategy === 'input' ? parseDef_parseDef(_def.schema._def, refs, forceResolution) : {}; +} +//# sourceMappingURL=effects.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs +function enum_parseEnumDef(def) { + return { + type: 'string', + enum: [...def.values], + }; +} +//# sourceMappingURL=enum.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs + +const intersection_isJsonSchema7AllOfType = (type) => { + if ('type' in type && type.type === 'string') + return false; + return 'allOf' in type; +}; +function intersection_parseIntersectionDef(def, refs) { + const allOf = [ + parseDef_parseDef(def.left._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '0'], + }), + parseDef_parseDef(def.right._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '1'], + }), + ].filter((x) => !!x); + let unevaluatedProperties = refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined; + const mergedAllOf = []; + // If either of the schemas is an allOf, merge them into a single allOf + allOf.forEach((schema) => { + if (intersection_isJsonSchema7AllOfType(schema)) { + mergedAllOf.push(...schema.allOf); + if (schema.unevaluatedProperties === undefined) { + // If one of the schemas has no unevaluatedProperties set, + // the merged schema should also have no unevaluatedProperties set + unevaluatedProperties = undefined; + } + } + else { + let nestedSchema = schema; + if ('additionalProperties' in schema && schema.additionalProperties === false) { + const { additionalProperties, ...rest } = schema; + nestedSchema = rest; + } + else { + // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties + unevaluatedProperties = undefined; + } + mergedAllOf.push(nestedSchema); + } + }); + return mergedAllOf.length ? + { + allOf: mergedAllOf, + ...unevaluatedProperties, + } + : undefined; +} +//# sourceMappingURL=intersection.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs +function literal_parseLiteralDef(def, refs) { + const parsedType = typeof def.value; + if (parsedType !== 'bigint' && + parsedType !== 'number' && + parsedType !== 'boolean' && + parsedType !== 'string') { + return { + type: Array.isArray(def.value) ? 'array' : 'object', + }; + } + if (refs.target === 'openApi3') { + return { + type: parsedType === 'bigint' ? 'integer' : parsedType, + enum: [def.value], + }; + } + return { + type: parsedType === 'bigint' ? 'integer' : parsedType, + const: def.value, + }; +} +//# sourceMappingURL=literal.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs + +let parsers_string_emojiRegex; +/** + * Generated from the regular expressions found here as of 2024-05-22: + * https://github.com/colinhacks/zod/blob/master/src/types.ts. + * + * Expressions with /i flag have been changed accordingly. + */ +const string_zodPatterns = { + /** + * `c` was changed to `[cC]` to replicate /i flag + */ + cuid: /^[cC][^\s-]{8,}$/, + cuid2: /^[0-9a-z]+$/, + ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, + /** + * `a-z` was added to replicate /i flag + */ + email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, + /** + * Constructed a valid Unicode RegExp + * + * Lazily instantiate since this type of regex isn't supported + * in all envs (e.g. React Native). + * + * See: + * https://github.com/colinhacks/zod/issues/2433 + * Fix in Zod: + * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b + */ + emoji: () => { + if (parsers_string_emojiRegex === undefined) { + parsers_string_emojiRegex = RegExp('^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$', 'u'); + } + return parsers_string_emojiRegex; + }, + /** + * Unused + */ + uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, + /** + * Unused + */ + ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, + /** + * Unused + */ + ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, + base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, + nanoid: /^[a-zA-Z0-9_-]{21}$/, +}; +function string_parseStringDef(def, refs) { + const res = { + type: 'string', + }; + function processPattern(value) { + return refs.patternStrategy === 'escape' ? string_escapeNonAlphaNumeric(value) : value; + } + if (def.checks) { + for (const check of def.checks) { + switch (check.kind) { + case 'min': + errorMessages_setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + break; + case 'max': + errorMessages_setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case 'email': + switch (refs.emailStrategy) { + case 'format:email': + string_addFormat(res, 'email', check.message, refs); + break; + case 'format:idn-email': + string_addFormat(res, 'idn-email', check.message, refs); + break; + case 'pattern:zod': + string_addPattern(res, string_zodPatterns.email, check.message, refs); + break; + } + break; + case 'url': + string_addFormat(res, 'uri', check.message, refs); + break; + case 'uuid': + string_addFormat(res, 'uuid', check.message, refs); + break; + case 'regex': + string_addPattern(res, check.regex, check.message, refs); + break; + case 'cuid': + string_addPattern(res, string_zodPatterns.cuid, check.message, refs); + break; + case 'cuid2': + string_addPattern(res, string_zodPatterns.cuid2, check.message, refs); + break; + case 'startsWith': + string_addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs); + break; + case 'endsWith': + string_addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs); + break; + case 'datetime': + string_addFormat(res, 'date-time', check.message, refs); + break; + case 'date': + string_addFormat(res, 'date', check.message, refs); + break; + case 'time': + string_addFormat(res, 'time', check.message, refs); + break; + case 'duration': + string_addFormat(res, 'duration', check.message, refs); + break; + case 'length': + errorMessages_setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs); + errorMessages_setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); + break; + case 'includes': { + string_addPattern(res, RegExp(processPattern(check.value)), check.message, refs); + break; + } + case 'ip': { + if (check.version !== 'v6') { + string_addFormat(res, 'ipv4', check.message, refs); + } + if (check.version !== 'v4') { + string_addFormat(res, 'ipv6', check.message, refs); + } + break; + } + case 'emoji': + string_addPattern(res, string_zodPatterns.emoji, check.message, refs); + break; + case 'ulid': { + string_addPattern(res, string_zodPatterns.ulid, check.message, refs); + break; + } + case 'base64': { + switch (refs.base64Strategy) { + case 'format:binary': { + string_addFormat(res, 'binary', check.message, refs); + break; + } + case 'contentEncoding:base64': { + errorMessages_setResponseValueAndErrors(res, 'contentEncoding', 'base64', check.message, refs); + break; + } + case 'pattern:zod': { + string_addPattern(res, string_zodPatterns.base64, check.message, refs); + break; + } + } + break; + } + case 'nanoid': { + string_addPattern(res, string_zodPatterns.nanoid, check.message, refs); + } + case 'toLowerCase': + case 'toUpperCase': + case 'trim': + break; + default: + ((_) => { })(check); + } + } + } + return res; +} +const string_escapeNonAlphaNumeric = (value) => Array.from(value) + .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\${c}`)) + .join(''); +const string_addFormat = (schema, value, message, refs) => { + if (schema.format || schema.anyOf?.some((x) => x.format)) { + if (!schema.anyOf) { + schema.anyOf = []; + } + if (schema.format) { + schema.anyOf.push({ + format: schema.format, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { format: schema.errorMessage.format }, + }), + }); + delete schema.format; + if (schema.errorMessage) { + delete schema.errorMessage.format; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.anyOf.push({ + format: value, + ...(message && refs.errorMessages && { errorMessage: { format: message } }), + }); + } + else { + errorMessages_setResponseValueAndErrors(schema, 'format', value, message, refs); + } +}; +const string_addPattern = (schema, regex, message, refs) => { + if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { + if (!schema.allOf) { + schema.allOf = []; + } + if (schema.pattern) { + schema.allOf.push({ + pattern: schema.pattern, + ...(schema.errorMessage && + refs.errorMessages && { + errorMessage: { pattern: schema.errorMessage.pattern }, + }), + }); + delete schema.pattern; + if (schema.errorMessage) { + delete schema.errorMessage.pattern; + if (Object.keys(schema.errorMessage).length === 0) { + delete schema.errorMessage; + } + } + } + schema.allOf.push({ + pattern: processRegExp(regex, refs), + ...(message && refs.errorMessages && { errorMessage: { pattern: message } }), + }); + } + else { + errorMessages_setResponseValueAndErrors(schema, 'pattern', processRegExp(regex, refs), message, refs); + } +}; +// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true +const processRegExp = (regexOrFunction, refs) => { + const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction; + if (!refs.applyRegexFlags || !regex.flags) + return regex.source; + // Currently handled flags + const flags = { + i: regex.flags.includes('i'), // Case-insensitive + m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters + s: regex.flags.includes('s'), // `.` matches newlines + }; + // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! + const source = flags.i ? regex.source.toLowerCase() : regex.source; + let pattern = ''; + let isEscaped = false; + let inCharGroup = false; + let inCharRange = false; + for (let i = 0; i < source.length; i++) { + if (isEscaped) { + pattern += source[i]; + isEscaped = false; + continue; + } + if (flags.i) { + if (inCharGroup) { + if (source[i].match(/[a-z]/)) { + if (inCharRange) { + pattern += source[i]; + pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); + inCharRange = false; + } + else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) { + pattern += source[i]; + inCharRange = true; + } + else { + pattern += `${source[i]}${source[i].toUpperCase()}`; + } + continue; + } + } + else if (source[i].match(/[a-z]/)) { + pattern += `[${source[i]}${source[i].toUpperCase()}]`; + continue; + } + } + if (flags.m) { + if (source[i] === '^') { + pattern += `(^|(?<=[\r\n]))`; + continue; + } + else if (source[i] === '$') { + pattern += `($|(?=[\r\n]))`; + continue; + } + } + if (flags.s && source[i] === '.') { + pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; + continue; + } + pattern += source[i]; + if (source[i] === '\\') { + isEscaped = true; + } + else if (inCharGroup && source[i] === ']') { + inCharGroup = false; + } + else if (!inCharGroup && source[i] === '[') { + inCharGroup = true; + } + } + try { + const regexTest = new RegExp(pattern); + } + catch { + console.warn(`Could not convert regex pattern at ${refs.currentPath.join('/')} to a flag-independent form! Falling back to the flag-ignorant source`); + return regex.source; + } + return pattern; +}; +//# sourceMappingURL=string.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs + + + +function record_parseRecordDef(def, refs) { + if (refs.target === 'openApi3' && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + type: 'object', + required: def.keyType._def.values, + properties: def.keyType._def.values.reduce((acc, key) => ({ + ...acc, + [key]: parseDef_parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'properties', key], + }) ?? {}, + }), {}), + additionalProperties: false, + }; + } + const schema = { + type: 'object', + additionalProperties: parseDef_parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? {}, + }; + if (refs.target === 'openApi3') { + return schema; + } + if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { + const keyType = Object.entries(string_parseStringDef(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === 'type' ? acc : { ...acc, [key]: value }), {}); + return { + ...schema, + propertyNames: keyType, + }; + } + else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { + return { + ...schema, + propertyNames: { + enum: def.keyType._def.values, + }, + }; + } + return schema; +} +//# sourceMappingURL=record.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs + + +function map_parseMapDef(def, refs) { + if (refs.mapStrategy === 'record') { + return record_parseRecordDef(def, refs); + } + const keys = parseDef_parseDef(def.keyType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', 'items', '0'], + }) || {}; + const values = parseDef_parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', 'items', '1'], + }) || {}; + return { + type: 'array', + maxItems: 125, + items: { + type: 'array', + items: [keys, values], + minItems: 2, + maxItems: 2, + }, + }; +} +//# sourceMappingURL=map.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs +function nativeEnum_parseNativeEnumDef(def) { + const object = def.values; + const actualKeys = Object.keys(def.values).filter((key) => { + return typeof object[object[key]] !== 'number'; + }); + const actualValues = actualKeys.map((key) => object[key]); + const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); + return { + type: parsedTypes.length === 1 ? + parsedTypes[0] === 'string' ? + 'string' + : 'number' + : ['string', 'number'], + enum: actualValues, + }; +} +//# sourceMappingURL=nativeEnum.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs +function never_parseNeverDef() { + return { + not: {}, + }; +} +//# sourceMappingURL=never.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs +function null_parseNullDef(refs) { + return refs.target === 'openApi3' ? + { + enum: ['null'], + nullable: true, + } + : { + type: 'null', + }; +} +//# sourceMappingURL=null.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs + +const union_primitiveMappings = { + ZodString: 'string', + ZodNumber: 'number', + ZodBigInt: 'integer', + ZodBoolean: 'boolean', + ZodNull: 'null', +}; +function union_parseUnionDef(def, refs) { + if (refs.target === 'openApi3') + return union_asAnyOf(def, refs); + const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; + // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. + if (options.every((x) => x._def.typeName in union_primitiveMappings && (!x._def.checks || !x._def.checks.length))) { + // all types in union are primitive and lack checks, so might as well squash into {type: [...]} + const types = options.reduce((types, x) => { + const type = union_primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 + return type && !types.includes(type) ? [...types, type] : types; + }, []); + return { + type: types.length > 1 ? types : types[0], + }; + } + else if (options.every((x) => x._def.typeName === 'ZodLiteral' && !x.description)) { + // all options literals + const types = options.reduce((acc, x) => { + const type = typeof x._def.value; + switch (type) { + case 'string': + case 'number': + case 'boolean': + return [...acc, type]; + case 'bigint': + return [...acc, 'integer']; + case 'object': + if (x._def.value === null) + return [...acc, 'null']; + case 'symbol': + case 'undefined': + case 'function': + default: + return acc; + } + }, []); + if (types.length === options.length) { + // all the literals are primitive, as far as null can be considered primitive + const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); + return { + type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], + enum: options.reduce((acc, x) => { + return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; + }, []), + }; + } + } + else if (options.every((x) => x._def.typeName === 'ZodEnum')) { + return { + type: 'string', + enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []), + }; + } + return union_asAnyOf(def, refs); +} +const union_asAnyOf = (def, refs) => { + const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options) + .map((x, i) => parseDef_parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', `${i}`], + })) + .filter((x) => !!x && (!refs.strictUnions || (typeof x === 'object' && Object.keys(x).length > 0))); + return anyOf.length ? { anyOf } : undefined; +}; +//# sourceMappingURL=union.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs + + +function nullable_parseNullableDef(def, refs) { + if (['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) && + (!def.innerType._def.checks || !def.innerType._def.checks.length)) { + if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') { + return { + type: union_primitiveMappings[def.innerType._def.typeName], + nullable: true, + }; + } + return { + type: [union_primitiveMappings[def.innerType._def.typeName], 'null'], + }; + } + if (refs.target === 'openApi3') { + const base = parseDef_parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath], + }); + if (base && '$ref' in base) + return { allOf: [base], nullable: true }; + return base && { ...base, nullable: true }; + } + const base = parseDef_parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', '0'], + }); + return base && { anyOf: [base, { type: 'null' }] }; +} +//# sourceMappingURL=nullable.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs + +function number_parseNumberDef(def, refs) { + const res = { + type: 'number', + }; + if (!def.checks) + return res; + for (const check of def.checks) { + switch (check.kind) { + case 'int': + res.type = 'integer'; + errorMessages_addErrorMessage(res, 'type', check.message, refs); + break; + case 'min': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } + else { + errorMessages_setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMinimum = true; + } + errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); + } + break; + case 'max': + if (refs.target === 'jsonSchema7') { + if (check.inclusive) { + errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } + else { + errorMessages_setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs); + } + } + else { + if (!check.inclusive) { + res.exclusiveMaximum = true; + } + errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); + } + break; + case 'multipleOf': + errorMessages_setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs); + break; + } + } + return res; +} +//# sourceMappingURL=number.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs + +function object_decideAdditionalProperties(def, refs) { + if (refs.removeAdditionalStrategy === 'strict') { + return def.catchall._def.typeName === 'ZodNever' ? + def.unknownKeys !== 'strict' + : parseDef_parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? true; + } + else { + return def.catchall._def.typeName === 'ZodNever' ? + def.unknownKeys === 'passthrough' + : parseDef_parseDef(def.catchall._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalProperties'], + }) ?? true; + } +} +function object_parseObjectDef(def, refs) { + const result = { + type: 'object', + ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { + if (propDef === undefined || propDef._def === undefined) + return acc; + const propertyPath = [...refs.currentPath, 'properties', propName]; + const parsedDef = parseDef_parseDef(propDef._def, { + ...refs, + currentPath: propertyPath, + propertyPath, + }); + if (parsedDef === undefined) + return acc; + if (refs.openaiStrictMode && + propDef.isOptional() && + !propDef.isNullable() && + typeof propDef._def?.defaultValue === 'undefined') { + throw new Error(`Zod field at \`${propertyPath.join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`); + } + return { + properties: { + ...acc.properties, + [propName]: parsedDef, + }, + required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName], + }; + }, { properties: {}, required: [] }), + additionalProperties: object_decideAdditionalProperties(def, refs), + }; + if (!result.required.length) + delete result.required; + return result; +} +//# sourceMappingURL=object.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs + +const optional_parseOptionalDef = (def, refs) => { + if (refs.propertyPath && + refs.currentPath.slice(0, refs.propertyPath.length).toString() === refs.propertyPath.toString()) { + return parseDef_parseDef(def.innerType._def, { ...refs, currentPath: refs.currentPath }); + } + const innerSchema = parseDef_parseDef(def.innerType._def, { + ...refs, + currentPath: [...refs.currentPath, 'anyOf', '1'], + }); + return innerSchema ? + { + anyOf: [ + { + not: {}, + }, + innerSchema, + ], + } + : {}; +}; +//# sourceMappingURL=optional.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs + +const pipeline_parsePipelineDef = (def, refs) => { + if (refs.pipeStrategy === 'input') { + return parseDef_parseDef(def.in._def, refs); + } + else if (refs.pipeStrategy === 'output') { + return parseDef_parseDef(def.out._def, refs); + } + const a = parseDef_parseDef(def.in._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', '0'], + }); + const b = parseDef_parseDef(def.out._def, { + ...refs, + currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'], + }); + return { + allOf: [a, b].filter((x) => x !== undefined), + }; +}; +//# sourceMappingURL=pipeline.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs + +function promise_parsePromiseDef(def, refs) { + return parseDef_parseDef(def.type._def, refs); +} +//# sourceMappingURL=promise.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs + + +function set_parseSetDef(def, refs) { + const items = parseDef_parseDef(def.valueType._def, { + ...refs, + currentPath: [...refs.currentPath, 'items'], + }); + const schema = { + type: 'array', + uniqueItems: true, + items, + }; + if (def.minSize) { + errorMessages_setResponseValueAndErrors(schema, 'minItems', def.minSize.value, def.minSize.message, refs); + } + if (def.maxSize) { + errorMessages_setResponseValueAndErrors(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs); + } + return schema; +} +//# sourceMappingURL=set.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs + +function tuple_parseTupleDef(def, refs) { + if (def.rest) { + return { + type: 'array', + minItems: def.items.length, + items: def.items + .map((x, i) => parseDef_parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + additionalItems: parseDef_parseDef(def.rest._def, { + ...refs, + currentPath: [...refs.currentPath, 'additionalItems'], + }), + }; + } + else { + return { + type: 'array', + minItems: def.items.length, + maxItems: def.items.length, + items: def.items + .map((x, i) => parseDef_parseDef(x._def, { + ...refs, + currentPath: [...refs.currentPath, 'items', `${i}`], + })) + .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), + }; + } +} +//# sourceMappingURL=tuple.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs +function undefined_parseUndefinedDef() { + return { + not: {}, + }; +} +//# sourceMappingURL=undefined.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs +function unknown_parseUnknownDef() { + return {}; +} +//# sourceMappingURL=unknown.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs + +const readonly_parseReadonlyDef = (def, refs) => { + return parseDef_parseDef(def.innerType._def, refs); +}; +//# sourceMappingURL=readonly.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +function parseDef_parseDef(def, refs, forceResolution = false) { + const seenItem = refs.seen.get(def); + if (refs.override) { + const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); + if (overrideResult !== Options_ignoreOverride) { + return overrideResult; + } + } + if (seenItem && !forceResolution) { + const seenSchema = parseDef_get$ref(seenItem, refs); + if (seenSchema !== undefined) { + if ('$ref' in seenSchema) { + refs.seenRefs.add(seenSchema.$ref); + } + return seenSchema; + } + } + const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; + refs.seen.set(def, newItem); + const jsonSchema = parseDef_selectParser(def, def.typeName, refs, forceResolution); + if (jsonSchema) { + parseDef_addMeta(def, refs, jsonSchema); + } + newItem.jsonSchema = jsonSchema; + return jsonSchema; +} +const parseDef_get$ref = (item, refs) => { + switch (refs.$refStrategy) { + case 'root': + return { $ref: item.path.join('/') }; + // this case is needed as OpenAI strict mode doesn't support top-level `$ref`s, i.e. + // the top-level schema *must* be `{"type": "object", "properties": {...}}` but if we ever + // need to define a `$ref`, relative `$ref`s aren't supported, so we need to extract + // the schema to `#/definitions/` and reference that. + // + // e.g. if we need to reference a schema at + // `["#","definitions","contactPerson","properties","person1","properties","name"]` + // then we'll extract it out to `contactPerson_properties_person1_properties_name` + case 'extract-to-root': + const name = item.path.slice(refs.basePath.length + 1).join('_'); + // we don't need to extract the root schema in this case, as it's already + // been added to the definitions + if (name !== refs.name && refs.nameStrategy === 'duplicate-ref') { + refs.definitions[name] = item.def; + } + return { $ref: [...refs.basePath, refs.definitionPath, name].join('/') }; + case 'relative': + return { $ref: parseDef_getRelativePath(refs.currentPath, item.path) }; + case 'none': + case 'seen': { + if (item.path.length < refs.currentPath.length && + item.path.every((value, index) => refs.currentPath[index] === value)) { + console.warn(`Recursive reference detected at ${refs.currentPath.join('/')}! Defaulting to any`); + return {}; + } + return refs.$refStrategy === 'seen' ? {} : undefined; + } + } +}; +const parseDef_getRelativePath = (pathA, pathB) => { + let i = 0; + for (; i < pathA.length && i < pathB.length; i++) { + if (pathA[i] !== pathB[i]) + break; + } + return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/'); +}; +const parseDef_selectParser = (def, typeName, refs, forceResolution) => { + switch (typeName) { + case ZodFirstPartyTypeKind.ZodString: + return string_parseStringDef(def, refs); + case ZodFirstPartyTypeKind.ZodNumber: + return number_parseNumberDef(def, refs); + case ZodFirstPartyTypeKind.ZodObject: + return object_parseObjectDef(def, refs); + case ZodFirstPartyTypeKind.ZodBigInt: + return bigint_parseBigintDef(def, refs); + case ZodFirstPartyTypeKind.ZodBoolean: + return boolean_parseBooleanDef(); + case ZodFirstPartyTypeKind.ZodDate: + return date_parseDateDef(def, refs); + case ZodFirstPartyTypeKind.ZodUndefined: + return undefined_parseUndefinedDef(); + case ZodFirstPartyTypeKind.ZodNull: + return null_parseNullDef(refs); + case ZodFirstPartyTypeKind.ZodArray: + return array_parseArrayDef(def, refs); + case ZodFirstPartyTypeKind.ZodUnion: + case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: + return union_parseUnionDef(def, refs); + case ZodFirstPartyTypeKind.ZodIntersection: + return intersection_parseIntersectionDef(def, refs); + case ZodFirstPartyTypeKind.ZodTuple: + return tuple_parseTupleDef(def, refs); + case ZodFirstPartyTypeKind.ZodRecord: + return record_parseRecordDef(def, refs); + case ZodFirstPartyTypeKind.ZodLiteral: + return literal_parseLiteralDef(def, refs); + case ZodFirstPartyTypeKind.ZodEnum: + return enum_parseEnumDef(def); + case ZodFirstPartyTypeKind.ZodNativeEnum: + return nativeEnum_parseNativeEnumDef(def); + case ZodFirstPartyTypeKind.ZodNullable: + return nullable_parseNullableDef(def, refs); + case ZodFirstPartyTypeKind.ZodOptional: + return optional_parseOptionalDef(def, refs); + case ZodFirstPartyTypeKind.ZodMap: + return map_parseMapDef(def, refs); + case ZodFirstPartyTypeKind.ZodSet: + return set_parseSetDef(def, refs); + case ZodFirstPartyTypeKind.ZodLazy: + return parseDef_parseDef(def.getter()._def, refs); + case ZodFirstPartyTypeKind.ZodPromise: + return promise_parsePromiseDef(def, refs); + case ZodFirstPartyTypeKind.ZodNaN: + case ZodFirstPartyTypeKind.ZodNever: + return never_parseNeverDef(); + case ZodFirstPartyTypeKind.ZodEffects: + return effects_parseEffectsDef(def, refs, forceResolution); + case ZodFirstPartyTypeKind.ZodAny: + return any_parseAnyDef(); + case ZodFirstPartyTypeKind.ZodUnknown: + return unknown_parseUnknownDef(); + case ZodFirstPartyTypeKind.ZodDefault: + return default_parseDefaultDef(def, refs); + case ZodFirstPartyTypeKind.ZodBranded: + return branded_parseBrandedDef(def, refs); + case ZodFirstPartyTypeKind.ZodReadonly: + return readonly_parseReadonlyDef(def, refs); + case ZodFirstPartyTypeKind.ZodCatch: + return catch_parseCatchDef(def, refs); + case ZodFirstPartyTypeKind.ZodPipeline: + return pipeline_parsePipelineDef(def, refs); + case ZodFirstPartyTypeKind.ZodFunction: + case ZodFirstPartyTypeKind.ZodVoid: + case ZodFirstPartyTypeKind.ZodSymbol: + return undefined; + default: + return ((_) => undefined)(typeName); + } +}; +const parseDef_addMeta = (def, refs, jsonSchema) => { + if (def.description) { + jsonSchema.description = def.description; + if (refs.markdownDescription) { + jsonSchema.markdownDescription = def.description; + } + } + return jsonSchema; +}; +//# sourceMappingURL=parseDef.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs + + + +const zod_to_json_schema_zodToJsonSchema_zodToJsonSchema = (schema, options) => { + const refs = Refs_getRefs(options); + const name = typeof options === 'string' ? options + : options?.nameStrategy === 'title' ? undefined + : options?.name; + const main = parseDef_parseDef(schema._def, name === undefined ? refs : ({ + ...refs, + currentPath: [...refs.basePath, refs.definitionPath, name], + }), false) ?? {}; + const title = typeof options === 'object' && options.name !== undefined && options.nameStrategy === 'title' ? + options.name + : undefined; + if (title !== undefined) { + main.title = title; + } + const definitions = (() => { + if (util_isEmptyObj(refs.definitions)) { + return undefined; + } + const definitions = {}; + const processedDefinitions = new Set(); + // the call to `parseDef()` here might itself add more entries to `.definitions` + // so we need to continually evaluate definitions until we've resolved all of them + // + // we have a generous iteration limit here to avoid blowing up the stack if there + // are any bugs that would otherwise result in us iterating indefinitely + for (let i = 0; i < 500; i++) { + const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key)); + if (newDefinitions.length === 0) + break; + for (const [key, schema] of newDefinitions) { + definitions[key] = + parseDef_parseDef(zodDef(schema), { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, true) ?? {}; + processedDefinitions.add(key); + } + } + return definitions; + })(); + const combined = name === undefined ? + definitions ? + { + ...main, + [refs.definitionPath]: definitions, + } + : main + : refs.nameStrategy === 'duplicate-ref' ? + { + ...main, + ...(definitions || refs.seenRefs.size ? + { + [refs.definitionPath]: { + ...definitions, + // only actually duplicate the schema definition if it was ever referenced + // otherwise the duplication is completely pointless + ...(refs.seenRefs.size ? { [name]: main } : undefined), + }, + } + : undefined), + } + : { + $ref: [...(refs.$refStrategy === 'relative' ? [] : refs.basePath), refs.definitionPath, name].join('/'), + [refs.definitionPath]: { + ...definitions, + [name]: main, + }, + }; + if (refs.target === 'jsonSchema7') { + combined.$schema = 'http://json-schema.org/draft-07/schema#'; + } + else if (refs.target === 'jsonSchema2019-09') { + combined.$schema = 'https://json-schema.org/draft/2019-09/schema#'; + } + return combined; +}; + +//# sourceMappingURL=zodToJsonSchema.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/index.mjs + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +/* harmony default export */ const zod_to_json_schema = ((/* unused pure expression or super */ null && (zodToJsonSchema))); +//# sourceMappingURL=index.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/lib/transform.mjs +function toStrictJsonSchema(schema) { + if (schema.type !== 'object') { + throw new Error(`Root schema must have type: 'object' but got type: ${schema.type ? `'${schema.type}'` : 'undefined'}`); + } + const schemaCopy = structuredClone(schema); + return ensureStrictJsonSchema(schemaCopy, [], schemaCopy); +} +function isNullable(schema) { + if (typeof schema === 'boolean') { + return false; + } + if (schema.type === 'null') { + return true; + } + for (const oneOfVariant of schema.oneOf ?? []) { + if (isNullable(oneOfVariant)) { + return true; + } + } + for (const allOfVariant of schema.anyOf ?? []) { + if (isNullable(allOfVariant)) { + return true; + } + } + return false; +} +/** + * Mutates the given JSON schema to ensure it conforms to the `strict` standard + * that the API expects. + */ +function ensureStrictJsonSchema(jsonSchema, path, root) { + if (typeof jsonSchema === 'boolean') { + throw new TypeError(`Expected object schema but got boolean; path=${path.join('/')}`); + } + if (!transform_isObject(jsonSchema)) { + throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be an object; path=${path.join('/')}`); + } + // Handle $defs (non-standard but sometimes used) + const defs = jsonSchema.$defs; + if (transform_isObject(defs)) { + for (const [defName, defSchema] of Object.entries(defs)) { + ensureStrictJsonSchema(defSchema, [...path, '$defs', defName], root); + } + } + // Handle definitions (draft-04 style, deprecated in draft-07 but still used) + const definitions = jsonSchema.definitions; + if (transform_isObject(definitions)) { + for (const [definitionName, definitionSchema] of Object.entries(definitions)) { + ensureStrictJsonSchema(definitionSchema, [...path, 'definitions', definitionName], root); + } + } + // Add additionalProperties: false to object types + const typ = jsonSchema.type; + if (typ === 'object' && !('additionalProperties' in jsonSchema)) { + jsonSchema.additionalProperties = false; + } + const required = jsonSchema.required ?? []; + // Handle object properties + const properties = jsonSchema.properties; + if (transform_isObject(properties)) { + for (const [key, value] of Object.entries(properties)) { + if (!isNullable(value) && !required.includes(key)) { + throw new Error(`Zod field at \`${[...path, 'properties', key].join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`); + } + } + jsonSchema.required = Object.keys(properties); + jsonSchema.properties = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [ + key, + ensureStrictJsonSchema(propSchema, [...path, 'properties', key], root), + ])); + } + // Handle arrays + const items = jsonSchema.items; + if (transform_isObject(items)) { + jsonSchema.items = ensureStrictJsonSchema(items, [...path, 'items'], root); + } + // Handle unions (anyOf) + const anyOf = jsonSchema.anyOf; + if (Array.isArray(anyOf)) { + jsonSchema.anyOf = anyOf.map((variant, i) => ensureStrictJsonSchema(variant, [...path, 'anyOf', String(i)], root)); + } + // Handle intersections (allOf) + const allOf = jsonSchema.allOf; + if (Array.isArray(allOf)) { + if (allOf.length === 1) { + const resolved = ensureStrictJsonSchema(allOf[0], [...path, 'allOf', '0'], root); + Object.assign(jsonSchema, resolved); + delete jsonSchema.allOf; + } + else { + jsonSchema.allOf = allOf.map((entry, i) => ensureStrictJsonSchema(entry, [...path, 'allOf', String(i)], root)); + } + } + // Strip `null` defaults as there's no meaningful distinction + if (jsonSchema.default === null) { + delete jsonSchema.default; + } + // Handle $ref with additional properties + const ref = jsonSchema.$ref; + if (ref && hasMoreThanNKeys(jsonSchema, 1)) { + if (typeof ref !== 'string') { + throw new TypeError(`Received non-string $ref - ${ref}; path=${path.join('/')}`); + } + const resolved = transform_resolveRef(root, ref); + if (typeof resolved === 'boolean') { + throw new Error(`Expected \`$ref: ${ref}\` to resolve to an object schema but got boolean`); + } + if (!transform_isObject(resolved)) { + throw new Error(`Expected \`$ref: ${ref}\` to resolve to an object but got ${JSON.stringify(resolved)}`); + } + // Properties from the json schema take priority over the ones on the `$ref` + Object.assign(jsonSchema, { ...resolved, ...jsonSchema }); + delete jsonSchema.$ref; + // Since the schema expanded from `$ref` might not have `additionalProperties: false` applied, + // we call `ensureStrictJsonSchema` again to fix the inlined schema and ensure it's valid. + return ensureStrictJsonSchema(jsonSchema, path, root); + } + return jsonSchema; +} +function transform_resolveRef(root, ref) { + if (!ref.startsWith('#/')) { + throw new Error(`Unexpected $ref format ${JSON.stringify(ref)}; Does not start with #/`); + } + const pathParts = ref.slice(2).split('/'); + let resolved = root; + for (const key of pathParts) { + if (!transform_isObject(resolved)) { + throw new Error(`encountered non-object entry while resolving ${ref} - ${JSON.stringify(resolved)}`); + } + const value = resolved[key]; + if (value === undefined) { + throw new Error(`Key ${key} not found while resolving ${ref}`); + } + resolved = value; + } + return resolved; +} +function transform_isObject(obj) { + return typeof obj === 'object' && obj !== null && !Array.isArray(obj); +} +function hasMoreThanNKeys(obj, n) { + let i = 0; + for (const _ in obj) { + i++; + if (i > n) { + return true; + } + } + return false; +} +//# sourceMappingURL=transform.mjs.map +;// CONCATENATED MODULE: ./node_modules/openai/helpers/zod.mjs + + + + + +function zodV3ToJsonSchema(schema, options) { + return zod_to_json_schema_zodToJsonSchema_zodToJsonSchema(schema, { + openaiStrictMode: true, + name: options.name, + nameStrategy: 'duplicate-ref', + $refStrategy: 'extract-to-root', + nullableStrategy: 'property', + }); +} +function zodV4ToJsonSchema(schema) { + return toStrictJsonSchema(toJSONSchema(schema, { + target: 'draft-7', + })); +} +function isZodV4(zodObject) { + return '_zod' in zodObject; +} +/** + * Creates a chat completion `JSONSchema` response format object from + * the given Zod schema. + * + * If this is passed to the `.parse()`, `.stream()` or `.runTools()` + * chat completion methods then the response message will contain a + * `.parsed` property that is the result of parsing the content with + * the given Zod object. + * + * ```ts + * const completion = await client.chat.completions.parse({ + * model: 'gpt-4o-2024-08-06', + * messages: [ + * { role: 'system', content: 'You are a helpful math tutor.' }, + * { role: 'user', content: 'solve 8x + 31 = 2' }, + * ], + * response_format: zodResponseFormat( + * z.object({ + * steps: z.array(z.object({ + * explanation: z.string(), + * answer: z.string(), + * })), + * final_answer: z.string(), + * }), + * 'math_answer', + * ), + * }); + * const message = completion.choices[0]?.message; + * if (message?.parsed) { + * console.log(message.parsed); + * console.log(message.parsed.final_answer); + * } + * ``` + * + * This can be passed directly to the `.create()` method but will not + * result in any automatic parsing, you'll have to parse the response yourself. + */ +function zodResponseFormat(zodObject, name, props) { + return makeParseableResponseFormat({ + type: 'json_schema', + json_schema: { + ...props, + name, + strict: true, + schema: isZodV4(zodObject) ? zodV4ToJsonSchema(zodObject) : zodV3ToJsonSchema(zodObject, { name }), + }, + }, (content) => zodObject.parse(JSON.parse(content))); +} +function zodTextFormat(zodObject, name, props) { + return makeParseableTextFormat({ + type: 'json_schema', + ...props, + name, + strict: true, + schema: isZodV4(zodObject) ? zodV4ToJsonSchema(zodObject) : zodV3ToJsonSchema(zodObject, { name }), + }, (content) => zodObject.parse(JSON.parse(content))); +} +/** + * Creates a chat completion `function` tool that can be invoked + * automatically by the chat completion `.runTools()` method or automatically + * parsed by `.parse()` / `.stream()`. + */ +function zodFunction(options) { + // @ts-expect-error TODO + return makeParseableTool({ + type: 'function', + function: { + name: options.name, + parameters: isZodV4(options.parameters) ? + zodV4ToJsonSchema(options.parameters) + : zodV3ToJsonSchema(options.parameters, { name: options.name }), + strict: true, + ...(options.description ? { description: options.description } : undefined), + }, + }, { + callback: options.function, + parser: (args) => options.parameters.parse(JSON.parse(args)), + }); +} +function zodResponsesFunction(options) { + return makeParseableResponseTool({ + type: 'function', + name: options.name, + parameters: isZodV4(options.parameters) ? + zodV4ToJsonSchema(options.parameters) + : zodV3ToJsonSchema(options.parameters, { name: options.name }), + strict: true, + ...(options.description ? { description: options.description } : undefined), + }, { + callback: options.function, + parser: (args) => options.parameters.parse(JSON.parse(args)), + }); +} +//# sourceMappingURL=zod.mjs.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/output.js + + + + + +//#region src/utils/output.ts +const SUPPORTED_METHODS = [ + "jsonSchema", + "functionCalling", + "jsonMode" +]; +/** +* Get the structured output method for a given model. By default, it uses +* `jsonSchema` if the model supports it, otherwise it uses `functionCalling`. +* +* @throws if the method is invalid, e.g. is not a string or invalid method is provided. +* @param model - The model name. +* @param config - The structured output method options. +* @returns The structured output method. +*/ +function getStructuredOutputMethod(model, method) { + /** + * If a method is provided, validate it. + */ + if (typeof method !== "undefined" && !SUPPORTED_METHODS.includes(method)) throw new Error(`Invalid method: ${method}. Supported methods are: ${SUPPORTED_METHODS.join(", ")}`); + const hasSupportForJsonSchema = !model.startsWith("gpt-3") && !model.startsWith("gpt-4-") && model !== "gpt-4"; + /** + * If the model supports JSON Schema, use it by default. + */ + if (hasSupportForJsonSchema && !method) return "jsonSchema"; + if (!hasSupportForJsonSchema && method === "jsonSchema") throw new Error(`JSON Schema is not supported for model "${model}". Please use a different method, e.g. "functionCalling" or "jsonMode".`); + /** + * If the model does not support JSON Schema, use function calling by default. + */ + return method ?? "functionCalling"; +} +function output_makeParseableResponseFormat(response_format, parser) { + const obj = { ...response_format }; + Object.defineProperties(obj, { + $brand: { + value: "auto-parseable-response-format", + enumerable: false + }, + $parseRaw: { + value: parser, + enumerable: false + } + }); + return obj; +} +function interopZodResponseFormat(zodSchema, name, props) { + if (isZodSchemaV3(zodSchema)) return zodResponseFormat(zodSchema, name, props); + if (isZodSchemaV4(zodSchema)) return output_makeParseableResponseFormat({ + type: "json_schema", + json_schema: { + ...props, + name, + strict: true, + schema: toJsonSchema(zodSchema, { + cycles: "ref", + reused: "ref", + override(ctx) { + ctx.jsonSchema.title = name; + } + }) + } + }, (content) => parse_parse(zodSchema, JSON.parse(content))); + throw new Error("Unsupported schema response format"); +} +/** +* Handle multi modal response content. +* +* @param content The content of the message. +* @param messages The messages of the response. +* @returns The new content of the message. +*/ +function handleMultiModalOutput(content, messages) { + /** + * Handle OpenRouter image responses + * @see https://openrouter.ai/docs/features/multimodal/image-generation#api-usage + */ + if (messages && typeof messages === "object" && "images" in messages && Array.isArray(messages.images)) { + const images = messages.images.filter((image) => typeof image?.image_url?.url === "string").map((image) => ({ + type: "image", + url: image.image_url.url + })); + return [{ + type: "text", + text: content + }, ...images]; + } + return content; +} + +//#endregion + +//# sourceMappingURL=output.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/profiles.js +//#region src/chat_models/profiles.ts +const profiles_PROFILES = { + "gpt-4.1-nano": { + maxInputTokens: 1047576, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32768, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "text-embedding-3-small": { + maxInputTokens: 8191, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1536, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4": { + maxInputTokens: 8192, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o1-pro": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4o-2024-05-13": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4o-2024-08-06": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 16384, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4.1-mini": { + maxInputTokens: 1047576, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32768, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o3-deep-research": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-3.5-turbo": { + maxInputTokens: 16385, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: false, + imageUrlInputs: false, + pdfToolMessage: false, + imageToolMessage: false, + toolChoice: true + }, + "text-embedding-3-large": { + maxInputTokens: 8191, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 3072, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4-turbo": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 4096, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o1-preview": { + maxInputTokens: 128e3, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32768, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o3-mini": { + maxInputTokens: 2e5, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "codex-mini-latest": { + maxInputTokens: 2e5, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5-nano": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5-codex": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4o": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 16384, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4.1": { + maxInputTokens: 1047576, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 32768, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o4-mini": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + o1: { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5-mini": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o1-mini": { + maxInputTokens: 128e3, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "text-embedding-ada-002": { + maxInputTokens: 8192, + imageInputs: false, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1536, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o3-pro": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4o-2024-11-20": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 16384, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + o3: { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "o4-mini-deep-research": { + maxInputTokens: 2e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 1e5, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5-chat-latest": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-4o-mini": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 16384, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 128e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + }, + "gpt-5-pro": { + maxInputTokens: 4e5, + imageInputs: true, + audioInputs: false, + pdfInputs: true, + videoInputs: false, + maxOutputTokens: 272e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true, + imageUrlInputs: true, + pdfToolMessage: true, + imageToolMessage: true, + toolChoice: true + } +}; +var profiles_profiles_default = profiles_PROFILES; + +//#endregion + +//# sourceMappingURL=profiles.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/base.js + + + + + + + + + + + + + + + + +//#region src/chat_models/base.ts +/** @internal */ +var BaseChatOpenAI = class extends BaseChatModel { + temperature; + topP; + frequencyPenalty; + presencePenalty; + n; + logitBias; + model = "gpt-3.5-turbo"; + modelKwargs; + stop; + stopSequences; + user; + timeout; + streaming = false; + streamUsage = true; + maxTokens; + logprobs; + topLogprobs; + apiKey; + organization; + __includeRawResponse; + /** @internal */ + client; + /** @internal */ + clientConfig; + /** + * Whether the model supports the `strict` argument when passing in tools. + * If `undefined` the `strict` argument will not be passed to OpenAI. + */ + supportsStrictToolCalling; + audio; + modalities; + reasoning; + /** + * Must be set to `true` in tenancies with Zero Data Retention. Setting to `true` will disable + * output storage in the Responses API, but this DOES NOT enable Zero Data Retention in your + * OpenAI organization or project. This must be configured directly with OpenAI. + * + * See: + * https://platform.openai.com/docs/guides/your-data + * https://platform.openai.com/docs/api-reference/responses/create#responses-create-store + * + * @default false + */ + zdrEnabled; + /** + * Service tier to use for this request. Can be "auto", "default", or "flex" or "priority". + * Specifies the service tier for prioritization and latency optimization. + */ + service_tier; + /** + * Used by OpenAI to cache responses for similar requests to optimize your cache + * hit rates. + * [Learn more](https://platform.openai.com/docs/guides/prompt-caching). + */ + promptCacheKey; + /** + * Used by OpenAI to set cache retention time + */ + promptCacheRetention; + /** + * The verbosity of the model's response. + */ + verbosity; + defaultOptions; + _llmType() { + return "openai"; + } + static lc_name() { + return "ChatOpenAI"; + } + get callKeys() { + return [ + ...super.callKeys, + "options", + "function_call", + "functions", + "tools", + "tool_choice", + "promptIndex", + "response_format", + "seed", + "reasoning", + "service_tier" + ]; + } + lc_serializable = true; + get lc_secrets() { + return { + apiKey: "OPENAI_API_KEY", + organization: "OPENAI_ORGANIZATION" + }; + } + get lc_aliases() { + return { + apiKey: "openai_api_key", + modelName: "model" + }; + } + get lc_serializable_keys() { + return [ + "configuration", + "logprobs", + "topLogprobs", + "prefixMessages", + "supportsStrictToolCalling", + "modalities", + "audio", + "temperature", + "maxTokens", + "topP", + "frequencyPenalty", + "presencePenalty", + "n", + "logitBias", + "user", + "streaming", + "streamUsage", + "model", + "modelName", + "modelKwargs", + "stop", + "stopSequences", + "timeout", + "apiKey", + "cache", + "maxConcurrency", + "maxRetries", + "verbose", + "callbacks", + "tags", + "metadata", + "disableStreaming", + "zdrEnabled", + "reasoning", + "promptCacheKey", + "promptCacheRetention", + "verbosity" + ]; + } + getLsParams(options) { + const params = this.invocationParams(options); + return { + ls_provider: "openai", + ls_model_name: this.model, + ls_model_type: "chat", + ls_temperature: params.temperature ?? void 0, + ls_max_tokens: params.max_tokens ?? void 0, + ls_stop: options.stop + }; + } + /** @ignore */ + _identifyingParams() { + return { + model_name: this.model, + ...this.invocationParams(), + ...this.clientConfig + }; + } + /** + * Get the identifying parameters for the model + */ + identifyingParams() { + return this._identifyingParams(); + } + constructor(fields) { + super(fields ?? {}); + const configApiKey = typeof fields?.configuration?.apiKey === "string" || typeof fields?.configuration?.apiKey === "function" ? fields?.configuration?.apiKey : void 0; + this.apiKey = fields?.apiKey ?? configApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); + this.organization = fields?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); + this.model = fields?.model ?? fields?.modelName ?? this.model; + this.modelKwargs = fields?.modelKwargs ?? {}; + this.timeout = fields?.timeout; + this.temperature = fields?.temperature ?? this.temperature; + this.topP = fields?.topP ?? this.topP; + this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; + this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; + this.logprobs = fields?.logprobs; + this.topLogprobs = fields?.topLogprobs; + this.n = fields?.n ?? this.n; + this.logitBias = fields?.logitBias; + this.stop = fields?.stopSequences ?? fields?.stop; + this.stopSequences = this.stop; + this.user = fields?.user; + this.__includeRawResponse = fields?.__includeRawResponse; + this.audio = fields?.audio; + this.modalities = fields?.modalities; + this.reasoning = fields?.reasoning; + this.maxTokens = fields?.maxCompletionTokens ?? fields?.maxTokens; + this.promptCacheKey = fields?.promptCacheKey ?? this.promptCacheKey; + this.promptCacheRetention = fields?.promptCacheRetention ?? this.promptCacheRetention; + this.verbosity = fields?.verbosity ?? this.verbosity; + this.disableStreaming = fields?.disableStreaming === true; + this.streaming = fields?.streaming === true; + if (this.disableStreaming) this.streaming = false; + if (fields?.streaming === false) this.disableStreaming = true; + this.streamUsage = fields?.streamUsage ?? this.streamUsage; + if (this.disableStreaming) this.streamUsage = false; + this.clientConfig = { + apiKey: this.apiKey, + organization: this.organization, + dangerouslyAllowBrowser: true, + ...fields?.configuration + }; + if (fields?.supportsStrictToolCalling !== void 0) this.supportsStrictToolCalling = fields.supportsStrictToolCalling; + if (fields?.service_tier !== void 0) this.service_tier = fields.service_tier; + this.zdrEnabled = fields?.zdrEnabled ?? false; + } + /** + * Returns backwards compatible reasoning parameters from constructor params and call options + * @internal + */ + _getReasoningParams(options) { + if (!isReasoningModel(this.model)) return; + let reasoning; + if (this.reasoning !== void 0) reasoning = { + ...reasoning, + ...this.reasoning + }; + if (options?.reasoning !== void 0) reasoning = { + ...reasoning, + ...options.reasoning + }; + return reasoning; + } + /** + * Returns an openai compatible response format from a set of options + * @internal + */ + _getResponseFormat(resFormat) { + if (resFormat && resFormat.type === "json_schema" && resFormat.json_schema.schema && isInteropZodSchema(resFormat.json_schema.schema)) return interopZodResponseFormat(resFormat.json_schema.schema, resFormat.json_schema.name, { description: resFormat.json_schema.description }); + return resFormat; + } + _combineCallOptions(additionalOptions) { + return { + ...this.defaultOptions, + ...additionalOptions ?? {} + }; + } + /** @internal */ + _getClientOptions(options) { + if (!this.client) { + const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL }; + const endpoint = getEndpoint(openAIEndpointConfig); + const params = { + ...this.clientConfig, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0 + }; + if (!params.baseURL) delete params.baseURL; + params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders); + this.client = new OpenAI(params); + } + const requestOptions = { + ...this.clientConfig, + ...options + }; + return requestOptions; + } + _convertChatOpenAIToolToCompletionsTool(tool, fields) { + if (isCustomTool(tool)) return convertResponsesCustomTool(tool.metadata.customTool); + if (isOpenAITool(tool)) { + if (fields?.strict !== void 0) return { + ...tool, + function: { + ...tool.function, + strict: fields.strict + } + }; + return tool; + } + return _convertToOpenAITool(tool, fields); + } + bindTools(tools, kwargs) { + let strict; + if (kwargs?.strict !== void 0) strict = kwargs.strict; + else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; + return this.withConfig({ + tools: tools.map((tool) => { + if (isBuiltInTool(tool) || isCustomTool(tool)) return tool; + if (hasProviderToolDefinition(tool)) return tool.extras.providerToolDefinition; + return this._convertChatOpenAIToolToCompletionsTool(tool, { strict }); + }), + ...kwargs + }); + } + async stream(input, options) { + return super.stream(input, this._combineCallOptions(options)); + } + async invoke(input, options) { + return super.invoke(input, this._combineCallOptions(options)); + } + /** @ignore */ + _combineLLMOutput(...llmOutputs) { + return llmOutputs.reduce((acc, llmOutput) => { + if (llmOutput && llmOutput.tokenUsage) { + acc.tokenUsage.completionTokens += llmOutput.tokenUsage.completionTokens ?? 0; + acc.tokenUsage.promptTokens += llmOutput.tokenUsage.promptTokens ?? 0; + acc.tokenUsage.totalTokens += llmOutput.tokenUsage.totalTokens ?? 0; + } + return acc; + }, { tokenUsage: { + completionTokens: 0, + promptTokens: 0, + totalTokens: 0 + } }); + } + async getNumTokensFromMessages(messages) { + let totalCount = 0; + let tokensPerMessage = 0; + let tokensPerName = 0; + if (this.model === "gpt-3.5-turbo-0301") { + tokensPerMessage = 4; + tokensPerName = -1; + } else { + tokensPerMessage = 3; + tokensPerName = 1; + } + const countPerMessage = await Promise.all(messages.map(async (message) => { + const textCount = await this.getNumTokens(message.content); + const roleCount = await this.getNumTokens(messageToOpenAIRole(message)); + const nameCount = message.name !== void 0 ? tokensPerName + await this.getNumTokens(message.name) : 0; + let count = textCount + tokensPerMessage + roleCount + nameCount; + const openAIMessage = message; + if (openAIMessage._getType() === "function") count -= 2; + if (openAIMessage.additional_kwargs?.function_call) count += 3; + if (openAIMessage?.additional_kwargs.function_call?.name) count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.name); + if (openAIMessage.additional_kwargs.function_call?.arguments) try { + count += await this.getNumTokens(JSON.stringify(JSON.parse(openAIMessage.additional_kwargs.function_call?.arguments))); + } catch (error) { + console.error("Error parsing function arguments", error, JSON.stringify(openAIMessage.additional_kwargs.function_call)); + count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.arguments); + } + totalCount += count; + return count; + })); + totalCount += 3; + return { + totalCount, + countPerMessage + }; + } + /** @internal */ + async _getNumTokensFromGenerations(generations) { + const generationUsages = await Promise.all(generations.map(async (generation) => { + if (generation.message.additional_kwargs?.function_call) return (await this.getNumTokensFromMessages([generation.message])).countPerMessage[0]; + else return await this.getNumTokens(generation.message.content); + })); + return generationUsages.reduce((a, b) => a + b, 0); + } + /** @internal */ + async _getEstimatedTokenCountFromPrompt(messages, functions, function_call) { + let tokens = (await this.getNumTokensFromMessages(messages)).totalCount; + if (functions && function_call !== "auto") { + const promptDefinitions = formatFunctionDefinitions(functions); + tokens += await this.getNumTokens(promptDefinitions); + tokens += 9; + } + if (functions && messages.find((m) => m._getType() === "system")) tokens -= 4; + if (function_call === "none") tokens += 1; + else if (typeof function_call === "object") tokens += await this.getNumTokens(function_call.name) + 4; + return tokens; + } + /** + * Moderate content using OpenAI's Moderation API. + * + * This method checks whether content violates OpenAI's content policy by + * analyzing text for categories such as hate, harassment, self-harm, + * sexual content, violence, and more. + * + * @param input - The text or array of texts to moderate + * @param params - Optional parameters for the moderation request + * @param params.model - The moderation model to use. Defaults to "omni-moderation-latest". + * @param params.options - Additional options to pass to the underlying request + * @returns A promise that resolves to the moderation response containing results for each input + * + * @example + * ```typescript + * const model = new ChatOpenAI({ model: "gpt-4o-mini" }); + * + * // Moderate a single text + * const result = await model.moderateContent("This is a test message"); + * console.log(result.results[0].flagged); // false + * console.log(result.results[0].categories); // { hate: false, harassment: false, ... } + * + * // Moderate multiple texts + * const results = await model.moderateContent([ + * "Hello, how are you?", + * "This is inappropriate content" + * ]); + * results.results.forEach((result, index) => { + * console.log(`Text ${index + 1} flagged:`, result.flagged); + * }); + * + * // Use a specific moderation model + * const stableResult = await model.moderateContent( + * "Test content", + * { model: "omni-moderation-latest" } + * ); + * ``` + */ + async moderateContent(input, params) { + const clientOptions = this._getClientOptions(params?.options); + const moderationModel = params?.model ?? "omni-moderation-latest"; + const moderationRequest = { + input, + model: moderationModel + }; + return this.caller.call(async () => { + try { + const response = await this.client.moderations.create(moderationRequest, clientOptions); + return response; + } catch (e) { + const error = wrapOpenAIClientError(e); + throw error; + } + }); + } + /** + * Return profiling information for the model. + * + * Provides information about the model's capabilities and constraints, + * including token limits, multimodal support, and advanced features like + * tool calling and structured output. + * + * @returns {ModelProfile} An object describing the model's capabilities and constraints + * + * @example + * ```typescript + * const model = new ChatOpenAI({ model: "gpt-4o" }); + * const profile = model.profile; + * console.log(profile.maxInputTokens); // 128000 + * console.log(profile.imageInputs); // true + * ``` + */ + get profile() { + return profiles_profiles_default[this.model] ?? {}; + } + /** @internal */ + _getStructuredOutputMethod(config) { + const ensuredConfig = { ...config }; + if (!this.model.startsWith("gpt-3") && !this.model.startsWith("gpt-4-") && this.model !== "gpt-4") { + if (ensuredConfig?.method === void 0) return "jsonSchema"; + } else if (ensuredConfig.method === "jsonSchema") console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`); + return ensuredConfig.method; + } + /** + * Add structured output to the model. + * + * The OpenAI model family supports the following structured output methods: + * - `jsonSchema`: Use the `response_format` field in the response to return a JSON schema. Only supported with the `gpt-4o-mini`, + * `gpt-4o-mini-2024-07-18`, and `gpt-4o-2024-08-06` model snapshots and later. + * - `functionCalling`: Function calling is useful when you are building an application that bridges the models and functionality + * of your application. + * - `jsonMode`: JSON mode is a more basic version of the Structured Outputs feature. While JSON mode ensures that model + * output is valid JSON, Structured Outputs reliably matches the model's output to the schema you specify. + * We recommend you use `functionCalling` or `jsonSchema` if it is supported for your use case. + * + * The default method is `functionCalling`. + * + * @see https://platform.openai.com/docs/guides/structured-outputs + * @param outputSchema - The schema to use for structured output. + * @param config - The structured output method options. + * @returns The model with structured output. + */ + withStructuredOutput(outputSchema, config) { + let llm; + let outputParser; + const { schema, name, includeRaw } = { + ...config, + schema: outputSchema + }; + if (config?.strict !== void 0 && config.method === "jsonMode") throw new Error("Argument `strict` is only supported for `method` = 'function_calling'"); + const method = getStructuredOutputMethod(this.model, config?.method); + if (method === "jsonMode") { + if (isInteropZodSchema(schema)) outputParser = StructuredOutputParser.fromZodSchema(schema); + else outputParser = new JsonOutputParser(); + const asJsonSchema = toJsonSchema(schema); + llm = this.withConfig({ + outputVersion: "v0", + response_format: { type: "json_object" }, + ls_structured_output_format: { + kwargs: { method: "json_mode" }, + schema: { + title: name ?? "extract", + ...asJsonSchema + } + } + }); + } else if (method === "jsonSchema") { + const openaiJsonSchemaParams = { + name: name ?? "extract", + description: getSchemaDescription(schema), + schema, + strict: config?.strict + }; + const asJsonSchema = toJsonSchema(openaiJsonSchemaParams.schema); + llm = this.withConfig({ + outputVersion: "v0", + response_format: { + type: "json_schema", + json_schema: openaiJsonSchemaParams + }, + ls_structured_output_format: { + kwargs: { method: "json_schema" }, + schema: { + title: openaiJsonSchemaParams.name, + description: openaiJsonSchemaParams.description, + ...asJsonSchema + } + } + }); + if (isInteropZodSchema(schema)) { + const altParser = StructuredOutputParser.fromZodSchema(schema); + outputParser = RunnableLambda.from((aiMessage) => { + if ("parsed" in aiMessage.additional_kwargs) return aiMessage.additional_kwargs.parsed; + return altParser; + }); + } else outputParser = new JsonOutputParser(); + } else { + let functionName = name ?? "extract"; + if (isInteropZodSchema(schema)) { + const asJsonSchema = toJsonSchema(schema); + llm = this.withConfig({ + outputVersion: "v0", + tools: [{ + type: "function", + function: { + name: functionName, + description: asJsonSchema.description, + parameters: asJsonSchema + } + }], + tool_choice: { + type: "function", + function: { name: functionName } + }, + ls_structured_output_format: { + kwargs: { method: "function_calling" }, + schema: { + title: functionName, + ...asJsonSchema + } + }, + ...config?.strict !== void 0 ? { strict: config.strict } : {} + }); + outputParser = new JsonOutputKeyToolsParser({ + returnSingle: true, + keyName: functionName, + zodSchema: schema + }); + } else { + let openAIFunctionDefinition; + if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) { + openAIFunctionDefinition = schema; + functionName = schema.name; + } else { + functionName = schema.title ?? functionName; + openAIFunctionDefinition = { + name: functionName, + description: schema.description ?? "", + parameters: schema + }; + } + const asJsonSchema = toJsonSchema(schema); + llm = this.withConfig({ + outputVersion: "v0", + tools: [{ + type: "function", + function: openAIFunctionDefinition + }], + tool_choice: { + type: "function", + function: { name: functionName } + }, + ls_structured_output_format: { + kwargs: { method: "function_calling" }, + schema: { + title: functionName, + ...asJsonSchema + } + }, + ...config?.strict !== void 0 ? { strict: config.strict } : {} + }); + outputParser = new JsonOutputKeyToolsParser({ + returnSingle: true, + keyName: functionName + }); + } + } + if (!includeRaw) return llm.pipe(outputParser); + const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); + const parserNone = RunnablePassthrough.assign({ parsed: () => null }); + const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); + return RunnableSequence.from([{ raw: llm }, parsedWithFallback]); + } +}; + +//#endregion + +//# sourceMappingURL=base.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/converters/completions.js + + + + + +//#region src/converters/completions.ts +/** +* @deprecated This converter is an internal detail of the OpenAI provider. Do not use it directly. This will be revisited in a future release. +*/ +const completionsApiContentBlockConverter = { + providerName: "ChatOpenAI", + fromStandardTextBlock(block) { + return { + type: "text", + text: block.text + }; + }, + fromStandardImageBlock(block) { + if (block.source_type === "url") return { + type: "image_url", + image_url: { + url: block.url, + ...block.metadata?.detail ? { detail: block.metadata.detail } : {} + } + }; + if (block.source_type === "base64") { + const url = `data:${block.mime_type ?? ""};base64,${block.data}`; + return { + type: "image_url", + image_url: { + url, + ...block.metadata?.detail ? { detail: block.metadata.detail } : {} + } + }; + } + throw new Error(`Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); + }, + fromStandardAudioBlock(block) { + if (block.source_type === "url") { + const data = parseBase64DataUrl({ dataUrl: block.url }); + if (!data) throw new Error(`URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`); + const rawMimeType = data.mime_type || block.mime_type || ""; + let mimeType; + try { + mimeType = parseMimeType(rawMimeType); + } catch { + throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); + } + if (mimeType.type !== "audio" || mimeType.subtype !== "wav" && mimeType.subtype !== "mp3") throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); + return { + type: "input_audio", + input_audio: { + format: mimeType.subtype, + data: data.data + } + }; + } + if (block.source_type === "base64") { + let mimeType; + try { + mimeType = parseMimeType(block.mime_type ?? ""); + } catch { + throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); + } + if (mimeType.type !== "audio" || mimeType.subtype !== "wav" && mimeType.subtype !== "mp3") throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); + return { + type: "input_audio", + input_audio: { + format: mimeType.subtype, + data: block.data + } + }; + } + throw new Error(`Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); + }, + fromStandardFileBlock(block) { + if (block.source_type === "url") { + const data = parseBase64DataUrl({ dataUrl: block.url }); + const filename = getRequiredFilenameFromMetadata(block); + if (!data) throw new Error(`URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`); + return { + type: "file", + file: { + file_data: block.url, + ...block.metadata?.filename || block.metadata?.name ? { filename } : {} + } + }; + } + if (block.source_type === "base64") { + const filename = getRequiredFilenameFromMetadata(block); + return { + type: "file", + file: { + file_data: `data:${block.mime_type ?? ""};base64,${block.data}`, + ...block.metadata?.filename || block.metadata?.name || block.metadata?.title ? { filename } : {} + } + }; + } + if (block.source_type === "id") return { + type: "file", + file: { file_id: block.id } + }; + throw new Error(`File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); + } +}; +/** +* Converts an OpenAI Chat Completions API message to a LangChain BaseMessage. +* +* This converter transforms messages from OpenAI's Chat Completions API format into +* LangChain's internal message representation, handling various message types and +* preserving metadata, tool calls, and other relevant information. +* +* @remarks +* The converter handles the following message roles: +* - `assistant`: Converted to {@link AIMessage} with support for tool calls, function calls, +* audio content, and multi-modal outputs +* - Other roles: Converted to generic {@link ChatMessage} +* +* For assistant messages, the converter: +* - Parses and validates tool calls, separating valid and invalid calls +* - Preserves function call information in additional_kwargs +* - Includes usage statistics and system fingerprint in response_metadata +* - Handles multi-modal content (text, images, audio) +* - Optionally includes the raw API response for debugging +* +* @param params - Conversion parameters +* @param params.message - The OpenAI chat completion message to convert +* @param params.rawResponse - The complete raw response from OpenAI's API, used to extract +* metadata like model name, usage statistics, and system fingerprint +* @param params.includeRawResponse - If true, includes the raw OpenAI response in the +* message's additional_kwargs under the `__raw_response` key. Useful for debugging +* or accessing provider-specific fields. Defaults to false. +* +* @returns A LangChain BaseMessage instance: +* - {@link AIMessage} for assistant messages with tool calls, metadata, and content +* - {@link ChatMessage} for all other message types +* +* @example +* ```typescript +* const baseMessage = convertCompletionsMessageToBaseMessage({ +* message: { +* role: "assistant", +* content: "Hello! How can I help you?", +* tool_calls: [ +* { +* id: "call_123", +* type: "function", +* function: { name: "get_weather", arguments: '{"location":"NYC"}' } +* } +* ] +* }, +* rawResponse: completionResponse, +* includeRawResponse: true +* }); +* // Returns an AIMessage with parsed tool calls and metadata +* ``` +* +* @throws {Error} If tool call parsing fails, the invalid tool call is captured in +* the `invalid_tool_calls` array rather than throwing an error +* +*/ +const convertCompletionsMessageToBaseMessage = ({ message, rawResponse, includeRawResponse }) => { + const rawToolCalls = message.tool_calls; + switch (message.role) { + case "assistant": { + const toolCalls = []; + const invalidToolCalls = []; + for (const rawToolCall of rawToolCalls ?? []) try { + toolCalls.push(parseToolCall(rawToolCall, { returnId: true })); + } catch (e) { + invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e.message)); + } + const additional_kwargs = { + function_call: message.function_call, + tool_calls: rawToolCalls + }; + if (includeRawResponse !== void 0) additional_kwargs.__raw_response = rawResponse; + const response_metadata = { + model_provider: "openai", + model_name: rawResponse.model, + ...rawResponse.system_fingerprint ? { + usage: { ...rawResponse.usage }, + system_fingerprint: rawResponse.system_fingerprint + } : {} + }; + if (message.audio) additional_kwargs.audio = message.audio; + const content = handleMultiModalOutput(message.content || "", rawResponse.choices?.[0]?.message); + return new AIMessage({ + content, + tool_calls: toolCalls, + invalid_tool_calls: invalidToolCalls, + additional_kwargs, + response_metadata, + id: rawResponse.id + }); + } + default: return new ChatMessage(message.content || "", message.role ?? "unknown"); + } +}; +/** +* Converts an OpenAI Chat Completions API delta (streaming chunk) to a LangChain BaseMessageChunk. +* +* This converter is used during streaming responses to transform incremental updates from OpenAI's +* Chat Completions API into LangChain message chunks. It handles various message types, tool calls, +* function calls, audio content, and role-specific message chunk creation. +* +* @param params - Conversion parameters +* @param params.delta - The delta object from an OpenAI streaming chunk containing incremental +* message updates. May include content, role, tool_calls, function_call, audio, etc. +* @param params.rawResponse - The complete raw ChatCompletionChunk response from OpenAI, +* containing metadata like model info, usage stats, and the delta +* @param params.includeRawResponse - Optional flag to include the raw OpenAI response in the +* message chunk's additional_kwargs. Useful for debugging or accessing provider-specific data +* @param params.defaultRole - Optional default role to use if the delta doesn't specify one. +* Typically used to maintain role consistency across chunks in a streaming response +* +* @returns A BaseMessageChunk subclass appropriate for the message role: +* - HumanMessageChunk for "user" role +* - AIMessageChunk for "assistant" role (includes tool call chunks) +* - SystemMessageChunk for "system" or "developer" roles +* - FunctionMessageChunk for "function" role +* - ToolMessageChunk for "tool" role +* - ChatMessageChunk for any other role +* +* @example +* Basic streaming text chunk: +* ```typescript +* const chunk = convertCompletionsDeltaToBaseMessageChunk({ +* delta: { role: "assistant", content: "Hello" }, +* rawResponse: { id: "chatcmpl-123", model: "gpt-4", ... } +* }); +* // Returns: AIMessageChunk with content "Hello" +* ``` +* +* @example +* Streaming chunk with tool call: +* ```typescript +* const chunk = convertCompletionsDeltaToBaseMessageChunk({ +* delta: { +* role: "assistant", +* tool_calls: [{ +* index: 0, +* id: "call_123", +* function: { name: "get_weather", arguments: '{"location":' } +* }] +* }, +* rawResponse: { id: "chatcmpl-123", ... } +* }); +* // Returns: AIMessageChunk with tool_call_chunks containing partial tool call data +* ``` +* +* @remarks +* - Tool calls are converted to ToolCallChunk objects with incremental data +* - Audio content includes the chunk index from the raw response +* - The "developer" role is mapped to SystemMessageChunk with a special marker +* - Response metadata includes model provider info and usage statistics +* - Function calls and tool calls are stored in additional_kwargs for compatibility +*/ +const convertCompletionsDeltaToBaseMessageChunk = ({ delta, rawResponse, includeRawResponse, defaultRole }) => { + const role = delta.role ?? defaultRole; + const content = delta.content ?? ""; + let additional_kwargs; + if (delta.function_call) additional_kwargs = { function_call: delta.function_call }; + else if (delta.tool_calls) additional_kwargs = { tool_calls: delta.tool_calls }; + else additional_kwargs = {}; + if (includeRawResponse) additional_kwargs.__raw_response = rawResponse; + if (delta.audio) additional_kwargs.audio = { + ...delta.audio, + index: rawResponse.choices[0].index + }; + const response_metadata = { + model_provider: "openai", + usage: { ...rawResponse.usage } + }; + if (role === "user") return new HumanMessageChunk({ + content, + response_metadata + }); + else if (role === "assistant") { + const toolCallChunks = []; + if (Array.isArray(delta.tool_calls)) for (const rawToolCall of delta.tool_calls) toolCallChunks.push({ + name: rawToolCall.function?.name, + args: rawToolCall.function?.arguments, + id: rawToolCall.id, + index: rawToolCall.index, + type: "tool_call_chunk" + }); + return new AIMessageChunk({ + content, + tool_call_chunks: toolCallChunks, + additional_kwargs, + id: rawResponse.id, + response_metadata + }); + } else if (role === "system") return new SystemMessageChunk({ + content, + response_metadata + }); + else if (role === "developer") return new SystemMessageChunk({ + content, + response_metadata, + additional_kwargs: { __openai_role__: "developer" } + }); + else if (role === "function") return new FunctionMessageChunk({ + content, + additional_kwargs, + name: delta.name, + response_metadata + }); + else if (role === "tool") return new ToolMessageChunk({ + content, + additional_kwargs, + tool_call_id: delta.tool_call_id, + response_metadata + }); + else return new ChatMessageChunk({ + content, + role, + response_metadata + }); +}; +/** +* Converts a standard LangChain content block to an OpenAI Completions API content part. +* +* This converter transforms LangChain's standardized content blocks (image, audio, file) +* into the format expected by OpenAI's Chat Completions API. It handles various content +* types including images (URL or base64), audio (base64), and files (data or file ID). +* +* @param block - The standard content block to convert. Can be an image, audio, or file block. +* +* @returns An OpenAI Chat Completions content part object, or undefined if the block +* cannot be converted (e.g., missing required data). +* +* @example +* Image with URL: +* ```typescript +* const block = { type: "image", url: "https://example.com/image.jpg" }; +* const part = convertStandardContentBlockToCompletionsContentPart(block); +* // Returns: { type: "image_url", image_url: { url: "https://example.com/image.jpg" } } +* ``` +* +* @example +* Image with base64 data: +* ```typescript +* const block = { type: "image", data: "iVBORw0KGgo...", mimeType: "image/png" }; +* const part = convertStandardContentBlockToCompletionsContentPart(block); +* // Returns: { type: "image_url", image_url: { url: "data:image/png;base64,iVBORw0KGgo..." } } +* ``` +*/ +const convertStandardContentBlockToCompletionsContentPart = (block) => { + if (block.type === "image") { + if (block.url) return { + type: "image_url", + image_url: { url: block.url } + }; + else if (block.data) return { + type: "image_url", + image_url: { url: `data:${block.mimeType};base64,${block.data}` } + }; + } + if (block.type === "audio") { + if (block.data) { + const format = utils_iife(() => { + const [, format$1] = block.mimeType.split("/"); + if (format$1 === "wav" || format$1 === "mp3") return format$1; + return "wav"; + }); + return { + type: "input_audio", + input_audio: { + data: block.data.toString(), + format + } + }; + } + } + if (block.type === "file") { + if (block.data) { + const filename = getRequiredFilenameFromMetadata(block); + return { + type: "file", + file: { + file_data: `data:${block.mimeType};base64,${block.data}`, + filename + } + }; + } + if (block.fileId) return { + type: "file", + file: { file_id: block.fileId } + }; + } + return void 0; +}; +/** +* Converts a LangChain BaseMessage with standard content blocks to an OpenAI Chat Completions API message parameter. +* +* This converter transforms LangChain's standardized message format (using contentBlocks) into the format +* expected by OpenAI's Chat Completions API. It handles role mapping, content filtering, and multi-modal +* content conversion for various message types. +* +* @remarks +* The converter performs the following transformations: +* - Maps LangChain message roles to OpenAI API roles (user, assistant, system, developer, tool, function) +* - For reasoning models, automatically converts "system" role to "developer" role +* - Filters content blocks based on message role (most roles only include text blocks) +* - For user messages, converts multi-modal content blocks (images, audio, files) to OpenAI format +* - Preserves tool call IDs for tool messages and function names for function messages +* +* Role-specific behavior: +* - **developer**: Returns only text content blocks (used for reasoning models) +* - **system**: Returns only text content blocks +* - **assistant**: Returns only text content blocks +* - **tool**: Returns only text content blocks with tool_call_id preserved +* - **function**: Returns text content blocks joined as a single string with function name +* - **user** (default): Returns multi-modal content including text, images, audio, and files +* +* @param params - Conversion parameters +* @param params.message - The LangChain BaseMessage to convert. Must have contentBlocks property +* containing an array of standard content blocks (text, image, audio, file, etc.) +* @param params.model - Optional model name. Used to determine if special role mapping is needed +* (e.g., "system" -> "developer" for reasoning models like o1) +* +* @returns An OpenAI ChatCompletionMessageParam object formatted for the Chat Completions API. +* The structure varies by role: +* - Developer/System/Assistant: `{ role, content: TextBlock[] }` +* - Tool: `{ role: "tool", tool_call_id, content: TextBlock[] }` +* - Function: `{ role: "function", name, content: string }` +* - User: `{ role: "user", content: Array }` +* +* @example +* Simple text message: +* ```typescript +* const message = new HumanMessage({ +* content: [{ type: "text", text: "Hello!" }] +* }); +* const param = convertStandardContentMessageToCompletionsMessage({ message }); +* // Returns: { role: "user", content: [{ type: "text", text: "Hello!" }] } +* ``` +* +* @example +* Multi-modal user message with image: +* ```typescript +* const message = new HumanMessage({ +* content: [ +* { type: "text", text: "What's in this image?" }, +* { type: "image", url: "https://example.com/image.jpg" } +* ] +* }); +* const param = convertStandardContentMessageToCompletionsMessage({ message }); +* // Returns: { +* // role: "user", +* // content: [ +* // { type: "text", text: "What's in this image?" }, +* // { type: "image_url", image_url: { url: "https://example.com/image.jpg" } } +* // ] +* // } +* ``` +*/ +const convertStandardContentMessageToCompletionsMessage = ({ message, model }) => { + let role = messageToOpenAIRole(message); + if (role === "system" && isReasoningModel(model)) role = "developer"; + if (role === "developer") return { + role: "developer", + content: message.contentBlocks.filter((block) => block.type === "text") + }; + else if (role === "system") return { + role: "system", + content: message.contentBlocks.filter((block) => block.type === "text") + }; + else if (role === "assistant") return { + role: "assistant", + content: message.contentBlocks.filter((block) => block.type === "text") + }; + else if (role === "tool" && ToolMessage.isInstance(message)) return { + role: "tool", + tool_call_id: message.tool_call_id, + content: message.contentBlocks.filter((block) => block.type === "text") + }; + else if (role === "function") return { + role: "function", + name: message.name ?? "", + content: message.contentBlocks.filter((block) => block.type === "text").join("") + }; + function* iterateUserContent(blocks) { + for (const block of blocks) { + if (block.type === "text") yield { + type: "text", + text: block.text + }; + const data = convertStandardContentBlockToCompletionsContentPart(block); + if (data) yield data; + } + } + return { + role: "user", + content: Array.from(iterateUserContent(message.contentBlocks)) + }; +}; +/** +* Converts an array of LangChain BaseMessages to OpenAI Chat Completions API message parameters. +* +* This converter transforms LangChain's internal message representation into the format required +* by OpenAI's Chat Completions API. It handles various message types, roles, content formats, +* tool calls, function calls, audio messages, and special model-specific requirements. +* +* @remarks +* The converter performs several key transformations: +* - Maps LangChain message types to OpenAI roles (user, assistant, system, tool, function, developer) +* - Converts standard content blocks (v1 format) using a specialized converter +* - Handles multimodal content including text, images, audio, and data blocks +* - Preserves tool calls and function calls with proper formatting +* - Applies model-specific role mappings (e.g., "system" → "developer" for reasoning models) +* - Splits audio messages into separate message parameters when needed +* +* @param params - Conversion parameters +* @param params.messages - Array of LangChain BaseMessages to convert. Can include any message +* type: HumanMessage, AIMessage, SystemMessage, ToolMessage, FunctionMessage, etc. +* @param params.model - Optional model name used to determine if special role mapping is needed. +* For reasoning models (o1, o3, etc.), "system" role is converted to "developer" role. +* +* @returns Array of ChatCompletionMessageParam objects formatted for OpenAI's Chat Completions API. +* Some messages may be split into multiple parameters (e.g., audio messages). +* +* @example +* Basic message conversion: +* ```typescript +* const messages = [ +* new HumanMessage("What's the weather like?"), +* new AIMessage("Let me check that for you.") +* ]; +* +* const params = convertMessagesToCompletionsMessageParams({ +* messages, +* model: "gpt-4" +* }); +* // Returns: +* // [ +* // { role: "user", content: "What's the weather like?" }, +* // { role: "assistant", content: "Let me check that for you." } +* // ] +* ``` +* +* @example +* Message with tool calls: +* ```typescript +* const messages = [ +* new AIMessage({ +* content: "", +* tool_calls: [{ +* id: "call_123", +* name: "get_weather", +* args: { location: "San Francisco" } +* }] +* }) +* ]; +* +* const params = convertMessagesToCompletionsMessageParams({ messages }); +* // Returns: +* // [{ +* // role: "assistant", +* // content: "", +* // tool_calls: [{ +* // id: "call_123", +* // type: "function", +* // function: { name: "get_weather", arguments: '{"location":"San Francisco"}' } +* // }] +* // }] +* ``` +*/ +const completions_convertMessagesToCompletionsMessageParams = ({ messages, model }) => { + return messages.flatMap((message) => { + if ("output_version" in message.response_metadata && message.response_metadata?.output_version === "v1") return convertStandardContentMessageToCompletionsMessage({ message }); + let role = messageToOpenAIRole(message); + if (role === "system" && isReasoningModel(model)) role = "developer"; + const content = typeof message.content === "string" ? message.content : message.content.map((m) => { + if (isDataContentBlock(m)) return convertToProviderContentBlock(m, completionsApiContentBlockConverter); + return m; + }); + const completionParam = { + role, + content + }; + if (message.name != null) completionParam.name = message.name; + if (message.additional_kwargs.function_call != null) completionParam.function_call = message.additional_kwargs.function_call; + if (AIMessage.isInstance(message) && !!message.tool_calls?.length) completionParam.tool_calls = message.tool_calls.map(convertLangChainToolCallToOpenAI); + else { + if (message.additional_kwargs.tool_calls != null) completionParam.tool_calls = message.additional_kwargs.tool_calls; + if (ToolMessage.isInstance(message) && message.tool_call_id != null) completionParam.tool_call_id = message.tool_call_id; + } + if (message.additional_kwargs.audio && typeof message.additional_kwargs.audio === "object" && "id" in message.additional_kwargs.audio) { + const audioMessage = { + role: "assistant", + audio: { id: message.additional_kwargs.audio.id } + }; + return [completionParam, audioMessage]; + } + return completionParam; + }); +}; + +//#endregion + +//# sourceMappingURL=completions.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/completions.js + + + + + + + + +//#region src/chat_models/completions.ts +/** +* OpenAI Completions API implementation. +* @internal +*/ +var ChatOpenAICompletions = class extends BaseChatOpenAI { + /** @internal */ + invocationParams(options, extra) { + let strict; + if (options?.strict !== void 0) strict = options.strict; + else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; + let streamOptionsConfig = {}; + if (options?.stream_options !== void 0) streamOptionsConfig = { stream_options: options.stream_options }; + else if (this.streamUsage && (this.streaming || extra?.streaming)) streamOptionsConfig = { stream_options: { include_usage: true } }; + const params = { + model: this.model, + temperature: this.temperature, + top_p: this.topP, + frequency_penalty: this.frequencyPenalty, + presence_penalty: this.presencePenalty, + logprobs: this.logprobs, + top_logprobs: this.topLogprobs, + n: this.n, + logit_bias: this.logitBias, + stop: options?.stop ?? this.stopSequences, + user: this.user, + stream: this.streaming, + functions: options?.functions, + function_call: options?.function_call, + tools: options?.tools?.length ? options.tools.map((tool) => this._convertChatOpenAIToolToCompletionsTool(tool, { strict })) : void 0, + tool_choice: formatToOpenAIToolChoice(options?.tool_choice), + response_format: this._getResponseFormat(options?.response_format), + seed: options?.seed, + ...streamOptionsConfig, + parallel_tool_calls: options?.parallel_tool_calls, + ...this.audio || options?.audio ? { audio: this.audio || options?.audio } : {}, + ...this.modalities || options?.modalities ? { modalities: this.modalities || options?.modalities } : {}, + ...this.modelKwargs, + prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey, + prompt_cache_retention: options?.promptCacheRetention ?? this.promptCacheRetention, + verbosity: options?.verbosity ?? this.verbosity + }; + if (options?.prediction !== void 0) params.prediction = options.prediction; + if (this.service_tier !== void 0) params.service_tier = this.service_tier; + if (options?.service_tier !== void 0) params.service_tier = options.service_tier; + const reasoning = this._getReasoningParams(options); + if (reasoning !== void 0 && reasoning.effort !== void 0) params.reasoning_effort = reasoning.effort; + if (isReasoningModel(params.model)) params.max_completion_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens; + else params.max_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens; + return params; + } + async _generate(messages, options, runManager) { + const usageMetadata = {}; + const params = this.invocationParams(options); + const messagesMapped = completions_convertMessagesToCompletionsMessageParams({ + messages, + model: this.model + }); + if (params.stream) { + const stream = this._streamResponseChunks(messages, options, runManager); + const finalChunks = {}; + for await (const chunk of stream) { + chunk.message.response_metadata = { + ...chunk.generationInfo, + ...chunk.message.response_metadata + }; + const index = chunk.generationInfo?.completion ?? 0; + if (finalChunks[index] === void 0) finalChunks[index] = chunk; + else finalChunks[index] = finalChunks[index].concat(chunk); + } + const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value); + const { functions, function_call } = this.invocationParams(options); + const promptTokenUsage = await this._getEstimatedTokenCountFromPrompt(messages, functions, function_call); + const completionTokenUsage = await this._getNumTokensFromGenerations(generations); + usageMetadata.input_tokens = promptTokenUsage; + usageMetadata.output_tokens = completionTokenUsage; + usageMetadata.total_tokens = promptTokenUsage + completionTokenUsage; + return { + generations, + llmOutput: { estimatedTokenUsage: { + promptTokens: usageMetadata.input_tokens, + completionTokens: usageMetadata.output_tokens, + totalTokens: usageMetadata.total_tokens + } } + }; + } else { + const data = await this.completionWithRetry({ + ...params, + stream: false, + messages: messagesMapped + }, { + signal: options?.signal, + ...options?.options + }); + const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, prompt_tokens_details: promptTokensDetails, completion_tokens_details: completionTokensDetails } = data?.usage ?? {}; + if (completionTokens) usageMetadata.output_tokens = (usageMetadata.output_tokens ?? 0) + completionTokens; + if (promptTokens) usageMetadata.input_tokens = (usageMetadata.input_tokens ?? 0) + promptTokens; + if (totalTokens) usageMetadata.total_tokens = (usageMetadata.total_tokens ?? 0) + totalTokens; + if (promptTokensDetails?.audio_tokens !== null || promptTokensDetails?.cached_tokens !== null) usageMetadata.input_token_details = { + ...promptTokensDetails?.audio_tokens !== null && { audio: promptTokensDetails?.audio_tokens }, + ...promptTokensDetails?.cached_tokens !== null && { cache_read: promptTokensDetails?.cached_tokens } + }; + if (completionTokensDetails?.audio_tokens !== null || completionTokensDetails?.reasoning_tokens !== null) usageMetadata.output_token_details = { + ...completionTokensDetails?.audio_tokens !== null && { audio: completionTokensDetails?.audio_tokens }, + ...completionTokensDetails?.reasoning_tokens !== null && { reasoning: completionTokensDetails?.reasoning_tokens } + }; + const generations = []; + for (const part of data?.choices ?? []) { + const text = part.message?.content ?? ""; + const generation = { + text, + message: this._convertCompletionsMessageToBaseMessage(part.message ?? { role: "assistant" }, data) + }; + generation.generationInfo = { + ...part.finish_reason ? { finish_reason: part.finish_reason } : {}, + ...part.logprobs ? { logprobs: part.logprobs } : {} + }; + if (isAIMessage(generation.message)) generation.message.usage_metadata = usageMetadata; + generation.message = new AIMessage(Object.fromEntries(Object.entries(generation.message).filter(([key]) => !key.startsWith("lc_")))); + generations.push(generation); + } + return { + generations, + llmOutput: { tokenUsage: { + promptTokens: usageMetadata.input_tokens, + completionTokens: usageMetadata.output_tokens, + totalTokens: usageMetadata.total_tokens + } } + }; + } + } + async *_streamResponseChunks(messages, options, runManager) { + const messagesMapped = completions_convertMessagesToCompletionsMessageParams({ + messages, + model: this.model + }); + const params = { + ...this.invocationParams(options, { streaming: true }), + messages: messagesMapped, + stream: true + }; + let defaultRole; + const streamIterable = await this.completionWithRetry(params, options); + let usage; + for await (const data of streamIterable) { + const choice = data?.choices?.[0]; + if (data.usage) usage = data.usage; + if (!choice) continue; + const { delta } = choice; + if (!delta) continue; + const chunk = this._convertCompletionsDeltaToBaseMessageChunk(delta, data, defaultRole); + defaultRole = delta.role ?? defaultRole; + const newTokenIndices = { + prompt: options.promptIndex ?? 0, + completion: choice.index ?? 0 + }; + if (typeof chunk.content !== "string") { + console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported."); + continue; + } + const generationInfo = { ...newTokenIndices }; + if (choice.finish_reason != null) { + generationInfo.finish_reason = choice.finish_reason; + generationInfo.system_fingerprint = data.system_fingerprint; + generationInfo.model_name = data.model; + generationInfo.service_tier = data.service_tier; + } + if (this.logprobs) generationInfo.logprobs = choice.logprobs; + const generationChunk = new ChatGenerationChunk({ + message: chunk, + text: chunk.content, + generationInfo + }); + yield generationChunk; + await runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, void 0, void 0, void 0, { chunk: generationChunk }); + } + if (usage) { + const inputTokenDetails = { + ...usage.prompt_tokens_details?.audio_tokens !== null && { audio: usage.prompt_tokens_details?.audio_tokens }, + ...usage.prompt_tokens_details?.cached_tokens !== null && { cache_read: usage.prompt_tokens_details?.cached_tokens } + }; + const outputTokenDetails = { + ...usage.completion_tokens_details?.audio_tokens !== null && { audio: usage.completion_tokens_details?.audio_tokens }, + ...usage.completion_tokens_details?.reasoning_tokens !== null && { reasoning: usage.completion_tokens_details?.reasoning_tokens } + }; + const generationChunk = new ChatGenerationChunk({ + message: new AIMessageChunk({ + content: "", + response_metadata: { usage: { ...usage } }, + usage_metadata: { + input_tokens: usage.prompt_tokens, + output_tokens: usage.completion_tokens, + total_tokens: usage.total_tokens, + ...Object.keys(inputTokenDetails).length > 0 && { input_token_details: inputTokenDetails }, + ...Object.keys(outputTokenDetails).length > 0 && { output_token_details: outputTokenDetails } + } + }), + text: "" + }); + yield generationChunk; + } + if (options.signal?.aborted) throw new Error("AbortError"); + } + async completionWithRetry(request, requestOptions) { + const clientOptions = this._getClientOptions(requestOptions); + const isParseableFormat = request.response_format && request.response_format.type === "json_schema"; + return this.caller.call(async () => { + try { + if (isParseableFormat && !request.stream) return await this.client.chat.completions.parse(request, clientOptions); + else return await this.client.chat.completions.create(request, clientOptions); + } catch (e) { + const error = wrapOpenAIClientError(e); + throw error; + } + }); + } + /** + * @deprecated + * This function was hoisted into a publicly accessible function from a + * different export, but to maintain backwards compatibility with chat models + * that depend on ChatOpenAICompletions, we'll keep it here as an overridable + * method. This will be removed in a future release + */ + _convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole) { + return convertCompletionsDeltaToBaseMessageChunk({ + delta, + rawResponse, + includeRawResponse: this.__includeRawResponse, + defaultRole + }); + } + /** + * @deprecated + * This function was hoisted into a publicly accessible function from a + * different export, but to maintain backwards compatibility with chat models + * that depend on ChatOpenAICompletions, we'll keep it here as an overridable + * method. This will be removed in a future release + */ + _convertCompletionsMessageToBaseMessage(message, rawResponse) { + return convertCompletionsMessageToBaseMessage({ + message, + rawResponse, + includeRawResponse: this.__includeRawResponse + }); + } +}; + +//#endregion + +//# sourceMappingURL=completions.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/common.js + + + + +//#region src/azure/chat_models/common.ts +const AZURE_ALIASES = { + openAIApiKey: "openai_api_key", + openAIApiVersion: "openai_api_version", + openAIBasePath: "openai_api_base", + deploymentName: "deployment_name", + azureOpenAIEndpoint: "azure_endpoint", + azureOpenAIApiVersion: "openai_api_version", + azureOpenAIBasePath: "openai_api_base", + azureOpenAIApiDeploymentName: "deployment_name" +}; +const AZURE_SECRETS = { azureOpenAIApiKey: "AZURE_OPENAI_API_KEY" }; +const AZURE_SERIALIZABLE_KEYS = [ + "azureOpenAIApiKey", + "azureOpenAIApiVersion", + "azureOpenAIBasePath", + "azureOpenAIEndpoint", + "azureOpenAIApiInstanceName", + "azureOpenAIApiDeploymentName", + "deploymentName", + "openAIApiKey", + "openAIApiVersion" +]; +function _constructAzureFields(fields) { + this.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? (typeof fields?.openAIApiKey === "string" ? fields?.openAIApiKey : void 0) ?? (typeof fields?.apiKey === "string" ? fields?.apiKey : void 0) ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); + this.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); + this.azureOpenAIApiDeploymentName = fields?.azureOpenAIApiDeploymentName ?? fields?.deploymentName ?? getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME"); + this.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); + this.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); + this.azureOpenAIEndpoint = fields?.azureOpenAIEndpoint ?? getEnvironmentVariable("AZURE_OPENAI_ENDPOINT"); + this.azureADTokenProvider = fields?.azureADTokenProvider; + if (!this.azureOpenAIApiKey && !this.apiKey && !this.azureADTokenProvider) throw new Error("Azure OpenAI API key or Token Provider not found"); +} +function _getAzureClientOptions(options) { + if (!this.client) { + const openAIEndpointConfig = { + azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, + azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, + azureOpenAIApiKey: this.azureOpenAIApiKey, + azureOpenAIBasePath: this.azureOpenAIBasePath, + azureADTokenProvider: this.azureADTokenProvider, + baseURL: this.clientConfig.baseURL, + azureOpenAIEndpoint: this.azureOpenAIEndpoint + }; + const endpoint = getEndpoint(openAIEndpointConfig); + const { apiKey: existingApiKey,...clientConfigRest } = this.clientConfig; + const params = { + ...clientConfigRest, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0 + }; + if (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey; + if (!params.baseURL) delete params.baseURL; + params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders, true, "2.0.0"); + this.client = new AzureOpenAI({ + apiVersion: this.azureOpenAIApiVersion, + azureADTokenProvider: this.azureADTokenProvider, + deployment: this.azureOpenAIApiDeploymentName, + ...params + }); + } + const requestOptions = { + ...this.clientConfig, + ...options + }; + if (this.azureOpenAIApiKey) { + requestOptions.headers = { + "api-key": this.azureOpenAIApiKey, + ...requestOptions.headers + }; + requestOptions.query = { + "api-version": this.azureOpenAIApiVersion, + ...requestOptions.query + }; + } + return requestOptions; +} +function _serializeAzureChat(input) { + const json = input; + function isRecord(obj) { + return typeof obj === "object" && obj != null; + } + if (isRecord(json) && isRecord(json.kwargs)) { + delete json.kwargs.azure_openai_base_path; + delete json.kwargs.azure_openai_api_deployment_name; + delete json.kwargs.azure_openai_api_key; + delete json.kwargs.azure_openai_api_version; + delete json.kwargs.azure_open_ai_base_path; + if (!json.kwargs.azure_endpoint && this.azureOpenAIEndpoint) json.kwargs.azure_endpoint = this.azureOpenAIEndpoint; + if (!json.kwargs.azure_endpoint && this.azureOpenAIBasePath) { + const parts = this.azureOpenAIBasePath.split("/openai/deployments/"); + if (parts.length === 2 && parts[0].startsWith("http")) { + const [endpoint] = parts; + json.kwargs.azure_endpoint = endpoint; + } + } + if (!json.kwargs.azure_endpoint && this.azureOpenAIApiInstanceName) json.kwargs.azure_endpoint = `https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`; + if (!json.kwargs.deployment_name && this.azureOpenAIApiDeploymentName) json.kwargs.deployment_name = this.azureOpenAIApiDeploymentName; + if (!json.kwargs.deployment_name && this.azureOpenAIBasePath) { + const parts = this.azureOpenAIBasePath.split("/openai/deployments/"); + if (parts.length === 2) { + const [, deployment] = parts; + json.kwargs.deployment_name = deployment; + } + } + if (json.kwargs.azure_endpoint && json.kwargs.deployment_name && json.kwargs.openai_api_base) delete json.kwargs.openai_api_base; + if (json.kwargs.azure_openai_api_instance_name && json.kwargs.azure_endpoint) delete json.kwargs.azure_openai_api_instance_name; + } + return json; +} + +//#endregion + +//# sourceMappingURL=common.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/completions.js + + + +//#region src/azure/chat_models/completions.ts +var AzureChatOpenAICompletions = class extends ChatOpenAICompletions { + azureOpenAIApiVersion; + azureOpenAIApiKey; + azureADTokenProvider; + azureOpenAIApiInstanceName; + azureOpenAIApiDeploymentName; + azureOpenAIBasePath; + azureOpenAIEndpoint; + _llmType() { + return "azure_openai"; + } + get lc_aliases() { + return { + ...super.lc_aliases, + ...AZURE_ALIASES + }; + } + get lc_secrets() { + return { + ...super.lc_secrets, + ...AZURE_SECRETS + }; + } + get lc_serializable_keys() { + return [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS]; + } + getLsParams(options) { + const params = super.getLsParams(options); + params.ls_provider = "azure"; + return params; + } + constructor(fields) { + super(fields); + _constructAzureFields.call(this, fields); + } + _getClientOptions(options) { + return _getAzureClientOptions.call(this, options); + } + toJSON() { + return _serializeAzureChat.call(this, super.toJSON()); + } +}; + +//#endregion + +//# sourceMappingURL=completions.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/converters/responses.js + + + + + + + +//#region src/converters/responses.ts +const _FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__"; +/** +* Converts OpenAI Responses API usage statistics to LangChain's UsageMetadata format. +* +* This converter transforms token usage information from OpenAI's Responses API into +* the standardized UsageMetadata format used throughout LangChain. It handles both +* basic token counts and detailed token breakdowns including cached tokens and +* reasoning tokens. +* +* @param usage - The usage statistics object from OpenAI's Responses API containing +* token counts and optional detailed breakdowns. +* +* @returns A UsageMetadata object containing: +* - `input_tokens`: Total number of tokens in the input/prompt (defaults to 0 if not provided) +* - `output_tokens`: Total number of tokens in the model's output (defaults to 0 if not provided) +* - `total_tokens`: Combined total of input and output tokens (defaults to 0 if not provided) +* - `input_token_details`: Object containing detailed input token information: +* - `cache_read`: Number of tokens read from cache (only included if available) +* - `output_token_details`: Object containing detailed output token information: +* - `reasoning`: Number of tokens used for reasoning (only included if available) +* +* @example +* ```typescript +* const usage = { +* input_tokens: 100, +* output_tokens: 50, +* total_tokens: 150, +* input_tokens_details: { cached_tokens: 20 }, +* output_tokens_details: { reasoning_tokens: 10 } +* }; +* +* const metadata = convertResponsesUsageToUsageMetadata(usage); +* // Returns: +* // { +* // input_tokens: 100, +* // output_tokens: 50, +* // total_tokens: 150, +* // input_token_details: { cache_read: 20 }, +* // output_token_details: { reasoning: 10 } +* // } +* ``` +* +* @remarks +* - The function safely handles undefined or null values by using optional chaining +* and nullish coalescing operators +* - Detailed token information (cache_read, reasoning) is only included in the result +* if the corresponding values are present in the input +* - Token counts default to 0 if not provided in the usage object +* - This converter is specifically designed for OpenAI's Responses API format and +* may differ from other OpenAI API endpoints +*/ +const convertResponsesUsageToUsageMetadata = (usage) => { + const inputTokenDetails = { ...usage?.input_tokens_details?.cached_tokens != null && { cache_read: usage?.input_tokens_details?.cached_tokens } }; + const outputTokenDetails = { ...usage?.output_tokens_details?.reasoning_tokens != null && { reasoning: usage?.output_tokens_details?.reasoning_tokens } }; + return { + input_tokens: usage?.input_tokens ?? 0, + output_tokens: usage?.output_tokens ?? 0, + total_tokens: usage?.total_tokens ?? 0, + input_token_details: inputTokenDetails, + output_token_details: outputTokenDetails + }; +}; +/** +* Converts an OpenAI Responses API response to a LangChain AIMessage. +* +* This converter processes the output from OpenAI's Responses API (both `create` and `parse` methods) +* and transforms it into a LangChain AIMessage object with all relevant metadata, tool calls, and content. +* +* @param response - The response object from OpenAI's Responses API. Can be either: +* - ResponsesCreateInvoke: Result from `responses.create()` +* - ResponsesParseInvoke: Result from `responses.parse()` +* +* @returns An AIMessage containing: +* - `id`: The message ID from the response output +* - `content`: Array of message content blocks (text, images, etc.) +* - `tool_calls`: Array of successfully parsed tool calls +* - `invalid_tool_calls`: Array of tool calls that failed to parse +* - `usage_metadata`: Token usage information converted to LangChain format +* - `additional_kwargs`: Extra data including: +* - `refusal`: Refusal text if the model refused to respond +* - `reasoning`: Reasoning output for reasoning models +* - `tool_outputs`: Results from built-in tools (web search, file search, etc.) +* - `parsed`: Parsed structured output when using json_schema format +* - Function call ID mappings for tracking +* - `response_metadata`: Metadata about the response including model, timestamps, status, etc. +* +* @throws Error if the response contains an error object. The error message and code are extracted +* from the response.error field. +* +* @example +* ```typescript +* const response = await client.responses.create({ +* model: "gpt-4", +* input: [{ type: "message", content: "Hello" }] +* }); +* const message = convertResponsesMessageToAIMessage(response); +* console.log(message.content); // Message content +* console.log(message.tool_calls); // Any tool calls made +* ``` +* +* @remarks +* The converter handles multiple output item types: +* - `message`: Text and structured content from the model +* - `function_call`: Tool/function calls that need to be executed +* - `reasoning`: Reasoning traces from reasoning models (o1, o3, etc.) +* - `custom_tool_call`: Custom tool invocations +* - Built-in tool outputs: web_search, file_search, code_interpreter, etc. +* +* Tool calls are parsed and validated. Invalid tool calls (malformed JSON, etc.) are captured +* in the `invalid_tool_calls` array rather than throwing errors. +*/ +const convertResponsesMessageToAIMessage = (response) => { + if (response.error) { + const error = new Error(response.error.message); + error.name = response.error.code; + throw error; + } + let messageId; + const content = []; + const tool_calls = []; + const invalid_tool_calls = []; + const response_metadata = { + model_provider: "openai", + model: response.model, + created_at: response.created_at, + id: response.id, + incomplete_details: response.incomplete_details, + metadata: response.metadata, + object: response.object, + status: response.status, + user: response.user, + service_tier: response.service_tier, + model_name: response.model + }; + const additional_kwargs = {}; + for (const item of response.output) if (item.type === "message") { + messageId = item.id; + content.push(...item.content.flatMap((part) => { + if (part.type === "output_text") { + if ("parsed" in part && part.parsed != null) additional_kwargs.parsed = part.parsed; + return { + type: "text", + text: part.text, + annotations: part.annotations + }; + } + if (part.type === "refusal") { + additional_kwargs.refusal = part.refusal; + return []; + } + return part; + })); + } else if (item.type === "function_call") { + const fnAdapter = { + function: { + name: item.name, + arguments: item.arguments + }, + id: item.call_id + }; + try { + tool_calls.push(parseToolCall(fnAdapter, { returnId: true })); + } catch (e) { + let errMessage; + if (typeof e === "object" && e != null && "message" in e && typeof e.message === "string") errMessage = e.message; + invalid_tool_calls.push(makeInvalidToolCall(fnAdapter, errMessage)); + } + additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {}; + if (item.id) additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id; + } else if (item.type === "reasoning") additional_kwargs.reasoning = item; + else if (item.type === "custom_tool_call") { + const parsed = parseCustomToolCall(item); + if (parsed) tool_calls.push(parsed); + else invalid_tool_calls.push(makeInvalidToolCall(item, "Malformed custom tool call")); + } else if (item.type === "computer_call") { + const parsed = parseComputerCall(item); + if (parsed) tool_calls.push(parsed); + else invalid_tool_calls.push(makeInvalidToolCall(item, "Malformed computer call")); + } else { + additional_kwargs.tool_outputs ??= []; + additional_kwargs.tool_outputs.push(item); + } + return new AIMessage({ + id: messageId, + content, + tool_calls, + invalid_tool_calls, + usage_metadata: convertResponsesUsageToUsageMetadata(response.usage), + additional_kwargs, + response_metadata + }); +}; +/** +* Converts a LangChain ChatOpenAI reasoning summary to an OpenAI Responses API reasoning item. +* +* This converter transforms reasoning summaries that have been accumulated during streaming +* (where summary parts may arrive in multiple chunks with the same index) into the final +* consolidated format expected by OpenAI's Responses API. It combines summary parts that +* share the same index and removes the index field from the final output. +* +* @param reasoning - A ChatOpenAI reasoning summary object containing: +* - `id`: The reasoning item ID +* - `type`: The type of reasoning (typically "reasoning") +* - `summary`: Array of summary parts, each with: +* - `text`: The summary text content +* - `type`: The summary type (e.g., "summary_text") +* - `index`: The index used to group related summary parts during streaming +* +* @returns An OpenAI Responses API ResponseReasoningItem with: +* - All properties from the input reasoning object +* - `summary`: Consolidated array of summary objects with: +* - `text`: Combined text from all parts with the same index +* - `type`: The summary type +* - No `index` field (removed after consolidation) +* +* @example +* ```typescript +* // Input: Reasoning summary with multiple parts at the same index +* const reasoning = { +* id: "reasoning_123", +* type: "reasoning", +* summary: [ +* { text: "First ", type: "summary_text", index: 0 }, +* { text: "part", type: "summary_text", index: 0 }, +* { text: "Second part", type: "summary_text", index: 1 } +* ] +* }; +* +* const result = convertReasoningSummaryToResponsesReasoningItem(reasoning); +* // Returns: +* // { +* // id: "reasoning_123", +* // type: "reasoning", +* // summary: [ +* // { text: "First part", type: "summary_text" }, +* // { text: "Second part", type: "summary_text" } +* // ] +* // } +* ``` +* +* @remarks +* - This converter is primarily used when reconstructing complete reasoning items from +* streaming chunks, where summary parts may arrive incrementally with index markers +* - Summary parts with the same index are concatenated in the order they appear +* - If the reasoning summary contains only one part, no reduction is performed +* - The index field is used internally during streaming to track which summary parts +* belong together, but is removed from the final output as it's not part of the +* OpenAI Responses API schema +* - This is the inverse operation of the streaming accumulation that happens in +* `convertResponsesDeltaToChatGenerationChunk` +*/ +const convertReasoningSummaryToResponsesReasoningItem = (reasoning) => { + const summary = (reasoning.summary.length > 1 ? reasoning.summary.reduce((acc, curr) => { + const last = acc[acc.length - 1]; + if (last.index === curr.index) last.text += curr.text; + else acc.push(curr); + return acc; + }, [{ ...reasoning.summary[0] }]) : reasoning.summary).map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => k !== "index"))); + return { + ...reasoning, + summary + }; +}; +/** +* Converts OpenAI Responses API stream events to LangChain ChatGenerationChunk objects. +* +* This converter processes streaming events from OpenAI's Responses API and transforms them +* into LangChain ChatGenerationChunk objects that can be used in streaming chat applications. +* It handles various event types including text deltas, tool calls, reasoning, and metadata updates. +* +* @param event - A streaming event from OpenAI's Responses API +* +* @returns A ChatGenerationChunk containing: +* - `text`: Concatenated text content from all text parts in the event +* - `message`: An AIMessageChunk with: +* - `id`: Message ID (set when a message output item is added) +* - `content`: Array of content blocks (text with optional annotations) +* - `tool_call_chunks`: Incremental tool call data (name, args, id) +* - `usage_metadata`: Token usage information (only in completion events) +* - `additional_kwargs`: Extra data including: +* - `refusal`: Refusal text if the model refused to respond +* - `reasoning`: Reasoning output for reasoning models (id, type, summary) +* - `tool_outputs`: Results from built-in tools (web search, file search, etc.) +* - `parsed`: Parsed structured output when using json_schema format +* - Function call ID mappings for tracking +* - `response_metadata`: Metadata about the response (model, id, etc.) +* - `generationInfo`: Additional generation information (e.g., tool output status) +* +* Returns `null` for events that don't produce meaningful chunks: +* - Partial image generation events (to avoid storing all partial images in history) +* - Unrecognized event types +* +* @example +* ```typescript +* const stream = await client.responses.create({ +* model: "gpt-4", +* input: [{ type: "message", content: "Hello" }], +* stream: true +* }); +* +* for await (const event of stream) { +* const chunk = convertResponsesDeltaToChatGenerationChunk(event); +* if (chunk) { +* console.log(chunk.text); // Incremental text +* console.log(chunk.message.tool_call_chunks); // Tool call updates +* } +* } +* ``` +* +* @remarks +* - Text content is accumulated in an array with index tracking for proper ordering +* - Tool call chunks include incremental arguments that need to be concatenated by the consumer +* - Reasoning summaries are built incrementally across multiple events +* - Function call IDs are tracked in `additional_kwargs` to map call_id to item id +* - The `text` field is provided for legacy compatibility with `onLLMNewToken` callbacks +* - Usage metadata is only available in `response.completed` events +* - Partial images are intentionally ignored to prevent memory bloat in conversation history +*/ +const convertResponsesDeltaToChatGenerationChunk = (event) => { + const content = []; + let generationInfo = {}; + let usage_metadata; + const tool_call_chunks = []; + const response_metadata = { model_provider: "openai" }; + const additional_kwargs = {}; + let id; + if (event.type === "response.output_text.delta") content.push({ + type: "text", + text: event.delta, + index: event.content_index + }); + else if (event.type === "response.output_text.annotation.added") content.push({ + type: "text", + text: "", + annotations: [event.annotation], + index: event.content_index + }); + else if (event.type === "response.output_item.added" && event.item.type === "message") id = event.item.id; + else if (event.type === "response.output_item.added" && event.item.type === "function_call") { + tool_call_chunks.push({ + type: "tool_call_chunk", + name: event.item.name, + args: event.item.arguments, + id: event.item.call_id, + index: event.output_index + }); + additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = { [event.item.call_id]: event.item.id }; + } else if (event.type === "response.output_item.done" && event.item.type === "computer_call") { + tool_call_chunks.push({ + type: "tool_call_chunk", + name: "computer_use", + args: JSON.stringify({ action: event.item.action }), + id: event.item.call_id, + index: event.output_index + }); + additional_kwargs.tool_outputs = [event.item]; + } else if (event.type === "response.output_item.done" && [ + "web_search_call", + "file_search_call", + "code_interpreter_call", + "mcp_call", + "mcp_list_tools", + "mcp_approval_request", + "image_generation_call", + "custom_tool_call" + ].includes(event.item.type)) additional_kwargs.tool_outputs = [event.item]; + else if (event.type === "response.created") { + response_metadata.id = event.response.id; + response_metadata.model_name = event.response.model; + response_metadata.model = event.response.model; + } else if (event.type === "response.completed") { + const msg = convertResponsesMessageToAIMessage(event.response); + usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage); + if (event.response.text?.format?.type === "json_schema") additional_kwargs.parsed ??= JSON.parse(msg.text); + for (const [key, value] of Object.entries(event.response)) if (key !== "id") response_metadata[key] = value; + } else if (event.type === "response.function_call_arguments.delta" || event.type === "response.custom_tool_call_input.delta") tool_call_chunks.push({ + type: "tool_call_chunk", + args: event.delta, + index: event.output_index + }); + else if (event.type === "response.web_search_call.completed" || event.type === "response.file_search_call.completed") generationInfo = { tool_outputs: { + id: event.item_id, + type: event.type.replace("response.", "").replace(".completed", ""), + status: "completed" + } }; + else if (event.type === "response.refusal.done") additional_kwargs.refusal = event.refusal; + else if (event.type === "response.output_item.added" && "item" in event && event.item.type === "reasoning") { + const summary = event.item.summary ? event.item.summary.map((s, index) => ({ + ...s, + index + })) : void 0; + additional_kwargs.reasoning = { + id: event.item.id, + type: event.item.type, + ...summary ? { summary } : {} + }; + } else if (event.type === "response.reasoning_summary_part.added") additional_kwargs.reasoning = { + type: "reasoning", + summary: [{ + ...event.part, + index: event.summary_index + }] + }; + else if (event.type === "response.reasoning_summary_text.delta") additional_kwargs.reasoning = { + type: "reasoning", + summary: [{ + text: event.delta, + type: "summary_text", + index: event.summary_index + }] + }; + else if (event.type === "response.image_generation_call.partial_image") return null; + else return null; + return new ChatGenerationChunk({ + text: content.map((part) => part.text).join(""), + message: new AIMessageChunk({ + id, + content, + tool_call_chunks, + usage_metadata, + additional_kwargs, + response_metadata + }), + generationInfo + }); +}; +/** +* Converts a single LangChain BaseMessage to OpenAI Responses API input format. +* +* This converter transforms a LangChain message into one or more ResponseInputItem objects +* that can be used with OpenAI's Responses API. It handles complex message structures including +* tool calls, reasoning blocks, multimodal content, and various content block types. +* +* @param message - The LangChain BaseMessage to convert. Can be any message type including +* HumanMessage, AIMessage, SystemMessage, ToolMessage, etc. +* +* @returns An array of ResponseInputItem objects. +* +* @example +* Basic text message conversion: +* ```typescript +* const message = new HumanMessage("Hello, how are you?"); +* const items = convertStandardContentMessageToResponsesInput(message); +* // Returns: [{ type: "message", role: "user", content: [{ type: "input_text", text: "Hello, how are you?" }] }] +* ``` +* +* @example +* AI message with tool calls: +* ```typescript +* const message = new AIMessage({ +* content: "I'll check the weather for you.", +* tool_calls: [{ +* id: "call_123", +* name: "get_weather", +* args: { location: "San Francisco" } +* }] +* }); +* const items = convertStandardContentMessageToResponsesInput(message); +* // Returns: +* // [ +* // { type: "message", role: "assistant", content: [{ type: "input_text", text: "I'll check the weather for you." }] }, +* // { type: "function_call", call_id: "call_123", name: "get_weather", arguments: '{"location":"San Francisco"}' } +* // ] +* ``` +*/ +const convertStandardContentMessageToResponsesInput = (message) => { + const isResponsesMessage = AIMessage.isInstance(message) && message.response_metadata?.model_provider === "openai"; + function* iterateItems() { + const messageRole = iife$1(() => { + try { + const role = messageToOpenAIRole(message); + if (role === "system" || role === "developer" || role === "assistant" || role === "user") return role; + return "assistant"; + } catch { + return "assistant"; + } + }); + let currentMessage = void 0; + const functionCallIdsWithBlocks = /* @__PURE__ */ new Set(); + const serverFunctionCallIdsWithBlocks = /* @__PURE__ */ new Set(); + const pendingFunctionChunks = /* @__PURE__ */ new Map(); + const pendingServerFunctionChunks = /* @__PURE__ */ new Map(); + function* flushMessage() { + if (!currentMessage) return; + const content = currentMessage.content; + if (typeof content === "string" && content.length > 0 || Array.isArray(content) && content.length > 0) yield currentMessage; + currentMessage = void 0; + } + const pushMessageContent = (content) => { + if (!currentMessage) currentMessage = { + type: "message", + role: messageRole, + content: [] + }; + if (typeof currentMessage.content === "string") currentMessage.content = currentMessage.content.length > 0 ? [{ + type: "input_text", + text: currentMessage.content + }, ...content] : [...content]; + else currentMessage.content.push(...content); + }; + const toJsonString = (value) => { + if (typeof value === "string") return value; + try { + return JSON.stringify(value ?? {}); + } catch { + return "{}"; + } + }; + const resolveImageItem = (block) => { + const detail = iife$1(() => { + const raw = block.metadata?.detail; + if (raw === "low" || raw === "high" || raw === "auto") return raw; + return "auto"; + }); + if (block.fileId) return { + type: "input_image", + detail, + file_id: block.fileId + }; + if (block.url) return { + type: "input_image", + detail, + image_url: block.url + }; + if (block.data) { + const base64Data = typeof block.data === "string" ? block.data : Buffer.from(block.data).toString("base64"); + const mimeType = block.mimeType ?? "image/png"; + return { + type: "input_image", + detail, + image_url: `data:${mimeType};base64,${base64Data}` + }; + } + return void 0; + }; + const resolveFileItem = (block) => { + const filename = getRequiredFilenameFromMetadata(block); + if (block.fileId && typeof filename === "string") return { + type: "input_file", + file_id: block.fileId, + ...filename ? { filename } : {} + }; + if (block.url && typeof filename === "string") return { + type: "input_file", + file_url: block.url, + ...filename ? { filename } : {} + }; + if (block.data && typeof filename === "string") { + const encoded = typeof block.data === "string" ? block.data : Buffer.from(block.data).toString("base64"); + const mimeType = block.mimeType ?? "application/octet-stream"; + return { + type: "input_file", + file_data: `data:${mimeType};base64,${encoded}`, + ...filename ? { filename } : {} + }; + } + return void 0; + }; + const convertReasoningBlock = (block) => { + const summaryEntries = iife$1(() => { + if (Array.isArray(block.summary)) { + const candidate = block.summary; + const mapped = candidate?.map((item) => item?.text).filter((text) => typeof text === "string") ?? []; + if (mapped.length > 0) return mapped; + } + return block.reasoning ? [block.reasoning] : []; + }); + const summary = summaryEntries.length > 0 ? summaryEntries.map((text) => ({ + type: "summary_text", + text + })) : [{ + type: "summary_text", + text: "" + }]; + const reasoningItem = { + type: "reasoning", + id: block.id ?? "", + summary + }; + if (block.reasoning) reasoningItem.content = [{ + type: "reasoning_text", + text: block.reasoning + }]; + return reasoningItem; + }; + const convertFunctionCall = (block) => ({ + type: "function_call", + name: block.name ?? "", + call_id: block.id ?? "", + arguments: toJsonString(block.args) + }); + const convertFunctionCallOutput = (block) => { + const output = toJsonString(block.output); + const status = block.status === "success" ? "completed" : block.status === "error" ? "incomplete" : void 0; + return { + type: "function_call_output", + call_id: block.toolCallId ?? "", + output, + ...status ? { status } : {} + }; + }; + for (const block of message.contentBlocks) if (block.type === "text") pushMessageContent([{ + type: "input_text", + text: block.text + }]); + else if (block.type === "invalid_tool_call") {} else if (block.type === "reasoning") { + yield* flushMessage(); + yield convertReasoningBlock(block); + } else if (block.type === "tool_call") { + yield* flushMessage(); + const id = block.id ?? ""; + if (id) { + functionCallIdsWithBlocks.add(id); + pendingFunctionChunks.delete(id); + } + yield convertFunctionCall(block); + } else if (block.type === "tool_call_chunk") { + if (block.id) { + const existing = pendingFunctionChunks.get(block.id) ?? { + name: block.name, + args: [] + }; + if (block.name) existing.name = block.name; + if (block.args) existing.args.push(block.args); + pendingFunctionChunks.set(block.id, existing); + } + } else if (block.type === "server_tool_call") { + yield* flushMessage(); + const id = block.id ?? ""; + if (id) { + serverFunctionCallIdsWithBlocks.add(id); + pendingServerFunctionChunks.delete(id); + } + yield convertFunctionCall(block); + } else if (block.type === "server_tool_call_chunk") { + if (block.id) { + const existing = pendingServerFunctionChunks.get(block.id) ?? { + name: block.name, + args: [] + }; + if (block.name) existing.name = block.name; + if (block.args) existing.args.push(block.args); + pendingServerFunctionChunks.set(block.id, existing); + } + } else if (block.type === "server_tool_call_result") { + yield* flushMessage(); + yield convertFunctionCallOutput(block); + } else if (block.type === "audio") {} else if (block.type === "file") { + const fileItem = resolveFileItem(block); + if (fileItem) pushMessageContent([fileItem]); + } else if (block.type === "image") { + const imageItem = resolveImageItem(block); + if (imageItem) pushMessageContent([imageItem]); + } else if (block.type === "video") { + const videoItem = resolveFileItem(block); + if (videoItem) pushMessageContent([videoItem]); + } else if (block.type === "text-plain") { + if (block.text) pushMessageContent([{ + type: "input_text", + text: block.text + }]); + } else if (block.type === "non_standard" && isResponsesMessage) { + yield* flushMessage(); + yield block.value; + } + yield* flushMessage(); + for (const [id, chunk] of pendingFunctionChunks) { + if (!id || functionCallIdsWithBlocks.has(id)) continue; + const args = chunk.args.join(""); + if (!chunk.name && !args) continue; + yield { + type: "function_call", + call_id: id, + name: chunk.name ?? "", + arguments: args + }; + } + for (const [id, chunk] of pendingServerFunctionChunks) { + if (!id || serverFunctionCallIdsWithBlocks.has(id)) continue; + const args = chunk.args.join(""); + if (!chunk.name && !args) continue; + yield { + type: "function_call", + call_id: id, + name: chunk.name ?? "", + arguments: args + }; + } + } + return Array.from(iterateItems()); +}; +/** +* - MCP (Model Context Protocol) approval responses +* - Zero Data Retention (ZDR) mode handling +* +* @param params - Conversion parameters +* @param params.messages - Array of LangChain BaseMessages to convert +* @param params.zdrEnabled - Whether Zero Data Retention mode is enabled. When true, certain +* metadata like message IDs and function call IDs are omitted from the output +* @param params.model - The model name being used. Used to determine if special role mapping +* is needed (e.g., "system" -> "developer" for reasoning models) +* +* @returns Array of ResponsesInputItem objects formatted for the OpenAI Responses API +* +* @throws {Error} When a function message is encountered (not supported) +* @throws {Error} When computer call output format is invalid +* +* @example +* ```typescript +* const messages = [ +* new HumanMessage("Hello"), +* new AIMessage({ content: "Hi there!", tool_calls: [...] }) +* ]; +* +* const input = convertMessagesToResponsesInput({ +* messages, +* zdrEnabled: false, +* model: "gpt-4" +* }); +* ``` +*/ +const convertMessagesToResponsesInput = ({ messages, zdrEnabled, model }) => { + return messages.flatMap((lcMsg) => { + const responseMetadata = lcMsg.response_metadata; + if (responseMetadata?.output_version === "v1") return convertStandardContentMessageToResponsesInput(lcMsg); + const additional_kwargs = lcMsg.additional_kwargs; + let role = messageToOpenAIRole(lcMsg); + if (role === "system" && isReasoningModel(model)) role = "developer"; + if (role === "function") throw new Error("Function messages are not supported in Responses API"); + if (role === "tool") { + const toolMessage = lcMsg; + if (additional_kwargs?.type === "computer_call_output") { + const output = (() => { + if (typeof toolMessage.content === "string") return { + type: "input_image", + image_url: toolMessage.content + }; + if (Array.isArray(toolMessage.content)) { + /** + * Check for input_image type first (computer-use-preview format) + */ + const inputImage = toolMessage.content.find((i) => i.type === "input_image"); + if (inputImage) return inputImage; + /** + * Check for computer_screenshot type (legacy format) + */ + const oaiScreenshot = toolMessage.content.find((i) => i.type === "computer_screenshot"); + if (oaiScreenshot) return oaiScreenshot; + /** + * Convert image_url content block to input_image format + */ + const lcImage = toolMessage.content.find((i) => i.type === "image_url"); + if (lcImage) return { + type: "input_image", + image_url: typeof lcImage.image_url === "string" ? lcImage.image_url : lcImage.image_url.url + }; + } + throw new Error("Invalid computer call output"); + })(); + /** + * Cast needed because OpenAI SDK types don't yet include input_image + * for computer-use-preview model output format + */ + return { + type: "computer_call_output", + output, + call_id: toolMessage.tool_call_id + }; + } + if (toolMessage.additional_kwargs?.customTool) return { + type: "custom_tool_call_output", + call_id: toolMessage.tool_call_id, + output: toolMessage.content + }; + return { + type: "function_call_output", + call_id: toolMessage.tool_call_id, + id: toolMessage.id?.startsWith("fc_") ? toolMessage.id : void 0, + output: typeof toolMessage.content !== "string" ? JSON.stringify(toolMessage.content) : toolMessage.content + }; + } + if (role === "assistant") { + if (!zdrEnabled && responseMetadata?.output != null && Array.isArray(responseMetadata?.output) && responseMetadata?.output.length > 0 && responseMetadata?.output.every((item) => "type" in item)) return responseMetadata?.output; + const input = []; + if (additional_kwargs?.reasoning && !zdrEnabled) { + const reasoningItem = convertReasoningSummaryToResponsesReasoningItem(additional_kwargs.reasoning); + input.push(reasoningItem); + } + let { content } = lcMsg; + if (additional_kwargs?.refusal) { + if (typeof content === "string") content = [{ + type: "output_text", + text: content, + annotations: [] + }]; + content = [...content, { + type: "refusal", + refusal: additional_kwargs.refusal + }]; + } + if (typeof content === "string" || content.length > 0) input.push({ + type: "message", + role: "assistant", + ...lcMsg.id && !zdrEnabled && lcMsg.id.startsWith("msg_") ? { id: lcMsg.id } : {}, + content: iife$1(() => { + if (typeof content === "string") return content; + return content.flatMap((item) => { + if (item.type === "text") return { + type: "output_text", + text: item.text, + annotations: item.annotations ?? [] + }; + if (item.type === "output_text" || item.type === "refusal") return item; + return []; + }); + }) + }); + const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY]; + if (AIMessage.isInstance(lcMsg) && !!lcMsg.tool_calls?.length) input.push(...lcMsg.tool_calls.map((toolCall) => { + if (isCustomToolCall(toolCall)) return { + type: "custom_tool_call", + id: toolCall.call_id, + call_id: toolCall.id ?? "", + input: toolCall.args.input, + name: toolCall.name + }; + if (isComputerToolCall(toolCall)) return { + type: "computer_call", + id: toolCall.call_id, + call_id: toolCall.id ?? "", + action: toolCall.args.action + }; + return { + type: "function_call", + name: toolCall.name, + arguments: JSON.stringify(toolCall.args), + call_id: toolCall.id, + ...!zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {} + }; + })); + else if (additional_kwargs?.tool_calls) input.push(...additional_kwargs.tool_calls.map((toolCall) => ({ + type: "function_call", + name: toolCall.function.name, + call_id: toolCall.id, + arguments: toolCall.function.arguments, + ...!zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {} + }))); + const toolOutputs = (responseMetadata?.output)?.length ? responseMetadata?.output : additional_kwargs.tool_outputs; + const fallthroughCallTypes = [ + "computer_call", + "mcp_call", + "code_interpreter_call", + "image_generation_call" + ]; + if (toolOutputs != null) { + const castToolOutputs = toolOutputs; + const fallthroughCalls = castToolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type)); + if (fallthroughCalls.length > 0) input.push(...fallthroughCalls); + } + return input; + } + if (role === "user" || role === "system" || role === "developer") { + if (typeof lcMsg.content === "string") return { + type: "message", + role, + content: lcMsg.content + }; + const messages$1 = []; + const content = lcMsg.content.flatMap((item) => { + if (item.type === "mcp_approval_response") messages$1.push({ + type: "mcp_approval_response", + approval_request_id: item.approval_request_id, + approve: item.approve + }); + if (isDataContentBlock(item)) return convertToProviderContentBlock(item, completionsApiContentBlockConverter); + if (item.type === "text") return { + type: "input_text", + text: item.text + }; + if (item.type === "image_url") { + const imageUrl = iife$1(() => { + if (typeof item.image_url === "string") return item.image_url; + else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) return item.image_url.url; + return void 0; + }); + const detail = iife$1(() => { + if (typeof item.image_url === "string") return "auto"; + else if (typeof item.image_url === "object" && item.image_url !== null && "detail" in item.image_url) return item.image_url.detail; + return void 0; + }); + return { + type: "input_image", + image_url: imageUrl, + detail + }; + } + if (item.type === "input_text" || item.type === "input_image" || item.type === "input_file") return item; + return []; + }); + if (content.length > 0) messages$1.push({ + type: "message", + role, + content + }); + return messages$1; + } + console.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`); + return []; + }); +}; + +//#endregion + +//# sourceMappingURL=responses.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/responses.js + + + + + + +//#region src/chat_models/responses.ts +/** +* OpenAI Responses API implementation. +* +* Will be exported in a later version of @langchain/openai. +* +* @internal +*/ +var ChatOpenAIResponses = class extends BaseChatOpenAI { + invocationParams(options) { + let strict; + if (options?.strict !== void 0) strict = options.strict; + if (strict === void 0 && this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; + const params = { + model: this.model, + temperature: this.temperature, + top_p: this.topP, + user: this.user, + stream: this.streaming, + previous_response_id: options?.previous_response_id, + truncation: options?.truncation, + include: options?.include, + tools: options?.tools?.length ? this._reduceChatOpenAITools(options.tools, { + stream: this.streaming, + strict + }) : void 0, + tool_choice: isBuiltInToolChoice(options?.tool_choice) ? options?.tool_choice : (() => { + const formatted = formatToOpenAIToolChoice(options?.tool_choice); + if (typeof formatted === "object" && "type" in formatted) { + if (formatted.type === "function") return { + type: "function", + name: formatted.function.name + }; + else if (formatted.type === "allowed_tools") return { + type: "allowed_tools", + mode: formatted.allowed_tools.mode, + tools: formatted.allowed_tools.tools + }; + else if (formatted.type === "custom") return { + type: "custom", + name: formatted.custom.name + }; + } + return void 0; + })(), + text: (() => { + if (options?.text) return options.text; + const format = this._getResponseFormat(options?.response_format); + if (format?.type === "json_schema") { + if (format.json_schema.schema != null) return { + format: { + type: "json_schema", + schema: format.json_schema.schema, + description: format.json_schema.description, + name: format.json_schema.name, + strict: format.json_schema.strict + }, + verbosity: options?.verbosity + }; + return void 0; + } + return { + format, + verbosity: options?.verbosity + }; + })(), + parallel_tool_calls: options?.parallel_tool_calls, + max_output_tokens: this.maxTokens === -1 ? void 0 : this.maxTokens, + prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey, + prompt_cache_retention: options?.promptCacheRetention ?? this.promptCacheRetention, + ...this.zdrEnabled ? { store: false } : {}, + ...this.modelKwargs + }; + const reasoning = this._getReasoningParams(options); + if (reasoning !== void 0) params.reasoning = reasoning; + return params; + } + async _generate(messages, options) { + const invocationParams = this.invocationParams(options); + if (invocationParams.stream) { + const stream = this._streamResponseChunks(messages, options); + let finalChunk; + for await (const chunk of stream) { + chunk.message.response_metadata = { + ...chunk.generationInfo, + ...chunk.message.response_metadata + }; + finalChunk = finalChunk?.concat(chunk) ?? chunk; + } + return { + generations: finalChunk ? [finalChunk] : [], + llmOutput: { estimatedTokenUsage: (finalChunk?.message)?.usage_metadata } + }; + } else { + const data = await this.completionWithRetry({ + input: convertMessagesToResponsesInput({ + messages, + zdrEnabled: this.zdrEnabled ?? false, + model: this.model + }), + ...invocationParams, + stream: false + }, { + signal: options?.signal, + ...options?.options + }); + return { + generations: [{ + text: data.output_text, + message: convertResponsesMessageToAIMessage(data) + }], + llmOutput: { + id: data.id, + estimatedTokenUsage: data.usage ? { + promptTokens: data.usage.input_tokens, + completionTokens: data.usage.output_tokens, + totalTokens: data.usage.total_tokens + } : void 0 + } + }; + } + } + async *_streamResponseChunks(messages, options, runManager) { + const streamIterable = await this.completionWithRetry({ + ...this.invocationParams(options), + input: convertMessagesToResponsesInput({ + messages, + zdrEnabled: this.zdrEnabled ?? false, + model: this.model + }), + stream: true + }, options); + for await (const data of streamIterable) { + const chunk = convertResponsesDeltaToChatGenerationChunk(data); + if (chunk == null) continue; + yield chunk; + await runManager?.handleLLMNewToken(chunk.text || "", { + prompt: options.promptIndex ?? 0, + completion: 0 + }, void 0, void 0, void 0, { chunk }); + } + } + async completionWithRetry(request, requestOptions) { + return this.caller.call(async () => { + const clientOptions = this._getClientOptions(requestOptions); + try { + if (request.text?.format?.type === "json_schema" && !request.stream) return await this.client.responses.parse(request, clientOptions); + return await this.client.responses.create(request, clientOptions); + } catch (e) { + const error = wrapOpenAIClientError(e); + throw error; + } + }); + } + /** @internal */ + _reduceChatOpenAITools(tools, fields) { + const reducedTools = []; + for (const tool of tools) if (isBuiltInTool(tool)) { + if (tool.type === "image_generation" && fields?.stream) tool.partial_images = 1; + reducedTools.push(tool); + } else if (isCustomTool(tool)) { + const customToolData = tool.metadata.customTool; + reducedTools.push({ + type: "custom", + name: customToolData.name, + description: customToolData.description, + format: customToolData.format + }); + } else if (isOpenAITool(tool)) reducedTools.push({ + type: "function", + name: tool.function.name, + parameters: tool.function.parameters, + description: tool.function.description, + strict: fields?.strict ?? null + }); + else if (isOpenAICustomTool(tool)) reducedTools.push(convertCompletionsCustomTool(tool)); + return reducedTools; + } +}; + +//#endregion + +//# sourceMappingURL=responses.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/responses.js + + + +//#region src/azure/chat_models/responses.ts +var AzureChatOpenAIResponses = class extends ChatOpenAIResponses { + azureOpenAIApiVersion; + azureOpenAIApiKey; + azureADTokenProvider; + azureOpenAIApiInstanceName; + azureOpenAIApiDeploymentName; + azureOpenAIBasePath; + azureOpenAIEndpoint; + _llmType() { + return "azure_openai"; + } + get lc_aliases() { + return { + ...super.lc_aliases, + ...AZURE_ALIASES + }; + } + get lc_secrets() { + return { + ...super.lc_secrets, + ...AZURE_SECRETS + }; + } + get lc_serializable_keys() { + return [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS]; + } + getLsParams(options) { + const params = super.getLsParams(options); + params.ls_provider = "azure"; + return params; + } + constructor(fields) { + super(fields); + _constructAzureFields.call(this, fields); + } + _getClientOptions(options) { + return _getAzureClientOptions.call(this, options); + } + toJSON() { + return _serializeAzureChat.call(this, super.toJSON()); + } +}; + +//#endregion + +//# sourceMappingURL=responses.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/index.js + + + + + + +//#region src/chat_models/index.ts +/** +* OpenAI chat model integration. +* +* To use with Azure, import the `AzureChatOpenAI` class. +* +* Setup: +* Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`. +* +* ```bash +* npm install @langchain/openai +* export OPENAI_API_KEY="your-api-key" +* ``` +* +* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor) +* +* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html) +* +* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. +* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: +* +* ```typescript +* // When calling `.withConfig`, call options should be passed via the first argument +* const llmWithArgsBound = llm.withConfig({ +* stop: ["\n"], +* tools: [...], +* }); +* +* // When calling `.bindTools`, call options should be passed via the second argument +* const llmWithTools = llm.bindTools( +* [...], +* { +* tool_choice: "auto", +* } +* ); +* ``` +* +* ## Examples +* +*
+* Instantiate +* +* ```typescript +* import { ChatOpenAI } from '@langchain/openai'; +* +* const llm = new ChatOpenAI({ +* model: "gpt-4o-mini", +* temperature: 0, +* maxTokens: undefined, +* timeout: undefined, +* maxRetries: 2, +* // apiKey: "...", +* // configuration: { +* // baseURL: "...", +* // } +* // organization: "...", +* // other params... +* }); +* ``` +*
+* +*
+* +*
+* Invoking +* +* ```typescript +* const input = `Translate "I love programming" into French.`; +* +* // Models also accept a list of chat messages or a formatted prompt +* const result = await llm.invoke(input); +* console.log(result); +* ``` +* +* ```txt +* AIMessage { +* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz", +* "content": "J'adore la programmation.", +* "response_metadata": { +* "tokenUsage": { +* "completionTokens": 5, +* "promptTokens": 28, +* "totalTokens": 33 +* }, +* "finish_reason": "stop", +* "system_fingerprint": "fp_3aa7262c27" +* }, +* "usage_metadata": { +* "input_tokens": 28, +* "output_tokens": 5, +* "total_tokens": 33 +* } +* } +* ``` +*
+* +*
+* +*
+* Streaming Chunks +* +* ```typescript +* for await (const chunk of await llm.stream(input)) { +* console.log(chunk); +* } +* ``` +* +* ```txt +* AIMessageChunk { +* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs", +* "content": "" +* } +* AIMessageChunk { +* "content": "J" +* } +* AIMessageChunk { +* "content": "'adore" +* } +* AIMessageChunk { +* "content": " la" +* } +* AIMessageChunk { +* "content": " programmation",, +* } +* AIMessageChunk { +* "content": ".",, +* } +* AIMessageChunk { +* "content": "", +* "response_metadata": { +* "finish_reason": "stop", +* "system_fingerprint": "fp_c9aa9c0491" +* }, +* } +* AIMessageChunk { +* "content": "", +* "usage_metadata": { +* "input_tokens": 28, +* "output_tokens": 5, +* "total_tokens": 33 +* } +* } +* ``` +*
+* +*
+* +*
+* Aggregate Streamed Chunks +* +* ```typescript +* import { AIMessageChunk } from '@langchain/core/messages'; +* import { concat } from '@langchain/core/utils/stream'; +* +* const stream = await llm.stream(input); +* let full: AIMessageChunk | undefined; +* for await (const chunk of stream) { +* full = !full ? chunk : concat(full, chunk); +* } +* console.log(full); +* ``` +* +* ```txt +* AIMessageChunk { +* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu", +* "content": "J'adore la programmation.", +* "response_metadata": { +* "prompt": 0, +* "completion": 0, +* "finish_reason": "stop", +* }, +* "usage_metadata": { +* "input_tokens": 28, +* "output_tokens": 5, +* "total_tokens": 33 +* } +* } +* ``` +*
+* +*
+* +*
+* Bind tools +* +* ```typescript +* import { z } from 'zod'; +* +* const GetWeather = { +* name: "GetWeather", +* description: "Get the current weather in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const GetPopulation = { +* name: "GetPopulation", +* description: "Get the current population in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const llmWithTools = llm.bindTools( +* [GetWeather, GetPopulation], +* { +* // strict: true // enforce tool args schema is respected +* } +* ); +* const aiMsg = await llmWithTools.invoke( +* "Which city is hotter today and which is bigger: LA or NY?" +* ); +* console.log(aiMsg.tool_calls); +* ``` +* +* ```txt +* [ +* { +* name: 'GetWeather', +* args: { location: 'Los Angeles, CA' }, +* type: 'tool_call', +* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK' +* }, +* { +* name: 'GetWeather', +* args: { location: 'New York, NY' }, +* type: 'tool_call', +* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'Los Angeles, CA' }, +* type: 'tool_call', +* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'New York, NY' }, +* type: 'tool_call', +* id: 'call_s9KQB1UWj45LLGaEnjz0179q' +* } +* ] +* ``` +*
+* +*
+* +*
+* Structured Output +* +* ```typescript +* import { z } from 'zod'; +* +* const Joke = z.object({ +* setup: z.string().describe("The setup of the joke"), +* punchline: z.string().describe("The punchline to the joke"), +* rating: z.number().nullable().describe("How funny the joke is, from 1 to 10") +* }).describe('Joke to tell user.'); +* +* const structuredLlm = llm.withStructuredOutput(Joke, { +* name: "Joke", +* strict: true, // Optionally enable OpenAI structured outputs +* }); +* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); +* console.log(jokeResult); +* ``` +* +* ```txt +* { +* setup: 'Why was the cat sitting on the computer?', +* punchline: 'Because it wanted to keep an eye on the mouse!', +* rating: 7 +* } +* ``` +*
+* +*
+* +*
+* JSON Object Response Format +* +* ```typescript +* const jsonLlm = llm.withConfig({ response_format: { type: "json_object" } }); +* const jsonLlmAiMsg = await jsonLlm.invoke( +* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]" +* ); +* console.log(jsonLlmAiMsg.content); +* ``` +* +* ```txt +* { +* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67] +* } +* ``` +*
+* +*
+* +*
+* Multimodal +* +* ```typescript +* import { HumanMessage } from '@langchain/core/messages'; +* +* const imageUrl = "https://example.com/image.jpg"; +* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); +* const base64Image = Buffer.from(imageData).toString('base64'); +* +* const message = new HumanMessage({ +* content: [ +* { type: "text", text: "describe the weather in this image" }, +* { +* type: "image_url", +* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, +* }, +* ] +* }); +* +* const imageDescriptionAiMsg = await llm.invoke([message]); +* console.log(imageDescriptionAiMsg.content); +* ``` +* +* ```txt +* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions. +* ``` +*
+* +*
+* +*
+* Usage Metadata +* +* ```typescript +* const aiMsgForMetadata = await llm.invoke(input); +* console.log(aiMsgForMetadata.usage_metadata); +* ``` +* +* ```txt +* { input_tokens: 28, output_tokens: 5, total_tokens: 33 } +* ``` +*
+* +*
+* +*
+* Logprobs +* +* ```typescript +* const logprobsLlm = new ChatOpenAI({ model: "gpt-4o-mini", logprobs: true }); +* const aiMsgForLogprobs = await logprobsLlm.invoke(input); +* console.log(aiMsgForLogprobs.response_metadata.logprobs); +* ``` +* +* ```txt +* { +* content: [ +* { +* token: 'J', +* logprob: -0.000050616763, +* bytes: [Array], +* top_logprobs: [] +* }, +* { +* token: "'", +* logprob: -0.01868736, +* bytes: [Array], +* top_logprobs: [] +* }, +* { +* token: 'ad', +* logprob: -0.0000030545007, +* bytes: [Array], +* top_logprobs: [] +* }, +* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] }, +* { +* token: ' la', +* logprob: -0.515404, +* bytes: [Array], +* top_logprobs: [] +* }, +* { +* token: ' programm', +* logprob: -0.0000118755715, +* bytes: [Array], +* top_logprobs: [] +* }, +* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] }, +* { +* token: '.', +* logprob: -0.0000037697225, +* bytes: [Array], +* top_logprobs: [] +* } +* ], +* refusal: null +* } +* ``` +*
+* +*
+* +*
+* Response Metadata +* +* ```typescript +* const aiMsgForResponseMetadata = await llm.invoke(input); +* console.log(aiMsgForResponseMetadata.response_metadata); +* ``` +* +* ```txt +* { +* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 }, +* finish_reason: 'stop', +* system_fingerprint: 'fp_3aa7262c27' +* } +* ``` +*
+* +*
+* +*
+* JSON Schema Structured Output +* +* ```typescript +* const llmForJsonSchema = new ChatOpenAI({ +* model: "gpt-4o-2024-08-06", +* }).withStructuredOutput( +* z.object({ +* command: z.string().describe("The command to execute"), +* expectedOutput: z.string().describe("The expected output of the command"), +* options: z +* .array(z.string()) +* .describe("The options you can pass to the command"), +* }), +* { +* method: "jsonSchema", +* strict: true, // Optional when using the `jsonSchema` method +* } +* ); +* +* const jsonSchemaRes = await llmForJsonSchema.invoke( +* "What is the command to list files in a directory?" +* ); +* console.log(jsonSchemaRes); +* ``` +* +* ```txt +* { +* command: 'ls', +* expectedOutput: 'A list of files and subdirectories within the specified directory.', +* options: [ +* '-a: include directory entries whose names begin with a dot (.).', +* '-l: use a long listing format.', +* '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).', +* '-t: sort by time, newest first.', +* '-r: reverse order while sorting.', +* '-S: sort by file size, largest first.', +* '-R: list subdirectories recursively.' +* ] +* } +* ``` +*
+* +*
+* +*
+* Audio Outputs +* +* ```typescript +* import { ChatOpenAI } from "@langchain/openai"; +* +* const modelWithAudioOutput = new ChatOpenAI({ +* model: "gpt-4o-audio-preview", +* // You may also pass these fields to `.withConfig` as a call argument. +* modalities: ["text", "audio"], // Specifies that the model should output audio. +* audio: { +* voice: "alloy", +* format: "wav", +* }, +* }); +* +* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats."); +* const castMessageContent = audioOutputResult.content[0] as Record; +* +* console.log({ +* ...castMessageContent, +* data: castMessageContent.data.slice(0, 100) // Sliced for brevity +* }) +* ``` +* +* ```txt +* { +* id: 'audio_67117718c6008190a3afad3e3054b9b6', +* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg', +* expires_at: 1729201448, +* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!' +* } +* ``` +*
+* +*
+* +*
+* Audio Outputs +* +* ```typescript +* import { ChatOpenAI } from "@langchain/openai"; +* +* const modelWithAudioOutput = new ChatOpenAI({ +* model: "gpt-4o-audio-preview", +* // You may also pass these fields to `.withConfig` as a call argument. +* modalities: ["text", "audio"], // Specifies that the model should output audio. +* audio: { +* voice: "alloy", +* format: "wav", +* }, +* }); +* +* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats."); +* const castAudioContent = audioOutputResult.additional_kwargs.audio as Record; +* +* console.log({ +* ...castAudioContent, +* data: castAudioContent.data.slice(0, 100) // Sliced for brevity +* }) +* ``` +* +* ```txt +* { +* id: 'audio_67117718c6008190a3afad3e3054b9b6', +* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg', +* expires_at: 1729201448, +* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!' +* } +* ``` +*
+* +*
+*/ +var ChatOpenAI = class ChatOpenAI extends BaseChatOpenAI { + /** + * Whether to use the responses API for all requests. If `false` the responses API will be used + * only when required in order to fulfill the request. + */ + useResponsesApi = false; + responses; + completions; + get lc_serializable_keys() { + return [...super.lc_serializable_keys, "useResponsesApi"]; + } + get callKeys() { + return [...super.callKeys, "useResponsesApi"]; + } + constructor(fields) { + super(fields); + this.fields = fields; + this.useResponsesApi = fields?.useResponsesApi ?? false; + this.responses = fields?.responses ?? new ChatOpenAIResponses(fields); + this.completions = fields?.completions ?? new ChatOpenAICompletions(fields); + } + _useResponsesApi(options) { + const usesBuiltInTools = options?.tools?.some(isBuiltInTool); + const hasResponsesOnlyKwargs = options?.previous_response_id != null || options?.text != null || options?.truncation != null || options?.include != null || options?.reasoning?.summary != null || this.reasoning?.summary != null; + const hasCustomTools = options?.tools?.some(isOpenAICustomTool) || options?.tools?.some(isCustomTool); + return this.useResponsesApi || usesBuiltInTools || hasResponsesOnlyKwargs || hasCustomTools || _modelPrefersResponsesAPI(this.model); + } + getLsParams(options) { + const optionsWithDefaults = this._combineCallOptions(options); + if (this._useResponsesApi(options)) return this.responses.getLsParams(optionsWithDefaults); + return this.completions.getLsParams(optionsWithDefaults); + } + invocationParams(options) { + const optionsWithDefaults = this._combineCallOptions(options); + if (this._useResponsesApi(options)) return this.responses.invocationParams(optionsWithDefaults); + return this.completions.invocationParams(optionsWithDefaults); + } + /** @ignore */ + async _generate(messages, options, runManager) { + if (this._useResponsesApi(options)) return this.responses._generate(messages, options); + return this.completions._generate(messages, options, runManager); + } + async *_streamResponseChunks(messages, options, runManager) { + if (this._useResponsesApi(options)) { + yield* this.responses._streamResponseChunks(messages, this._combineCallOptions(options), runManager); + return; + } + yield* this.completions._streamResponseChunks(messages, this._combineCallOptions(options), runManager); + } + withConfig(config) { + const newModel = new ChatOpenAI(this.fields); + newModel.defaultOptions = { + ...this.defaultOptions, + ...config + }; + return newModel; + } +}; + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/index.js + + + + + +//#region src/azure/chat_models/index.ts +/** +* Azure OpenAI chat model integration. +* +* Setup: +* Install `@langchain/openai` and set the following environment variables: +* +* ```bash +* npm install @langchain/openai +* export AZURE_OPENAI_API_KEY="your-api-key" +* export AZURE_OPENAI_API_DEPLOYMENT_NAME="your-deployment-name" +* export AZURE_OPENAI_API_VERSION="your-version" +* export AZURE_OPENAI_BASE_PATH="your-base-path" +* ``` +* +* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.AzureChatOpenAI.html#constructor) +* +* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html) +* +* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. +* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: +* +* ```typescript +* // When calling `.withConfig`, call options should be passed via the first argument +* const llmWithArgsBound = llm.withConfig({ +* stop: ["\n"], +* tools: [...], +* }); +* +* // When calling `.bindTools`, call options should be passed via the second argument +* const llmWithTools = llm.bindTools( +* [...], +* { +* tool_choice: "auto", +* } +* ); +* ``` +* +* ## Examples +* +*
+* Instantiate +* +* ```typescript +* import { AzureChatOpenAI } from '@langchain/openai'; +* +* const llm = new AzureChatOpenAI({ +* azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY, // In Node.js defaults to process.env.AZURE_OPENAI_API_KEY +* azureOpenAIApiInstanceName: process.env.AZURE_OPENAI_API_INSTANCE_NAME, // In Node.js defaults to process.env.AZURE_OPENAI_API_INSTANCE_NAME +* azureOpenAIApiDeploymentName: process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME, // In Node.js defaults to process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME +* azureOpenAIApiVersion: process.env.AZURE_OPENAI_API_VERSION, // In Node.js defaults to process.env.AZURE_OPENAI_API_VERSION +* temperature: 0, +* maxTokens: undefined, +* timeout: undefined, +* maxRetries: 2, +* // apiKey: "...", +* // baseUrl: "...", +* // other params... +* }); +* ``` +*
+* +*
+* +*
+* Invoking +* +* ```typescript +* const input = `Translate "I love programming" into French.`; +* +* // Models also accept a list of chat messages or a formatted prompt +* const result = await llm.invoke(input); +* console.log(result); +* ``` +* +* ```txt +* AIMessage { +* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz", +* "content": "J'adore la programmation.", +* "response_metadata": { +* "tokenUsage": { +* "completionTokens": 5, +* "promptTokens": 28, +* "totalTokens": 33 +* }, +* "finish_reason": "stop", +* "system_fingerprint": "fp_3aa7262c27" +* }, +* "usage_metadata": { +* "input_tokens": 28, +* "output_tokens": 5, +* "total_tokens": 33 +* } +* } +* ``` +*
+* +*
+* +*
+* Streaming Chunks +* +* ```typescript +* for await (const chunk of await llm.stream(input)) { +* console.log(chunk); +* } +* ``` +* +* ```txt +* AIMessageChunk { +* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs", +* "content": "" +* } +* AIMessageChunk { +* "content": "J" +* } +* AIMessageChunk { +* "content": "'adore" +* } +* AIMessageChunk { +* "content": " la" +* } +* AIMessageChunk { +* "content": " programmation",, +* } +* AIMessageChunk { +* "content": ".",, +* } +* AIMessageChunk { +* "content": "", +* "response_metadata": { +* "finish_reason": "stop", +* "system_fingerprint": "fp_c9aa9c0491" +* }, +* } +* AIMessageChunk { +* "content": "", +* "usage_metadata": { +* "input_tokens": 28, +* "output_tokens": 5, +* "total_tokens": 33 +* } +* } +* ``` +*
+* +*
+* +*
+* Aggregate Streamed Chunks +* +* ```typescript +* import { AIMessageChunk } from '@langchain/core/messages'; +* import { concat } from '@langchain/core/utils/stream'; +* +* const stream = await llm.stream(input); +* let full: AIMessageChunk | undefined; +* for await (const chunk of stream) { +* full = !full ? chunk : concat(full, chunk); +* } +* console.log(full); +* ``` +* +* ```txt +* AIMessageChunk { +* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu", +* "content": "J'adore la programmation.", +* "response_metadata": { +* "prompt": 0, +* "completion": 0, +* "finish_reason": "stop", +* }, +* "usage_metadata": { +* "input_tokens": 28, +* "output_tokens": 5, +* "total_tokens": 33 +* } +* } +* ``` +*
+* +*
+* +*
+* Bind tools +* +* ```typescript +* import { z } from 'zod'; +* +* const GetWeather = { +* name: "GetWeather", +* description: "Get the current weather in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const GetPopulation = { +* name: "GetPopulation", +* description: "Get the current population in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); +* const aiMsg = await llmWithTools.invoke( +* "Which city is hotter today and which is bigger: LA or NY?" +* ); +* console.log(aiMsg.tool_calls); +* ``` +* +* ```txt +* [ +* { +* name: 'GetWeather', +* args: { location: 'Los Angeles, CA' }, +* type: 'tool_call', +* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK' +* }, +* { +* name: 'GetWeather', +* args: { location: 'New York, NY' }, +* type: 'tool_call', +* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'Los Angeles, CA' }, +* type: 'tool_call', +* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'New York, NY' }, +* type: 'tool_call', +* id: 'call_s9KQB1UWj45LLGaEnjz0179q' +* } +* ] +* ``` +*
+* +*
+* +*
+* Structured Output +* +* ```typescript +* import { z } from 'zod'; +* +* const Joke = z.object({ +* setup: z.string().describe("The setup of the joke"), +* punchline: z.string().describe("The punchline to the joke"), +* rating: z.number().nullable().describe("How funny the joke is, from 1 to 10") +* }).describe('Joke to tell user.'); +* +* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); +* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); +* console.log(jokeResult); +* ``` +* +* ```txt +* { +* setup: 'Why was the cat sitting on the computer?', +* punchline: 'Because it wanted to keep an eye on the mouse!', +* rating: 7 +* } +* ``` +*
+* +*
+* +*
+* JSON Object Response Format +* +* ```typescript +* const jsonLlm = llm.withConfig({ response_format: { type: "json_object" } }); +* const jsonLlmAiMsg = await jsonLlm.invoke( +* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]" +* ); +* console.log(jsonLlmAiMsg.content); +* ``` +* +* ```txt +* { +* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67] +* } +* ``` +*
+* +*
+* +*
+* Multimodal +* +* ```typescript +* import { HumanMessage } from '@langchain/core/messages'; +* +* const imageUrl = "https://example.com/image.jpg"; +* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); +* const base64Image = Buffer.from(imageData).toString('base64'); +* +* const message = new HumanMessage({ +* content: [ +* { type: "text", text: "describe the weather in this image" }, +* { +* type: "image_url", +* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, +* }, +* ] +* }); +* +* const imageDescriptionAiMsg = await llm.invoke([message]); +* console.log(imageDescriptionAiMsg.content); +* ``` +* +* ```txt +* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions. +* ``` +*
+* +*
+* +*
+* Usage Metadata +* +* ```typescript +* const aiMsgForMetadata = await llm.invoke(input); +* console.log(aiMsgForMetadata.usage_metadata); +* ``` +* +* ```txt +* { input_tokens: 28, output_tokens: 5, total_tokens: 33 } +* ``` +*
+* +*
+* +*
+* Logprobs +* +* ```typescript +* const logprobsLlm = new ChatOpenAI({ model: "gpt-4o-mini", logprobs: true }); +* const aiMsgForLogprobs = await logprobsLlm.invoke(input); +* console.log(aiMsgForLogprobs.response_metadata.logprobs); +* ``` +* +* ```txt +* { +* content: [ +* { +* token: 'J', +* logprob: -0.000050616763, +* bytes: [Array], +* top_logprobs: [] +* }, +* { +* token: "'", +* logprob: -0.01868736, +* bytes: [Array], +* top_logprobs: [] +* }, +* { +* token: 'ad', +* logprob: -0.0000030545007, +* bytes: [Array], +* top_logprobs: [] +* }, +* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] }, +* { +* token: ' la', +* logprob: -0.515404, +* bytes: [Array], +* top_logprobs: [] +* }, +* { +* token: ' programm', +* logprob: -0.0000118755715, +* bytes: [Array], +* top_logprobs: [] +* }, +* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] }, +* { +* token: '.', +* logprob: -0.0000037697225, +* bytes: [Array], +* top_logprobs: [] +* } +* ], +* refusal: null +* } +* ``` +*
+* +*
+* +*
+* Response Metadata +* +* ```typescript +* const aiMsgForResponseMetadata = await llm.invoke(input); +* console.log(aiMsgForResponseMetadata.response_metadata); +* ``` +* +* ```txt +* { +* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 }, +* finish_reason: 'stop', +* system_fingerprint: 'fp_3aa7262c27' +* } +* ``` +*
+*/ +var AzureChatOpenAI = class extends ChatOpenAI { + azureOpenAIApiVersion; + azureOpenAIApiKey; + azureADTokenProvider; + azureOpenAIApiInstanceName; + azureOpenAIApiDeploymentName; + azureOpenAIBasePath; + azureOpenAIEndpoint; + _llmType() { + return "azure_openai"; + } + get lc_aliases() { + return { + ...super.lc_aliases, + ...AZURE_ALIASES + }; + } + get lc_secrets() { + return { + ...super.lc_secrets, + ...AZURE_SECRETS + }; + } + get lc_serializable_keys() { + return [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS]; + } + getLsParams(options) { + const params = super.getLsParams(options); + params.ls_provider = "azure"; + return params; + } + constructor(fields) { + super({ + ...fields, + completions: new AzureChatOpenAICompletions(fields), + responses: new AzureChatOpenAIResponses(fields) + }); + _constructAzureFields.call(this, fields); + } + /** @internal */ + _getStructuredOutputMethod(config) { + const ensuredConfig = { ...config }; + if (this.model.startsWith("gpt-4o")) { + if (ensuredConfig?.method === void 0) return "functionCalling"; + } + return super._getStructuredOutputMethod(ensuredConfig); + } + toJSON() { + return _serializeAzureChat.call(this, super.toJSON()); + } +}; + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/llms.js + + + + + + + + + +//#region src/llms.ts +/** +* Wrapper around OpenAI large language models. +* +* To use you should have the `openai` package installed, with the +* `OPENAI_API_KEY` environment variable set. +* +* To use with Azure, import the `AzureOpenAI` class. +* +* @remarks +* Any parameters that are valid to be passed to {@link +* https://platform.openai.com/docs/api-reference/completions/create | +* `openai.createCompletion`} can be passed through {@link modelKwargs}, even +* if not explicitly available on this class. +* @example +* ```typescript +* const model = new OpenAI({ +* modelName: "gpt-4", +* temperature: 0.7, +* maxTokens: 1000, +* maxRetries: 5, +* }); +* +* const res = await model.invoke( +* "Question: What would be a good company name for a company that makes colorful socks?\nAnswer:" +* ); +* console.log({ res }); +* ``` +*/ +var OpenAI$2 = class extends BaseLLM { + static lc_name() { + return "OpenAI"; + } + get callKeys() { + return [...super.callKeys, "options"]; + } + lc_serializable = true; + get lc_secrets() { + return { + openAIApiKey: "OPENAI_API_KEY", + apiKey: "OPENAI_API_KEY", + organization: "OPENAI_ORGANIZATION" + }; + } + get lc_aliases() { + return { + modelName: "model", + openAIApiKey: "openai_api_key", + apiKey: "openai_api_key" + }; + } + temperature; + maxTokens; + topP; + frequencyPenalty; + presencePenalty; + n = 1; + bestOf; + logitBias; + model = "gpt-3.5-turbo-instruct"; + /** @deprecated Use "model" instead */ + modelName; + modelKwargs; + batchSize = 20; + timeout; + stop; + stopSequences; + user; + streaming = false; + openAIApiKey; + apiKey; + organization; + client; + clientConfig; + constructor(fields) { + super(fields ?? {}); + this.openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); + this.apiKey = this.openAIApiKey; + this.organization = fields?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); + this.model = fields?.model ?? fields?.modelName ?? this.model; + if ((this.model?.startsWith("gpt-3.5-turbo") || this.model?.startsWith("gpt-4") || this.model?.startsWith("o1")) && !this.model?.includes("-instruct")) throw new Error([ + `Your chosen OpenAI model, "${this.model}", is a chat model and not a text-in/text-out LLM.`, + `Passing it into the "OpenAI" class is no longer supported.`, + `Please use the "ChatOpenAI" class instead.`, + "", + `See this page for more information:`, + "|", + `└> https://js.langchain.com/docs/integrations/chat/openai` + ].join("\n")); + this.modelName = this.model; + this.modelKwargs = fields?.modelKwargs ?? {}; + this.batchSize = fields?.batchSize ?? this.batchSize; + this.timeout = fields?.timeout; + this.temperature = fields?.temperature ?? this.temperature; + this.maxTokens = fields?.maxTokens ?? this.maxTokens; + this.topP = fields?.topP ?? this.topP; + this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; + this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; + this.n = fields?.n ?? this.n; + this.bestOf = fields?.bestOf ?? this.bestOf; + this.logitBias = fields?.logitBias; + this.stop = fields?.stopSequences ?? fields?.stop; + this.stopSequences = this.stop; + this.user = fields?.user; + this.streaming = fields?.streaming ?? false; + if (this.streaming && this.bestOf && this.bestOf > 1) throw new Error("Cannot stream results when bestOf > 1"); + this.clientConfig = { + apiKey: this.apiKey, + organization: this.organization, + dangerouslyAllowBrowser: true, + ...fields?.configuration + }; + } + /** + * Get the parameters used to invoke the model + */ + invocationParams(options) { + return { + model: this.model, + temperature: this.temperature, + max_tokens: this.maxTokens, + top_p: this.topP, + frequency_penalty: this.frequencyPenalty, + presence_penalty: this.presencePenalty, + n: this.n, + best_of: this.bestOf, + logit_bias: this.logitBias, + stop: options?.stop ?? this.stopSequences, + user: this.user, + stream: this.streaming, + ...this.modelKwargs + }; + } + /** @ignore */ + _identifyingParams() { + return { + model_name: this.model, + ...this.invocationParams(), + ...this.clientConfig + }; + } + /** + * Get the identifying parameters for the model + */ + identifyingParams() { + return this._identifyingParams(); + } + /** + * Call out to OpenAI's endpoint with k unique prompts + * + * @param [prompts] - The prompts to pass into the model. + * @param [options] - Optional list of stop words to use when generating. + * @param [runManager] - Optional callback manager to use when generating. + * + * @returns The full LLM output. + * + * @example + * ```ts + * import { OpenAI } from "langchain/llms/openai"; + * const openai = new OpenAI(); + * const response = await openai.generate(["Tell me a joke."]); + * ``` + */ + async _generate(prompts, options, runManager) { + const subPrompts = chunkArray(prompts, this.batchSize); + const choices = []; + const tokenUsage = {}; + const params = this.invocationParams(options); + if (params.max_tokens === -1) { + if (prompts.length !== 1) throw new Error("max_tokens set to -1 not supported for multiple inputs"); + params.max_tokens = await calculateMaxTokens({ + prompt: prompts[0], + modelName: this.model + }); + } + for (let i = 0; i < subPrompts.length; i += 1) { + const data = params.stream ? await (async () => { + const choices$1 = []; + let response; + const stream = await this.completionWithRetry({ + ...params, + stream: true, + prompt: subPrompts[i] + }, options); + for await (const message of stream) { + if (!response) response = { + id: message.id, + object: message.object, + created: message.created, + model: message.model + }; + for (const part of message.choices) { + if (!choices$1[part.index]) choices$1[part.index] = part; + else { + const choice = choices$1[part.index]; + choice.text += part.text; + choice.finish_reason = part.finish_reason; + choice.logprobs = part.logprobs; + } + runManager?.handleLLMNewToken(part.text, { + prompt: Math.floor(part.index / this.n), + completion: part.index % this.n + }); + } + } + if (options.signal?.aborted) throw new Error("AbortError"); + return { + ...response, + choices: choices$1 + }; + })() : await this.completionWithRetry({ + ...params, + stream: false, + prompt: subPrompts[i] + }, { + signal: options.signal, + ...options.options + }); + choices.push(...data.choices); + const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens } = data.usage ? data.usage : { + completion_tokens: void 0, + prompt_tokens: void 0, + total_tokens: void 0 + }; + if (completionTokens) tokenUsage.completionTokens = (tokenUsage.completionTokens ?? 0) + completionTokens; + if (promptTokens) tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens; + if (totalTokens) tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens; + } + const generations = chunkArray(choices, this.n).map((promptChoices) => promptChoices.map((choice) => ({ + text: choice.text ?? "", + generationInfo: { + finishReason: choice.finish_reason, + logprobs: choice.logprobs + } + }))); + return { + generations, + llmOutput: { tokenUsage } + }; + } + async *_streamResponseChunks(input, options, runManager) { + const params = { + ...this.invocationParams(options), + prompt: input, + stream: true + }; + const stream = await this.completionWithRetry(params, options); + for await (const data of stream) { + const choice = data?.choices[0]; + if (!choice) continue; + const chunk = new GenerationChunk({ + text: choice.text, + generationInfo: { finishReason: choice.finish_reason } + }); + yield chunk; + runManager?.handleLLMNewToken(chunk.text ?? ""); + } + if (options.signal?.aborted) throw new Error("AbortError"); + } + async completionWithRetry(request, options) { + const requestOptions = this._getClientOptions(options); + return this.caller.call(async () => { + try { + const res = await this.client.completions.create(request, requestOptions); + return res; + } catch (e) { + const error = wrapOpenAIClientError(e); + throw error; + } + }); + } + /** + * Calls the OpenAI API with retry logic in case of failures. + * @param request The request to send to the OpenAI API. + * @param options Optional configuration for the API call. + * @returns The response from the OpenAI API. + */ + _getClientOptions(options) { + if (!this.client) { + const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL }; + const endpoint = getEndpoint(openAIEndpointConfig); + const params = { + ...this.clientConfig, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0 + }; + if (!params.baseURL) delete params.baseURL; + params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders); + this.client = new OpenAI(params); + } + const requestOptions = { + ...this.clientConfig, + ...options + }; + return requestOptions; + } + _llmType() { + return "openai"; + } +}; + +//#endregion + +//# sourceMappingURL=llms.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/llms.js + + + + + +//#region src/azure/llms.ts +var AzureOpenAI$1 = class extends OpenAI$2 { + azureOpenAIApiVersion; + azureOpenAIApiKey; + azureADTokenProvider; + azureOpenAIApiInstanceName; + azureOpenAIApiDeploymentName; + azureOpenAIBasePath; + azureOpenAIEndpoint; + get lc_aliases() { + return { + ...super.lc_aliases, + openAIApiKey: "openai_api_key", + openAIApiVersion: "openai_api_version", + openAIBasePath: "openai_api_base", + deploymentName: "deployment_name", + azureOpenAIEndpoint: "azure_endpoint", + azureOpenAIApiVersion: "openai_api_version", + azureOpenAIBasePath: "openai_api_base", + azureOpenAIApiDeploymentName: "deployment_name" + }; + } + get lc_secrets() { + return { + ...super.lc_secrets, + azureOpenAIApiKey: "AZURE_OPENAI_API_KEY" + }; + } + constructor(fields) { + super(fields); + this.azureOpenAIApiDeploymentName = (fields?.azureOpenAIApiCompletionsDeploymentName || fields?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") || getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME")); + this.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? (typeof fields?.openAIApiKey === "string" ? fields?.openAIApiKey : void 0) ?? (typeof fields?.apiKey === "string" ? fields?.apiKey : void 0) ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); + this.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); + this.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); + this.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); + this.azureOpenAIEndpoint = fields?.azureOpenAIEndpoint ?? getEnvironmentVariable("AZURE_OPENAI_ENDPOINT"); + this.azureADTokenProvider = fields?.azureADTokenProvider; + if (!this.azureOpenAIApiKey && !this.apiKey && !this.azureADTokenProvider) throw new Error("Azure OpenAI API key or Token Provider not found"); + } + _getClientOptions(options) { + if (!this.client) { + const openAIEndpointConfig = { + azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, + azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, + azureOpenAIApiKey: this.azureOpenAIApiKey, + azureOpenAIBasePath: this.azureOpenAIBasePath, + azureADTokenProvider: this.azureADTokenProvider, + baseURL: this.clientConfig.baseURL + }; + const endpoint = getEndpoint(openAIEndpointConfig); + const { apiKey: existingApiKey,...clientConfigRest } = this.clientConfig; + const params = { + ...clientConfigRest, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0 + }; + if (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey; + if (!params.baseURL) delete params.baseURL; + params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders, true, "2.0.0"); + this.client = new AzureOpenAI({ + apiVersion: this.azureOpenAIApiVersion, + azureADTokenProvider: this.azureADTokenProvider, + ...params + }); + } + const requestOptions = { + ...this.clientConfig, + ...options + }; + if (this.azureOpenAIApiKey) { + requestOptions.headers = { + "api-key": this.azureOpenAIApiKey, + ...requestOptions.headers + }; + requestOptions.query = { + "api-version": this.azureOpenAIApiVersion, + ...requestOptions.query + }; + } + return requestOptions; + } + toJSON() { + const json = super.toJSON(); + function isRecord(obj) { + return typeof obj === "object" && obj != null; + } + if (isRecord(json) && isRecord(json.kwargs)) { + delete json.kwargs.azure_openai_base_path; + delete json.kwargs.azure_openai_api_deployment_name; + delete json.kwargs.azure_openai_api_key; + delete json.kwargs.azure_openai_api_version; + delete json.kwargs.azure_open_ai_base_path; + } + return json; + } +}; + +//#endregion + +//# sourceMappingURL=llms.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/embeddings.js + + + + + + + +//#region src/embeddings.ts +/** +* Class for generating embeddings using the OpenAI API. +* +* To use with Azure, import the `AzureOpenAIEmbeddings` class. +* +* @example +* ```typescript +* // Embed a query using OpenAIEmbeddings to generate embeddings for a given text +* const model = new OpenAIEmbeddings(); +* const res = await model.embedQuery( +* "What would be a good company name for a company that makes colorful socks?", +* ); +* console.log({ res }); +* +* ``` +*/ +var OpenAIEmbeddings = class extends Embeddings { + model = "text-embedding-ada-002"; + /** @deprecated Use "model" instead */ + modelName; + batchSize = 512; + stripNewLines = true; + /** + * The number of dimensions the resulting output embeddings should have. + * Only supported in `text-embedding-3` and later models. + */ + dimensions; + timeout; + organization; + encodingFormat; + client; + clientConfig; + apiKey; + constructor(fields) { + const fieldsWithDefaults = { + maxConcurrency: 2, + ...fields + }; + super(fieldsWithDefaults); + const apiKey = fieldsWithDefaults?.apiKey ?? fieldsWithDefaults?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); + this.organization = fieldsWithDefaults?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); + this.model = fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model; + this.modelName = this.model; + this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize; + this.stripNewLines = fieldsWithDefaults?.stripNewLines ?? this.stripNewLines; + this.timeout = fieldsWithDefaults?.timeout; + this.dimensions = fieldsWithDefaults?.dimensions; + this.encodingFormat = fieldsWithDefaults?.encodingFormat; + this.clientConfig = { + apiKey, + organization: this.organization, + dangerouslyAllowBrowser: true, + ...fields?.configuration + }; + } + /** + * Method to generate embeddings for an array of documents. Splits the + * documents into batches and makes requests to the OpenAI API to generate + * embeddings. + * @param texts Array of documents to generate embeddings for. + * @returns Promise that resolves to a 2D array of embeddings for each document. + */ + async embedDocuments(texts) { + const batches = chunkArray(this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts, this.batchSize); + const batchRequests = batches.map((batch) => { + const params = { + model: this.model, + input: batch + }; + if (this.dimensions) params.dimensions = this.dimensions; + if (this.encodingFormat) params.encoding_format = this.encodingFormat; + return this.embeddingWithRetry(params); + }); + const batchResponses = await Promise.all(batchRequests); + const embeddings = []; + for (let i = 0; i < batchResponses.length; i += 1) { + const batch = batches[i]; + const { data: batchResponse } = batchResponses[i]; + for (let j = 0; j < batch.length; j += 1) embeddings.push(batchResponse[j].embedding); + } + return embeddings; + } + /** + * Method to generate an embedding for a single document. Calls the + * embeddingWithRetry method with the document as the input. + * @param text Document to generate an embedding for. + * @returns Promise that resolves to an embedding for the document. + */ + async embedQuery(text) { + const params = { + model: this.model, + input: this.stripNewLines ? text.replace(/\n/g, " ") : text + }; + if (this.dimensions) params.dimensions = this.dimensions; + if (this.encodingFormat) params.encoding_format = this.encodingFormat; + const { data } = await this.embeddingWithRetry(params); + return data[0].embedding; + } + /** + * Private method to make a request to the OpenAI API to generate + * embeddings. Handles the retry logic and returns the response from the + * API. + * @param request Request to send to the OpenAI API. + * @returns Promise that resolves to the response from the API. + */ + async embeddingWithRetry(request) { + if (!this.client) { + const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL }; + const endpoint = getEndpoint(openAIEndpointConfig); + const params = { + ...this.clientConfig, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0 + }; + if (!params.baseURL) delete params.baseURL; + params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders); + this.client = new OpenAI(params); + } + const requestOptions = {}; + return this.caller.call(async () => { + try { + const res = await this.client.embeddings.create(request, requestOptions); + return res; + } catch (e) { + const error = wrapOpenAIClientError(e); + throw error; + } + }); + } +}; + +//#endregion + +//# sourceMappingURL=embeddings.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/embeddings.js + + + + + + +//#region src/azure/embeddings.ts +var AzureOpenAIEmbeddings = class extends OpenAIEmbeddings { + azureOpenAIApiVersion; + azureOpenAIApiKey; + azureADTokenProvider; + azureOpenAIApiInstanceName; + azureOpenAIApiDeploymentName; + azureOpenAIBasePath; + constructor(fields) { + super(fields); + this.batchSize = fields?.batchSize ?? 1; + this.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? (typeof fields?.apiKey === "string" ? fields?.apiKey : void 0) ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); + this.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); + this.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); + this.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); + this.azureOpenAIApiDeploymentName = (fields?.azureOpenAIApiEmbeddingsDeploymentName || fields?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME") || getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME")); + this.azureADTokenProvider = fields?.azureADTokenProvider; + } + async embeddingWithRetry(request) { + if (!this.client) { + const openAIEndpointConfig = { + azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, + azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, + azureOpenAIApiKey: this.azureOpenAIApiKey, + azureOpenAIBasePath: this.azureOpenAIBasePath, + azureADTokenProvider: this.azureADTokenProvider, + baseURL: this.clientConfig.baseURL + }; + const endpoint = getEndpoint(openAIEndpointConfig); + const { apiKey: existingApiKey,...clientConfigRest } = this.clientConfig; + const params = { + ...clientConfigRest, + baseURL: endpoint, + timeout: this.timeout, + maxRetries: 0 + }; + if (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey; + if (!params.baseURL) delete params.baseURL; + params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders, true, "2.0.0"); + this.client = new AzureOpenAI({ + apiVersion: this.azureOpenAIApiVersion, + azureADTokenProvider: this.azureADTokenProvider, + deployment: this.azureOpenAIApiDeploymentName, + ...params + }); + } + const requestOptions = {}; + if (this.azureOpenAIApiKey) { + requestOptions.headers = { + "api-key": this.azureOpenAIApiKey, + ...requestOptions.headers + }; + requestOptions.query = { + "api-version": this.azureOpenAIApiVersion, + ...requestOptions.query + }; + } + return this.caller.call(async () => { + try { + const res = await this.client.embeddings.create(request, requestOptions); + return res; + } catch (e) { + const error = wrapOpenAIClientError(e); + throw error; + } + }); + } +}; + +//#endregion + +//# sourceMappingURL=embeddings.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/dalle.js + + + + +//#region src/tools/dalle.ts +/** +* A tool for generating images with Open AIs Dall-E 2 or 3 API. +*/ +var DallEAPIWrapper = class extends Tool { + static lc_name() { + return "DallEAPIWrapper"; + } + name = "dalle_api_wrapper"; + description = "A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."; + client; + static toolName = "dalle_api_wrapper"; + model = "dall-e-3"; + style = "vivid"; + quality = "standard"; + n = 1; + size = "1024x1024"; + dallEResponseFormat = "url"; + user; + constructor(fields) { + if (fields?.responseFormat !== void 0 && ["url", "b64_json"].includes(fields.responseFormat)) { + fields.dallEResponseFormat = fields.responseFormat; + fields.responseFormat = "content"; + } + super(fields); + const openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); + const organization = fields?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); + const clientConfig = { + apiKey: openAIApiKey, + organization, + dangerouslyAllowBrowser: true, + baseURL: fields?.baseUrl + }; + this.client = new OpenAI(clientConfig); + this.model = fields?.model ?? fields?.modelName ?? this.model; + this.style = fields?.style ?? this.style; + this.quality = fields?.quality ?? this.quality; + this.n = fields?.n ?? this.n; + this.size = fields?.size ?? this.size; + this.dallEResponseFormat = fields?.dallEResponseFormat ?? this.dallEResponseFormat; + this.user = fields?.user; + } + /** + * Processes the API response if multiple images are generated. + * Returns a list of MessageContentImageUrl objects. If the response + * format is `url`, then the `image_url` field will contain the URL. + * If it is `b64_json`, then the `image_url` field will contain an object + * with a `url` field with the base64 encoded image. + * + * @param {OpenAIClient.Images.ImagesResponse[]} response The API response + * @returns {MessageContentImageUrl[]} + */ + processMultipleGeneratedUrls(response) { + if (this.dallEResponseFormat === "url") return response.flatMap((res) => { + const imageUrlContent = res.data?.flatMap((item) => { + if (!item.url) return []; + return { + type: "image_url", + image_url: item.url + }; + }).filter((item) => item !== void 0 && item.type === "image_url" && typeof item.image_url === "string" && item.image_url !== void 0) ?? []; + return imageUrlContent; + }); + else return response.flatMap((res) => { + const b64Content = res.data?.flatMap((item) => { + if (!item.b64_json) return []; + return { + type: "image_url", + image_url: { url: item.b64_json } + }; + }).filter((item) => item !== void 0 && item.type === "image_url" && typeof item.image_url === "object" && "url" in item.image_url && typeof item.image_url.url === "string" && item.image_url.url !== void 0) ?? []; + return b64Content; + }); + } + /** @ignore */ + async _call(input) { + const generateImageFields = { + model: this.model, + prompt: input, + n: 1, + size: this.size, + response_format: this.dallEResponseFormat, + style: this.style, + quality: this.quality, + user: this.user + }; + if (this.n > 1) { + const results = await Promise.all(Array.from({ length: this.n }).map(() => this.client.images.generate(generateImageFields))); + return this.processMultipleGeneratedUrls(results); + } + const response = await this.client.images.generate(generateImageFields); + let data = ""; + if (this.dallEResponseFormat === "url") [data] = response.data?.map((item) => item.url).filter((url) => url !== "undefined") ?? []; + else [data] = response.data?.map((item) => item.b64_json).filter((b64_json) => b64_json !== "undefined") ?? []; + return data; + } +}; + +//#endregion + +//# sourceMappingURL=dalle.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/webSearch.js +//#region src/tools/webSearch.ts +/** +* Creates a web search tool that allows OpenAI models to search the web +* for up-to-date information before generating a response. +* +* Web search supports three main types: +* 1. **Non-reasoning web search**: Quick lookups where the model passes queries +* directly to the search tool. +* 2. **Agentic search with reasoning models**: The model actively manages the +* search process, analyzing results and deciding whether to keep searching. +* 3. **Deep research**: Extended investigations using models like `o3-deep-research` +* or `gpt-5` with high reasoning effort. +* +* @see {@link https://platform.openai.com/docs/guides/tools-web-search | OpenAI Web Search Documentation} +* @param options - Configuration options for the web search tool +* @returns A web search tool definition to be passed to the OpenAI Responses API +* +* @example +* ```typescript +* import { ChatOpenAI, tools } from "@langchain/openai"; +* +* const model = new ChatOpenAI({ +* model: "gpt-4o", +* }); +* +* // Basic usage +* const response = await model.invoke("What was a positive news story from today?", { +* tools: [tools.webSearch()], +* }); +* +* // With domain filtering +* const filteredResponse = await model.invoke("Latest AI research news", { +* tools: [tools.webSearch({ +* filters: { +* allowedDomains: ["arxiv.org", "nature.com", "science.org"], +* }, +* })], +* }); +* +* // With user location for geographic relevance +* const localResponse = await model.invoke("What are the best restaurants near me?", { +* tools: [tools.webSearch({ +* userLocation: { +* type: "approximate", +* country: "US", +* city: "San Francisco", +* region: "California", +* timezone: "America/Los_Angeles", +* }, +* })], +* }); +* +* // Cache-only mode (no live internet access) +* const cachedResponse = await model.invoke("Find information about OpenAI", { +* tools: [tools.webSearch({ +* externalWebAccess: false, +* })], +* }); +* ``` +*/ +function webSearch(options) { + return { + type: "web_search", + filters: options?.filters?.allowedDomains ? { allowed_domains: options.filters.allowedDomains } : void 0, + user_location: options?.userLocation, + search_context_size: options?.search_context_size + }; +} + +//#endregion + +//# sourceMappingURL=webSearch.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/mcp.js +//#region src/tools/mcp.ts +/** +* Converts a McpToolFilter to the API format. +*/ +function convertToolFilter(filter) { + return { + tool_names: filter.toolNames, + read_only: filter.readOnly + }; +} +/** +* Converts allowed_tools option to API format. +*/ +function convertAllowedTools(allowedTools) { + if (!allowedTools) return void 0; + if (Array.isArray(allowedTools)) return allowedTools; + return convertToolFilter(allowedTools); +} +/** +* Converts require_approval option to API format. +*/ +function convertRequireApproval(requireApproval) { + if (!requireApproval) return void 0; + if (typeof requireApproval === "string") return requireApproval; + return { + always: requireApproval.always ? convertToolFilter(requireApproval.always) : void 0, + never: requireApproval.never ? convertToolFilter(requireApproval.never) : void 0 + }; +} +function mcp(options) { + const baseConfig = { + type: "mcp", + server_label: options.serverLabel, + allowed_tools: convertAllowedTools(options.allowedTools), + authorization: options.authorization, + headers: options.headers, + require_approval: convertRequireApproval(options.requireApproval), + server_description: options.serverDescription + }; + if ("serverUrl" in options) return { + ...baseConfig, + server_url: options.serverUrl + }; + return { + ...baseConfig, + connector_id: options.connectorId + }; +} + +//#endregion + +//# sourceMappingURL=mcp.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/codeInterpreter.js +//#region src/tools/codeInterpreter.ts +/** +* Converts container options to the API format. +*/ +function convertContainer(container) { + if (typeof container === "string") return container; + return { + type: "auto", + file_ids: container?.fileIds, + memory_limit: container?.memoryLimit + }; +} +/** +* Creates a Code Interpreter tool that allows models to write and run Python code +* in a sandboxed environment to solve complex problems. +* +* Use Code Interpreter for: +* - **Data analysis**: Processing files with diverse data and formatting +* - **File generation**: Creating files with data and images of graphs +* - **Iterative coding**: Writing and running code iteratively to solve problems +* - **Visual intelligence**: Cropping, zooming, rotating, and transforming images +* +* The tool runs in a container, which is a fully sandboxed virtual machine. +* Containers can be created automatically (auto mode) or explicitly via the +* `/v1/containers` endpoint. +* +* @see {@link https://platform.openai.com/docs/guides/tools-code-interpreter | OpenAI Code Interpreter Documentation} +* +* @param options - Configuration options for the Code Interpreter tool +* @returns A Code Interpreter tool definition to be passed to the OpenAI Responses API +* +* @example +* ```typescript +* import { ChatOpenAI, tools } from "@langchain/openai"; +* +* const model = new ChatOpenAI({ model: "gpt-4.1" }); +* +* // Basic usage with auto container (default 1GB memory) +* const response = await model.invoke( +* "Solve the equation 3x + 11 = 14", +* { tools: [tools.codeInterpreter()] } +* ); +* +* // With increased memory limit for larger computations +* const response = await model.invoke( +* "Analyze this large dataset and create visualizations", +* { +* tools: [tools.codeInterpreter({ +* container: { memoryLimit: "4g" } +* })] +* } +* ); +* +* // With specific files available to the code +* const response = await model.invoke( +* "Process the uploaded CSV file", +* { +* tools: [tools.codeInterpreter({ +* container: { +* memoryLimit: "4g", +* fileIds: ["file-abc123", "file-def456"] +* } +* })] +* } +* ); +* +* // Using an explicit container ID (created via /v1/containers) +* const response = await model.invoke( +* "Continue working with the data", +* { +* tools: [tools.codeInterpreter({ +* container: "cntr_abc123" +* })] +* } +* ); +* ``` +* +* @remarks +* - Containers expire after 20 minutes of inactivity +* - While called "Code Interpreter", the model knows it as the "python tool" +* - For explicit prompting, ask for "the python tool" in your prompts +* - Files in model input are automatically uploaded to the container +* - Generated files are returned as `container_file_citation` annotations +*/ +function codeInterpreter(options) { + return { + type: "code_interpreter", + container: convertContainer(options?.container) + }; +} + +//#endregion + +//# sourceMappingURL=codeInterpreter.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/fileSearch.js +//#region src/tools/fileSearch.ts +/** +* Converts ranking options to the API format. +*/ +function convertRankingOptions(options) { + if (!options) return void 0; + return { + ranker: options.ranker, + score_threshold: options.scoreThreshold, + hybrid_search: options.hybridSearch ? { + embedding_weight: options.hybridSearch.embeddingWeight, + text_weight: options.hybridSearch.textWeight + } : void 0 + }; +} +/** +* Creates a File Search tool that allows models to search your files +* for relevant information using semantic and keyword search. +* +* File Search enables models to retrieve information from a knowledge base +* of previously uploaded files stored in vector stores. This is a hosted tool +* managed by OpenAI - you don't need to implement the search execution yourself. +* +* **Prerequisites**: Before using File Search, you must: +* 1. Upload files to the File API with `purpose: "assistants"` +* 2. Create a vector store +* 3. Add files to the vector store +* +* @see {@link https://platform.openai.com/docs/guides/tools-file-search | OpenAI File Search Documentation} +* +* @param options - Configuration options for the File Search tool +* @returns A File Search tool definition to be passed to the OpenAI Responses API +* +* @example +* ```typescript +* import { ChatOpenAI, tools } from "@langchain/openai"; +* +* const model = new ChatOpenAI({ model: "gpt-4.1" }); +* +* // Basic usage with a vector store +* const response = await model.invoke( +* "What is deep research by OpenAI?", +* { +* tools: [tools.fileSearch({ +* vectorStoreIds: ["vs_abc123"] +* })] +* } +* ); +* +* // Limit the number of results for lower latency +* const response = await model.invoke( +* "Find information about pricing", +* { +* tools: [tools.fileSearch({ +* vectorStoreIds: ["vs_abc123"], +* maxNumResults: 5 +* })] +* } +* ); +* +* // With metadata filtering +* const response = await model.invoke( +* "Find recent blog posts about AI", +* { +* tools: [tools.fileSearch({ +* vectorStoreIds: ["vs_abc123"], +* filters: { +* type: "eq", +* key: "category", +* value: "blog" +* } +* })] +* } +* ); +* +* // With compound filters (AND/OR) +* const response = await model.invoke( +* "Find technical docs from 2024", +* { +* tools: [tools.fileSearch({ +* vectorStoreIds: ["vs_abc123"], +* filters: { +* type: "and", +* filters: [ +* { type: "eq", key: "category", value: "technical" }, +* { type: "gte", key: "year", value: 2024 } +* ] +* } +* })] +* } +* ); +* +* // With ranking options for more relevant results +* const response = await model.invoke( +* "Find the most relevant information", +* { +* tools: [tools.fileSearch({ +* vectorStoreIds: ["vs_abc123"], +* rankingOptions: { +* scoreThreshold: 0.8, +* ranker: "auto" +* } +* })] +* } +* ); +* +* // Search multiple vector stores +* const response = await model.invoke( +* "Search across all knowledge bases", +* { +* tools: [tools.fileSearch({ +* vectorStoreIds: ["vs_abc123", "vs_def456"] +* })] +* } +* ); +* ``` +* +* @remarks +* - Vector stores must be created and populated before using this tool +* - The tool returns file citations in the response annotations +* - Use `include: ["file_search_call.results"]` in the API call to get search results +* - Supported file types include PDF, DOCX, TXT, MD, and many code file formats +*/ +function fileSearch(options) { + return { + type: "file_search", + vector_store_ids: options.vectorStoreIds, + max_num_results: options.maxNumResults, + filters: options.filters, + ranking_options: convertRankingOptions(options.rankingOptions) + }; +} + +//#endregion + +//# sourceMappingURL=fileSearch.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/imageGeneration.js +//#region src/tools/imageGeneration.ts +/** +* Converts input mask options to the API format. +*/ +function convertInputImageMask(mask) { + if (!mask) return void 0; + return { + image_url: mask.imageUrl, + file_id: mask.fileId + }; +} +/** +* Creates an Image Generation tool that allows models to generate or edit images +* using text prompts and optional image inputs. +* +* The image generation tool leverages the GPT Image model and automatically +* optimizes text inputs for improved performance. When included in a request, +* the model can decide when and how to generate images as part of the conversation. +* +* **Key Features**: +* - Generate images from text descriptions +* - Edit existing images with text instructions +* - Multi-turn image editing by referencing previous responses +* - Configurable output options (size, quality, format) +* - Streaming support for partial image generation +* +* **Prompting Tips**: +* - Use terms like "draw" or "edit" in your prompt for best results +* - For combining images, say "edit the first image by adding this element" instead of "combine" +* +* @see {@link https://platform.openai.com/docs/guides/tools-image-generation | OpenAI Image Generation Documentation} +* +* @param options - Configuration options for the Image Generation tool +* @returns An Image Generation tool definition to be passed to the OpenAI Responses API +* +* @example +* ```typescript +* import { ChatOpenAI, tools } from "@langchain/openai"; +* +* const model = new ChatOpenAI({ model: "gpt-4o" }); +* +* // Basic usage - generate an image +* const response = await model.invoke( +* "Generate an image of a gray tabby cat hugging an otter with an orange scarf", +* { tools: [tools.imageGeneration()] } +* ); +* +* // Access the generated image +* const imageData = response.additional_kwargs.tool_outputs?.find( +* (output) => output.type === "image_generation_call" +* ); +* if (imageData?.result) { +* // imageData.result contains the base64-encoded image +* const fs = await import("fs"); +* fs.writeFileSync("output.png", Buffer.from(imageData.result, "base64")); +* } +* +* // With custom options +* const response = await model.invoke( +* "Draw a beautiful sunset over mountains", +* { +* tools: [tools.imageGeneration({ +* size: "1536x1024", // Landscape format +* quality: "high", // Higher quality output +* outputFormat: "jpeg", // JPEG format +* outputCompression: 90, // 90% compression +* })] +* } +* ); +* +* // With transparent background +* const response = await model.invoke( +* "Create a logo with a transparent background", +* { +* tools: [tools.imageGeneration({ +* background: "transparent", +* outputFormat: "png", +* })] +* } +* ); +* +* // Force the model to use image generation +* const response = await model.invoke( +* "A serene lake at dawn", +* { +* tools: [tools.imageGeneration()], +* tool_choice: { type: "image_generation" }, +* } +* ); +* +* // Enable streaming with partial images +* const response = await model.invoke( +* "Draw a detailed fantasy castle", +* { +* tools: [tools.imageGeneration({ +* partialImages: 2, // Get 2 partial images during generation +* })] +* } +* ); +* ``` +* +* @remarks +* - Supported models: gpt-4o, gpt-4o-mini, gpt-4.1, gpt-4.1-mini, gpt-4.1-nano, o3 +* - The image generation process always uses `gpt-image-1` model internally +* - The model will automatically revise prompts for improved performance +* - Access the revised prompt via `revised_prompt` field in the output +* - Multi-turn editing is supported by passing previous response messages +*/ +function imageGeneration(options) { + return { + type: "image_generation", + background: options?.background, + input_fidelity: options?.inputFidelity, + input_image_mask: convertInputImageMask(options?.inputImageMask), + model: options?.model, + moderation: options?.moderation, + output_compression: options?.outputCompression, + output_format: options?.outputFormat, + partial_images: options?.partialImages, + quality: options?.quality, + size: options?.size + }; +} + +//#endregion + +//# sourceMappingURL=imageGeneration.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/computerUse.js + + + + +//#region src/tools/computerUse.ts +const ComputerUseScreenshotActionSchema = object({ type: literal("screenshot") }); +const ComputerUseClickActionSchema = object({ + type: literal("click"), + x: schemas_number(), + y: schemas_number(), + button: schemas_enum([ + "left", + "right", + "wheel", + "back", + "forward" + ]).default("left") +}); +const ComputerUseDoubleClickActionSchema = object({ + type: literal("double_click"), + x: schemas_number(), + y: schemas_number(), + button: schemas_enum([ + "left", + "right", + "wheel", + "back", + "forward" + ]).default("left") +}); +const ComputerUseDragActionSchema = object({ + type: literal("drag"), + path: array(object({ + x: schemas_number(), + y: schemas_number() + })) +}); +const ComputerUseKeypressActionSchema = object({ + type: literal("keypress"), + keys: array(schemas_string()) +}); +const ComputerUseMoveActionSchema = object({ + type: literal("move"), + x: schemas_number(), + y: schemas_number() +}); +const ComputerUseScrollActionSchema = object({ + type: literal("scroll"), + x: schemas_number(), + y: schemas_number(), + scroll_x: schemas_number(), + scroll_y: schemas_number() +}); +const ComputerUseTypeActionSchema = object({ + type: literal("type"), + text: schemas_string() +}); +const ComputerUseWaitActionSchema = object({ + type: literal("wait"), + duration: schemas_number().optional() +}); +const ComputerUseActionUnionSchema = discriminatedUnion("type", [ + ComputerUseScreenshotActionSchema, + ComputerUseClickActionSchema, + ComputerUseDoubleClickActionSchema, + ComputerUseDragActionSchema, + ComputerUseKeypressActionSchema, + ComputerUseMoveActionSchema, + ComputerUseScrollActionSchema, + ComputerUseTypeActionSchema, + ComputerUseWaitActionSchema +]); +const ComputerUseActionSchema = object({ action: ComputerUseActionUnionSchema }); +const computerUse_TOOL_NAME = "computer_use"; +/** +* Creates a Computer Use tool that allows models to control computer interfaces +* and perform tasks by simulating mouse clicks, keyboard input, scrolling, and more. +* +* **Computer Use** is a practical application of OpenAI's Computer-Using Agent (CUA) +* model (`computer-use-preview`), which combines vision capabilities with advanced +* reasoning to simulate controlling computer interfaces. +* +* **How it works**: +* The tool operates in a continuous loop: +* 1. Model sends computer actions (click, type, scroll, etc.) +* 2. Your code executes these actions in a controlled environment +* 3. You capture a screenshot of the result +* 4. Send the screenshot back to the model +* 5. Repeat until the task is complete +* +* **Important**: Computer use is in beta and requires careful consideration: +* - Use in sandboxed environments only +* - Do not use for high-stakes or authenticated tasks +* - Always implement human-in-the-loop for important decisions +* - Handle safety checks appropriately +* +* @see {@link https://platform.openai.com/docs/guides/tools-computer-use | OpenAI Computer Use Documentation} +* +* @param options - Configuration options for the Computer Use tool +* @returns A Computer Use tool that can be passed to `bindTools` +* +* @example +* ```typescript +* import { ChatOpenAI, tools } from "@langchain/openai"; +* +* const model = new ChatOpenAI({ model: "computer-use-preview" }); +* +* // With execute callback for automatic action handling +* const computer = tools.computerUse({ +* displayWidth: 1024, +* displayHeight: 768, +* environment: "browser", +* execute: async (action) => { +* if (action.type === "screenshot") { +* return captureScreenshot(); +* } +* if (action.type === "click") { +* await page.mouse.click(action.x, action.y, { button: action.button }); +* return captureScreenshot(); +* } +* if (action.type === "type") { +* await page.keyboard.type(action.text); +* return captureScreenshot(); +* } +* // Handle other actions... +* return captureScreenshot(); +* }, +* }); +* +* const llmWithComputer = model.bindTools([computer]); +* const response = await llmWithComputer.invoke( +* "Check the latest news on bing.com" +* ); +* ``` +* +* @example +* ```typescript +* // Without execute callback (manual action handling) +* const computer = tools.computerUse({ +* displayWidth: 1024, +* displayHeight: 768, +* environment: "browser", +* }); +* +* const response = await model.invoke("Check the news", { +* tools: [computer], +* }); +* +* // Access the computer call from the response +* const computerCall = response.additional_kwargs.tool_outputs?.find( +* (output) => output.type === "computer_call" +* ); +* if (computerCall) { +* console.log("Action to execute:", computerCall.action); +* // Execute the action manually, then send back a screenshot +* } +* ``` +* +* @example +* ```typescript +* // For macOS desktop automation with Docker +* const computer = tools.computerUse({ +* displayWidth: 1920, +* displayHeight: 1080, +* environment: "mac", +* execute: async (action) => { +* if (action.type === "click") { +* await dockerExec( +* `DISPLAY=:99 xdotool mousemove ${action.x} ${action.y} click 1`, +* containerName +* ); +* } +* // Capture screenshot from container +* return await getDockerScreenshot(containerName); +* }, +* }); +* ``` +* +* @remarks +* - Only available through the Responses API (not Chat Completions) +* - Requires `computer-use-preview` model +* - Actions include: click, double_click, drag, keypress, move, screenshot, scroll, type, wait +* - Safety checks may be returned that require acknowledgment before proceeding +* - Use `truncation: "auto"` parameter when making requests +* - Recommended to use with `reasoning.summary` for debugging +*/ +function computerUse(options) { + const computerTool = tool(async (input, runtime) => { + /** + * get computer_use call id from runtime + */ + const aiMessage = runtime.state?.messages.at(-1); + const computerToolCall = aiMessage?.tool_calls?.find((tc) => tc.name === "computer_use"); + const computerToolCallId = computerToolCall?.id; + if (!computerToolCallId) throw new Error("Computer use call id not found"); + const result = await options.execute(input.action, runtime); + /** + * make sure {@link ToolMessage} is returned with the correct additional kwargs + */ + if (typeof result === "string") return new ToolMessage({ + content: result, + tool_call_id: computerToolCallId, + additional_kwargs: { type: "computer_call_output" } + }); + /** + * make sure {@link ToolMessage} is returned with the correct additional kwargs + */ + return new ToolMessage({ + ...result, + tool_call_id: computerToolCallId, + additional_kwargs: { + type: "computer_call_output", + ...result.additional_kwargs + } + }); + }, { + name: computerUse_TOOL_NAME, + description: "Control a computer interface by executing mouse clicks, keyboard input, scrolling, and other actions.", + schema: ComputerUseActionSchema + }); + computerTool.extras = { + ...computerTool.extras ?? {}, + providerToolDefinition: { + type: "computer_use_preview", + display_width: options.displayWidth, + display_height: options.displayHeight, + environment: options.environment + } + }; + /** + * return as typed {@link DynamicStructuredTool} so we don't get any type + * errors like "can't export tool without reference" + */ + return computerTool; +} + +//#endregion + +//# sourceMappingURL=computerUse.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/localShell.js + + + +//#region src/tools/localShell.ts +const LocalShellExecActionSchema = object({ + type: literal("exec"), + command: array(schemas_string()), + env: record(schemas_string(), schemas_string()).optional(), + working_directory: schemas_string().optional(), + timeout_ms: schemas_number().optional(), + user: schemas_string().optional() +}); +const LocalShellActionSchema = discriminatedUnion("type", [LocalShellExecActionSchema]); +const localShell_TOOL_NAME = "local_shell"; +/** +* Creates a Local Shell tool that allows models to run shell commands locally +* on a machine you provide. Commands are executed inside your own runtime— +* the API only returns the instructions, but does not execute them on OpenAI infrastructure. +* +* **Important**: The local shell tool is designed to work with +* [Codex CLI](https://github.com/openai/codex) and the `codex-mini-latest` model. +* +* **How it works**: +* The tool operates in a continuous loop: +* 1. Model sends shell commands (`local_shell_call` with `exec` action) +* 2. Your code executes the command locally +* 3. You return the output back to the model +* 4. Repeat until the task is complete +* +* **Security Warning**: Running arbitrary shell commands can be dangerous. +* Always sandbox execution or add strict allow/deny-lists before forwarding +* a command to the system shell. +* +* @see {@link https://platform.openai.com/docs/guides/tools-local-shell | OpenAI Local Shell Documentation} +* +* @param options - Optional configuration for the Local Shell tool +* @returns A Local Shell tool that can be passed to `bindTools` +* +* @example +* ```typescript +* import { ChatOpenAI, tools } from "@langchain/openai"; +* import { exec } from "child_process"; +* import { promisify } from "util"; +* +* const execAsync = promisify(exec); +* const model = new ChatOpenAI({ model: "codex-mini-latest" }); +* +* // With execute callback for automatic command handling +* const shell = tools.localShell({ +* execute: async (action) => { +* const { command, env, working_directory, timeout_ms } = action; +* const result = await execAsync(command.join(' '), { +* cwd: working_directory ?? process.cwd(), +* env: { ...process.env, ...env }, +* timeout: timeout_ms ?? undefined, +* }); +* return result.stdout + result.stderr; +* }, +* }); +* +* const llmWithShell = model.bindTools([shell]); +* const response = await llmWithShell.invoke( +* "List files in the current directory" +* ); +* ``` +* +* @example +* ```typescript +* // Without execute callback (manual handling) +* const shell = tools.localShell(); +* +* const response = await model.invoke("List files", { +* tools: [shell], +* }); +* +* // Access the shell call from the response +* const shellCall = response.additional_kwargs.tool_outputs?.find( +* (output) => output.type === "local_shell_call" +* ); +* if (shellCall) { +* console.log("Command to execute:", shellCall.action.command); +* // Execute the command manually, then send back the output +* } +* ``` +* +* @example +* ```typescript +* // Full shell loop example +* async function shellLoop(model, task) { +* let response = await model.invoke(task, { +* tools: [tools.localShell()], +* }); +* +* while (true) { +* const shellCall = response.additional_kwargs.tool_outputs?.find( +* (output) => output.type === "local_shell_call" +* ); +* +* if (!shellCall) break; +* +* // Execute command (with proper sandboxing!) +* const output = await executeCommand(shellCall.action); +* +* // Send output back to model +* response = await model.invoke([ +* response, +* { +* type: "local_shell_call_output", +* id: shellCall.call_id, +* output: output, +* }, +* ], { +* tools: [tools.localShell()], +* }); +* } +* +* return response; +* } +* ``` +* +* @remarks +* - Only available through the Responses API (not Chat Completions) +* - Designed for use with `codex-mini-latest` model +* - Commands are provided as argv tokens in `action.command` +* - Action includes: `command`, `env`, `working_directory`, `timeout_ms`, `user` +* - Always sandbox or validate commands before execution +* - The `timeout_ms` from the model is only a hint—enforce your own limits +*/ +function localShell(options) { + const shellTool = tool(options.execute, { + name: localShell_TOOL_NAME, + description: "Execute shell commands locally on the machine. Commands are provided as argv tokens.", + schema: LocalShellActionSchema + }); + shellTool.extras = { + ...shellTool.extras ?? {}, + providerToolDefinition: { type: "local_shell" } + }; + return shellTool; +} + +//#endregion + +//# sourceMappingURL=localShell.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/shell.js + + + +//#region src/tools/shell.ts +const ShellActionSchema = object({ + commands: array(schemas_string()).describe("Array of shell commands to execute"), + timeout_ms: schemas_number().optional().describe("Optional timeout in milliseconds for the commands"), + max_output_length: schemas_number().optional().describe("Optional maximum number of characters to return from each command") +}); +const shell_TOOL_NAME = "shell"; +/** +* Creates a Shell tool that allows models to run shell commands through your integration. +* +* The shell tool allows the model to interact with your local computer through a controlled +* command-line interface. The model proposes shell commands; your integration executes them +* and returns the outputs. This creates a simple plan-execute loop that lets models inspect +* the system, run utilities, and gather data until they can finish the task. +* +* **Important**: The shell tool is available through the Responses API for use with `GPT-5.1`. +* It is not available on other models, or via the Chat Completions API. +* +* **When to use**: +* - **Automating filesystem or process diagnostics** – For example, "find the largest PDF +* under ~/Documents" or "show running gunicorn processes." +* - **Extending the model's capabilities** – Using built-in UNIX utilities, python runtime +* and other CLIs in your environment. +* - **Running multi-step build and test flows** – Chaining commands like `pip install` and `pytest`. +* - **Complex agentic coding workflows** – Using other tools like `apply_patch` to complete +* workflows that involve complex file operations. +* +* **How it works**: +* The tool operates in a continuous loop: +* 1. Model sends shell commands (`shell_call` with `commands` array) +* 2. Your code executes the commands (can be concurrent) +* 3. You return stdout, stderr, and outcome for each command +* 4. Repeat until the task is complete +* +* **Security Warning**: Running arbitrary shell commands can be dangerous. +* Always sandbox execution or add strict allow/deny-lists before forwarding +* a command to the system shell. +* +* @see {@link https://platform.openai.com/docs/guides/tools-shell | OpenAI Shell Documentation} +* @see {@link https://github.com/openai/codex | Codex CLI} for reference implementation. +* +* @param options - Configuration for the Shell tool +* @returns A Shell tool that can be passed to `bindTools` +* +* @example +* ```typescript +* import { ChatOpenAI, tools } from "@langchain/openai"; +* import { exec } from "child_process/promises"; +* +* const model = new ChatOpenAI({ model: "gpt-5.1" }); +* +* // With execute callback for automatic command handling +* const shellTool = tools.shell({ +* execute: async (action) => { +* const outputs = await Promise.all( +* action.commands.map(async (cmd) => { +* try { +* const { stdout, stderr } = await exec(cmd, { +* timeout: action.timeout_ms ?? undefined, +* }); +* return { +* stdout, +* stderr, +* outcome: { type: "exit" as const, exit_code: 0 }, +* }; +* } catch (error) { +* const timedOut = error.killed && error.signal === "SIGTERM"; +* return { +* stdout: error.stdout ?? "", +* stderr: error.stderr ?? String(error), +* outcome: timedOut +* ? { type: "timeout" as const } +* : { type: "exit" as const, exit_code: error.code ?? 1 }, +* }; +* } +* }) +* ); +* return { +* output: outputs, +* maxOutputLength: action.max_output_length, +* }; +* }, +* }); +* +* const llmWithShell = model.bindTools([shellTool]); +* const response = await llmWithShell.invoke( +* "Find the largest PDF file in ~/Documents" +* ); +* ``` +* +* @example +* ```typescript +* // Full shell loop example +* async function shellLoop(model, task) { +* let response = await model.invoke(task, { +* tools: [tools.shell({ execute: myExecutor })], +* }); +* +* while (true) { +* const shellCall = response.additional_kwargs.tool_outputs?.find( +* (output) => output.type === "shell_call" +* ); +* +* if (!shellCall) break; +* +* // Execute commands (with proper sandboxing!) +* const result = await executeCommands(shellCall.action); +* +* // Send output back to model +* response = await model.invoke([ +* response, +* { +* type: "shell_call_output", +* call_id: shellCall.call_id, +* output: result.output, +* max_output_length: result.maxOutputLength, +* }, +* ], { +* tools: [tools.shell({ execute: myExecutor })], +* }); +* } +* +* return response; +* } +* ``` +* +* @remarks +* - Only available through the Responses API (not Chat Completions) +* - Designed for use with `gpt-5.1` model +* - Commands are provided as an array of strings that can be executed concurrently +* - Action includes: `commands`, `timeout_ms`, `max_output_length` +* - Always sandbox or validate commands before execution +* - The `timeout_ms` from the model is only a hint—enforce your own limits +* - If `max_output_length` exists in the action, always pass it back in the output +* - Many CLI tools return non-zero exit codes for warnings; still capture stdout/stderr +*/ +function shell(options) { + const executeWrapper = async (action) => { + const result = await options.execute(action); + return JSON.stringify({ + output: result.output, + max_output_length: result.maxOutputLength + }); + }; + const shellTool = tool(executeWrapper, { + name: shell_TOOL_NAME, + description: "Execute shell commands in a managed environment. Commands can be run concurrently.", + schema: ShellActionSchema + }); + shellTool.extras = { + ...shellTool.extras ?? {}, + providerToolDefinition: { type: "shell" } + }; + return shellTool; +} + +//#endregion + +//# sourceMappingURL=shell.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/applyPatch.js + + + +//#region src/tools/applyPatch.ts +const ApplyPatchCreateFileOperationSchema = object({ + type: literal("create_file"), + path: schemas_string(), + diff: schemas_string() +}); +const ApplyPatchUpdateFileOperationSchema = object({ + type: literal("update_file"), + path: schemas_string(), + diff: schemas_string() +}); +const ApplyPatchDeleteFileOperationSchema = object({ + type: literal("delete_file"), + path: schemas_string() +}); +const ApplyPatchOperationSchema = discriminatedUnion("type", [ + ApplyPatchCreateFileOperationSchema, + ApplyPatchUpdateFileOperationSchema, + ApplyPatchDeleteFileOperationSchema +]); +const applyPatch_TOOL_NAME = "apply_patch"; +/** +* Creates an Apply Patch tool that allows models to propose structured diffs +* that your integration applies. This enables iterative, multi-step code +* editing workflows. +* +* **Apply Patch** lets GPT-5.1 create, update, and delete files in your codebase +* using structured diffs. Instead of just suggesting edits, the model emits +* patch operations that your application applies and then reports back on. +* +* **When to use**: +* - **Multi-file refactors** – Rename symbols, extract helpers, or reorganize modules +* - **Bug fixes** – Have the model both diagnose issues and emit precise patches +* - **Tests & docs generation** – Create new test files, fixtures, and documentation +* - **Migrations & mechanical edits** – Apply repetitive, structured updates +* +* **How it works**: +* The tool operates in a continuous loop: +* 1. Model sends patch operations (`apply_patch_call` with operation type) +* 2. Your code applies the patch to your working directory or repo +* 3. You return success/failure status and optional output +* 4. Repeat until the task is complete +* +* **Security Warning**: Applying patches can modify files in your codebase. +* Always validate paths, implement backups, and consider sandboxing. +* +* @see {@link https://platform.openai.com/docs/guides/tools-apply-patch | OpenAI Apply Patch Documentation} +* +* @param options - Configuration options for the Apply Patch tool +* @returns An Apply Patch tool that can be passed to `bindTools` +* +* @example +* ```typescript +* import { ChatOpenAI, tools } from "@langchain/openai"; +* import { applyDiff } from "@openai/agents"; +* import * as fs from "fs/promises"; +* +* const model = new ChatOpenAI({ model: "gpt-5.1" }); +* +* // With execute callback for automatic patch handling +* const patchTool = tools.applyPatch({ +* execute: async (operation) => { +* if (operation.type === "create_file") { +* const content = applyDiff("", operation.diff, "create"); +* await fs.writeFile(operation.path, content); +* return `Created ${operation.path}`; +* } +* if (operation.type === "update_file") { +* const current = await fs.readFile(operation.path, "utf-8"); +* const newContent = applyDiff(current, operation.diff); +* await fs.writeFile(operation.path, newContent); +* return `Updated ${operation.path}`; +* } +* if (operation.type === "delete_file") { +* await fs.unlink(operation.path); +* return `Deleted ${operation.path}`; +* } +* return "Unknown operation type"; +* }, +* }); +* +* const llmWithPatch = model.bindTools([patchTool]); +* const response = await llmWithPatch.invoke( +* "Rename the fib() function to fibonacci() in lib/fib.py" +* ); +* ``` +* +* @remarks +* - Only available through the Responses API (not Chat Completions) +* - Designed for use with `gpt-5.1` model +* - Operations include: `create_file`, `update_file`, `delete_file` +* - Patches use V4A diff format for updates +* - Always validate paths to prevent directory traversal attacks +* - Consider backing up files before applying patches +* - Implement "all-or-nothing" semantics if atomicity is required +*/ +function applyPatch_applyPatch(options) { + const patchTool = tool(options.execute, { + name: applyPatch_TOOL_NAME, + description: "Apply structured diffs to create, update, or delete files in the codebase.", + schema: ApplyPatchOperationSchema + }); + patchTool.extras = { + ...patchTool.extras ?? {}, + providerToolDefinition: { type: "apply_patch" } + }; + return patchTool; +} + +//#endregion + +//# sourceMappingURL=applyPatch.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/index.js + + + + + + + + + + + +//#region src/tools/index.ts +const tools_tools = { + webSearch: webSearch, + mcp: mcp, + codeInterpreter: codeInterpreter, + fileSearch: fileSearch, + imageGeneration: imageGeneration, + computerUse: computerUse, + localShell: localShell, + shell: shell, + applyPatch: applyPatch_applyPatch +}; + +//#endregion + +//# sourceMappingURL=index.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/custom.js + + + + +//#region src/tools/custom.ts +function customTool(func, fields) { + return new DynamicTool({ + ...fields, + description: "", + metadata: { customTool: fields }, + func: async (input, runManager, config) => new Promise((resolve, reject) => { + const childConfig = patchConfig(config, { callbacks: runManager?.getChild() }); + AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { + try { + resolve(func(input, childConfig)); + } catch (e) { + reject(e); + } + }); + }) + }); +} + +//#endregion + +//# sourceMappingURL=custom.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/prompts.js + + +//#region src/utils/prompts.ts +/** +* Convert a formatted LangChain prompt (e.g. pulled from the hub) into +* a format expected by OpenAI's JS SDK. +* +* Requires the "@langchain/openai" package to be installed in addition +* to the OpenAI SDK. +* +* @example +* ```ts +* import { convertPromptToOpenAI } from "langsmith/utils/hub/openai"; +* import { pull } from "langchain/hub"; +* +* import OpenAI from 'openai'; +* +* const prompt = await pull("jacob/joke-generator"); +* const formattedPrompt = await prompt.invoke({ +* topic: "cats", +* }); +* +* const { messages } = convertPromptToOpenAI(formattedPrompt); +* +* const openAIClient = new OpenAI(); +* +* const openaiResponse = await openAIClient.chat.completions.create({ +* model: "gpt-4o-mini", +* messages, +* }); +* ``` +* @param formattedPrompt +* @returns A partial OpenAI payload. +*/ +function convertPromptToOpenAI(formattedPrompt) { + const messages = formattedPrompt.toChatMessages(); + return { messages: convertMessagesToCompletionsMessageParams({ messages }) }; +} + +//#endregion + +//# sourceMappingURL=prompts.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/converters/index.js + + + +;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/index.js + + + + + + + + + + + + + + + + + + + + + + + + +;// CONCATENATED MODULE: ./src/providers/openai.provider.ts + +/** + * OpenAI GPT provider implementation + */ +class OpenAIProvider { + name = 'openai'; + apiKey; + constructor(apiKey) { + this.apiKey = apiKey || process.env.OPENAI_API_KEY || ''; + } + isConfigured() { + return !!this.apiKey; + } + getDefaultModel() { + return 'gpt-4-turbo-preview'; + } + getChatModel(config = {}) { + if (!this.isConfigured()) { + throw new Error('OpenAI API key is not configured'); + } + return new ChatOpenAI({ + apiKey: this.apiKey, + modelName: config.model || this.getDefaultModel(), + temperature: config.temperature ?? 0.2, + maxTokens: config.maxTokens ?? 4000, + }); + } +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/utils/zod_to_genai_parameters.js + + + +//#region src/utils/zod_to_genai_parameters.ts +function removeAdditionalProperties(obj) { + if (typeof obj === "object" && obj !== null) { + const newObj = { ...obj }; + if ("additionalProperties" in newObj) delete newObj.additionalProperties; + if ("$schema" in newObj) delete newObj.$schema; + if ("strict" in newObj) delete newObj.strict; + for (const key in newObj) if (key in newObj) { + if (Array.isArray(newObj[key])) newObj[key] = newObj[key].map(removeAdditionalProperties); + else if (typeof newObj[key] === "object" && newObj[key] !== null) newObj[key] = removeAdditionalProperties(newObj[key]); + } + return newObj; + } + return obj; +} +function schemaToGenerativeAIParameters(schema) { + const jsonSchema = removeAdditionalProperties(isInteropZodSchema(schema) ? toJsonSchema(schema) : schema); + const { $schema,...rest } = jsonSchema; + return rest; +} +function jsonSchemaToGeminiParameters(schema) { + const jsonSchema = removeAdditionalProperties(schema); + const { $schema,...rest } = jsonSchema; + return rest; +} + +//#endregion + +//# sourceMappingURL=zod_to_genai_parameters.js.map +// EXTERNAL MODULE: external "crypto" +var external_crypto_ = __nccwpck_require__(6982); +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/native.js + +/* harmony default export */ const esm_native = ({ randomUUID: external_crypto_.randomUUID }); + +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/rng.js + +const rnds8Pool = new Uint8Array(256); +let poolPtr = rnds8Pool.length; +function rng() { + if (poolPtr > rnds8Pool.length - 16) { + (0,external_crypto_.randomFillSync)(rnds8Pool); + poolPtr = 0; + } + return rnds8Pool.slice(poolPtr, (poolPtr += 16)); +} + +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/stringify.js + +const byteToHex = []; +for (let i = 0; i < 256; ++i) { + byteToHex.push((i + 0x100).toString(16).slice(1)); +} +function unsafeStringify(arr, offset = 0) { + return (byteToHex[arr[offset + 0]] + + byteToHex[arr[offset + 1]] + + byteToHex[arr[offset + 2]] + + byteToHex[arr[offset + 3]] + + '-' + + byteToHex[arr[offset + 4]] + + byteToHex[arr[offset + 5]] + + '-' + + byteToHex[arr[offset + 6]] + + byteToHex[arr[offset + 7]] + + '-' + + byteToHex[arr[offset + 8]] + + byteToHex[arr[offset + 9]] + + '-' + + byteToHex[arr[offset + 10]] + + byteToHex[arr[offset + 11]] + + byteToHex[arr[offset + 12]] + + byteToHex[arr[offset + 13]] + + byteToHex[arr[offset + 14]] + + byteToHex[arr[offset + 15]]).toLowerCase(); +} +function esm_stringify_stringify(arr, offset = 0) { + const uuid = unsafeStringify(arr, offset); + if (!validate(uuid)) { + throw TypeError('Stringified UUID is invalid'); + } + return uuid; +} +/* harmony default export */ const esm_stringify = ((/* unused pure expression or super */ null && (esm_stringify_stringify))); + +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/v4.js + + + +function v4_v4(options, buf, offset) { + if (esm_native.randomUUID && !buf && !options) { + return esm_native.randomUUID(); + } + options = options || {}; + const rnds = options.random ?? options.rng?.() ?? rng(); + if (rnds.length < 16) { + throw new Error('Random bytes length must be >= 16'); + } + rnds[6] = (rnds[6] & 0x0f) | 0x40; + rnds[8] = (rnds[8] & 0x3f) | 0x80; + if (buf) { + offset = offset || 0; + if (offset < 0 || offset + 16 > buf.length) { + throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); + } + for (let i = 0; i < 16; ++i) { + buf[offset + i] = rnds[i]; + } + return buf; + } + return unsafeStringify(rnds); +} +/* harmony default export */ const esm_v4 = (v4_v4); + +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/utils/common.js + + + + + + + +//#region src/utils/common.ts +const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY = "__gemini_function_call_thought_signatures__"; +const DUMMY_SIGNATURE = "ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ=="; +const common_iife = (fn) => fn(); +function getMessageAuthor(message) { + if (ChatMessage.isInstance(message)) return message.role; + return message.type; +} +/** +* Maps a message type to a Google Generative AI chat author. +* @param message The message to map. +* @param model The model to use for mapping. +* @returns The message type mapped to a Google Generative AI chat author. +*/ +function convertAuthorToRole(author) { + switch (author) { + case "supervisor": + case "ai": + case "model": return "model"; + case "system": return "system"; + case "human": return "user"; + case "tool": + case "function": return "function"; + default: throw new Error(`Unknown / unsupported author: ${author}`); + } +} +function messageContentMedia(content) { + if ("mimeType" in content && "data" in content) return { inlineData: { + mimeType: content.mimeType, + data: content.data + } }; + if ("mimeType" in content && "fileUri" in content) return { fileData: { + mimeType: content.mimeType, + fileUri: content.fileUri + } }; + throw new Error("Invalid media content"); +} +function inferToolNameFromPreviousMessages(message, previousMessages) { + return previousMessages.map((msg) => { + if (isAIMessage(msg)) return msg.tool_calls ?? []; + return []; + }).flat().find((toolCall) => { + return toolCall.id === message.tool_call_id; + })?.name; +} +function _getStandardContentBlockConverter(isMultimodalModel) { + const standardContentBlockConverter = { + providerName: "Google Gemini", + fromStandardTextBlock(block) { + return { text: block.text }; + }, + fromStandardImageBlock(block) { + if (!isMultimodalModel) throw new Error("This model does not support images"); + if (block.source_type === "url") { + const data = parseBase64DataUrl({ dataUrl: block.url }); + if (data) return { inlineData: { + mimeType: data.mime_type, + data: data.data + } }; + else return { fileData: { + mimeType: block.mime_type ?? "", + fileUri: block.url + } }; + } + if (block.source_type === "base64") return { inlineData: { + mimeType: block.mime_type ?? "", + data: block.data + } }; + throw new Error(`Unsupported source type: ${block.source_type}`); + }, + fromStandardAudioBlock(block) { + if (!isMultimodalModel) throw new Error("This model does not support audio"); + if (block.source_type === "url") { + const data = parseBase64DataUrl({ dataUrl: block.url }); + if (data) return { inlineData: { + mimeType: data.mime_type, + data: data.data + } }; + else return { fileData: { + mimeType: block.mime_type ?? "", + fileUri: block.url + } }; + } + if (block.source_type === "base64") return { inlineData: { + mimeType: block.mime_type ?? "", + data: block.data + } }; + throw new Error(`Unsupported source type: ${block.source_type}`); + }, + fromStandardFileBlock(block) { + if (!isMultimodalModel) throw new Error("This model does not support files"); + if (block.source_type === "text") return { text: block.text }; + if (block.source_type === "url") { + const data = parseBase64DataUrl({ dataUrl: block.url }); + if (data) return { inlineData: { + mimeType: data.mime_type, + data: data.data + } }; + else return { fileData: { + mimeType: block.mime_type ?? "", + fileUri: block.url + } }; + } + if (block.source_type === "base64") return { inlineData: { + mimeType: block.mime_type ?? "", + data: block.data + } }; + throw new Error(`Unsupported source type: ${block.source_type}`); + } + }; + return standardContentBlockConverter; +} +function _convertLangChainContentToPart(content, isMultimodalModel) { + if (isDataContentBlock(content)) return convertToProviderContentBlock(content, _getStandardContentBlockConverter(isMultimodalModel)); + if (content.type === "text") return { text: content.text }; + else if (content.type === "executableCode") return { executableCode: content.executableCode }; + else if (content.type === "codeExecutionResult") return { codeExecutionResult: content.codeExecutionResult }; + else if (content.type === "image_url") { + if (!isMultimodalModel) throw new Error(`This model does not support images`); + let source; + if (typeof content.image_url === "string") source = content.image_url; + else if (typeof content.image_url === "object" && "url" in content.image_url) source = content.image_url.url; + else throw new Error("Please provide image as base64 encoded data URL"); + const [dm, data] = source.split(","); + if (!dm.startsWith("data:")) throw new Error("Please provide image as base64 encoded data URL"); + const [mimeType, encoding] = dm.replace(/^data:/, "").split(";"); + if (encoding !== "base64") throw new Error("Please provide image as base64 encoded data URL"); + return { inlineData: { + data, + mimeType + } }; + } else if (content.type === "media") return messageContentMedia(content); + else if (content.type === "tool_use") return { functionCall: { + name: content.name, + args: content.input + } }; + else if (content.type?.includes("/") && content.type.split("/").length === 2 && "data" in content && typeof content.data === "string") return { inlineData: { + mimeType: content.type, + data: content.data + } }; + else if ("functionCall" in content) return void 0; + else if ("type" in content) throw new Error(`Unknown content type ${content.type}`); + else throw new Error(`Unknown content ${JSON.stringify(content)}`); +} +function convertMessageContentToParts(message, isMultimodalModel, previousMessages, model) { + if (isToolMessage(message)) { + const messageName = message.name ?? inferToolNameFromPreviousMessages(message, previousMessages); + if (messageName === void 0) throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${message.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`); + const result = Array.isArray(message.content) ? message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0) : message.content; + if (message.status === "error") return [{ functionResponse: { + name: messageName, + response: { error: { details: result } } + } }]; + return [{ functionResponse: { + name: messageName, + response: { result } + } }]; + } + let functionCalls = []; + const messageParts = []; + if (typeof message.content === "string" && message.content) messageParts.push({ text: message.content }); + if (Array.isArray(message.content)) messageParts.push(...message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0)); + const functionThoughtSignatures = message.additional_kwargs?.[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]; + if (isAIMessage(message) && message.tool_calls?.length) functionCalls = message.tool_calls.map((tc) => { + const thoughtSignature = common_iife(() => { + if (tc.id) { + const signature = functionThoughtSignatures?.[tc.id]; + if (signature) return signature; + } + if (model?.includes("gemini-3")) return DUMMY_SIGNATURE; + return ""; + }); + return { + functionCall: { + name: tc.name, + args: tc.args + }, + ...thoughtSignature ? { thoughtSignature } : {} + }; + }); + return [...messageParts, ...functionCalls]; +} +function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystemMessageToHumanContent = false, model) { + return messages.reduce((acc, message, index) => { + if (!isBaseMessage(message)) throw new Error("Unsupported message input"); + const author = getMessageAuthor(message); + if (author === "system" && index !== 0) throw new Error("System message should be the first one"); + const role = convertAuthorToRole(author); + const prevContent = acc.content[acc.content.length]; + if (!acc.mergeWithPreviousContent && prevContent && prevContent.role === role) throw new Error("Google Generative AI requires alternate messages between authors"); + const parts = convertMessageContentToParts(message, isMultimodalModel, messages.slice(0, index), model); + if (acc.mergeWithPreviousContent) { + const prevContent$1 = acc.content[acc.content.length - 1]; + if (!prevContent$1) throw new Error("There was a problem parsing your system message. Please try a prompt without one."); + prevContent$1.parts.push(...parts); + return { + mergeWithPreviousContent: false, + content: acc.content + }; + } + let actualRole = role; + if (actualRole === "function" || actualRole === "system" && !convertSystemMessageToHumanContent) actualRole = "user"; + const content = { + role: actualRole, + parts + }; + return { + mergeWithPreviousContent: author === "system" && !convertSystemMessageToHumanContent, + content: [...acc.content, content] + }; + }, { + content: [], + mergeWithPreviousContent: false + }).content; +} +function mapGenerateContentResultToChatResult(response, extra) { + if (!response.candidates || response.candidates.length === 0 || !response.candidates[0]) return { + generations: [], + llmOutput: { filters: response.promptFeedback } + }; + const [candidate] = response.candidates; + const { content: candidateContent,...generationInfo } = candidate; + const functionCalls = candidateContent.parts?.reduce((acc, p) => { + if ("functionCall" in p && p.functionCall) acc.push({ + ...p, + id: "id" in p.functionCall && typeof p.functionCall.id === "string" ? p.functionCall.id : esm_v4() + }); + return acc; + }, []); + let content; + if (Array.isArray(candidateContent?.parts) && candidateContent.parts.length === 1 && candidateContent.parts[0].text) content = candidateContent.parts[0].text; + else if (Array.isArray(candidateContent?.parts) && candidateContent.parts.length > 0) content = candidateContent.parts.map((p) => { + if ("text" in p) return { + type: "text", + text: p.text + }; + else if ("inlineData" in p) return { + type: "inlineData", + inlineData: p.inlineData + }; + else if ("functionCall" in p) return { + type: "functionCall", + functionCall: p.functionCall + }; + else if ("functionResponse" in p) return { + type: "functionResponse", + functionResponse: p.functionResponse + }; + else if ("fileData" in p) return { + type: "fileData", + fileData: p.fileData + }; + else if ("executableCode" in p) return { + type: "executableCode", + executableCode: p.executableCode + }; + else if ("codeExecutionResult" in p) return { + type: "codeExecutionResult", + codeExecutionResult: p.codeExecutionResult + }; + return p; + }); + else content = []; + const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => { + if ("thoughtSignature" in fc && typeof fc.thoughtSignature === "string") acc[fc.id] = fc.thoughtSignature; + return acc; + }, {}); + let text = ""; + if (typeof content === "string") text = content; + else if (Array.isArray(content) && content.length > 0) { + const block = content.find((b) => "text" in b); + text = block?.text ?? text; + } + const generation = { + text, + message: new AIMessage({ + content: content ?? "", + tool_calls: functionCalls?.map((fc) => ({ + type: "tool_call", + id: fc.id, + name: fc.functionCall.name, + args: fc.functionCall.args + })), + additional_kwargs: { + ...generationInfo, + [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures + }, + usage_metadata: extra?.usageMetadata + }), + generationInfo + }; + return { + generations: [generation], + llmOutput: { tokenUsage: { + promptTokens: extra?.usageMetadata?.input_tokens, + completionTokens: extra?.usageMetadata?.output_tokens, + totalTokens: extra?.usageMetadata?.total_tokens + } } + }; +} +function convertResponseContentToChatGenerationChunk(response, extra) { + if (!response.candidates || response.candidates.length === 0) return null; + const [candidate] = response.candidates; + const { content: candidateContent,...generationInfo } = candidate; + const functionCalls = candidateContent.parts?.reduce((acc, p) => { + if ("functionCall" in p && p.functionCall) acc.push({ + ...p, + id: "id" in p.functionCall && typeof p.functionCall.id === "string" ? p.functionCall.id : esm_v4() + }); + return acc; + }, []); + let content; + if (Array.isArray(candidateContent?.parts) && candidateContent.parts.every((p) => "text" in p)) content = candidateContent.parts.map((p) => p.text).join(""); + else if (Array.isArray(candidateContent?.parts)) content = candidateContent.parts.map((p) => { + if ("text" in p) return { + type: "text", + text: p.text + }; + else if ("inlineData" in p) return { + type: "inlineData", + inlineData: p.inlineData + }; + else if ("functionCall" in p) return { + type: "functionCall", + functionCall: p.functionCall + }; + else if ("functionResponse" in p) return { + type: "functionResponse", + functionResponse: p.functionResponse + }; + else if ("fileData" in p) return { + type: "fileData", + fileData: p.fileData + }; + else if ("executableCode" in p) return { + type: "executableCode", + executableCode: p.executableCode + }; + else if ("codeExecutionResult" in p) return { + type: "codeExecutionResult", + codeExecutionResult: p.codeExecutionResult + }; + return p; + }); + else content = []; + let text = ""; + if (content && typeof content === "string") text = content; + else if (Array.isArray(content)) { + const block = content.find((b) => "text" in b); + text = block?.text ?? ""; + } + const toolCallChunks = []; + if (functionCalls) toolCallChunks.push(...functionCalls.map((fc) => ({ + type: "tool_call_chunk", + id: fc.id, + name: fc.functionCall.name, + args: JSON.stringify(fc.functionCall.args) + }))); + const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => { + if ("thoughtSignature" in fc && typeof fc.thoughtSignature === "string") acc[fc.id] = fc.thoughtSignature; + return acc; + }, {}); + return new ChatGenerationChunk({ + text, + message: new AIMessageChunk({ + content: content || "", + name: !candidateContent ? void 0 : candidateContent.role, + tool_call_chunks: toolCallChunks, + additional_kwargs: { [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures }, + response_metadata: { model_provider: "google-genai" }, + usage_metadata: extra.usageMetadata + }), + generationInfo + }); +} +function convertToGenerativeAITools(tools) { + if (tools.every((tool) => "functionDeclarations" in tool && Array.isArray(tool.functionDeclarations))) return tools; + return [{ functionDeclarations: tools.map((tool) => { + if (isLangChainTool(tool)) { + const jsonSchema = schemaToGenerativeAIParameters(tool.schema); + if (jsonSchema.type === "object" && "properties" in jsonSchema && Object.keys(jsonSchema.properties).length === 0) return { + name: tool.name, + description: tool.description + }; + return { + name: tool.name, + description: tool.description, + parameters: jsonSchema + }; + } + if (isOpenAITool(tool)) return { + name: tool.function.name, + description: tool.function.description ?? `A function available to call.`, + parameters: jsonSchemaToGeminiParameters(tool.function.parameters) + }; + return tool; + }) }]; +} +function convertUsageMetadata(usageMetadata, model) { + const output = { + input_tokens: usageMetadata?.promptTokenCount ?? 0, + output_tokens: usageMetadata?.candidatesTokenCount ?? 0, + total_tokens: usageMetadata?.totalTokenCount ?? 0 + }; + if (usageMetadata?.cachedContentTokenCount) { + output.input_token_details ??= {}; + output.input_token_details.cache_read = usageMetadata.cachedContentTokenCount; + } + if (model === "gemini-3-pro-preview") { + const over200k = Math.max(0, usageMetadata?.promptTokenCount ?? -2e5); + const cachedOver200k = Math.max(0, usageMetadata?.cachedContentTokenCount ?? -2e5); + if (over200k) output.input_token_details = { + ...output.input_token_details, + over_200k: over200k + }; + if (cachedOver200k) output.input_token_details = { + ...output.input_token_details, + cache_read_over_200k: cachedOver200k + }; + } + return output; +} + +//#endregion + +//# sourceMappingURL=common.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/output_parsers.js + + + +//#region src/output_parsers.ts +var GoogleGenerativeAIToolsOutputParser = class extends BaseLLMOutputParser { + static lc_name() { + return "GoogleGenerativeAIToolsOutputParser"; + } + lc_namespace = [ + "langchain", + "google_genai", + "output_parsers" + ]; + returnId = false; + /** The type of tool calls to return. */ + keyName; + /** Whether to return only the first tool call. */ + returnSingle = false; + zodSchema; + constructor(params) { + super(params); + this.keyName = params.keyName; + this.returnSingle = params.returnSingle ?? this.returnSingle; + this.zodSchema = params.zodSchema; + } + async _validateResult(result) { + if (this.zodSchema === void 0) return result; + const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result); + if (zodParsedResult.success) return zodParsedResult.data; + else throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.issues)}`, JSON.stringify(result, null, 2)); + } + async parseResult(generations) { + const tools = generations.flatMap((generation) => { + const { message } = generation; + if (!("tool_calls" in message) || !Array.isArray(message.tool_calls)) return []; + return message.tool_calls; + }); + if (tools[0] === void 0) throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser."); + const [tool] = tools; + const validatedResult = await this._validateResult(tool.args); + return validatedResult; + } +}; + +//#endregion + +//# sourceMappingURL=output_parsers.js.map +;// CONCATENATED MODULE: ./node_modules/@google/generative-ai/dist/index.mjs +/** + * Contains the list of OpenAPI data types + * as defined by https://swagger.io/docs/specification/data-models/data-types/ + * @public + */ +var SchemaType; +(function (SchemaType) { + /** String type. */ + SchemaType["STRING"] = "string"; + /** Number type. */ + SchemaType["NUMBER"] = "number"; + /** Integer type. */ + SchemaType["INTEGER"] = "integer"; + /** Boolean type. */ + SchemaType["BOOLEAN"] = "boolean"; + /** Array type. */ + SchemaType["ARRAY"] = "array"; + /** Object type. */ + SchemaType["OBJECT"] = "object"; +})(SchemaType || (SchemaType = {})); + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * @public + */ +var ExecutableCodeLanguage; +(function (ExecutableCodeLanguage) { + ExecutableCodeLanguage["LANGUAGE_UNSPECIFIED"] = "language_unspecified"; + ExecutableCodeLanguage["PYTHON"] = "python"; +})(ExecutableCodeLanguage || (ExecutableCodeLanguage = {})); +/** + * Possible outcomes of code execution. + * @public + */ +var Outcome; +(function (Outcome) { + /** + * Unspecified status. This value should not be used. + */ + Outcome["OUTCOME_UNSPECIFIED"] = "outcome_unspecified"; + /** + * Code execution completed successfully. + */ + Outcome["OUTCOME_OK"] = "outcome_ok"; + /** + * Code execution finished but with a failure. `stderr` should contain the + * reason. + */ + Outcome["OUTCOME_FAILED"] = "outcome_failed"; + /** + * Code execution ran for too long, and was cancelled. There may or may not + * be a partial output present. + */ + Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded"; +})(Outcome || (Outcome = {})); + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Possible roles. + * @public + */ +const POSSIBLE_ROLES = ["user", "model", "function", "system"]; +/** + * Harm categories that would cause prompts or candidates to be blocked. + * @public + */ +var HarmCategory; +(function (HarmCategory) { + HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; + HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; + HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; + HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; + HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; + HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; +})(HarmCategory || (HarmCategory = {})); +/** + * Threshold above which a prompt or candidate will be blocked. + * @public + */ +var HarmBlockThreshold; +(function (HarmBlockThreshold) { + /** Threshold is unspecified. */ + HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; + /** Content with NEGLIGIBLE will be allowed. */ + HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; + /** Content with NEGLIGIBLE and LOW will be allowed. */ + HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; + /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */ + HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; + /** All content will be allowed. */ + HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; +})(HarmBlockThreshold || (HarmBlockThreshold = {})); +/** + * Probability that a prompt or candidate matches a harm category. + * @public + */ +var HarmProbability; +(function (HarmProbability) { + /** Probability is unspecified. */ + HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; + /** Content has a negligible chance of being unsafe. */ + HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; + /** Content has a low chance of being unsafe. */ + HarmProbability["LOW"] = "LOW"; + /** Content has a medium chance of being unsafe. */ + HarmProbability["MEDIUM"] = "MEDIUM"; + /** Content has a high chance of being unsafe. */ + HarmProbability["HIGH"] = "HIGH"; +})(HarmProbability || (HarmProbability = {})); +/** + * Reason that a prompt was blocked. + * @public + */ +var BlockReason; +(function (BlockReason) { + // A blocked reason was not specified. + BlockReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; + // Content was blocked by safety settings. + BlockReason["SAFETY"] = "SAFETY"; + // Content was blocked, but the reason is uncategorized. + BlockReason["OTHER"] = "OTHER"; +})(BlockReason || (BlockReason = {})); +/** + * Reason that a candidate finished. + * @public + */ +var FinishReason; +(function (FinishReason) { + // Default value. This value is unused. + FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; + // Natural stop point of the model or provided stop sequence. + FinishReason["STOP"] = "STOP"; + // The maximum number of tokens as specified in the request was reached. + FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; + // The candidate content was flagged for safety reasons. + FinishReason["SAFETY"] = "SAFETY"; + // The candidate content was flagged for recitation reasons. + FinishReason["RECITATION"] = "RECITATION"; + // The candidate content was flagged for using an unsupported language. + FinishReason["LANGUAGE"] = "LANGUAGE"; + // Token generation stopped because the content contains forbidden terms. + FinishReason["BLOCKLIST"] = "BLOCKLIST"; + // Token generation stopped for potentially containing prohibited content. + FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; + // Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). + FinishReason["SPII"] = "SPII"; + // The function call generated by the model is invalid. + FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; + // Unknown reason. + FinishReason["OTHER"] = "OTHER"; +})(FinishReason || (FinishReason = {})); +/** + * Task type for embedding content. + * @public + */ +var TaskType; +(function (TaskType) { + TaskType["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED"; + TaskType["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY"; + TaskType["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT"; + TaskType["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY"; + TaskType["CLASSIFICATION"] = "CLASSIFICATION"; + TaskType["CLUSTERING"] = "CLUSTERING"; +})(TaskType || (TaskType = {})); +/** + * @public + */ +var FunctionCallingMode; +(function (FunctionCallingMode) { + // Unspecified function calling mode. This value should not be used. + FunctionCallingMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + // Default model behavior, model decides to predict either a function call + // or a natural language repspose. + FunctionCallingMode["AUTO"] = "AUTO"; + // Model is constrained to always predicting a function call only. + // If "allowed_function_names" are set, the predicted function call will be + // limited to any one of "allowed_function_names", else the predicted + // function call will be any one of the provided "function_declarations". + FunctionCallingMode["ANY"] = "ANY"; + // Model will not predict any function call. Model behavior is same as when + // not passing any function declarations. + FunctionCallingMode["NONE"] = "NONE"; +})(FunctionCallingMode || (FunctionCallingMode = {})); +/** + * The mode of the predictor to be used in dynamic retrieval. + * @public + */ +var DynamicRetrievalMode; +(function (DynamicRetrievalMode) { + // Unspecified function calling mode. This value should not be used. + DynamicRetrievalMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; + // Run retrieval only when system decides it is necessary. + DynamicRetrievalMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; +})(DynamicRetrievalMode || (DynamicRetrievalMode = {})); + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Basic error type for this SDK. + * @public + */ +class GoogleGenerativeAIError extends Error { + constructor(message) { + super(`[GoogleGenerativeAI Error]: ${message}`); + } +} +/** + * Errors in the contents of a response from the model. This includes parsing + * errors, or responses including a safety block reason. + * @public + */ +class GoogleGenerativeAIResponseError extends GoogleGenerativeAIError { + constructor(message, response) { + super(message); + this.response = response; + } +} +/** + * Error class covering HTTP errors when calling the server. Includes HTTP + * status, statusText, and optional details, if provided in the server response. + * @public + */ +class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError { + constructor(message, status, statusText, errorDetails) { + super(message); + this.status = status; + this.statusText = statusText; + this.errorDetails = errorDetails; + } +} +/** + * Errors in the contents of a request originating from user input. + * @public + */ +class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError { +} +/** + * Error thrown when a request is aborted, either due to a timeout or + * intentional cancellation by the user. + * @public + */ +class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError { +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com"; +const DEFAULT_API_VERSION = "v1beta"; +/** + * We can't `require` package.json if this runs on web. We will use rollup to + * swap in the version number here at build time. + */ +const PACKAGE_VERSION = "0.24.1"; +const PACKAGE_LOG_HEADER = "genai-js"; +var Task; +(function (Task) { + Task["GENERATE_CONTENT"] = "generateContent"; + Task["STREAM_GENERATE_CONTENT"] = "streamGenerateContent"; + Task["COUNT_TOKENS"] = "countTokens"; + Task["EMBED_CONTENT"] = "embedContent"; + Task["BATCH_EMBED_CONTENTS"] = "batchEmbedContents"; +})(Task || (Task = {})); +class RequestUrl { + constructor(model, task, apiKey, stream, requestOptions) { + this.model = model; + this.task = task; + this.apiKey = apiKey; + this.stream = stream; + this.requestOptions = requestOptions; + } + toString() { + var _a, _b; + const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION; + const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL; + let url = `${baseUrl}/${apiVersion}/${this.model}:${this.task}`; + if (this.stream) { + url += "?alt=sse"; + } + return url; + } +} +/** + * Simple, but may become more complex if we add more versions to log. + */ +function getClientHeaders(requestOptions) { + const clientHeaders = []; + if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) { + clientHeaders.push(requestOptions.apiClient); + } + clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`); + return clientHeaders.join(" "); +} +async function getHeaders(url) { + var _a; + const headers = new Headers(); + headers.append("Content-Type", "application/json"); + headers.append("x-goog-api-client", getClientHeaders(url.requestOptions)); + headers.append("x-goog-api-key", url.apiKey); + let customHeaders = (_a = url.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders; + if (customHeaders) { + if (!(customHeaders instanceof Headers)) { + try { + customHeaders = new Headers(customHeaders); + } + catch (e) { + throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e.message}`); + } + } + for (const [headerName, headerValue] of customHeaders.entries()) { + if (headerName === "x-goog-api-key") { + throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`); + } + else if (headerName === "x-goog-api-client") { + throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`); + } + headers.append(headerName, headerValue); + } + } + return headers; +} +async function constructModelRequest(model, task, apiKey, stream, body, requestOptions) { + const url = new RequestUrl(model, task, apiKey, stream, requestOptions); + return { + url: url.toString(), + fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), { method: "POST", headers: await getHeaders(url), body }), + }; +} +async function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {}, +// Allows this to be stubbed for tests +fetchFn = fetch) { + const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions); + return makeRequest(url, fetchOptions, fetchFn); +} +async function makeRequest(url, fetchOptions, fetchFn = fetch) { + let response; + try { + response = await fetchFn(url, fetchOptions); + } + catch (e) { + handleResponseError(e, url); + } + if (!response.ok) { + await handleResponseNotOk(response, url); + } + return response; +} +function handleResponseError(e, url) { + let err = e; + if (err.name === "AbortError") { + err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e.message}`); + err.stack = e.stack; + } + else if (!(e instanceof GoogleGenerativeAIFetchError || + e instanceof GoogleGenerativeAIRequestInputError)) { + err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e.message}`); + err.stack = e.stack; + } + throw err; +} +async function handleResponseNotOk(response, url) { + let message = ""; + let errorDetails; + try { + const json = await response.json(); + message = json.error.message; + if (json.error.details) { + message += ` ${JSON.stringify(json.error.details)}`; + errorDetails = json.error.details; + } + } + catch (e) { + // ignored + } + throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails); +} +/** + * Generates the request options to be passed to the fetch API. + * @param requestOptions - The user-defined request options. + * @returns The generated request options. + */ +function buildFetchOptions(requestOptions) { + const fetchOptions = {}; + if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) { + const controller = new AbortController(); + if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) { + setTimeout(() => controller.abort(), requestOptions.timeout); + } + if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) { + requestOptions.signal.addEventListener("abort", () => { + controller.abort(); + }); + } + fetchOptions.signal = controller.signal; + } + return fetchOptions; +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Adds convenience helper methods to a response object, including stream + * chunks (as long as each chunk is a complete GenerateContentResponse JSON). + */ +function addHelpers(response) { + response.text = () => { + if (response.candidates && response.candidates.length > 0) { + if (response.candidates.length > 1) { + console.warn(`This response had ${response.candidates.length} ` + + `candidates. Returning text from the first candidate only. ` + + `Access response.candidates directly to use the other candidates.`); + } + if (hadBadFinishReason(response.candidates[0])) { + throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); + } + return getText(response); + } + else if (response.promptFeedback) { + throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response); + } + return ""; + }; + /** + * TODO: remove at next major version + */ + response.functionCall = () => { + if (response.candidates && response.candidates.length > 0) { + if (response.candidates.length > 1) { + console.warn(`This response had ${response.candidates.length} ` + + `candidates. Returning function calls from the first candidate only. ` + + `Access response.candidates directly to use the other candidates.`); + } + if (hadBadFinishReason(response.candidates[0])) { + throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); + } + console.warn(`response.functionCall() is deprecated. ` + + `Use response.functionCalls() instead.`); + return getFunctionCalls(response)[0]; + } + else if (response.promptFeedback) { + throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response); + } + return undefined; + }; + response.functionCalls = () => { + if (response.candidates && response.candidates.length > 0) { + if (response.candidates.length > 1) { + console.warn(`This response had ${response.candidates.length} ` + + `candidates. Returning function calls from the first candidate only. ` + + `Access response.candidates directly to use the other candidates.`); + } + if (hadBadFinishReason(response.candidates[0])) { + throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); + } + return getFunctionCalls(response); + } + else if (response.promptFeedback) { + throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response); + } + return undefined; + }; + return response; +} +/** + * Returns all text found in all parts of first candidate. + */ +function getText(response) { + var _a, _b, _c, _d; + const textStrings = []; + if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) { + for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) { + if (part.text) { + textStrings.push(part.text); + } + if (part.executableCode) { + textStrings.push("\n```" + + part.executableCode.language + + "\n" + + part.executableCode.code + + "\n```\n"); + } + if (part.codeExecutionResult) { + textStrings.push("\n```\n" + part.codeExecutionResult.output + "\n```\n"); + } + } + } + if (textStrings.length > 0) { + return textStrings.join(""); + } + else { + return ""; + } +} /** - * Format agent analysis result for GitHub comment + * Returns functionCall of first candidate. */ -function formatAnalysisForGitHub(result) { - let output = ''; - // Summary - if (result.summary) { - output += `### 📋 Summary\n${result.summary}\n\n`; +function getFunctionCalls(response) { + var _a, _b, _c, _d; + const functionCalls = []; + if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) { + for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) { + if (part.functionCall) { + functionCalls.push(part.functionCall); + } + } + } + if (functionCalls.length > 0) { + return functionCalls; + } + else { + return undefined; + } +} +const badFinishReasons = [ + FinishReason.RECITATION, + FinishReason.SAFETY, + FinishReason.LANGUAGE, +]; +function hadBadFinishReason(candidate) { + return (!!candidate.finishReason && + badFinishReasons.includes(candidate.finishReason)); +} +function formatBlockErrorMessage(response) { + var _a, _b, _c; + let message = ""; + if ((!response.candidates || response.candidates.length === 0) && + response.promptFeedback) { + message += "Response was blocked"; + if ((_a = response.promptFeedback) === null || _a === void 0 ? void 0 : _a.blockReason) { + message += ` due to ${response.promptFeedback.blockReason}`; + } + if ((_b = response.promptFeedback) === null || _b === void 0 ? void 0 : _b.blockReasonMessage) { + message += `: ${response.promptFeedback.blockReasonMessage}`; + } + } + else if ((_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0]) { + const firstCandidate = response.candidates[0]; + if (hadBadFinishReason(firstCandidate)) { + message += `Candidate was blocked due to ${firstCandidate.finishReason}`; + if (firstCandidate.finishMessage) { + message += `: ${firstCandidate.finishMessage}`; + } + } + } + return message; +} + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol */ + + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; + function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +const responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/; +/** + * Process a response.body stream from the backend and return an + * iterator that provides one complete GenerateContentResponse at a time + * and a promise that resolves with a single aggregated + * GenerateContentResponse. + * + * @param response - Response from a fetch call + */ +function processStream(response) { + const inputStream = response.body.pipeThrough(new TextDecoderStream("utf8", { fatal: true })); + const responseStream = getResponseStream(inputStream); + const [stream1, stream2] = responseStream.tee(); + return { + stream: generateResponseSequence(stream1), + response: getResponsePromise(stream2), + }; +} +async function getResponsePromise(stream) { + const allResponses = []; + const reader = stream.getReader(); + while (true) { + const { done, value } = await reader.read(); + if (done) { + return addHelpers(aggregateResponses(allResponses)); + } + allResponses.push(value); + } +} +function generateResponseSequence(stream) { + return __asyncGenerator(this, arguments, function* generateResponseSequence_1() { + const reader = stream.getReader(); + while (true) { + const { value, done } = yield __await(reader.read()); + if (done) { + break; + } + yield yield __await(addHelpers(value)); + } + }); +} +/** + * Reads a raw stream from the fetch response and join incomplete + * chunks, returning a new stream that provides a single complete + * GenerateContentResponse in each iteration. + */ +function getResponseStream(inputStream) { + const reader = inputStream.getReader(); + const stream = new ReadableStream({ + start(controller) { + let currentText = ""; + return pump(); + function pump() { + return reader + .read() + .then(({ value, done }) => { + if (done) { + if (currentText.trim()) { + controller.error(new GoogleGenerativeAIError("Failed to parse stream")); + return; + } + controller.close(); + return; + } + currentText += value; + let match = currentText.match(responseLineRE); + let parsedResponse; + while (match) { + try { + parsedResponse = JSON.parse(match[1]); + } + catch (e) { + controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: "${match[1]}"`)); + return; + } + controller.enqueue(parsedResponse); + currentText = currentText.substring(match[0].length); + match = currentText.match(responseLineRE); + } + return pump(); + }) + .catch((e) => { + let err = e; + err.stack = e.stack; + if (err.name === "AbortError") { + err = new GoogleGenerativeAIAbortError("Request aborted when reading from the stream"); + } + else { + err = new GoogleGenerativeAIError("Error reading from the stream"); + } + throw err; + }); + } + }, + }); + return stream; +} +/** + * Aggregates an array of `GenerateContentResponse`s into a single + * GenerateContentResponse. + */ +function aggregateResponses(responses) { + const lastResponse = responses[responses.length - 1]; + const aggregatedResponse = { + promptFeedback: lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.promptFeedback, + }; + for (const response of responses) { + if (response.candidates) { + let candidateIndex = 0; + for (const candidate of response.candidates) { + if (!aggregatedResponse.candidates) { + aggregatedResponse.candidates = []; + } + if (!aggregatedResponse.candidates[candidateIndex]) { + aggregatedResponse.candidates[candidateIndex] = { + index: candidateIndex, + }; + } + // Keep overwriting, the last one will be final + aggregatedResponse.candidates[candidateIndex].citationMetadata = + candidate.citationMetadata; + aggregatedResponse.candidates[candidateIndex].groundingMetadata = + candidate.groundingMetadata; + aggregatedResponse.candidates[candidateIndex].finishReason = + candidate.finishReason; + aggregatedResponse.candidates[candidateIndex].finishMessage = + candidate.finishMessage; + aggregatedResponse.candidates[candidateIndex].safetyRatings = + candidate.safetyRatings; + /** + * Candidates should always have content and parts, but this handles + * possible malformed responses. + */ + if (candidate.content && candidate.content.parts) { + if (!aggregatedResponse.candidates[candidateIndex].content) { + aggregatedResponse.candidates[candidateIndex].content = { + role: candidate.content.role || "user", + parts: [], + }; + } + const newPart = {}; + for (const part of candidate.content.parts) { + if (part.text) { + newPart.text = part.text; + } + if (part.functionCall) { + newPart.functionCall = part.functionCall; + } + if (part.executableCode) { + newPart.executableCode = part.executableCode; + } + if (part.codeExecutionResult) { + newPart.codeExecutionResult = part.codeExecutionResult; + } + if (Object.keys(newPart).length === 0) { + newPart.text = ""; + } + aggregatedResponse.candidates[candidateIndex].content.parts.push(newPart); + } + } + } + candidateIndex++; + } + if (response.usageMetadata) { + aggregatedResponse.usageMetadata = response.usageMetadata; + } + } + return aggregatedResponse; +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +async function generateContentStream(apiKey, model, params, requestOptions) { + const response = await makeModelRequest(model, Task.STREAM_GENERATE_CONTENT, apiKey, + /* stream */ true, JSON.stringify(params), requestOptions); + return processStream(response); +} +async function generateContent(apiKey, model, params, requestOptions) { + const response = await makeModelRequest(model, Task.GENERATE_CONTENT, apiKey, + /* stream */ false, JSON.stringify(params), requestOptions); + const responseJson = await response.json(); + const enhancedResponse = addHelpers(responseJson); + return { + response: enhancedResponse, + }; +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +function formatSystemInstruction(input) { + // null or undefined + if (input == null) { + return undefined; + } + else if (typeof input === "string") { + return { role: "system", parts: [{ text: input }] }; + } + else if (input.text) { + return { role: "system", parts: [input] }; + } + else if (input.parts) { + if (!input.role) { + return { role: "system", parts: input.parts }; + } + else { + return input; + } + } +} +function formatNewContent(request) { + let newParts = []; + if (typeof request === "string") { + newParts = [{ text: request }]; + } + else { + for (const partOrString of request) { + if (typeof partOrString === "string") { + newParts.push({ text: partOrString }); + } + else { + newParts.push(partOrString); + } + } + } + return assignRoleToPartsAndValidateSendMessageRequest(newParts); +} +/** + * When multiple Part types (i.e. FunctionResponsePart and TextPart) are + * passed in a single Part array, we may need to assign different roles to each + * part. Currently only FunctionResponsePart requires a role other than 'user'. + * @private + * @param parts Array of parts to pass to the model + * @returns Array of content items + */ +function assignRoleToPartsAndValidateSendMessageRequest(parts) { + const userContent = { role: "user", parts: [] }; + const functionContent = { role: "function", parts: [] }; + let hasUserContent = false; + let hasFunctionContent = false; + for (const part of parts) { + if ("functionResponse" in part) { + functionContent.parts.push(part); + hasFunctionContent = true; + } + else { + userContent.parts.push(part); + hasUserContent = true; + } + } + if (hasUserContent && hasFunctionContent) { + throw new GoogleGenerativeAIError("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message."); + } + if (!hasUserContent && !hasFunctionContent) { + throw new GoogleGenerativeAIError("No content is provided for sending chat message."); + } + if (hasUserContent) { + return userContent; + } + return functionContent; +} +function formatCountTokensInput(params, modelParams) { + var _a; + let formattedGenerateContentRequest = { + model: modelParams === null || modelParams === void 0 ? void 0 : modelParams.model, + generationConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.generationConfig, + safetySettings: modelParams === null || modelParams === void 0 ? void 0 : modelParams.safetySettings, + tools: modelParams === null || modelParams === void 0 ? void 0 : modelParams.tools, + toolConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.toolConfig, + systemInstruction: modelParams === null || modelParams === void 0 ? void 0 : modelParams.systemInstruction, + cachedContent: (_a = modelParams === null || modelParams === void 0 ? void 0 : modelParams.cachedContent) === null || _a === void 0 ? void 0 : _a.name, + contents: [], + }; + const containsGenerateContentRequest = params.generateContentRequest != null; + if (params.contents) { + if (containsGenerateContentRequest) { + throw new GoogleGenerativeAIRequestInputError("CountTokensRequest must have one of contents or generateContentRequest, not both."); + } + formattedGenerateContentRequest.contents = params.contents; + } + else if (containsGenerateContentRequest) { + formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest); + } + else { + // Array or string + const content = formatNewContent(params); + formattedGenerateContentRequest.contents = [content]; + } + return { generateContentRequest: formattedGenerateContentRequest }; +} +function formatGenerateContentInput(params) { + let formattedRequest; + if (params.contents) { + formattedRequest = params; + } + else { + // Array or string + const content = formatNewContent(params); + formattedRequest = { contents: [content] }; + } + if (params.systemInstruction) { + formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction); + } + return formattedRequest; +} +function formatEmbedContentInput(params) { + if (typeof params === "string" || Array.isArray(params)) { + const content = formatNewContent(params); + return { content }; + } + return params; +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +// https://ai.google.dev/api/rest/v1beta/Content#part +const VALID_PART_FIELDS = [ + "text", + "inlineData", + "functionCall", + "functionResponse", + "executableCode", + "codeExecutionResult", +]; +const VALID_PARTS_PER_ROLE = { + user: ["text", "inlineData"], + function: ["functionResponse"], + model: ["text", "functionCall", "executableCode", "codeExecutionResult"], + // System instructions shouldn't be in history anyway. + system: ["text"], +}; +function validateChatHistory(history) { + let prevContent = false; + for (const currContent of history) { + const { role, parts } = currContent; + if (!prevContent && role !== "user") { + throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`); + } + if (!POSSIBLE_ROLES.includes(role)) { + throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`); + } + if (!Array.isArray(parts)) { + throw new GoogleGenerativeAIError("Content should have 'parts' property with an array of Parts"); + } + if (parts.length === 0) { + throw new GoogleGenerativeAIError("Each Content should have at least one part"); + } + const countFields = { + text: 0, + inlineData: 0, + functionCall: 0, + functionResponse: 0, + fileData: 0, + executableCode: 0, + codeExecutionResult: 0, + }; + for (const part of parts) { + for (const key of VALID_PART_FIELDS) { + if (key in part) { + countFields[key] += 1; + } + } + } + const validParts = VALID_PARTS_PER_ROLE[role]; + for (const key of VALID_PART_FIELDS) { + if (!validParts.includes(key) && countFields[key] > 0) { + throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`); + } + } + prevContent = true; + } +} +/** + * Returns true if the response is valid (could be appended to the history), flase otherwise. + */ +function isValidResponse(response) { + var _a; + if (response.candidates === undefined || response.candidates.length === 0) { + return false; + } + const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content; + if (content === undefined) { + return false; + } + if (content.parts === undefined || content.parts.length === 0) { + return false; + } + for (const part of content.parts) { + if (part === undefined || Object.keys(part).length === 0) { + return false; + } + if (part.text !== undefined && part.text === "") { + return false; + } + } + return true; +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Do not log a message for this error. + */ +const SILENT_ERROR = "SILENT_ERROR"; +/** + * ChatSession class that enables sending chat messages and stores + * history of sent and received messages so far. + * + * @public + */ +class ChatSession { + constructor(apiKey, model, params, _requestOptions = {}) { + this.model = model; + this.params = params; + this._requestOptions = _requestOptions; + this._history = []; + this._sendPromise = Promise.resolve(); + this._apiKey = apiKey; + if (params === null || params === void 0 ? void 0 : params.history) { + validateChatHistory(params.history); + this._history = params.history; + } + } + /** + * Gets the chat history so far. Blocked prompts are not added to history. + * Blocked candidates are not added to history, nor are the prompts that + * generated them. + */ + async getHistory() { + await this._sendPromise; + return this._history; } - // Risks - if (result.overallRisks && result.overallRisks.length > 0) { - output += `### ⚠️ Risks Identified\n`; - result.overallRisks.forEach((risk, i) => { - output += `${i + 1}. ${risk}\n`; + /** + * Sends a chat message and receives a non-streaming + * {@link GenerateContentResult}. + * + * Fields set in the optional {@link SingleRequestOptions} parameter will + * take precedence over the {@link RequestOptions} values provided to + * {@link GoogleGenerativeAI.getGenerativeModel }. + */ + async sendMessage(request, requestOptions = {}) { + var _a, _b, _c, _d, _e, _f; + await this._sendPromise; + const newContent = formatNewContent(request); + const generateContentRequest = { + safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings, + generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig, + tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools, + toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig, + systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction, + cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent, + contents: [...this._history, newContent], + }; + const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + let finalResult; + // Add onto the chain. + this._sendPromise = this._sendPromise + .then(() => generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions)) + .then((result) => { + var _a; + if (isValidResponse(result.response)) { + this._history.push(newContent); + const responseContent = Object.assign({ parts: [], + // Response seems to come back without a role set. + role: "model" }, (_a = result.response.candidates) === null || _a === void 0 ? void 0 : _a[0].content); + this._history.push(responseContent); + } + else { + const blockErrorMessage = formatBlockErrorMessage(result.response); + if (blockErrorMessage) { + console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`); + } + } + finalResult = result; + }) + .catch((e) => { + // Resets _sendPromise to avoid subsequent calls failing and throw error. + this._sendPromise = Promise.resolve(); + throw e; + }); + await this._sendPromise; + return finalResult; + } + /** + * Sends a chat message and receives the response as a + * {@link GenerateContentStreamResult} containing an iterable stream + * and a response promise. + * + * Fields set in the optional {@link SingleRequestOptions} parameter will + * take precedence over the {@link RequestOptions} values provided to + * {@link GoogleGenerativeAI.getGenerativeModel }. + */ + async sendMessageStream(request, requestOptions = {}) { + var _a, _b, _c, _d, _e, _f; + await this._sendPromise; + const newContent = formatNewContent(request); + const generateContentRequest = { + safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings, + generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig, + tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools, + toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig, + systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction, + cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent, + contents: [...this._history, newContent], + }; + const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions); + // Add onto the chain. + this._sendPromise = this._sendPromise + .then(() => streamPromise) + // This must be handled to avoid unhandled rejection, but jump + // to the final catch block with a label to not log this error. + .catch((_ignored) => { + throw new Error(SILENT_ERROR); + }) + .then((streamResult) => streamResult.response) + .then((response) => { + if (isValidResponse(response)) { + this._history.push(newContent); + const responseContent = Object.assign({}, response.candidates[0].content); + // Response seems to come back without a role set. + if (!responseContent.role) { + responseContent.role = "model"; + } + this._history.push(responseContent); + } + else { + const blockErrorMessage = formatBlockErrorMessage(response); + if (blockErrorMessage) { + console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`); + } + } + }) + .catch((e) => { + // Errors in streamPromise are already catchable by the user as + // streamPromise is returned. + // Avoid duplicating the error message in logs. + if (e.message !== SILENT_ERROR) { + // Users do not have access to _sendPromise to catch errors + // downstream from streamPromise, so they should not throw. + console.error(e); + } }); - output += '\n'; + return streamPromise; + } +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +async function countTokens(apiKey, model, params, singleRequestOptions) { + const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions); + return response.json(); +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +async function embedContent(apiKey, model, params, requestOptions) { + const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions); + return response.json(); +} +async function batchEmbedContents(apiKey, model, params, requestOptions) { + const requestsWithModel = params.requests.map((request) => { + return Object.assign(Object.assign({}, request), { model }); + }); + const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({ requests: requestsWithModel }), requestOptions); + return response.json(); +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Class for generative model APIs. + * @public + */ +class GenerativeModel { + constructor(apiKey, modelParams, _requestOptions = {}) { + this.apiKey = apiKey; + this._requestOptions = _requestOptions; + if (modelParams.model.includes("/")) { + // Models may be named "models/model-name" or "tunedModels/model-name" + this.model = modelParams.model; + } + else { + // If path is not included, assume it's a non-tuned model. + this.model = `models/${modelParams.model}`; + } + this.generationConfig = modelParams.generationConfig || {}; + this.safetySettings = modelParams.safetySettings || []; + this.tools = modelParams.tools; + this.toolConfig = modelParams.toolConfig; + this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction); + this.cachedContent = modelParams.cachedContent; } - // Complexity - if (result.overallComplexity) { - output += `### 📊 Complexity Score: ${result.overallComplexity}/5\n\n`; + /** + * Makes a single non-streaming call to the model + * and returns an object containing a single {@link GenerateContentResponse}. + * + * Fields set in the optional {@link SingleRequestOptions} parameter will + * take precedence over the {@link RequestOptions} values provided to + * {@link GoogleGenerativeAI.getGenerativeModel }. + */ + async generateContent(request, requestOptions = {}) { + var _a; + const formattedParams = formatGenerateContentInput(request); + const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions); } - // Recommendations - if (result.recommendations && result.recommendations.length > 0) { - output += `### 💡 Recommendations\n`; - result.recommendations.forEach((rec, i) => { - output += `${i + 1}. ${rec}\n`; + /** + * Makes a single streaming call to the model and returns an object + * containing an iterable stream that iterates over all chunks in the + * streaming response as well as a promise that returns the final + * aggregated response. + * + * Fields set in the optional {@link SingleRequestOptions} parameter will + * take precedence over the {@link RequestOptions} values provided to + * {@link GoogleGenerativeAI.getGenerativeModel }. + */ + async generateContentStream(request, requestOptions = {}) { + var _a; + const formattedParams = formatGenerateContentInput(request); + const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions); + } + /** + * Gets a new {@link ChatSession} instance which can be used for + * multi-turn chats. + */ + startChat(startChatParams) { + var _a; + return new ChatSession(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, startChatParams), this._requestOptions); + } + /** + * Counts the tokens in the provided request. + * + * Fields set in the optional {@link SingleRequestOptions} parameter will + * take precedence over the {@link RequestOptions} values provided to + * {@link GoogleGenerativeAI.getGenerativeModel }. + */ + async countTokens(request, requestOptions = {}) { + const formattedParams = formatCountTokensInput(request, { + model: this.model, + generationConfig: this.generationConfig, + safetySettings: this.safetySettings, + tools: this.tools, + toolConfig: this.toolConfig, + systemInstruction: this.systemInstruction, + cachedContent: this.cachedContent, }); - output += '\n'; + const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions); + } + /** + * Embeds the provided content. + * + * Fields set in the optional {@link SingleRequestOptions} parameter will + * take precedence over the {@link RequestOptions} values provided to + * {@link GoogleGenerativeAI.getGenerativeModel }. + */ + async embedContent(request, requestOptions = {}) { + const formattedParams = formatEmbedContentInput(request); + const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions); + } + /** + * Embeds an array of {@link EmbedContentRequest}s. + * + * Fields set in the optional {@link SingleRequestOptions} parameter will + * take precedence over the {@link RequestOptions} values provided to + * {@link GoogleGenerativeAI.getGenerativeModel }. + */ + async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) { + const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); + return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions); + } +} + +/** + * @license + * Copyright 2024 Google LLC + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +/** + * Top-level class for this SDK + * @public + */ +class GoogleGenerativeAI { + constructor(apiKey) { + this.apiKey = apiKey; + } + /** + * Gets a {@link GenerativeModel} instance for the provided model name. + */ + getGenerativeModel(modelParams, requestOptions) { + if (!modelParams.model) { + throw new GoogleGenerativeAIError(`Must provide a model name. ` + + `Example: genai.getGenerativeModel({ model: 'my-model-name' })`); + } + return new GenerativeModel(this.apiKey, modelParams, requestOptions); } - // File-level details (top 5 most complex) - if (result.fileAnalyses && result.fileAnalyses.size > 0) { - const files = Array.from(result.fileAnalyses.entries()); - const sortedFiles = files - .sort((a, b) => b[1].complexity - a[1].complexity) - .slice(0, 5); - if (sortedFiles.length > 0) { - output += `### 📁 Files of Interest\n`; - sortedFiles.forEach(([path, analysis]) => { - output += `- **${path}** (complexity: ${analysis.complexity}/5)\n`; - if (analysis.risks && analysis.risks.length > 0) { - output += ` - ⚠️ ${analysis.risks.join(', ')}\n`; + /** + * Creates a {@link GenerativeModel} instance from provided content cache. + */ + getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) { + if (!cachedContent.name) { + throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `name` field."); + } + if (!cachedContent.model) { + throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field."); + } + /** + * Not checking tools and toolConfig for now as it would require a deep + * equality comparison and isn't likely to be a common case. + */ + const disallowedDuplicates = ["model", "systemInstruction"]; + for (const key of disallowedDuplicates) { + if ((modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) && + cachedContent[key] && + (modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) !== cachedContent[key]) { + if (key === "model") { + const modelParamsComp = modelParams.model.startsWith("models/") + ? modelParams.model.replace("models/", "") + : modelParams.model; + const cachedContentComp = cachedContent.model.startsWith("models/") + ? cachedContent.model.replace("models/", "") + : cachedContent.model; + if (modelParamsComp === cachedContentComp) { + continue; + } } - }); + throw new GoogleGenerativeAIRequestInputError(`Different value for "${key}" specified in modelParams` + + ` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`); + } } + const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), { model: cachedContent.model, tools: cachedContent.tools, toolConfig: cachedContent.toolConfig, systemInstruction: cachedContent.systemInstruction, cachedContent }); + return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions); } - return output; } -export default (app) => { - app.log.info('🤖 PR Agent (LangChain) started'); - app.on(['pull_request.opened', 'pull_request.synchronize'], async (context) => { - const { pull_request: pr, repository } = context.payload; - app.log.info(`Analyzing PR #${pr.number} in ${repository.full_name}`); + + +//# sourceMappingURL=index.mjs.map + +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/utils/tools.js + + + + + + +//#region src/utils/tools.ts +function convertToolsToGenAI(tools, extra) { + const genAITools = processTools(tools); + const toolConfig = createToolConfig(genAITools, extra); + return { + tools: genAITools, + toolConfig + }; +} +function processTools(tools) { + let functionDeclarationTools = []; + const genAITools = []; + tools.forEach((tool) => { + if (isLangChainTool(tool)) { + const [convertedTool] = convertToGenerativeAITools([tool]); + if (convertedTool.functionDeclarations) functionDeclarationTools.push(...convertedTool.functionDeclarations); + } else if (isOpenAITool(tool)) { + const { functionDeclarations } = convertOpenAIToolToGenAI(tool); + if (functionDeclarations) functionDeclarationTools.push(...functionDeclarations); + else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool"); + } else genAITools.push(tool); + }); + const genAIFunctionDeclaration = genAITools.find((t) => "functionDeclarations" in t); + if (genAIFunctionDeclaration) return genAITools.map((tool) => { + if (functionDeclarationTools?.length > 0 && "functionDeclarations" in tool) { + const newTool = { functionDeclarations: [...tool.functionDeclarations || [], ...functionDeclarationTools] }; + functionDeclarationTools = []; + return newTool; + } + return tool; + }); + return [...genAITools, ...functionDeclarationTools.length > 0 ? [{ functionDeclarations: functionDeclarationTools }] : []]; +} +function convertOpenAIToolToGenAI(tool) { + return { functionDeclarations: [{ + name: tool.function.name, + description: tool.function.description, + parameters: removeAdditionalProperties(tool.function.parameters) + }] }; +} +function createToolConfig(genAITools, extra) { + if (!genAITools.length || !extra) return void 0; + const { toolChoice, allowedFunctionNames } = extra; + const modeMap = { + any: FunctionCallingMode.ANY, + auto: FunctionCallingMode.AUTO, + none: FunctionCallingMode.NONE + }; + if (toolChoice && [ + "any", + "auto", + "none" + ].includes(toolChoice)) return { functionCallingConfig: { + mode: modeMap[toolChoice] ?? "MODE_UNSPECIFIED", + allowedFunctionNames + } }; + if (typeof toolChoice === "string" || allowedFunctionNames) return { functionCallingConfig: { + mode: FunctionCallingMode.ANY, + allowedFunctionNames: [...allowedFunctionNames ?? [], ...toolChoice && typeof toolChoice === "string" ? [toolChoice] : []] + } }; + return void 0; +} + +//#endregion + +//# sourceMappingURL=tools.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/profiles.js +//#region src/profiles.ts +const dist_profiles_PROFILES = { + "gemini-embedding-001": { + maxInputTokens: 2048, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 3072, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: false + }, + "gemini-2.5-flash-image": { + maxInputTokens: 32768, + imageInputs: true, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 32768, + reasoningOutput: true, + imageOutputs: true, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: false + }, + "gemini-2.5-flash-preview-05-20": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-flash-lite-latest": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-2.5-flash": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-flash-latest": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-2.5-pro-preview-05-06": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-2.5-flash-preview-tts": { + maxInputTokens: 8e3, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 16e3, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: true, + videoOutputs: false, + toolCalling: false, + structuredOutput: false + }, + "gemini-2.0-flash-lite": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-live-2.5-flash-preview-native-audio": { + maxInputTokens: 131072, + imageInputs: false, + audioInputs: true, + pdfInputs: false, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: true, + videoOutputs: false, + toolCalling: true, + structuredOutput: false + }, + "gemini-2.0-flash": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-2.5-flash-lite": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-2.5-pro-preview-06-05": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-live-2.5-flash": { + maxInputTokens: 128e3, + imageInputs: true, + audioInputs: true, + pdfInputs: false, + videoInputs: true, + maxOutputTokens: 8e3, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: true, + videoOutputs: false, + toolCalling: true, + structuredOutput: false + }, + "gemini-2.5-flash-lite-preview-06-17": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false + }, + "gemini-2.5-flash-image-preview": { + maxInputTokens: 32768, + imageInputs: true, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 32768, + reasoningOutput: true, + imageOutputs: true, + audioOutputs: false, + videoOutputs: false, + toolCalling: false, + structuredOutput: false + }, + "gemini-2.5-flash-preview-09-2025": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-2.5-flash-preview-04-17": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false + }, + "gemini-2.5-pro-preview-tts": { + maxInputTokens: 8e3, + imageInputs: false, + audioInputs: false, + pdfInputs: false, + videoInputs: false, + maxOutputTokens: 16e3, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: true, + videoOutputs: false, + toolCalling: false, + structuredOutput: false + }, + "gemini-2.5-pro": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-1.5-flash": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: true, + pdfInputs: false, + videoInputs: true, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false + }, + "gemini-1.5-flash-8b": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: true, + pdfInputs: false, + videoInputs: true, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false + }, + "gemini-2.5-flash-lite-preview-09-2025": { + maxInputTokens: 1048576, + imageInputs: true, + audioInputs: true, + pdfInputs: true, + videoInputs: true, + maxOutputTokens: 65536, + reasoningOutput: true, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: true + }, + "gemini-1.5-pro": { + maxInputTokens: 1e6, + imageInputs: true, + audioInputs: true, + pdfInputs: false, + videoInputs: true, + maxOutputTokens: 8192, + reasoningOutput: false, + imageOutputs: false, + audioOutputs: false, + videoOutputs: false, + toolCalling: true, + structuredOutput: false + } +}; +var dist_profiles_profiles_default = dist_profiles_PROFILES; + +//#endregion + +//# sourceMappingURL=profiles.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/chat_models.js + + + + + + + + + + + + +//#region src/chat_models.ts +/** +* Google Generative AI chat model integration. +* +* Setup: +* Install `@langchain/google-genai` and set an environment variable named `GOOGLE_API_KEY`. +* +* ```bash +* npm install @langchain/google-genai +* export GOOGLE_API_KEY="your-api-key" +* ``` +* +* ## [Constructor args](https://api.js.langchain.com/classes/langchain_google_genai.ChatGoogleGenerativeAI.html#constructor) +* +* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_genai.GoogleGenerativeAIChatCallOptions.html) +* +* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. +* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: +* +* ```typescript +* // When calling `.withConfig`, call options should be passed via the first argument +* const llmWithArgsBound = llm.withConfig({ +* stop: ["\n"], +* }); +* +* // When calling `.bindTools`, call options should be passed via the second argument +* const llmWithTools = llm.bindTools( +* [...], +* { +* stop: ["\n"], +* } +* ); +* ``` +* +* ## Examples +* +*
+* Instantiate +* +* ```typescript +* import { ChatGoogleGenerativeAI } from '@langchain/google-genai'; +* +* const llm = new ChatGoogleGenerativeAI({ +* model: "gemini-1.5-flash", +* temperature: 0, +* maxRetries: 2, +* // apiKey: "...", +* // other params... +* }); +* ``` +*
+* +*
+* +*
+* Invoking +* +* ```typescript +* const input = `Translate "I love programming" into French.`; +* +* // Models also accept a list of chat messages or a formatted prompt +* const result = await llm.invoke(input); +* console.log(result); +* ``` +* +* ```txt +* AIMessage { +* "content": "There are a few ways to translate \"I love programming\" into French, depending on the level of formality and nuance you want to convey:\n\n**Formal:**\n\n* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and your intended audience. \n", +* "response_metadata": { +* "finishReason": "STOP", +* "index": 0, +* "safetyRatings": [ +* { +* "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", +* "probability": "NEGLIGIBLE" +* }, +* { +* "category": "HARM_CATEGORY_HATE_SPEECH", +* "probability": "NEGLIGIBLE" +* }, +* { +* "category": "HARM_CATEGORY_HARASSMENT", +* "probability": "NEGLIGIBLE" +* }, +* { +* "category": "HARM_CATEGORY_DANGEROUS_CONTENT", +* "probability": "NEGLIGIBLE" +* } +* ] +* }, +* "usage_metadata": { +* "input_tokens": 10, +* "output_tokens": 149, +* "total_tokens": 159 +* } +* } +* ``` +*
+* +*
+* +*
+* Streaming Chunks +* +* ```typescript +* for await (const chunk of await llm.stream(input)) { +* console.log(chunk); +* } +* ``` +* +* ```txt +* AIMessageChunk { +* "content": "There", +* "response_metadata": { +* "index": 0 +* } +* "usage_metadata": { +* "input_tokens": 10, +* "output_tokens": 1, +* "total_tokens": 11 +* } +* } +* AIMessageChunk { +* "content": " are a few ways to translate \"I love programming\" into French, depending on", +* } +* AIMessageChunk { +* "content": " the level of formality and nuance you want to convey:\n\n**Formal:**\n\n", +* } +* AIMessageChunk { +* "content": "* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This", +* } +* AIMessageChunk { +* "content": " is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More", +* } +* AIMessageChunk { +* "content": " specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and", +* } +* AIMessageChunk { +* "content": " your intended audience. \n", +* } +* ``` +*
+* +*
+* +*
+* Aggregate Streamed Chunks +* +* ```typescript +* import { AIMessageChunk } from '@langchain/core/messages'; +* import { concat } from '@langchain/core/utils/stream'; +* +* const stream = await llm.stream(input); +* let full: AIMessageChunk | undefined; +* for await (const chunk of stream) { +* full = !full ? chunk : concat(full, chunk); +* } +* console.log(full); +* ``` +* +* ```txt +* AIMessageChunk { +* "content": "There are a few ways to translate \"I love programming\" into French, depending on the level of formality and nuance you want to convey:\n\n**Formal:**\n\n* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and your intended audience. \n", +* "usage_metadata": { +* "input_tokens": 10, +* "output_tokens": 277, +* "total_tokens": 287 +* } +* } +* ``` +*
+* +*
+* +*
+* Bind tools +* +* ```typescript +* import { z } from 'zod'; +* +* const GetWeather = { +* name: "GetWeather", +* description: "Get the current weather in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const GetPopulation = { +* name: "GetPopulation", +* description: "Get the current population in a given location", +* schema: z.object({ +* location: z.string().describe("The city and state, e.g. San Francisco, CA") +* }), +* } +* +* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); +* const aiMsg = await llmWithTools.invoke( +* "Which city is hotter today and which is bigger: LA or NY?" +* ); +* console.log(aiMsg.tool_calls); +* ``` +* +* ```txt +* [ +* { +* name: 'GetWeather', +* args: { location: 'Los Angeles, CA' }, +* type: 'tool_call' +* }, +* { +* name: 'GetWeather', +* args: { location: 'New York, NY' }, +* type: 'tool_call' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'Los Angeles, CA' }, +* type: 'tool_call' +* }, +* { +* name: 'GetPopulation', +* args: { location: 'New York, NY' }, +* type: 'tool_call' +* } +* ] +* ``` +*
+* +*
+* +*
+* Structured Output +* +* ```typescript +* const Joke = z.object({ +* setup: z.string().describe("The setup of the joke"), +* punchline: z.string().describe("The punchline to the joke"), +* rating: z.number().optional().describe("How funny the joke is, from 1 to 10") +* }).describe('Joke to tell user.'); +* +* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); +* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); +* console.log(jokeResult); +* ``` +* +* ```txt +* { +* setup: "Why don\\'t cats play poker?", +* punchline: "Why don\\'t cats play poker? Because they always have an ace up their sleeve!" +* } +* ``` +*
+* +*
+* +*
+* Multimodal +* +* ```typescript +* import { HumanMessage } from '@langchain/core/messages'; +* +* const imageUrl = "https://example.com/image.jpg"; +* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); +* const base64Image = Buffer.from(imageData).toString('base64'); +* +* const message = new HumanMessage({ +* content: [ +* { type: "text", text: "describe the weather in this image" }, +* { +* type: "image_url", +* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, +* }, +* ] +* }); +* +* const imageDescriptionAiMsg = await llm.invoke([message]); +* console.log(imageDescriptionAiMsg.content); +* ``` +* +* ```txt +* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions. +* ``` +*
+* +*
+* +*
+* Usage Metadata +* +* ```typescript +* const aiMsgForMetadata = await llm.invoke(input); +* console.log(aiMsgForMetadata.usage_metadata); +* ``` +* +* ```txt +* { input_tokens: 10, output_tokens: 149, total_tokens: 159 } +* ``` +*
+* +*
+* +*
+* Response Metadata +* +* ```typescript +* const aiMsgForResponseMetadata = await llm.invoke(input); +* console.log(aiMsgForResponseMetadata.response_metadata); +* ``` +* +* ```txt +* { +* finishReason: 'STOP', +* index: 0, +* safetyRatings: [ +* { +* category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', +* probability: 'NEGLIGIBLE' +* }, +* { +* category: 'HARM_CATEGORY_HATE_SPEECH', +* probability: 'NEGLIGIBLE' +* }, +* { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' }, +* { +* category: 'HARM_CATEGORY_DANGEROUS_CONTENT', +* probability: 'NEGLIGIBLE' +* } +* ] +* } +* ``` +*
+* +*
+* +*
+* Document Messages +* +* This example will show you how to pass documents such as PDFs to Google +* Generative AI through messages. +* +* ```typescript +* const pdfPath = "/Users/my_user/Downloads/invoice.pdf"; +* const pdfBase64 = await fs.readFile(pdfPath, "base64"); +* +* const response = await llm.invoke([ +* ["system", "Use the provided documents to answer the question"], +* [ +* "user", +* [ +* { +* type: "application/pdf", // If the `type` field includes a single slash (`/`), it will be treated as inline data. +* data: pdfBase64, +* }, +* { +* type: "text", +* text: "Summarize the contents of this PDF", +* }, +* ], +* ], +* ]); +* +* console.log(response.content); +* ``` +* +* ```txt +* This is a billing invoice from Twitter Developers for X API Basic Access. The transaction date is January 7, 2025, +* and the amount is $194.34, which has been paid. The subscription period is from January 7, 2025 21:02 to February 7, 2025 00:00 (UTC). +* The tax is $0.00, with a tax rate of 0%. The total amount is $194.34. The payment was made using a Visa card ending in 7022, +* expiring in 12/2026. The billing address is Brace Sproul, 1234 Main Street, San Francisco, CA, US 94103. The company being billed is +* X Corp, located at 865 FM 1209 Building 2, Bastrop, TX, US 78602. Terms and conditions apply. +* ``` +*
+* +*
+*/ +var ChatGoogleGenerativeAI = class extends BaseChatModel { + static lc_name() { + return "ChatGoogleGenerativeAI"; + } + lc_serializable = true; + get lc_secrets() { + return { apiKey: "GOOGLE_API_KEY" }; + } + lc_namespace = [ + "langchain", + "chat_models", + "google_genai" + ]; + get lc_aliases() { + return { apiKey: "google_api_key" }; + } + model; + temperature; + maxOutputTokens; + topP; + topK; + stopSequences = []; + safetySettings; + apiKey; + streaming = false; + json; + streamUsage = true; + convertSystemMessageToHumanContent; + thinkingConfig; + client; + get _isMultimodalModel() { + return this.model.includes("vision") || this.model.startsWith("gemini-1.5") || this.model.startsWith("gemini-2") || this.model.startsWith("gemma-3-") && !this.model.startsWith("gemma-3-1b") || this.model.startsWith("gemini-3"); + } + constructor(fields) { + super(fields); + this.model = fields.model.replace(/^models\//, ""); + this.maxOutputTokens = fields.maxOutputTokens ?? this.maxOutputTokens; + if (this.maxOutputTokens && this.maxOutputTokens < 0) throw new Error("`maxOutputTokens` must be a positive integer"); + this.temperature = fields.temperature ?? this.temperature; + if (this.temperature && (this.temperature < 0 || this.temperature > 2)) throw new Error("`temperature` must be in the range of [0.0,2.0]"); + this.topP = fields.topP ?? this.topP; + if (this.topP && this.topP < 0) throw new Error("`topP` must be a positive integer"); + if (this.topP && this.topP > 1) throw new Error("`topP` must be below 1."); + this.topK = fields.topK ?? this.topK; + if (this.topK && this.topK < 0) throw new Error("`topK` must be a positive integer"); + this.stopSequences = fields.stopSequences ?? this.stopSequences; + this.apiKey = fields.apiKey ?? getEnvironmentVariable("GOOGLE_API_KEY"); + if (!this.apiKey) throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor"); + this.safetySettings = fields.safetySettings ?? this.safetySettings; + if (this.safetySettings && this.safetySettings.length > 0) { + const safetySettingsSet = new Set(this.safetySettings.map((s) => s.category)); + if (safetySettingsSet.size !== this.safetySettings.length) throw new Error("The categories in `safetySettings` array must be unique"); + } + this.streaming = fields.streaming ?? this.streaming; + this.json = fields.json; + this.thinkingConfig = fields.thinkingConfig ?? this.thinkingConfig; + this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModel({ + model: this.model, + safetySettings: this.safetySettings, + generationConfig: { + stopSequences: this.stopSequences, + maxOutputTokens: this.maxOutputTokens, + temperature: this.temperature, + topP: this.topP, + topK: this.topK, + ...this.json ? { responseMimeType: "application/json" } : {}, + ...this.thinkingConfig ? { thinkingConfig: this.thinkingConfig } : {} + } + }, { + apiVersion: fields.apiVersion, + baseUrl: fields.baseUrl, + customHeaders: fields.customHeaders + }); + this.streamUsage = fields.streamUsage ?? this.streamUsage; + } + useCachedContent(cachedContent, modelParams, requestOptions) { + if (!this.apiKey) return; + this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions); + } + get useSystemInstruction() { + return typeof this.convertSystemMessageToHumanContent === "boolean" ? !this.convertSystemMessageToHumanContent : this.computeUseSystemInstruction; + } + get computeUseSystemInstruction() { + if (this.model === "gemini-1.0-pro-001") return false; + else if (this.model.startsWith("gemini-pro-vision")) return false; + else if (this.model.startsWith("gemini-1.0-pro-vision")) return false; + else if (this.model === "gemini-pro") return false; + return true; + } + getLsParams(options) { + return { + ls_provider: "google_genai", + ls_model_name: this.model, + ls_model_type: "chat", + ls_temperature: this.client.generationConfig.temperature, + ls_max_tokens: this.client.generationConfig.maxOutputTokens, + ls_stop: options.stop + }; + } + _combineLLMOutput() { + return []; + } + _llmType() { + return "googlegenerativeai"; + } + bindTools(tools, kwargs) { + return this.withConfig({ + tools: convertToolsToGenAI(tools)?.tools, + ...kwargs + }); + } + invocationParams(options) { + const toolsAndConfig = options?.tools?.length ? convertToolsToGenAI(options.tools, { + toolChoice: options.tool_choice, + allowedFunctionNames: options.allowedFunctionNames + }) : void 0; + if (options?.responseSchema) { + this.client.generationConfig.responseSchema = options.responseSchema; + this.client.generationConfig.responseMimeType = "application/json"; + } else { + this.client.generationConfig.responseSchema = void 0; + this.client.generationConfig.responseMimeType = this.json ? "application/json" : void 0; + } + return { + ...toolsAndConfig?.tools ? { tools: toolsAndConfig.tools } : {}, + ...toolsAndConfig?.toolConfig ? { toolConfig: toolsAndConfig.toolConfig } : {} + }; + } + async _generate(messages, options, runManager) { + const prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction, this.model); + let actualPrompt = prompt; + if (prompt[0].role === "system") { + const [systemInstruction] = prompt; + this.client.systemInstruction = systemInstruction; + actualPrompt = prompt.slice(1); + } + const parameters = this.invocationParams(options); + if (this.streaming) { + const tokenUsage = {}; + const stream = this._streamResponseChunks(messages, options, runManager); + const finalChunks = {}; + for await (const chunk of stream) { + const index = chunk.generationInfo?.completion ?? 0; + if (finalChunks[index] === void 0) finalChunks[index] = chunk; + else finalChunks[index] = finalChunks[index].concat(chunk); + } + const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value); + return { + generations, + llmOutput: { estimatedTokenUsage: tokenUsage } + }; + } + const res = await this.completionWithRetry({ + ...parameters, + contents: actualPrompt + }); + let usageMetadata; + if ("usageMetadata" in res.response) usageMetadata = convertUsageMetadata(res.response.usageMetadata, this.model); + const generationResult = mapGenerateContentResultToChatResult(res.response, { usageMetadata }); + if (generationResult.generations?.length > 0) await runManager?.handleLLMNewToken(generationResult.generations[0]?.text ?? ""); + return generationResult; + } + async *_streamResponseChunks(messages, options, runManager) { + const prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction, this.model); + let actualPrompt = prompt; + if (prompt[0].role === "system") { + const [systemInstruction] = prompt; + this.client.systemInstruction = systemInstruction; + actualPrompt = prompt.slice(1); + } + const parameters = this.invocationParams(options); + const request = { + ...parameters, + contents: actualPrompt + }; + const stream = await this.caller.callWithOptions({ signal: options?.signal }, async () => { + const { stream: stream$1 } = await this.client.generateContentStream(request); + return stream$1; + }); + let usageMetadata; + let prevPromptTokenCount = 0; + let prevCandidatesTokenCount = 0; + let prevTotalTokenCount = 0; + let index = 0; + for await (const response of stream) { + if ("usageMetadata" in response && response.usageMetadata !== void 0 && this.streamUsage !== false && options.streamUsage !== false) { + usageMetadata = convertUsageMetadata(response.usageMetadata, this.model); + const newPromptTokenCount = response.usageMetadata.promptTokenCount ?? 0; + usageMetadata.input_tokens = Math.max(0, newPromptTokenCount - prevPromptTokenCount); + prevPromptTokenCount = newPromptTokenCount; + const newCandidatesTokenCount = response.usageMetadata.candidatesTokenCount ?? 0; + usageMetadata.output_tokens = Math.max(0, newCandidatesTokenCount - prevCandidatesTokenCount); + prevCandidatesTokenCount = newCandidatesTokenCount; + const newTotalTokenCount = response.usageMetadata.totalTokenCount ?? 0; + usageMetadata.total_tokens = Math.max(0, newTotalTokenCount - prevTotalTokenCount); + prevTotalTokenCount = newTotalTokenCount; + } + const chunk = convertResponseContentToChatGenerationChunk(response, { + usageMetadata, + index + }); + index += 1; + if (!chunk) continue; + yield chunk; + await runManager?.handleLLMNewToken(chunk.text ?? ""); + } + } + async completionWithRetry(request, options) { + return this.caller.callWithOptions({ signal: options?.signal }, async () => { + try { + return await this.client.generateContent(request); + } catch (e) { + if (e.message?.includes("400 Bad Request")) e.status = 400; + throw e; + } + }); + } + /** + * Return profiling information for the model. + * + * Provides information about the model's capabilities and constraints, + * including token limits, multimodal support, and advanced features like + * tool calling and structured output. + * + * @returns {ModelProfile} An object describing the model's capabilities and constraints + * + * @example + * ```typescript + * const model = new ChatGoogleGenerativeAI({ model: "gemini-1.5-flash" }); + * const profile = model.profile; + * console.log(profile.maxInputTokens); // 2000000 + * console.log(profile.imageInputs); // true + * ``` + */ + get profile() { + return dist_profiles_profiles_default[this.model] ?? {}; + } + withStructuredOutput(outputSchema, config) { + const schema = outputSchema; + const name = config?.name; + const method = config?.method; + const includeRaw = config?.includeRaw; + if (method === "jsonMode") throw new Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`); + let llm; + let outputParser; + if (method === "functionCalling") { + let functionName = name ?? "extract"; + let tools; + if (isInteropZodSchema(schema)) { + const jsonSchema = schemaToGenerativeAIParameters(schema); + tools = [{ functionDeclarations: [{ + name: functionName, + description: jsonSchema.description ?? "A function available to call.", + parameters: jsonSchema + }] }]; + outputParser = new GoogleGenerativeAIToolsOutputParser({ + returnSingle: true, + keyName: functionName, + zodSchema: schema + }); + } else { + let geminiFunctionDefinition; + if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) { + geminiFunctionDefinition = schema; + geminiFunctionDefinition.parameters = removeAdditionalProperties(schema.parameters); + functionName = schema.name; + } else geminiFunctionDefinition = { + name: functionName, + description: schema.description ?? "", + parameters: removeAdditionalProperties(schema) + }; + tools = [{ functionDeclarations: [geminiFunctionDefinition] }]; + outputParser = new GoogleGenerativeAIToolsOutputParser({ + returnSingle: true, + keyName: functionName + }); + } + llm = this.bindTools(tools).withConfig({ allowedFunctionNames: [functionName] }); + } else { + const jsonSchema = schemaToGenerativeAIParameters(schema); + llm = this.withConfig({ responseSchema: jsonSchema }); + outputParser = new JsonOutputParser(); + } + if (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: "ChatGoogleGenerativeAIStructuredOutput" }); + const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); + const parserNone = RunnablePassthrough.assign({ parsed: () => null }); + const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); + return RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" }); + } +}; + +//#endregion + +//# sourceMappingURL=chat_models.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/embeddings.js + + + + + +//#region src/embeddings.ts +/** +* Class that extends the Embeddings class and provides methods for +* generating embeddings using the Google Palm API. +* @example +* ```typescript +* const model = new GoogleGenerativeAIEmbeddings({ +* apiKey: "", +* modelName: "embedding-001", +* }); +* +* // Embed a single query +* const res = await model.embedQuery( +* "What would be a good company name for a company that makes colorful socks?" +* ); +* console.log({ res }); +* +* // Embed multiple documents +* const documentRes = await model.embedDocuments(["Hello world", "Bye bye"]); +* console.log({ documentRes }); +* ``` +*/ +var GoogleGenerativeAIEmbeddings = class extends Embeddings { + apiKey; + modelName = "embedding-001"; + model = "embedding-001"; + taskType; + title; + stripNewLines = true; + maxBatchSize = 100; + client; + constructor(fields) { + super(fields ?? {}); + this.modelName = fields?.model?.replace(/^models\//, "") ?? fields?.modelName?.replace(/^models\//, "") ?? this.modelName; + this.model = this.modelName; + this.taskType = fields?.taskType ?? this.taskType; + this.title = fields?.title ?? this.title; + if (this.title && this.taskType !== "RETRIEVAL_DOCUMENT") throw new Error("title can only be sepcified with TaskType.RETRIEVAL_DOCUMENT"); + this.apiKey = fields?.apiKey ?? getEnvironmentVariable("GOOGLE_API_KEY"); + if (!this.apiKey) throw new Error("Please set an API key for Google GenerativeAI in the environmentb variable GOOGLE_API_KEY or in the `apiKey` field of the GoogleGenerativeAIEmbeddings constructor"); + this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModel({ model: this.model }, { baseUrl: fields?.baseUrl }); + } + _convertToContent(text) { + const cleanedText = this.stripNewLines ? text.replace(/\n/g, " ") : text; + return { + content: { + role: "user", + parts: [{ text: cleanedText }] + }, + taskType: this.taskType, + title: this.title + }; + } + async _embedQueryContent(text) { + const req = this._convertToContent(text); + const res = await this.client.embedContent(req); + return res.embedding.values ?? []; + } + async _embedDocumentsContent(documents) { + const batchEmbedChunks = chunkArray(documents, this.maxBatchSize); + const batchEmbedRequests = batchEmbedChunks.map((chunk) => ({ requests: chunk.map((doc) => this._convertToContent(doc)) })); + const responses = await Promise.allSettled(batchEmbedRequests.map((req) => this.client.batchEmbedContents(req))); + const embeddings = responses.flatMap((res, idx) => { + if (res.status === "fulfilled") return res.value.embeddings.map((e) => e.values || []); + else return Array(batchEmbedChunks[idx].length).fill([]); + }); + return embeddings; + } + /** + * Method that takes a document as input and returns a promise that + * resolves to an embedding for the document. It calls the _embedText + * method with the document as the input. + * @param document Document for which to generate an embedding. + * @returns Promise that resolves to an embedding for the input document. + */ + embedQuery(document) { + return this.caller.call(this._embedQueryContent.bind(this), document); + } + /** + * Method that takes an array of documents as input and returns a promise + * that resolves to a 2D array of embeddings for each document. It calls + * the _embedText method for each document in the array. + * @param documents Array of documents for which to generate embeddings. + * @returns Promise that resolves to a 2D array of embeddings for each input document. + */ + embedDocuments(documents) { + return this.caller.call(this._embedDocumentsContent.bind(this), documents); + } +}; + +//#endregion + +//# sourceMappingURL=embeddings.js.map +;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/index.js + + + + +;// CONCATENATED MODULE: ./src/providers/google.provider.ts + +/** + * Google Gemini provider implementation + */ +class GoogleProvider { + name = 'google'; + apiKey; + constructor(apiKey) { + this.apiKey = apiKey || process.env.GOOGLE_API_KEY || ''; + } + isConfigured() { + return !!this.apiKey; + } + getDefaultModel() { + return 'gemini-pro'; + } + getChatModel(config = {}) { + if (!this.isConfigured()) { + throw new Error('Google API key is not configured'); + } + return new ChatGoogleGenerativeAI({ + apiKey: this.apiKey, + model: config.model || this.getDefaultModel(), + temperature: config.temperature ?? 0.2, + maxOutputTokens: config.maxTokens ?? 4000, + }); + } +} + +;// CONCATENATED MODULE: ./src/providers/provider.factory.ts + + + +/** + * Factory for creating LLM providers + */ +class ProviderFactory { + static providers = new Map(); + /** + * Get or create a provider instance + */ + static getProvider(providerName, apiKey) { + // Normalize provider names + const normalizedName = this.normalizeProviderName(providerName); + // Check if we already have an instance (unless a specific API key is provided) + if (!apiKey && this.providers.has(normalizedName)) { + return this.providers.get(normalizedName); + } + // Create new provider instance + let provider; + switch (normalizedName) { + case 'anthropic': + provider = new AnthropicProvider(apiKey); + break; + case 'openai': + provider = new OpenAIProvider(apiKey); + break; + case 'google': + provider = new GoogleProvider(apiKey); + break; + default: + throw new Error(`Unsupported provider: ${providerName}. Supported: anthropic, openai, google`); + } + // Cache the provider if no specific API key was provided + if (!apiKey) { + this.providers.set(normalizedName, provider); + } + return provider; + } + /** + * Create a chat model with the specified options + */ + static createChatModel(options = {}) { + const providerName = options.provider || 'anthropic'; + const provider = this.getProvider(providerName, options.apiKey); + if (!provider.isConfigured()) { + throw new Error(`Provider ${providerName} is not configured. Please set the API key.`); + } + const config = { + model: options.model, + temperature: options.temperature, + maxTokens: options.maxTokens, + }; + return provider.getChatModel(config); + } + /** + * Get the default model for a provider + */ + static getDefaultModel(providerName) { + const provider = this.getProvider(providerName); + return provider.getDefaultModel(); + } + /** + * Check if a provider is configured + */ + static isProviderConfigured(providerName) { try { - app.log.info('Getting PR diffs'); - const diff = await getPRDiffs(context); - if (!apiKey) { - throw new Error('AI provider API key is not set (ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY)'); - } - // Use LangChain agent for intelligent analysis - app.log.info(`Running LangChain agent analysis with ${provider}...`); - const agent = new PRAnalyzerAgent({ - provider: provider, - apiKey, - model, - }); - const result = await agent.analyze(diff, pr.title); - // Format the analysis for GitHub comment - const summary = formatAnalysisForGitHub(result); - await context.octokit.issues.createComment({ - owner: repository.owner.login, - repo: repository.name, - issue_number: pr.number, - body: `## 🤖 AI Analysis (LangChain Agent)\n\n${summary}` - }); - app.log.info(`Analysis posted for PR #${pr.number}`); + const provider = this.getProvider(providerName); + return provider.isConfigured(); } - catch (error) { - app.log.error('Error analyzing PR:', error); + catch { + return false; + } + } + /** + * Normalize provider name (handle aliases) + */ + static normalizeProviderName(name) { + const normalized = name.toLowerCase(); + if (normalized === 'claude') + return 'anthropic'; + if (normalized === 'gemini') + return 'google'; + return normalized; + } + /** + * Get list of available providers + */ + static getAvailableProviders() { + return ['anthropic', 'openai', 'google']; + } +} + +;// CONCATENATED MODULE: ./src/providers/index.ts + + + + + + +;// CONCATENATED MODULE: ./src/agents/pr-analyzer-agent.ts +/** + * PR Analyzer Agent + * LangChain-based agent for intelligent PR analysis + */ + + + + + +/** + * PR Analysis Agent using LangChain and LangGraph + */ +class PRAnalyzerAgent extends BasePRAgentWorkflow { + constructor(options = {}) { + const model = ProviderFactory.createChatModel({ + provider: options.provider || 'anthropic', + apiKey: options.apiKey, + model: options.model, + temperature: options.temperature ?? 0.2, + maxTokens: options.maxTokens ?? 4000, + }); + super(model); + } + /** + * Get agent metadata + */ + getMetadata() { + return { + name: 'pr-analyzer', + version: '1.0.0', + description: 'AI-powered pull request analyzer using LangChain agent workflow', + capabilities: [ + 'file-level analysis', + 'risk detection', + 'complexity scoring', + 'intelligent recommendations', + 'self-refinement workflow', + ], + }; + } + /** + * Analyze a PR with full agent workflow + */ + async analyze(diff, title, mode, options) { + // Parse diff into files + const files = parseDiff(diff); + // Build arch-docs context if enabled + let archDocsContext = undefined; + if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) { + const docs = parseAllArchDocs(options?.repoPath); + archDocsContext = buildArchDocsContext(docs, { title, files, diff }); + } + // Create context + const context = { + diff, + title, + files, + tokenBudget: 100000, + maxCost: 5.0, + mode: mode || { summary: true, risks: true, complexity: true }, + archDocs: archDocsContext, + }; + // Execute workflow + const result = await this.execute(context, { + skipSelfRefinement: files.length < 5 || diff.length < 10000, // Skip for small PRs + }); + return result; + } + /** + * Quick analysis without refinement + */ + async quickAnalyze(diff, title, options) { + const files = parseDiff(diff); + // Build arch-docs context if enabled + let archDocsContext = undefined; + if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) { + const docs = parseAllArchDocs(options?.repoPath); + archDocsContext = buildArchDocsContext(docs, { title, files, diff }); } + const context = { + diff, + title, + files, + tokenBudget: 50000, + maxCost: 2.0, + mode: { summary: true, risks: true, complexity: true }, + archDocs: archDocsContext, + }; + return this.execute(context, { + skipSelfRefinement: true, + }); + } + /** + * Analyze specific files only + */ + async analyzeFiles(diff, filePaths, options) { + const allFiles = parseDiff(diff); + const files = allFiles.filter(f => filePaths.includes(f.path)); + // Build arch-docs context if enabled + let archDocsContext = undefined; + if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) { + const docs = parseAllArchDocs(options?.repoPath); + archDocsContext = buildArchDocsContext(docs, { files, diff }); + } + const context = { + diff, + files, + tokenBudget: 50000, + maxCost: 2.0, + mode: { summary: true, risks: true, complexity: true }, + archDocs: archDocsContext, + }; + return this.execute(context, { + skipSelfRefinement: true, + }); + } + /** + * Check if agent can execute with given context + */ + async canExecute(context) { + return context.files.length > 0 && context.diff.length > 0; + } + /** + * Estimate tokens for this analysis + */ + async estimateTokens(context) { + const baseTokens = 2000; + const diffTokens = Math.ceil(context.diff.length / 4); // ~4 chars per token + const filesTokens = context.files.length * 100; + return baseTokens + diffTokens + filesTokens; + } +} +/** + * Factory function to create PR analyzer agent + */ +function createPRAnalyzerAgent(options = {}) { + return new PRAnalyzerAgent(options); +} +/** + * Legacy factory function for backward compatibility + * @deprecated Use PRAnalyzerAgent constructor with ProviderOptions instead + */ +function createPRAnalyzerAgentLegacy(apiKey, modelName) { + return new PRAnalyzerAgent({ + apiKey, + model: modelName, + provider: 'anthropic' }); - // TODO: Re-implement code suggestions using the new agent's code suggestion tool - // The old code suggestion implementation has been removed - // To implement this feature: - // 1. Use the agent's createCodeSuggestionTool() from tools/pr-analysis-tools.ts - // 2. Call the agent with the tool to generate code fixes based on reviewer comments - // - // app.on(['pull_request_review_comment.created', 'pull_request_review_comment.edited'], async (context) => { - // // Implementation goes here - // }); -}; -async function getPRDiffs(context) { +} + +;// CONCATENATED MODULE: ./src/action.ts + + + +async function run() { + try { + // Get provider configuration from environment + const provider = (process.env.AI_PROVIDER || 'anthropic').toLowerCase(); + const apiKey = process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY || process.env.GOOGLE_API_KEY; + const model = process.env.AI_MODEL; + const ghToken = process.env.GITHUB_TOKEN; + if (!apiKey) { + core.setFailed('AI provider API key is required (ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY)'); + return; + } + if (!ghToken) { + core.setFailed('GITHUB_TOKEN environment variable is required'); + return; + } + core.info(`Using AI provider: ${provider}${model ? ` with model: ${model}` : ''}`); + const { context } = github; + const { pull_request: pr, repository } = context.payload; + if (!pr) { + core.setFailed('This action can only be run on pull request events'); + return; + } + core.info(`Analyzing PR #${pr.number} in ${repository?.full_name}`); + // Get PR diffs + const diff = await getPRDiffs(context, ghToken); + if (!diff) { + core.warning('No changes found in the pull request'); + return; + } + core.info(`Diff size: ${diff.length} characters`); + if (!repository) { + core.setFailed('Repository information not available'); + return; + } + // Use LangChain PRAnalyzerAgent + core.info('Running LangChain agent analysis...'); + const agent = new PRAnalyzerAgent({ + provider, + apiKey, + model, + }); + // Analyze with the LangChain agent + core.info('Parsing diff and analyzing...'); + const result = await agent.analyze(diff, pr.title); + core.info(`Analysis complete: ${result.fileAnalyses.size} files analyzed`); + // Format the summary + let summary = ''; + if (result.summary) { + summary += `### Summary\n${result.summary}\n\n`; + } + if (result.overallRisks.length > 0) { + summary += `### Potential Risks\n`; + result.overallRisks.forEach((risk) => { + if (typeof risk === 'string') { + summary += `- ${risk}\n`; + } + else if (typeof risk === 'object' && risk.description) { + summary += `- **${risk.description}**\n`; + if (risk.archDocsReference) { + summary += ` - 📚 *From ${risk.archDocsReference.source}*: "${risk.archDocsReference.excerpt}"\n`; + summary += ` - *Reason*: ${risk.archDocsReference.reason}\n`; + } + } + }); + summary += '\n'; + } + else { + summary += `### Potential Risks\nNone\n\n`; + } + summary += `### Complexity: ${result.overallComplexity}/5\n`; + if (result.recommendations && result.recommendations.length > 0) { + summary += `\n### Recommendations\n`; + result.recommendations.forEach((rec) => { + summary += `- ${rec}\n`; + }); + } + // Post comment + await postComment(pr.number, summary, repository, ghToken); + core.info('Analysis complete!'); + } + catch (error) { + core.setFailed(`Action failed with error: ${error}`); + } +} +async function getPRDiffs(context, ghToken) { try { const { pull_request: pr, repository } = context.payload; - const { data: files } = await context.octokit.pulls.listFiles({ + const octokit = github.getOctokit(ghToken); + const { data: files } = await octokit.rest.pulls.listFiles({ owner: repository.owner.login, repo: repository.name, pull_number: pr.number }); - const diff = files.map((f) => `--- ${f.filename}\n${f.patch}`).join('\n'); - return diff; + // Format as proper git diff that parseDiff expects + return files.map((f) => { + const status = f.status === 'added' ? 'new file mode 100644' : + f.status === 'removed' ? 'deleted file mode 100644' : ''; + const patch = f.patch || ''; + return `diff --git a/${f.filename} b/${f.filename} +${status ? status + '\n' : ''}--- ${f.status === 'added' ? '/dev/null' : 'a/' + f.filename} ++++ ${f.status === 'removed' ? '/dev/null' : 'b/' + f.filename} +${patch}`; + }).join('\n'); } catch (error) { - console.error('Error fetching PR diff:', error); + core.error('Error fetching PR diff:'); + core.error(String(error)); throw new Error('Failed to fetch PR diff'); } } -//# sourceMappingURL=index.js.map \ No newline at end of file +async function postComment(prNumber, summary, repository, ghToken) { + try { + const octokit = github.getOctokit(ghToken); + await octokit.rest.issues.createComment({ + owner: repository.owner.login, + repo: repository.name, + issue_number: prNumber, + body: `## 🤖 AI Analysis (PR Agent by TechDebtGPT)\n\n${summary}` + }); + } + catch (error) { + core.error('Error posting comment:'); + core.error(String(error)); + throw new Error('Failed to post comment'); + } +} +run(); + diff --git a/dist/types/issue-tracker.types.d.ts b/dist/types/issue-tracker.types.d.ts new file mode 100644 index 0000000..6f87aeb --- /dev/null +++ b/dist/types/issue-tracker.types.d.ts @@ -0,0 +1,138 @@ +/** + * Generic Issue Tracker Provider Interface + * + * This abstraction allows PR Agent to work with different issue tracking systems + * (Jira, Linear, Azure DevOps, GitHub Issues, etc.) through a unified interface. + * + * MVP: Jira implementation via Atlassian MCP + * Future: Linear, Azure DevOps, GitHub Issues, etc. + */ +/** + * Normalized ticket/issue representation across all providers + */ +export interface IssueTicket { + id: string; + key: string; + url: string; + title: string; + description: string; + type: IssueType; + status: string; + priority: IssuePriority; + assignee?: string; + reporter?: string; + labels: string[]; + components: string[]; + project?: string; + storyPoints?: number; + estimate?: string; + acceptanceCriteria?: string; + acceptanceCriteriaList?: string[]; + testScenarios?: string[]; + linkedTestCases?: string[]; + hasScreenshots: boolean; + hasDiagrams: boolean; + attachmentCount: number; + parentKey?: string; + epicKey?: string; + linkedIssues: LinkedIssue[]; + subtasks: SubtaskInfo[]; + createdAt: string; + updatedAt: string; + rawData?: Record; +} +export type IssueType = 'bug' | 'feature' | 'story' | 'task' | 'epic' | 'subtask' | 'improvement' | 'spike' | 'other'; +export type IssuePriority = 'critical' | 'high' | 'medium' | 'low' | 'none'; +export interface LinkedIssue { + key: string; + type: string; + title: string; + status: string; +} +export interface SubtaskInfo { + key: string; + title: string; + status: string; +} +/** + * Reference to a ticket found in PR metadata + */ +export interface TicketReference { + key: string; + source: 'title' | 'description' | 'branch' | 'commit' | 'manual'; + rawMatch: string; + confidence: number; +} +/** + * Issue tracker provider interface - implement this for each provider + */ +export interface IssueTrackerProvider { + /** + * Provider name for display and configuration + */ + readonly name: string; + /** + * Provider type identifier + */ + readonly type: IssueTrackerType; + /** + * Check if the provider is properly configured and accessible + */ + isConfigured(): boolean; + /** + * Test connection to the provider + */ + testConnection(): Promise; + /** + * Fetch a single ticket by key + */ + getTicket(key: string): Promise; + /** + * Fetch multiple tickets by keys + */ + getTickets(keys: string[]): Promise; + /** + * Extract ticket references from PR metadata + */ + extractTicketReferences(context: TicketExtractionContext): TicketReference[]; + /** + * Search for tickets matching a query + */ + searchTickets?(query: string, limit?: number): Promise; + /** + * Get ticket comments (if supported) + */ + getComments?(ticketKey: string): Promise; +} +export type IssueTrackerType = 'jira' | 'linear' | 'azure-devops' | 'github-issues' | 'gitlab-issues' | 'shortcut' | 'asana' | 'other'; +export interface TicketExtractionContext { + prTitle: string; + prDescription?: string; + branchName?: string; + commitMessages?: string[]; +} +export interface IssueComment { + id: string; + author: string; + body: string; + createdAt: string; +} +/** + * Configuration for issue tracker integration + */ +export interface IssueTrackerConfig { + enabled: boolean; + provider: IssueTrackerType; + providerConfig: Record; + analyzeAcceptanceCriteria: boolean; + rateTicketQuality: boolean; + generateTestSuggestions: boolean; + checkScopeCreep: boolean; + ticketPatterns?: string[]; + includeTicketDetails: boolean; + verbose: boolean; +} +/** + * Factory function type for creating providers + */ +export type IssueTrackerProviderFactory = (config: IssueTrackerConfig) => IssueTrackerProvider | null; diff --git a/dist/types/issue-tracker.types.js b/dist/types/issue-tracker.types.js new file mode 100644 index 0000000..5e61f2a --- /dev/null +++ b/dist/types/issue-tracker.types.js @@ -0,0 +1,11 @@ +/** + * Generic Issue Tracker Provider Interface + * + * This abstraction allows PR Agent to work with different issue tracking systems + * (Jira, Linear, Azure DevOps, GitHub Issues, etc.) through a unified interface. + * + * MVP: Jira implementation via Atlassian MCP + * Future: Linear, Azure DevOps, GitHub Issues, etc. + */ +export {}; +//# sourceMappingURL=issue-tracker.types.js.map \ No newline at end of file diff --git a/dist/types/issue-tracker.types.js.map b/dist/types/issue-tracker.types.js.map new file mode 100644 index 0000000..51d6878 --- /dev/null +++ b/dist/types/issue-tracker.types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"issue-tracker.types.js","sourceRoot":"","sources":["../../src/types/issue-tracker.types.ts"],"names":[],"mappings":"AAAA;;;;;;;;GAQG"} \ No newline at end of file diff --git a/dist/types/jira.types.d.ts b/dist/types/jira.types.d.ts new file mode 100644 index 0000000..356236e --- /dev/null +++ b/dist/types/jira.types.d.ts @@ -0,0 +1,211 @@ +/** + * Jira types and interfaces for Peer Review Agent + * Provides structures for Jira ticket analysis and acceptance criteria validation + */ +/** + * Jira ticket from the Atlassian API/MCP + */ +export interface JiraTicket { + key: string; + id: string; + summary: string; + description: string; + status: string; + type: JiraTicketType; + priority: string; + assignee?: string; + reporter?: string; + labels: string[]; + components: string[]; + fixVersions: string[]; + storyPoints?: number; + createdAt: string; + updatedAt: string; + acceptanceCriteria?: string; + acceptanceCriteriaItems?: AcceptanceCriteriaItem[]; + testScenarios?: string[]; + testCases?: string[]; + attachments?: JiraAttachment[]; + linkedIssues?: JiraLinkedIssue[]; + comments?: JiraComment[]; + subtasks?: JiraSubtask[]; + parentKey?: string; + epicKey?: string; + customFields?: Record; +} +export type JiraTicketType = 'bug' | 'feature' | 'task' | 'story' | 'epic' | 'subtask' | 'improvement' | 'other'; +export interface AcceptanceCriteriaItem { + id: string; + text: string; + isMet?: boolean; + coverageDetails?: string; + relatedFiles?: string[]; + confidence: number; +} +export interface JiraAttachment { + id: string; + filename: string; + mimeType: string; + url: string; + createdAt: string; + isScreenshot: boolean; +} +export interface JiraLinkedIssue { + key: string; + type: string; + summary: string; + status: string; +} +export interface JiraComment { + id: string; + author: string; + body: string; + createdAt: string; +} +export interface JiraSubtask { + key: string; + summary: string; + status: string; +} +/** + * Ticket quality rating based on best practices + */ +export interface TicketQualityRating { + overallScore: number; + dimensions: { + descriptionClarity: number; + acceptanceCriteriaQuality: number; + testabilityScore: number; + scopeDefinition: number; + technicalContext: number; + visualDocumentation: number; + estimationQuality: number; + completeness: number; + }; + feedback: { + strengths: string[]; + weaknesses: string[]; + suggestions: string[]; + }; + tier: 'excellent' | 'good' | 'adequate' | 'poor' | 'insufficient'; + reviewable: boolean; + reviewabilityReason: string; +} +/** + * Result of acceptance criteria validation against PR changes + */ +export interface AcceptanceCriteriaValidation { + ticketKey: string; + totalCriteria: number; + metCriteria: number; + unmetCriteria: number; + partialCriteria: number; + criteriaAnalysis: CriteriaAnalysisItem[]; + compliancePercentage: number; + gaps: AcceptanceCriteriaGap[]; + suggestedTestScenarios: TestScenarioSuggestion[]; +} +export interface CriteriaAnalysisItem { + criteriaId: string; + criteriaText: string; + status: 'met' | 'unmet' | 'partial' | 'unclear'; + confidence: number; + evidence: string[]; + explanation: string; + relatedFiles: string[]; +} +export interface AcceptanceCriteriaGap { + criteriaText: string; + gapDescription: string; + severity: 'critical' | 'major' | 'minor'; + suggestedAction: string; +} +export interface TestScenarioSuggestion { + scenario: string; + type: 'unit' | 'integration' | 'e2e' | 'manual'; + priority: 'high' | 'medium' | 'low'; + relatedCriteria: string[]; + suggestedApproach: string; +} +/** + * Complete Jira analysis result for a PR + */ +export interface JiraAnalysisResult { + linkedTickets: JiraTicket[]; + primaryTicket?: JiraTicket; + ticketQuality?: TicketQualityRating; + acValidation?: AcceptanceCriteriaValidation; + scopeAnalysis: { + inScope: string[]; + outOfScope: string[]; + scopeCreepRisk: boolean; + scopeCreepDetails?: string; + }; + edgeCaseAnalysis: { + identifiedEdgeCases: string[]; + coveredEdgeCases: string[]; + uncoveredEdgeCases: string[]; + testSuggestions: TestScenarioSuggestion[]; + }; + overallAssessment: { + implementationCompleteness: number; + qualityScore: number; + readyForReview: boolean; + blockers: string[]; + warnings: string[]; + recommendations: string[]; + }; + metrics: { + ticketsCovered: number; + criteriaTotal: number; + criteriaMet: number; + criteriaPartial: number; + criteriaUnmet: number; + testScenariosGenerated: number; + }; +} +/** + * Configuration for Jira integration + */ +export interface JiraConfig { + enabled: boolean; + mcpServerUrl?: string; + instanceUrl?: string; + projectKey?: string; + apiToken?: string; + email?: string; + analyzeAcceptanceCriteria: boolean; + rateTicketQuality: boolean; + generateTestSuggestions: boolean; + checkScopeCreep: boolean; + includeTicketDetailsInOutput: boolean; + verboseOutput: boolean; +} +/** + * Ticket reference extracted from PR title/description/branch + */ +export interface TicketReference { + key: string; + source: 'title' | 'description' | 'branch' | 'commit'; + confidence: number; +} +/** + * Context passed to Jira sub-agent + */ +export interface JiraAnalysisContext { + prTitle: string; + prDescription?: string; + branchName?: string; + commitMessages?: string[]; + diff: string; + files: Array<{ + path: string; + additions: number; + deletions: number; + status: string; + }>; + prSummary?: string; + prRisks?: string[]; + prComplexity?: number; + config: JiraConfig; +} diff --git a/dist/types/jira.types.js b/dist/types/jira.types.js new file mode 100644 index 0000000..edce57c --- /dev/null +++ b/dist/types/jira.types.js @@ -0,0 +1,6 @@ +/** + * Jira types and interfaces for Peer Review Agent + * Provides structures for Jira ticket analysis and acceptance criteria validation + */ +export {}; +//# sourceMappingURL=jira.types.js.map \ No newline at end of file diff --git a/dist/types/jira.types.js.map b/dist/types/jira.types.js.map new file mode 100644 index 0000000..961155b --- /dev/null +++ b/dist/types/jira.types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"jira.types.js","sourceRoot":"","sources":["../../src/types/jira.types.ts"],"names":[],"mappings":"AAAA;;;GAGG"} \ No newline at end of file diff --git a/src/agents/jira-sub-agent.ts b/src/agents/jira-sub-agent.ts index d72596b..0dfae6f 100644 --- a/src/agents/jira-sub-agent.ts +++ b/src/agents/jira-sub-agent.ts @@ -17,7 +17,7 @@ */ import { ChatPromptTemplate } from '@langchain/core/prompts'; -import { StructuredOutputParser } from 'langchain/output_parsers'; +import { StructuredOutputParser } from '@langchain/core/output_parsers'; import { z } from 'zod'; import { IssueTicket } from '../types/issue-tracker.types.js'; import { BaseLanguageModel } from '@langchain/core/language_models/base'; diff --git a/src/cli/commands/analyze.command.ts b/src/cli/commands/analyze.command.ts index 0a26cb7..ddb6c51 100644 --- a/src/cli/commands/analyze.command.ts +++ b/src/cli/commands/analyze.command.ts @@ -12,6 +12,7 @@ import { formatPeerReviewOutput, type PeerReviewResult, } from '../../issue-tracker/index.js'; +import { ProviderFactory, type SupportedProvider } from '../../providers/index.js'; interface AnalyzeOptions { diff?: string; @@ -267,15 +268,16 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { } throw error; } - + // Get provider and API key from config or environment if (options.verbose) { console.log(chalk.gray(` Debug: options.provider: ${options.provider || 'undefined'}`)); console.log(chalk.gray(` Debug: config.ai?.provider: ${config.ai?.provider || 'undefined'}`)); } - const provider = (options.provider || config.ai?.provider || 'anthropic').toLowerCase() as 'anthropic' | 'openai' | 'google'; + const provider = (options.provider || config.ai?.provider || 'anthropic').toLowerCase() as SupportedProvider; const apiKey = getApiKey(provider, config); - + const model = options.model || config.ai?.model; + if (!apiKey) { spinner.fail('No API key found'); console.error(chalk.yellow('💡 Please set it in one of these ways:')); @@ -286,7 +288,7 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { console.error(chalk.gray(' - Google (Gemini): export GOOGLE_API_KEY="your-api-key"')); process.exit(1); } - + spinner.succeed(`Using AI provider: ${provider}`); // Resolve default branch if needed @@ -299,13 +301,13 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { githubToken: process.env.GITHUB_TOKEN, fallbackToGit: true, }); - + defaultBranch = branchResult.branch; - + if (branchResult.warning && options.verbose) { console.log(chalk.yellow(`\n⚠️ ${branchResult.warning}`)); } - + if (options.verbose) { console.log(chalk.gray(` Using branch: ${defaultBranch} (source: ${branchResult.source})`)); } @@ -396,16 +398,15 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { // Check for arch-docs const useArchDocs = options.archDocs !== false; // Default to true if not specified const hasArchDocs = archDocsExists(); - + if (useArchDocs && hasArchDocs) { console.log(chalk.cyan('📚 Architecture documentation detected - including in analysis\n')); } else if (options.archDocs && !hasArchDocs) { console.log(chalk.yellow('⚠️ --arch-docs flag specified but no .arch-docs folder found\n')); } - const model = options.model || config.ai?.model; const agent = new PRAnalyzerAgent({ - provider: provider as any, + provider: provider, apiKey, model, }); @@ -420,11 +421,16 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { // Run Peer Review if enabled (via flag or config) const peerReviewEnabled = options.peerReview || config.peerReview?.enabled; if (peerReviewEnabled) { - await runPeerReview(config, diff, title, result, options.verbose || false); + // Pass the same provider config to peer review so it uses the same LLM + await runPeerReview(config, diff, title, result, options.verbose || false, { + provider, + apiKey, + model, + }); } } catch (error: any) { spinner.fail('Analysis failed'); - + // Handle specific error types with user-friendly messages if (error instanceof ConfigurationError) { console.error(chalk.red(`\n❌ Configuration Error: ${error.message}`)); @@ -453,7 +459,7 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { .replace(/sk-[a-zA-Z0-9_-]+/g, 'sk-***') .replace(/ghp_[a-zA-Z0-9]+/g, 'ghp_***') .substring(0, 500); // Limit length - + console.error(chalk.red(`\n❌ Error: ${sanitizedMessage}`)); if (options.verbose && error.stack) { console.error(chalk.gray('\nStack trace:')); @@ -591,10 +597,10 @@ function displayAgentResults(result: any, mode: AnalysisMode, verbose: boolean): if (result.archDocsImpact?.used) { console.log(chalk.gray('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━')); console.log(chalk.blue.bold('\n📚 Architecture Documentation Impact\n')); - + console.log(chalk.white(`Documents analyzed: ${result.archDocsImpact.docsAvailable}`)); console.log(chalk.white(`Relevant sections used: ${result.archDocsImpact.sectionsUsed}\n`)); - + if (result.archDocsImpact.influencedStages.length > 0) { console.log(chalk.cyan('Stages influenced by arch-docs:')); result.archDocsImpact.influencedStages.forEach((stage: string) => { @@ -607,7 +613,7 @@ function displayAgentResults(result: any, mode: AnalysisMode, verbose: boolean): }); console.log(''); } - + if (result.archDocsImpact.keyInsights.length > 0) { console.log(chalk.cyan('Key insights from arch-docs integration:\n')); result.archDocsImpact.keyInsights.forEach((insight: string, i: number) => { @@ -638,14 +644,24 @@ async function runPeerReview( diff: string, title: string | undefined, prAnalysisResult: any, - verbose: boolean + verbose: boolean, + providerOptions: { provider: SupportedProvider; apiKey: string; model?: string } ): Promise { const spinner = ora('Running Peer Review analysis...').start(); try { - // Create peer review integration from config + // Create LLM using the same provider as main analysis + const llm = ProviderFactory.createChatModel({ + provider: providerOptions.provider, + apiKey: providerOptions.apiKey, + model: providerOptions.model, + temperature: 0.2, + maxTokens: 4000, + }); + + // Create peer review integration from config, passing the LLM const peerReviewConfig = config.peerReview || {}; - const integration = createPeerReviewIntegration(peerReviewConfig); + const integration = createPeerReviewIntegration(peerReviewConfig, llm); if (!integration.isEnabled()) { spinner.warn('Peer Review enabled but not configured. Add Jira settings to config.'); diff --git a/src/issue-tracker/jira-mcp-client.ts b/src/issue-tracker/jira-mcp-client.ts index 89302f4..a332cc1 100644 --- a/src/issue-tracker/jira-mcp-client.ts +++ b/src/issue-tracker/jira-mcp-client.ts @@ -195,7 +195,7 @@ export class JiraMcpClient implements IssueTrackerProvider { }); // Parse and normalize results if (Array.isArray(result)) { - return result.map((r) => this.normalizeTicket(r)); + return result.map((r) => this.normalizeTicket(r as JiraApiIssue)); } } else { // Direct JQL search @@ -204,7 +204,7 @@ export class JiraMcpClient implements IssueTrackerProvider { `/rest/api/3/search?jql=${encodeURIComponent(jql)}&maxResults=${limit}` ); if (response.ok) { - const data = await response.json(); + const data = await response.json() as { issues?: JiraApiIssue[] }; return (data.issues || []).map((issue: JiraApiIssue) => this.normalizeTicket(issue) ); @@ -225,13 +225,21 @@ export class JiraMcpClient implements IssueTrackerProvider { `/rest/api/3/issue/${ticketKey}/comment` ); if (response.ok) { - const data = await response.json(); - return (data.comments || []).map((c: JiraApiComment) => ({ - id: c.id, - author: c.author?.displayName || 'Unknown', - body: c.body?.content?.[0]?.content?.[0]?.text || c.body || '', - createdAt: c.created, - })); + const data = await response.json() as { comments?: JiraApiComment[] }; + return (data.comments || []).map((c: JiraApiComment) => { + let bodyText = ''; + if (typeof c.body === 'string') { + bodyText = c.body; + } else if (c.body && typeof c.body === 'object' && 'content' in c.body) { + bodyText = c.body.content?.[0]?.content?.[0]?.text || ''; + } + return { + id: c.id, + author: c.author?.displayName || 'Unknown', + body: bodyText, + createdAt: c.created, + }; + }); } } catch (error) { console.error(`Failed to get comments for ${ticketKey}:`, error); @@ -302,7 +310,7 @@ export class JiraMcpClient implements IssueTrackerProvider { // Direct API fetch const response = await this.fetchJiraApi(`/rest/api/3/issue/${key}?expand=renderedFields`); if (response.ok) { - return response.json(); + return response.json() as Promise; } return null; } @@ -353,6 +361,9 @@ export class JiraMcpClient implements IssueTrackerProvider { a.mimeType?.includes('svg') ); + // Extract epic key - handle custom field which may be string or undefined + const epicKey = fields.epic?.key || (fields.customfield_10014 as string | undefined); + return { id: raw.id, key: raw.key, @@ -376,12 +387,12 @@ export class JiraMcpClient implements IssueTrackerProvider { hasDiagrams, attachmentCount: attachments.length, parentKey: fields.parent?.key, - epicKey: fields.epic?.key || fields.customfield_10014, // Common epic link field + epicKey, linkedIssues, subtasks, createdAt: fields.created || '', updatedAt: fields.updated || '', - rawData: raw, + rawData: raw as unknown as Record, }; } @@ -429,7 +440,14 @@ export class JiraMcpClient implements IssueTrackerProvider { if (this.config.acceptanceCriteriaField) { const customField = fields[this.config.acceptanceCriteriaField]; if (customField) { - const text = typeof customField === 'string' ? customField : this.adfToText(customField); + let text: string; + if (typeof customField === 'string') { + text = customField; + } else if (typeof customField === 'object' && customField !== null && 'type' in customField && 'version' in customField) { + text = this.adfToText(customField as JiraAdfDocument); + } else { + text = ''; + } return { text, list: this.parseAcceptanceCriteriaList(text) }; } } diff --git a/src/issue-tracker/peer-review-integration.ts b/src/issue-tracker/peer-review-integration.ts index 24808b5..65a0b71 100644 --- a/src/issue-tracker/peer-review-integration.ts +++ b/src/issue-tracker/peer-review-integration.ts @@ -188,7 +188,7 @@ export class PeerReviewIntegration { switch (this.config.provider) { case 'jira': - this.provider = new JiraMcpClient(this.config.providerConfig as JiraConfig); + this.provider = new JiraMcpClient(this.config.providerConfig as unknown as JiraConfig); break; // Future providers From 76b0ba207c261961a50d52fe7c6ea59f99a7dd1f Mon Sep 17 00:00:00 2001 From: ipanov Date: Mon, 29 Dec 2025 15:51:41 +0100 Subject: [PATCH 3/3] feat: Add Zhipu AI provider and fix peer review config validation MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Add Zhipu AI provider with Anthropic-compatible API support - Fix peerReview config being stripped by Zod validation (add schema) - Make criteriaId optional in AC validation to prevent parsing errors - Update README with comprehensive peer review documentation - Update README with Zhipu AI provider details - Add verbose debug output for peer review troubleshooting 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 --- README.md | 187 +- dist/agents/jira-sub-agent.d.ts | 2 +- dist/agents/jira-sub-agent.js | 2 +- dist/agents/jira-sub-agent.js.map | 2 +- dist/cli/commands/analyze.command.js | 10 + dist/cli/commands/analyze.command.js.map | 2 +- dist/cli/commands/help.command.js | 2 +- dist/cli/commands/help.command.js.map | 2 +- dist/cli/index.js | 2 +- dist/cli/index.js.map | 2 +- dist/cli/utils/config-loader.d.ts | 1 + dist/cli/utils/config-loader.js | 1 + dist/cli/utils/config-loader.js.map | 2 +- dist/index.js | 125011 +------------------- dist/licenses.txt | 499 +- dist/providers/index.d.ts | 1 + dist/providers/index.js | 1 + dist/providers/index.js.map | 2 +- dist/providers/provider.factory.d.ts | 2 +- dist/providers/provider.factory.js | 10 +- dist/providers/provider.factory.js.map | 2 +- dist/providers/zhipu.provider.d.ts | 16 + dist/providers/zhipu.provider.js | 34 + dist/providers/zhipu.provider.js.map | 1 + dist/types.d.ts | 2 +- dist/utils/config-validator.d.ts | 20 + dist/utils/config-validator.js | 23 +- dist/utils/config-validator.js.map | 2 +- package-lock.json | 658 +- src/agents/jira-sub-agent.ts | 2 +- src/cli/commands/analyze.command.ts | 10 + src/cli/commands/help.command.ts | 2 +- src/cli/index.ts | 2 +- src/cli/utils/config-loader.ts | 2 + src/providers/index.ts | 1 + src/providers/provider.factory.ts | 11 +- src/providers/zhipu.provider.ts | 41 + src/types.ts | 2 +- src/utils/config-validator.ts | 23 +- 39 files changed, 1252 insertions(+), 125345 deletions(-) create mode 100644 dist/providers/zhipu.provider.d.ts create mode 100644 dist/providers/zhipu.provider.js create mode 100644 dist/providers/zhipu.provider.js.map create mode 100644 src/providers/zhipu.provider.ts diff --git a/README.md b/README.md index a992feb..174b22d 100644 --- a/README.md +++ b/README.md @@ -12,14 +12,16 @@ PR Agent analyzes your code changes and provides: - **Complexity Rating**: A 1-5 scale rating of complexity with file-level breakdown - **Actionable Insights**: Specific recommendations based on your codebase - **Architecture-Aware Analysis**: Leverages your `.arch-docs` for context-aware reviews +- **Peer Review Integration**: Validates PRs against linked Jira tickets and acceptance criteria ## Features -✨ **Intelligent Agent Mode** - Automatically handles large diffs without chunking -🏗️ **Architecture Documentation Integration** - Uses `.arch-docs` for smarter analysis -🔌 **Multiple AI Providers** - Anthropic Claude, OpenAI GPT, Google Gemini -🖥️ **CLI & GitHub Action** - Use locally or in CI/CD pipelines -📊 **File-Level Analysis** - Individual risk and complexity scores per file +✨ **Intelligent Agent Mode** - Automatically handles large diffs without chunking +🏗️ **Architecture Documentation Integration** - Uses `.arch-docs` for smarter analysis +🔌 **Multiple AI Providers** - Anthropic Claude, OpenAI GPT, Google Gemini, Zhipu AI +🖥️ **CLI & GitHub Action** - Use locally or in CI/CD pipelines +📊 **File-Level Analysis** - Individual risk and complexity scores per file +🎫 **Peer Review Integration** - Validates against Jira tickets and acceptance criteria ⚙️ **Configurable** - Customize models, providers, and analysis modes ## Quick Reference @@ -54,6 +56,7 @@ pr-agent help # Show help - [Analyze Command](#analyze-command) - [Configuration](#configuration) - [Architecture Documentation Integration](#architecture-documentation-integration) +- [Peer Review Integration](#peer-review-integration) - [GitHub Action Usage](#github-action-usage) - [Supported AI Models](#supported-ai-models) - [Common Use Cases](#common-use-cases) @@ -70,6 +73,7 @@ Before using PR Agent, you'll need: - **Anthropic Claude**: Sign up at [Anthropic Console](https://console.anthropic.com/) (Recommended) - **OpenAI GPT**: Get your key from [OpenAI Platform](https://platform.openai.com/) - **Google Gemini**: Get your key from [Google AI Studio](https://makersuite.google.com/) + - **Zhipu AI**: Get your key from [Zhipu AI Platform](https://open.bigmodel.cn/) (Anthropic-compatible API) 2. **For GitHub Action**: Repository with permissions to add workflows and secrets @@ -168,6 +172,7 @@ pr-agent analyze --complexity pr-agent analyze --provider anthropic pr-agent analyze --provider openai pr-agent analyze --provider google +pr-agent analyze --provider zhipu # Use specific model pr-agent analyze --provider anthropic --model claude-sonnet-4-5-20250929 @@ -236,7 +241,8 @@ pr-agent config --reset "apiKeys": { "anthropic": "sk-ant-...", "openai": "", - "google": "" + "google": "", + "zhipu": "" }, "analysis": { "defaultMode": "full", @@ -257,6 +263,14 @@ pr-agent config --reset "verbose": false, "showStrategy": true, "showRecommendations": true + }, + "peerReview": { + "enabled": false, + "provider": "jira", + "instanceUrl": "https://your-company.atlassian.net", + "email": "your-email@company.com", + "apiToken": "your-jira-api-token", + "defaultProject": "PROJ" } } ``` @@ -274,6 +288,9 @@ export OPENAI_API_KEY="sk-..." # Google Gemini export GOOGLE_API_KEY="..." + +# Zhipu AI +export ZHIPU_API_KEY="..." ``` Add to your `.bashrc`, `.zshrc`, or `.env` file for persistence. @@ -398,12 +415,151 @@ Key insights from arch-docs integration: ### Benefits of Arch-Docs Integration -✅ **Context-Aware Analysis** - AI understands your specific architecture -✅ **Pattern Enforcement** - Detects violations of documented patterns -✅ **Security Alignment** - Checks against your security guidelines -✅ **Consistency** - Ensures PRs follow established conventions +✅ **Context-Aware Analysis** - AI understands your specific architecture +✅ **Pattern Enforcement** - Detects violations of documented patterns +✅ **Security Alignment** - Checks against your security guidelines +✅ **Consistency** - Ensures PRs follow established conventions ✅ **Better Recommendations** - Suggestions aligned with your architecture +## Peer Review Integration + +PR Agent can integrate with Jira to provide intelligent peer review analysis that validates your PR against linked tickets and acceptance criteria. + +### Overview + +When enabled, the peer review feature acts like a **senior developer reviewing your PR**: + +- **Extracts ticket references** from PR title, branch name, or commit messages +- **Fetches ticket details** from Jira (description, acceptance criteria, story points) +- **Rates ticket quality** to identify poorly-defined requirements +- **Validates implementation** against derived requirements +- **Provides verdict** with blockers, warnings, and recommendations + +### Setup + +1. **Configure Jira credentials** in `.pragent.config.json`: + +```json +{ + "peerReview": { + "enabled": true, + "provider": "jira", + "instanceUrl": "https://your-company.atlassian.net", + "email": "your-email@company.com", + "apiToken": "your-jira-api-token", + "defaultProject": "PROJ", + "analyzeAcceptanceCriteria": true, + "rateTicketQuality": true, + "checkScopeCreep": true + } +} +``` + +2. **Get a Jira API Token**: + - Go to [Atlassian Account Settings](https://id.atlassian.com/manage-profile/security/api-tokens) + - Click "Create API token" + - Copy the token to your config + +3. **Reference tickets in your PR**: + - PR title: `feat(PROJ-123): Add new feature` + - Branch name: `feature/PROJ-123-add-feature` + - Commit message: `PROJ-123: implement feature` + +### Usage + +```bash +# Run analysis with peer review +pr-agent analyze + +# The peer review runs automatically if enabled in config +# Or enable it for a single run: +pr-agent analyze --peer-review +``` + +### Example Output + +``` +═══════════════════════════════════════════════════════════════ + 🔍 PEER REVIEW ANALYSIS +═══════════════════════════════════════════════════════════════ + +📋 LINKED TICKET +─────────────────────────────────────────────────────────────── + Key: PROJ-123 + Title: Add user authentication + Type: STORY + Status: In Progress + Points: 5 + +📊 TICKET QUALITY RATING +─────────────────────────────────────────────────────────────── + Overall Score: 🟢 85/100 (GOOD) + + Dimension Scores: + • Description Clarity: 🟢 ████████░░ 85 + • Acceptance Criteria: 🟢 █████████░ 90 + • Testability: 🟡 ███████░░░ 75 + • Scope Definition: 🟢 ████████░░ 80 + +✅ REQUIREMENTS VALIDATION +─────────────────────────────────────────────────────────────── + Compliance: 🟢 92% + + 📊 REQUIREMENT STATUS: + ✅ Implement login endpoint with JWT tokens + ✅ Add password validation (min 8 chars) + 🟡 Create logout endpoint + └─ Endpoint exists but doesn't invalidate tokens + ✅ Store hashed passwords in database + + ❌ COVERAGE GAPS: + 🟡 [MINOR] Token invalidation not implemented + └─ Impact: Users cannot fully logout, tokens remain valid + +🎯 PEER REVIEW VERDICT +─────────────────────────────────────────────────────────────── + ✅ APPROVED (Confidence: 85%) + + The PR implements the core authentication functionality as specified. + Minor gaps in token invalidation should be addressed in a follow-up. + + Scores: + • Implementation Completeness: 🟢 ████████░░ 88 + • Quality Score: 🟢 ████████░░ 82 + + 💡 RECOMMENDATIONS: + • Add token invalidation on logout + • Consider adding rate limiting + • Add integration tests for auth flow + +═══════════════════════════════════════════════════════════════ +``` + +### Configuration Options + +| Option | Type | Default | Description | +|--------|------|---------|-------------| +| `enabled` | boolean | `false` | Enable peer review integration | +| `provider` | string | `"jira"` | Issue tracker provider (currently only Jira) | +| `instanceUrl` | string | - | Your Jira instance URL | +| `email` | string | - | Your Jira account email | +| `apiToken` | string | - | Jira API token | +| `defaultProject` | string | - | Default project key for ticket extraction | +| `analyzeAcceptanceCriteria` | boolean | `true` | Validate against acceptance criteria | +| `rateTicketQuality` | boolean | `true` | Rate ticket definition quality | +| `generateTestSuggestions` | boolean | `true` | Generate test suggestions | +| `checkScopeCreep` | boolean | `true` | Detect scope creep in PRs | +| `includeTicketDetails` | boolean | `true` | Show ticket details in output | +| `verbose` | boolean | `false` | Enable verbose output | + +### Benefits + +✅ **Requirement Validation** - Ensures PRs implement what the ticket specifies +✅ **Quality Gate** - Catches incomplete implementations before review +✅ **Ticket Quality Feedback** - Identifies poorly-defined requirements +✅ **Scope Creep Detection** - Flags changes outside ticket scope +✅ **Senior Developer Perspective** - Catches edge cases and missing behaviors + ## GitHub Action Usage ### Setup Instructions @@ -629,7 +785,11 @@ pr-agent/ │ │ ├── anthropic.provider.ts │ │ ├── openai.provider.ts │ │ ├── google.provider.ts +│ │ ├── zhipu.provider.ts │ │ └── factory.ts +│ ├── issue-tracker/ # Issue tracker integrations +│ │ ├── jira-mcp-client.ts # Jira API client +│ │ └── peer-review-integration.ts │ ├── tools/ # Agent tools │ │ ├── pr-analysis-tools.ts │ │ └── index.ts @@ -818,6 +978,13 @@ Best for: Quick analysis and cost-conscious usage Best for: Alternative to Claude/GPT with competitive performance +### Zhipu AI + +- **claude-sonnet-4-20250514** - Via Anthropic-compatible API +- **glm-4** - Zhipu's native model + +Best for: Users in China or those preferring Zhipu's platform with Claude-compatible models + ## Common Use Cases ### 1. Pre-Commit Review diff --git a/dist/agents/jira-sub-agent.d.ts b/dist/agents/jira-sub-agent.d.ts index c8d12e0..7d65ff1 100644 --- a/dist/agents/jira-sub-agent.d.ts +++ b/dist/agents/jira-sub-agent.d.ts @@ -74,7 +74,7 @@ declare const AcceptanceCriteriaValidationSchema: z.ZodObject<{ }>; }, z.core.$strip>>; criteriaAnalysis: z.ZodArray; criteriaText: z.ZodString; status: z.ZodEnum<{ met: "met"; diff --git a/dist/agents/jira-sub-agent.js b/dist/agents/jira-sub-agent.js index a851f1b..d1f3a6e 100644 --- a/dist/agents/jira-sub-agent.js +++ b/dist/agents/jira-sub-agent.js @@ -62,7 +62,7 @@ const AcceptanceCriteriaValidationSchema = z.object({ })).describe('Requirements derived by analyzing the full ticket, not just AC field'), // Analysis of each derived requirement against the PR criteriaAnalysis: z.array(z.object({ - criteriaId: z.string(), + criteriaId: z.string().optional(), criteriaText: z.string(), status: z.enum(['met', 'unmet', 'partial', 'unclear']), confidence: z.number().min(0).max(100), diff --git a/dist/agents/jira-sub-agent.js.map b/dist/agents/jira-sub-agent.js.map index 15e2e5d..628a181 100644 --- a/dist/agents/jira-sub-agent.js.map +++ b/dist/agents/jira-sub-agent.js.map @@ -1 +1 @@ -{"version":3,"file":"jira-sub-agent.js","sourceRoot":"","sources":["../../src/agents/jira-sub-agent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;GAgBG;AAEH,OAAO,EAAE,kBAAkB,EAAE,MAAM,yBAAyB,CAAC;AAC7D,OAAO,EAAE,sBAAsB,EAAE,MAAM,gCAAgC,CAAC;AACxE,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AAIxB,uCAAuC;AAEvC,MAAM,mBAAmB,GAAG,CAAC,CAAC,MAAM,CAAC;IACnC,YAAY,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC,QAAQ,CAAC,8BAA8B,CAAC;IACjF,UAAU,EAAE,CAAC,CAAC,MAAM,CAAC;QACnB,kBAAkB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;QAC9C,yBAAyB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;QACrD,gBAAgB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;QAC5C,eAAe,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,CAAC;QAC3C,gBAAgB,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,GAAG,C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Z,IAAI,EAAE,aAAa;YACnB,SAAS,EAAE,OAAO,CAAC,SAAS,IAAI,sBAAsB;YACtD,OAAO,EAAE,OAAO,CAAC,OAAO,EAAE,IAAI,CAAC,IAAI,CAAC,IAAI,iBAAiB;YACzD,kBAAkB,EAAE,aAAa,CAAC,YAAY;YAC9C,YAAY,EAAE,aAAa,CAAC,UAAU,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI;YACrD,sBAAsB,EAAE,YAAY,EAAE,oBAAoB,IAAI,KAAK;YACnE,SAAS;YACT,mBAAmB,EAAE,MAAM,CAAC,qBAAqB,EAAE;SACpD,CAAC,CAAC;QAEH,MAAM,OAAO,GAAG,OAAO,QAAQ,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,QAAQ,EAAE,IAAI,EAAE,CAAC;QAC7F,OAAO,MAAM,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC;IAC/B,CAAC;CACF"} \ No newline at end of file diff --git a/dist/cli/commands/analyze.command.js b/dist/cli/commands/analyze.command.js index 7852aab..7c6a132 100644 --- a/dist/cli/commands/analyze.command.js +++ b/dist/cli/commands/analyze.command.js @@ -243,6 +243,10 @@ export async function analyzePR(options = {}) { console.error(chalk.gray(' - Anthropic (Claude): export ANTHROPIC_API_KEY="your-api-key"')); console.error(chalk.gray(' - OpenAI (GPT): export OPENAI_API_KEY="your-api-key"')); console.error(chalk.gray(' - Google (Gemini): export GOOGLE_API_KEY="your-api-key"')); + console.error(chalk.gray(' - Zhipu (GLM): export ZHIPU_API_KEY="your-api-key"')); + if (options.verbose) { + console.error(chalk.gray(` Debug: Provider=${provider}, Config apiKeys=${JSON.stringify(config.apiKeys || {})}`)); + } process.exit(1); } spinner.succeed(`Using AI provider: ${provider}`); @@ -361,6 +365,9 @@ export async function analyzePR(options = {}) { displayAgentResults(result, mode, options.verbose || false); // Run Peer Review if enabled (via flag or config) const peerReviewEnabled = options.peerReview || config.peerReview?.enabled; + if (options.verbose) { + console.log(chalk.gray(`\n Debug: peerReviewEnabled=${peerReviewEnabled}, options.peerReview=${options.peerReview}, config.peerReview?.enabled=${config.peerReview?.enabled}`)); + } if (peerReviewEnabled) { // Pass the same provider config to peer review so it uses the same LLM await runPeerReview(config, diff, title, result, options.verbose || false, { @@ -583,6 +590,9 @@ async function runPeerReview(config, diff, title, prAnalysisResult, verbose, pro spinner.warn('Peer Review enabled but not configured. Add Jira settings to config.'); console.log(chalk.gray(' Run: pr-agent config --set peerReview.instanceUrl=https://your.atlassian.net')); console.log(chalk.gray(' Or configure MCP: peerReview.useMcp=true')); + if (verbose) { + console.log(chalk.gray(` Debug: peerReviewConfig=${JSON.stringify(peerReviewConfig)}`)); + } return; } // Get branch name for ticket extraction diff --git a/dist/cli/commands/analyze.command.js.map b/dist/cli/commands/analyze.command.js.map index 068375d..2153b49 100644 --- a/dist/cli/commands/analyze.command.js.map +++ b/dist/cli/commands/analyze.command.js.map @@ -1 +1 @@ -{"version":3,"file":"analyze.command.js","sourceRoot":"","sources":["../../../src/cli/commands/analyze.command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAC;AACzC,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,GAAG,MAAM,KAAK,CAAC;AACtB,OAAO,EAAE,eAAe,EAAE,MAAM,mCAAmC,CAAC;AACpE,OAAO,EAAE,cAAc,EAAE,SAAS,EAAE,MAAM,2BAA2B,CAAC;AACtE,OAAO,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACjE,OAAO,EAAE,oBAAoB,EAAE,MAAM,gCAAgC,CAAC;AACtE,OAAO,EAAE,kBAAkB,EAAE,cAAc,EAAE,QAAQ,EAAE,MAAM,uBAAuB,CAAC;AACrF,OAAO,EACL,2BAA2B,EAC3B,sBAAsB,GAEvB,MAAM,8BAA8B,CA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,CAAC,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAChE,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,WAAW,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;QAC1E,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,WAAW,CAAC;QAE3C,6CAA6C;QAC7C,MAAM,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC;QAC9B,MAAM,aAAa,GAAG,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC7C,MAAM,OAAO,GAAG,aAAa,CAAC,CAAC,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;QAClE,WAAW,CAAC,SAAS,GAAG,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,6CAA6C;QAEtF,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACvD,MAAM,SAAS,GAAG,CAAC,WAAW,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;QAChE,MAAM,SAAS,GAAG,CAAC,WAAW,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;QAE/D,KAAK,CAAC,IAAI,CAAC;YACT,IAAI,EAAE,QAAQ;YACd,SAAS;YACT,SAAS;YACT,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU;SAC7D,CAAC,CAAC;IACL,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"} \ No newline at end of file +{"version":3,"file":"analyze.command.js","sourceRoot":"","sources":["../../../src/cli/commands/analyze.command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAA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AChE,MAAM,KAAK,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,WAAW,IAAI,KAAK,CAAC,CAAC,CAAC,CAAC,UAAU,CAAC,UAAU,CAAC,CAAC;QAC1E,MAAM,SAAS,GAAG,KAAK,CAAC,CAAC,CAAC,KAAK,WAAW,CAAC;QAE3C,6CAA6C;QAC7C,MAAM,SAAS,GAAG,KAAK,CAAC,KAAK,CAAC;QAC9B,MAAM,aAAa,GAAG,WAAW,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QAC7C,MAAM,OAAO,GAAG,aAAa,CAAC,CAAC,CAAC,aAAa,CAAC,KAAK,CAAC,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;QAClE,WAAW,CAAC,SAAS,GAAG,KAAK,CAAC,KAAK,GAAG,CAAC,CAAC,CAAC,6CAA6C;QAEtF,MAAM,WAAW,GAAG,IAAI,CAAC,SAAS,CAAC,SAAS,EAAE,OAAO,CAAC,CAAC;QACvD,MAAM,SAAS,GAAG,CAAC,WAAW,CAAC,KAAK,CAAC,WAAW,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;QAChE,MAAM,SAAS,GAAG,CAAC,WAAW,CAAC,KAAK,CAAC,UAAU,CAAC,IAAI,EAAE,CAAC,CAAC,MAAM,CAAC;QAE/D,KAAK,CAAC,IAAI,CAAC;YACT,IAAI,EAAE,QAAQ;YACd,SAAS;YACT,SAAS;YACT,MAAM,EAAE,KAAK,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,UAAU;SAC7D,CAAC,CAAC;IACL,CAAC;IAED,OAAO,KAAK,CAAC;AACf,CAAC"} \ No newline at end of file diff --git a/dist/cli/commands/help.command.js b/dist/cli/commands/help.command.js index 8024f2a..c2dff9c 100644 --- a/dist/cli/commands/help.command.js +++ b/dist/cli/commands/help.command.js @@ -39,7 +39,7 @@ export function displayHelp() { console.log(' 4. Fallback to origin/main'); console.log(' Use --branch to override for a single analysis\n'); console.log(chalk.dim(' Advanced Options:')); - console.log(' --provider AI provider: anthropic|openai|google'); + console.log(' --provider AI provider: anthropic|openai|google|zhipu'); console.log(' --model Specific model to use'); console.log(' --title PR title (auto-detected from git)'); console.log(' --max-cost Maximum cost limit (default: $5.00)'); diff --git a/dist/cli/commands/help.command.js.map b/dist/cli/commands/help.command.js.map index 1aa82f6..719eeed 100644 --- a/dist/cli/commands/help.command.js.map +++ b/dist/cli/commands/help.command.js.map @@ -1 +1 @@ -{"version":3,"file":"help.command.js","sourceRoot":"","sources":["../../../src/cli/commands/help.command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAG1B;;GAEG;AACH,MAAM,UAAU,WAAW;IACzB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,qDAAqD,CAAC,CAAC,CAAC;IACpF,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,GAAG,CACP,uGAAuG,CACxG,CACF,CAAC;IAEF,cAAc;IACd,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC,CAAC;IACnD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,aAAa,CAAC,GAAG,iCAAiC,CAAC,CAAC;IAC5E,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,eAAe,CAAC,GAAG,yBAAyB,CAAC,CAAC;IACtE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,oDAAoD,CAAC,CAAC;IAEhG,gBAAgB;IAChB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,eAAe,CAAC,CAAC,CAAC;IAEhD,kBAAkB;IAClB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,WAAW,CAAC,CAAC,CAAC;IACrC,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2BAA2B,CAAC,CACnG,CAAC;IACF,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,mBAAmB,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,6CAA6C,CAAC,CAAC,CAAC;IACxG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;AAChD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAgB;IAClD,OAAO;SACJ,OAAO,CAAC,MAAM,CAAC;SACf,WAAW,CAAC,wCAAwC,CAAC;SACrD,MAAM,CAAC,GAAG,EAAE;QACX,WAAW,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACP,CAAC"} \ No newline at end of file +{"version":3,"file":"help.command.js","sourceRoot":"","sources":["../../../src/cli/commands/help.command.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,OAAO,CAAC;AAG1B;;GAEG;AACH,MAAM,UAAU,WAAW;IACzB,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,qDAAqD,CAAC,CAAC,CAAC;IACpF,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,GAAG,CACP,uGAAuG,CACxG,CACF,CAAC;IAEF,cAAc;IACd,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,kBAAkB,CAAC,CAAC,CAAC;IACnD,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,aAAa,CAAC,GAAG,iCAAiC,CAAC,CAAC;IAC5E,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,eAAe,CAAC,GAAG,yBAAyB,CAAC,CAAC;IACtE,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,oDAAoD,CAAC,CAAC;IAEhG,gBAAgB;IAChB,OAAO,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C,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,CAAC,CAAC,CAAC;IACvC,OAAO,CAAC,GAAG,CACT,KAAK,CAAC,GAAG,CAAC,6CAA6C,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,2BAA2B,CAAC,CACnG,CAAC;IACF,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,mBAAmB,CAAC,GAAG,KAAK,CAAC,IAAI,CAAC,6CAA6C,CAAC,CAAC,CAAC;IACxG,OAAO,CAAC,GAAG,CAAC,KAAK,CAAC,GAAG,CAAC,GAAG,CAAC,MAAM,CAAC,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,CAAC;AAChD,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,mBAAmB,CAAC,OAAgB;IAClD,OAAO;SACJ,OAAO,CAAC,MAAM,CAAC;SACf,WAAW,CAAC,wCAAwC,CAAC;SACrD,MAAM,CAAC,GAAG,EAAE;QACX,WAAW,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACP,CAAC"} \ No newline at end of file diff --git a/dist/cli/index.js b/dist/cli/index.js index 0a26553..586a044 100644 --- a/dist/cli/index.js +++ b/dist/cli/index.js @@ -27,7 +27,7 @@ program .option('--staged', 'Analyze staged changes (git diff --staged)') .option('--branch ', 'Analyze against specific branch') .option('--title ', 'PR title (auto-detected from git)') - .option('--provider ', 'AI provider (anthropic|openai|google)') + .option('--provider ', 'AI provider (anthropic|openai|google|zhipu)') .option('--model ', 'Specific model to use') .option('--agent', 'Force intelligent agent (recommended for large diffs)') .option('--summary', 'Show summary only') diff --git a/dist/cli/index.js.map b/dist/cli/index.js.map index f5b4186..01ab536 100644 --- a/dist/cli/index.js.map +++ b/dist/cli/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/cli/index.ts"],"names":[],"mappings":";AAEA,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO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C,CAAC;AAErB,iBAAiB;AACjB,qBAAqB,CAAC,OAAO,CAAC,CAAC;AAE/B,eAAe;AACf,mBAAmB,CAAC,OAAO,CAAC,CAAC;AAE7B,sBAAsB;AACtB,OAAO,CAAC,KAAK,EAAE,CAAC"} \ No newline at end of file diff --git a/dist/cli/utils/config-loader.d.ts b/dist/cli/utils/config-loader.d.ts index 87fd34f..5216ad8 100644 --- a/dist/cli/utils/config-loader.d.ts +++ b/dist/cli/utils/config-loader.d.ts @@ -3,6 +3,7 @@ export interface UserConfig { anthropic?: string; openai?: string; google?: string; + zhipu?: string; }; ai?: { provider?: string; diff --git a/dist/cli/utils/config-loader.js b/dist/cli/utils/config-loader.js index 43cb91a..137458f 100644 --- a/dist/cli/utils/config-loader.js +++ b/dist/cli/utils/config-loader.js @@ -130,6 +130,7 @@ export function getApiKey(provider, config) { anthropic: 'ANTHROPIC_API_KEY', openai: 'OPENAI_API_KEY', google: 'GOOGLE_API_KEY', + zhipu: 'ZHIPU_API_KEY', }; const envVar = envVarMap[provider.toLowerCase()]; if (envVar) { diff --git a/dist/cli/utils/config-loader.js.map b/dist/cli/utils/config-loader.js.map index e1e8469..f10d0e3 100644 --- a/dist/cli/utils/config-loader.js.map +++ b/dist/cli/utils/config-loader.js.map @@ -1 +1 @@ -{"version":3,"file":"config-loader.js","sourceRoot":"","sources":["../../../src/cli/utils/config-loader.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACxF,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,MAAM,WAAW,GAAG,sBAAsB,CAAC;AA+D3C;;GAEG;AACH,MAAM,UAAU,cAAc;IAC5B,IAAI,UAAU,GAAG,OAAO,CAAC,GAA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jC,OAAO,GAAG,CAAC;QACb,CAAC;IACH,CAAC;IAED,qCAAqC;IACrC,MAAM,SAAS,GAA2B;QACxC,SAAS,EAAE,mBAAmB;QAC9B,MAAM,EAAE,gBAAgB;QACxB,MAAM,EAAE,gBAAgB;KACzB,CAAC;IAEF,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IACjD,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACnC,IAAI,MAAM,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACvC,OAAO,MAAM,CAAC;QAChB,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,UAAU,CAAC,MAAkB,EAAE,UAAmB;IAChE,MAAM,UAAU,GAAG,UAAU,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,WAAW,CAAC,CAAC;IACvE,EAAE,CAAC,aAAa,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;AACzE,CAAC"} \ No newline at end of file +{"version":3,"file":"config-loader.js","sourceRoot":"","sources":["../../../src/cli/utils/config-loader.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,MAAM,IAAI,CAAC;AACzB,OAAO,KAAK,IAAI,MAAM,MAAM,CAAC;AAC7B,OAAO,KAAK,MAAM,OAAO,CAAC;AAC1B,OAAO,EAAE,qBAAqB,EAAE,cAAc,EAAE,MAAM,iCAAiC,CAAC;AACxF,OAAO,EAAE,kBAAkB,EAAE,MAAM,uBAAuB,CAAC;AAE3D,MAAM,WAAW,GAAG,sBAAsB,CAAC;AAgE3C;;GAEG;AACH,MAAM,UAAU,cAAc;IAC5B,IA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AAM,GAAG,CAAC,EAAE,CAAC;YACjC,OAAO,GAAG,CAAC;QACb,CAAC;IACH,CAAC;IAED,qCAAqC;IACrC,MAAM,SAAS,GAA2B;QACxC,SAAS,EAAE,mBAAmB;QAC9B,MAAM,EAAE,gBAAgB;QACxB,MAAM,EAAE,gBAAgB;QACxB,KAAK,EAAE,eAAe;KACvB,CAAC;IAEF,MAAM,MAAM,GAAG,SAAS,CAAC,QAAQ,CAAC,WAAW,EAAE,CAAC,CAAC;IACjD,IAAI,MAAM,EAAE,CAAC;QACX,MAAM,MAAM,GAAG,OAAO,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;QACnC,IAAI,MAAM,IAAI,MAAM,CAAC,IAAI,EAAE,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;YACvC,OAAO,MAAM,CAAC;QAChB,CAAC;IACH,CAAC;IAED,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;GAEG;AACH,MAAM,UAAU,UAAU,CAAC,MAAkB,EAAE,UAAmB;IAChE,MAAM,UAAU,GAAG,UAAU,IAAI,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,GAAG,EAAE,EAAE,WAAW,CAAC,CAAC;IACvE,EAAE,CAAC,aAAa,CAAC,UAAU,EAAE,IAAI,CAAC,SAAS,CAAC,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC;AACzE,CAAC"} \ No newline at end of file diff --git a/dist/index.js b/dist/index.js index 7dbb248..b2087ba 100644 --- a/dist/index.js +++ b/dist/index.js @@ -1,124954 +1,111 @@ -import { createRequire as __WEBPACK_EXTERNAL_createRequire } from "module"; -/******/ var __webpack_modules__ = ({ - -/***/ 4914: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.issue = exports.issueCommand = void 0; -const os = __importStar(__nccwpck_require__(857)); -const utils_1 = __nccwpck_require__(302); -/** - * Commands - * - * Command Format: - * ::name key=value,key=value::message - * - * Examples: - * ::warning::This is the message - * ::set-env name=MY_VAR::some value - */ -function issueCommand(command, properties, message) { - const cmd = new Command(command, properties, message); - process.stdout.write(cmd.toString() + os.EOL); -} -exports.issueCommand = issueCommand; -function issue(name, message = '') { - issueCommand(name, {}, message); -} -exports.issue = issue; -const CMD_STRING = '::'; -class Command { - constructor(command, properties, message) { - if (!command) { - command = 'missing.command'; - } - this.command = command; - this.properties = properties; - this.message = message; - } - toString() { - let cmdStr = CMD_STRING + this.command; - if (this.properties && Object.keys(this.properties).length > 0) { - cmdStr += ' '; - let first = true; - for (const key in this.properties) { - if (this.properties.hasOwnProperty(key)) { - const val = this.properties[key]; - if (val) { - if (first) { - first = false; - } - else { - cmdStr += ','; - } - cmdStr += `${key}=${escapeProperty(val)}`; - } - } - } - } - cmdStr += `${CMD_STRING}${escapeData(this.message)}`; - return cmdStr; - } -} -function escapeData(s) { - return (0, utils_1.toCommandValue)(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A'); -} -function escapeProperty(s) { - return (0, utils_1.toCommandValue)(s) - .replace(/%/g, '%25') - .replace(/\r/g, '%0D') - .replace(/\n/g, '%0A') - .replace(/:/g, '%3A') - .replace(/,/g, '%2C'); -} -//# sourceMappingURL=command.js.map - -/***/ }), - -/***/ 7484: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.platform = exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = exports.markdownSummary = exports.summary = exports.getIDToken = exports.getState = exports.saveState = exports.group = exports.endGroup = exports.startGroup = exports.info = exports.notice = exports.warning = exports.error = exports.debug = exports.isDebug = exports.setFailed = exports.setCommandEcho = exports.setOutput = exports.getBooleanInput = exports.getMultilineInput = exports.getInput = exports.addPath = exports.setSecret = exports.exportVariable = exports.ExitCode = void 0; -const command_1 = __nccwpck_require__(4914); -const file_command_1 = __nccwpck_require__(4753); -const utils_1 = __nccwpck_require__(302); -const os = __importStar(__nccwpck_require__(857)); -const path = __importStar(__nccwpck_require__(6928)); -const oidc_utils_1 = __nccwpck_require__(5306); -/** - * The code to exit an action - */ -var ExitCode; -(function (ExitCode) { - /** - * A code indicating that the action was successful - */ - ExitCode[ExitCode["Success"] = 0] = "Success"; - /** - * A code indicating that the action was a failure - */ - ExitCode[ExitCode["Failure"] = 1] = "Failure"; -})(ExitCode || (exports.ExitCode = ExitCode = {})); -//----------------------------------------------------------------------- -// Variables -//----------------------------------------------------------------------- -/** - * Sets env variable for this action and future actions in the job - * @param name the name of the variable to set - * @param val the value of the variable. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function exportVariable(name, val) { - const convertedVal = (0, utils_1.toCommandValue)(val); - process.env[name] = convertedVal; - const filePath = process.env['GITHUB_ENV'] || ''; - if (filePath) { - return (0, file_command_1.issueFileCommand)('ENV', (0, file_command_1.prepareKeyValueMessage)(name, val)); - } - (0, command_1.issueCommand)('set-env', { name }, convertedVal); -} -exports.exportVariable = exportVariable; -/** - * Registers a secret which will get masked from logs - * @param secret value of the secret - */ -function setSecret(secret) { - (0, command_1.issueCommand)('add-mask', {}, secret); -} -exports.setSecret = setSecret; -/** - * Prepends inputPath to the PATH (for this action and future actions) - * @param inputPath - */ -function addPath(inputPath) { - const filePath = process.env['GITHUB_PATH'] || ''; - if (filePath) { - (0, file_command_1.issueFileCommand)('PATH', inputPath); - } - else { - (0, command_1.issueCommand)('add-path', {}, inputPath); - } - process.env['PATH'] = `${inputPath}${path.delimiter}${process.env['PATH']}`; -} -exports.addPath = addPath; -/** - * Gets the value of an input. - * Unless trimWhitespace is set to false in InputOptions, the value is also trimmed. - * Returns an empty string if the value is not defined. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string - */ -function getInput(name, options) { - const val = process.env[`INPUT_${name.replace(/ /g, '_').toUpperCase()}`] || ''; - if (options && options.required && !val) { - throw new Error(`Input required and not supplied: ${name}`); - } - if (options && options.trimWhitespace === false) { - return val; - } - return val.trim(); -} -exports.getInput = getInput; -/** - * Gets the values of an multiline input. Each value is also trimmed. - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns string[] - * - */ -function getMultilineInput(name, options) { - const inputs = getInput(name, options) - .split('\n') - .filter(x => x !== ''); - if (options && options.trimWhitespace === false) { - return inputs; - } - return inputs.map(input => input.trim()); -} -exports.getMultilineInput = getMultilineInput; -/** - * Gets the input value of the boolean type in the YAML 1.2 "core schema" specification. - * Support boolean input list: `true | True | TRUE | false | False | FALSE` . - * The return value is also in boolean type. - * ref: https://yaml.org/spec/1.2/spec.html#id2804923 - * - * @param name name of the input to get - * @param options optional. See InputOptions. - * @returns boolean - */ -function getBooleanInput(name, options) { - const trueValue = ['true', 'True', 'TRUE']; - const falseValue = ['false', 'False', 'FALSE']; - const val = getInput(name, options); - if (trueValue.includes(val)) - return true; - if (falseValue.includes(val)) - return false; - throw new TypeError(`Input does not meet YAML 1.2 "Core Schema" specification: ${name}\n` + - `Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); -} -exports.getBooleanInput = getBooleanInput; -/** - * Sets the value of an output. - * - * @param name name of the output to set - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function setOutput(name, value) { - const filePath = process.env['GITHUB_OUTPUT'] || ''; - if (filePath) { - return (0, file_command_1.issueFileCommand)('OUTPUT', (0, file_command_1.prepareKeyValueMessage)(name, value)); - } - process.stdout.write(os.EOL); - (0, command_1.issueCommand)('set-output', { name }, (0, utils_1.toCommandValue)(value)); -} -exports.setOutput = setOutput; -/** - * Enables or disables the echoing of commands into stdout for the rest of the step. - * Echoing is disabled by default if ACTIONS_STEP_DEBUG is not set. - * - */ -function setCommandEcho(enabled) { - (0, command_1.issue)('echo', enabled ? 'on' : 'off'); -} -exports.setCommandEcho = setCommandEcho; -//----------------------------------------------------------------------- -// Results -//----------------------------------------------------------------------- -/** - * Sets the action status to failed. - * When the action exits it will be with an exit code of 1 - * @param message add error issue message - */ -function setFailed(message) { - process.exitCode = ExitCode.Failure; - error(message); -} -exports.setFailed = setFailed; -//----------------------------------------------------------------------- -// Logging Commands -//----------------------------------------------------------------------- -/** - * Gets whether Actions Step Debug is on or not - */ -function isDebug() { - return process.env['RUNNER_DEBUG'] === '1'; -} -exports.isDebug = isDebug; -/** - * Writes debug message to user log - * @param message debug message - */ -function debug(message) { - (0, command_1.issueCommand)('debug', {}, message); -} -exports.debug = debug; -/** - * Adds an error issue - * @param message error issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function error(message, properties = {}) { - (0, command_1.issueCommand)('error', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); -} -exports.error = error; -/** - * Adds a warning issue - * @param message warning issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function warning(message, properties = {}) { - (0, command_1.issueCommand)('warning', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); -} -exports.warning = warning; -/** - * Adds a notice issue - * @param message notice issue message. Errors will be converted to string via toString() - * @param properties optional properties to add to the annotation. - */ -function notice(message, properties = {}) { - (0, command_1.issueCommand)('notice', (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); -} -exports.notice = notice; -/** - * Writes info to log with console.log. - * @param message info message - */ -function info(message) { - process.stdout.write(message + os.EOL); -} -exports.info = info; -/** - * Begin an output group. - * - * Output until the next `groupEnd` will be foldable in this group - * - * @param name The name of the output group - */ -function startGroup(name) { - (0, command_1.issue)('group', name); -} -exports.startGroup = startGroup; -/** - * End an output group. - */ -function endGroup() { - (0, command_1.issue)('endgroup'); -} -exports.endGroup = endGroup; -/** - * Wrap an asynchronous function call in a group. - * - * Returns the same type as the function itself. - * - * @param name The name of the group - * @param fn The function to wrap in the group - */ -function group(name, fn) { - return __awaiter(this, void 0, void 0, function* () { - startGroup(name); - let result; - try { - result = yield fn(); - } - finally { - endGroup(); - } - return result; - }); -} -exports.group = group; -//----------------------------------------------------------------------- -// Wrapper action state -//----------------------------------------------------------------------- -/** - * Saves state for current action, the state can only be retrieved by this action's post job execution. - * - * @param name name of the state to store - * @param value value to store. Non-string values will be converted to a string via JSON.stringify - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function saveState(name, value) { - const filePath = process.env['GITHUB_STATE'] || ''; - if (filePath) { - return (0, file_command_1.issueFileCommand)('STATE', (0, file_command_1.prepareKeyValueMessage)(name, value)); - } - (0, command_1.issueCommand)('save-state', { name }, (0, utils_1.toCommandValue)(value)); -} -exports.saveState = saveState; -/** - * Gets the value of an state set by this action's main execution. - * - * @param name name of the state to get - * @returns string - */ -function getState(name) { - return process.env[`STATE_${name}`] || ''; -} -exports.getState = getState; -function getIDToken(aud) { - return __awaiter(this, void 0, void 0, function* () { - return yield oidc_utils_1.OidcClient.getIDToken(aud); - }); -} -exports.getIDToken = getIDToken; -/** - * Summary exports - */ -var summary_1 = __nccwpck_require__(1847); -Object.defineProperty(exports, "summary", ({ enumerable: true, get: function () { return summary_1.summary; } })); -/** - * @deprecated use core.summary - */ -var summary_2 = __nccwpck_require__(1847); -Object.defineProperty(exports, "markdownSummary", ({ enumerable: true, get: function () { return summary_2.markdownSummary; } })); -/** - * Path exports - */ -var path_utils_1 = __nccwpck_require__(1976); -Object.defineProperty(exports, "toPosixPath", ({ enumerable: true, get: function () { return path_utils_1.toPosixPath; } })); -Object.defineProperty(exports, "toWin32Path", ({ enumerable: true, get: function () { return path_utils_1.toWin32Path; } })); -Object.defineProperty(exports, "toPlatformPath", ({ enumerable: true, get: function () { return path_utils_1.toPlatformPath; } })); -/** - * Platform utilities exports - */ -exports.platform = __importStar(__nccwpck_require__(8968)); -//# sourceMappingURL=core.js.map - -/***/ }), - -/***/ 4753: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -// For internal use, subject to change. -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -const crypto = __importStar(__nccwpck_require__(6982)); -const fs = __importStar(__nccwpck_require__(9896)); -const os = __importStar(__nccwpck_require__(857)); -const utils_1 = __nccwpck_require__(302); -function issueFileCommand(command, message) { - const filePath = process.env[`GITHUB_${command}`]; - if (!filePath) { - throw new Error(`Unable to find environment variable for file command ${command}`); - } - if (!fs.existsSync(filePath)) { - throw new Error(`Missing file at path: ${filePath}`); - } - fs.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os.EOL}`, { - encoding: 'utf8' - }); -} -exports.issueFileCommand = issueFileCommand; -function prepareKeyValueMessage(key, value) { - const delimiter = `ghadelimiter_${crypto.randomUUID()}`; - const convertedValue = (0, utils_1.toCommandValue)(value); - // These should realistically never happen, but just in case someone finds a - // way to exploit uuid generation let's not allow keys or values that contain - // the delimiter. - if (key.includes(delimiter)) { - throw new Error(`Unexpected input: name should not contain the delimiter "${delimiter}"`); - } - if (convertedValue.includes(delimiter)) { - throw new Error(`Unexpected input: value should not contain the delimiter "${delimiter}"`); - } - return `${key}<<${delimiter}${os.EOL}${convertedValue}${os.EOL}${delimiter}`; -} -exports.prepareKeyValueMessage = prepareKeyValueMessage; -//# sourceMappingURL=file-command.js.map - -/***/ }), - -/***/ 5306: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.OidcClient = void 0; -const http_client_1 = __nccwpck_require__(4844); -const auth_1 = __nccwpck_require__(4552); -const core_1 = __nccwpck_require__(7484); -class OidcClient { - static createHttpClient(allowRetry = true, maxRetry = 10) { - const requestOptions = { - allowRetries: allowRetry, - maxRetries: maxRetry - }; - return new http_client_1.HttpClient('actions/oidc-client', [new auth_1.BearerCredentialHandler(OidcClient.getRequestToken())], requestOptions); - } - static getRequestToken() { - const token = process.env['ACTIONS_ID_TOKEN_REQUEST_TOKEN']; - if (!token) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_TOKEN env variable'); - } - return token; - } - static getIDTokenUrl() { - const runtimeUrl = process.env['ACTIONS_ID_TOKEN_REQUEST_URL']; - if (!runtimeUrl) { - throw new Error('Unable to get ACTIONS_ID_TOKEN_REQUEST_URL env variable'); - } - return runtimeUrl; - } - static getCall(id_token_url) { - var _a; - return __awaiter(this, void 0, void 0, function* () { - const httpclient = OidcClient.createHttpClient(); - const res = yield httpclient - .getJson(id_token_url) - .catch(error => { - throw new Error(`Failed to get ID Token. \n - Error Code : ${error.statusCode}\n - Error Message: ${error.message}`); - }); - const id_token = (_a = res.result) === null || _a === void 0 ? void 0 : _a.value; - if (!id_token) { - throw new Error('Response json body do not have ID Token field'); - } - return id_token; - }); - } - static getIDToken(audience) { - return __awaiter(this, void 0, void 0, function* () { - try { - // New ID Token is requested from action service - let id_token_url = OidcClient.getIDTokenUrl(); - if (audience) { - const encodedAudience = encodeURIComponent(audience); - id_token_url = `${id_token_url}&audience=${encodedAudience}`; - } - (0, core_1.debug)(`ID token url is ${id_token_url}`); - const id_token = yield OidcClient.getCall(id_token_url); - (0, core_1.setSecret)(id_token); - return id_token; - } - catch (error) { - throw new Error(`Error message: ${error.message}`); - } - }); - } -} -exports.OidcClient = OidcClient; -//# sourceMappingURL=oidc-utils.js.map - -/***/ }), - -/***/ 1976: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; -const path = __importStar(__nccwpck_require__(6928)); -/** - * toPosixPath converts the given path to the posix form. On Windows, \\ will be - * replaced with /. - * - * @param pth. Path to transform. - * @return string Posix path. - */ -function toPosixPath(pth) { - return pth.replace(/[\\]/g, '/'); -} -exports.toPosixPath = toPosixPath; -/** - * toWin32Path converts the given path to the win32 form. On Linux, / will be - * replaced with \\. - * - * @param pth. Path to transform. - * @return string Win32 path. - */ -function toWin32Path(pth) { - return pth.replace(/[/]/g, '\\'); -} -exports.toWin32Path = toWin32Path; -/** - * toPlatformPath converts the given path to a platform-specific path. It does - * this by replacing instances of / and \ with the platform-specific path - * separator. - * - * @param pth The path to platformize. - * @return string The platform-specific path. - */ -function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path.sep); -} -exports.toPlatformPath = toPlatformPath; -//# sourceMappingURL=path-utils.js.map - -/***/ }), - -/***/ 8968: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var __importDefault = (this && this.__importDefault) || function (mod) { - return (mod && mod.__esModule) ? mod : { "default": mod }; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getDetails = exports.isLinux = exports.isMacOS = exports.isWindows = exports.arch = exports.platform = void 0; -const os_1 = __importDefault(__nccwpck_require__(857)); -const exec = __importStar(__nccwpck_require__(5236)); -const getWindowsInfo = () => __awaiter(void 0, void 0, void 0, function* () { - const { stdout: version } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Version"', undefined, { - silent: true - }); - const { stdout: name } = yield exec.getExecOutput('powershell -command "(Get-CimInstance -ClassName Win32_OperatingSystem).Caption"', undefined, { - silent: true - }); - return { - name: name.trim(), - version: version.trim() - }; -}); -const getMacOsInfo = () => __awaiter(void 0, void 0, void 0, function* () { - var _a, _b, _c, _d; - const { stdout } = yield exec.getExecOutput('sw_vers', undefined, { - silent: true - }); - const version = (_b = (_a = stdout.match(/ProductVersion:\s*(.+)/)) === null || _a === void 0 ? void 0 : _a[1]) !== null && _b !== void 0 ? _b : ''; - const name = (_d = (_c = stdout.match(/ProductName:\s*(.+)/)) === null || _c === void 0 ? void 0 : _c[1]) !== null && _d !== void 0 ? _d : ''; - return { - name, - version - }; -}); -const getLinuxInfo = () => __awaiter(void 0, void 0, void 0, function* () { - const { stdout } = yield exec.getExecOutput('lsb_release', ['-i', '-r', '-s'], { - silent: true - }); - const [name, version] = stdout.trim().split('\n'); - return { - name, - version - }; -}); -exports.platform = os_1.default.platform(); -exports.arch = os_1.default.arch(); -exports.isWindows = exports.platform === 'win32'; -exports.isMacOS = exports.platform === 'darwin'; -exports.isLinux = exports.platform === 'linux'; -function getDetails() { - return __awaiter(this, void 0, void 0, function* () { - return Object.assign(Object.assign({}, (yield (exports.isWindows - ? getWindowsInfo() - : exports.isMacOS - ? getMacOsInfo() - : getLinuxInfo()))), { platform: exports.platform, - arch: exports.arch, - isWindows: exports.isWindows, - isMacOS: exports.isMacOS, - isLinux: exports.isLinux }); - }); -} -exports.getDetails = getDetails; -//# sourceMappingURL=platform.js.map - -/***/ }), - -/***/ 1847: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.summary = exports.markdownSummary = exports.SUMMARY_DOCS_URL = exports.SUMMARY_ENV_VAR = void 0; -const os_1 = __nccwpck_require__(857); -const fs_1 = __nccwpck_require__(9896); -const { access, appendFile, writeFile } = fs_1.promises; -exports.SUMMARY_ENV_VAR = 'GITHUB_STEP_SUMMARY'; -exports.SUMMARY_DOCS_URL = 'https://docs.github.com/actions/using-workflows/workflow-commands-for-github-actions#adding-a-job-summary'; -class Summary { - constructor() { - this._buffer = ''; - } - /** - * Finds the summary file path from the environment, rejects if env var is not found or file does not exist - * Also checks r/w permissions. - * - * @returns step summary file path - */ - filePath() { - return __awaiter(this, void 0, void 0, function* () { - if (this._filePath) { - return this._filePath; - } - const pathFromEnv = process.env[exports.SUMMARY_ENV_VAR]; - if (!pathFromEnv) { - throw new Error(`Unable to find environment variable for $${exports.SUMMARY_ENV_VAR}. Check if your runtime environment supports job summaries.`); - } - try { - yield access(pathFromEnv, fs_1.constants.R_OK | fs_1.constants.W_OK); - } - catch (_a) { - throw new Error(`Unable to access summary file: '${pathFromEnv}'. Check if the file has correct read/write permissions.`); - } - this._filePath = pathFromEnv; - return this._filePath; - }); - } - /** - * Wraps content in an HTML tag, adding any HTML attributes - * - * @param {string} tag HTML tag to wrap - * @param {string | null} content content within the tag - * @param {[attribute: string]: string} attrs key-value list of HTML attributes to add - * - * @returns {string} content wrapped in HTML element - */ - wrap(tag, content, attrs = {}) { - const htmlAttrs = Object.entries(attrs) - .map(([key, value]) => ` ${key}="${value}"`) - .join(''); - if (!content) { - return `<${tag}${htmlAttrs}>`; - } - return `<${tag}${htmlAttrs}>${content}`; - } - /** - * Writes text in the buffer to the summary buffer file and empties buffer. Will append by default. - * - * @param {SummaryWriteOptions} [options] (optional) options for write operation - * - * @returns {Promise} summary instance - */ - write(options) { - return __awaiter(this, void 0, void 0, function* () { - const overwrite = !!(options === null || options === void 0 ? void 0 : options.overwrite); - const filePath = yield this.filePath(); - const writeFunc = overwrite ? writeFile : appendFile; - yield writeFunc(filePath, this._buffer, { encoding: 'utf8' }); - return this.emptyBuffer(); - }); - } - /** - * Clears the summary buffer and wipes the summary file - * - * @returns {Summary} summary instance - */ - clear() { - return __awaiter(this, void 0, void 0, function* () { - return this.emptyBuffer().write({ overwrite: true }); - }); - } - /** - * Returns the current summary buffer as a string - * - * @returns {string} string of summary buffer - */ - stringify() { - return this._buffer; - } - /** - * If the summary buffer is empty - * - * @returns {boolen} true if the buffer is empty - */ - isEmptyBuffer() { - return this._buffer.length === 0; - } - /** - * Resets the summary buffer without writing to summary file - * - * @returns {Summary} summary instance - */ - emptyBuffer() { - this._buffer = ''; - return this; - } - /** - * Adds raw text to the summary buffer - * - * @param {string} text content to add - * @param {boolean} [addEOL=false] (optional) append an EOL to the raw text (default: false) - * - * @returns {Summary} summary instance - */ - addRaw(text, addEOL = false) { - this._buffer += text; - return addEOL ? this.addEOL() : this; - } - /** - * Adds the operating system-specific end-of-line marker to the buffer - * - * @returns {Summary} summary instance - */ - addEOL() { - return this.addRaw(os_1.EOL); - } - /** - * Adds an HTML codeblock to the summary buffer - * - * @param {string} code content to render within fenced code block - * @param {string} lang (optional) language to syntax highlight code - * - * @returns {Summary} summary instance - */ - addCodeBlock(code, lang) { - const attrs = Object.assign({}, (lang && { lang })); - const element = this.wrap('pre', this.wrap('code', code), attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML list to the summary buffer - * - * @param {string[]} items list of items to render - * @param {boolean} [ordered=false] (optional) if the rendered list should be ordered or not (default: false) - * - * @returns {Summary} summary instance - */ - addList(items, ordered = false) { - const tag = ordered ? 'ol' : 'ul'; - const listItems = items.map(item => this.wrap('li', item)).join(''); - const element = this.wrap(tag, listItems); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML table to the summary buffer - * - * @param {SummaryTableCell[]} rows table rows - * - * @returns {Summary} summary instance - */ - addTable(rows) { - const tableBody = rows - .map(row => { - const cells = row - .map(cell => { - if (typeof cell === 'string') { - return this.wrap('td', cell); - } - const { header, data, colspan, rowspan } = cell; - const tag = header ? 'th' : 'td'; - const attrs = Object.assign(Object.assign({}, (colspan && { colspan })), (rowspan && { rowspan })); - return this.wrap(tag, data, attrs); - }) - .join(''); - return this.wrap('tr', cells); - }) - .join(''); - const element = this.wrap('table', tableBody); - return this.addRaw(element).addEOL(); - } - /** - * Adds a collapsable HTML details element to the summary buffer - * - * @param {string} label text for the closed state - * @param {string} content collapsable content - * - * @returns {Summary} summary instance - */ - addDetails(label, content) { - const element = this.wrap('details', this.wrap('summary', label) + content); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML image tag to the summary buffer - * - * @param {string} src path to the image you to embed - * @param {string} alt text description of the image - * @param {SummaryImageOptions} options (optional) addition image attributes - * - * @returns {Summary} summary instance - */ - addImage(src, alt, options) { - const { width, height } = options || {}; - const attrs = Object.assign(Object.assign({}, (width && { width })), (height && { height })); - const element = this.wrap('img', null, Object.assign({ src, alt }, attrs)); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML section heading element - * - * @param {string} text heading text - * @param {number | string} [level=1] (optional) the heading level, default: 1 - * - * @returns {Summary} summary instance - */ - addHeading(text, level) { - const tag = `h${level}`; - const allowedTag = ['h1', 'h2', 'h3', 'h4', 'h5', 'h6'].includes(tag) - ? tag - : 'h1'; - const element = this.wrap(allowedTag, text); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML thematic break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addSeparator() { - const element = this.wrap('hr', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML line break (
) to the summary buffer - * - * @returns {Summary} summary instance - */ - addBreak() { - const element = this.wrap('br', null); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML blockquote to the summary buffer - * - * @param {string} text quote text - * @param {string} cite (optional) citation url - * - * @returns {Summary} summary instance - */ - addQuote(text, cite) { - const attrs = Object.assign({}, (cite && { cite })); - const element = this.wrap('blockquote', text, attrs); - return this.addRaw(element).addEOL(); - } - /** - * Adds an HTML anchor tag to the summary buffer - * - * @param {string} text link text/content - * @param {string} href hyperlink - * - * @returns {Summary} summary instance - */ - addLink(text, href) { - const element = this.wrap('a', text, { href }); - return this.addRaw(element).addEOL(); - } -} -const _summary = new Summary(); -/** - * @deprecated use `core.summary` - */ -exports.markdownSummary = _summary; -exports.summary = _summary; -//# sourceMappingURL=summary.js.map - -/***/ }), - -/***/ 302: -/***/ ((__unused_webpack_module, exports) => { - - -// We use any as a valid input type -/* eslint-disable @typescript-eslint/no-explicit-any */ -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.toCommandProperties = exports.toCommandValue = void 0; -/** - * Sanitizes an input into a string so it can be passed into issueCommand safely - * @param input input to sanitize into a string - */ -function toCommandValue(input) { - if (input === null || input === undefined) { - return ''; - } - else if (typeof input === 'string' || input instanceof String) { - return input; - } - return JSON.stringify(input); -} -exports.toCommandValue = toCommandValue; -/** - * - * @param annotationProperties - * @returns The command properties to send with the actual annotation command - * See IssueCommandProperties: https://github.com/actions/runner/blob/main/src/Runner.Worker/ActionCommandManager.cs#L646 - */ -function toCommandProperties(annotationProperties) { - if (!Object.keys(annotationProperties).length) { - return {}; - } - return { - title: annotationProperties.title, - file: annotationProperties.file, - line: annotationProperties.startLine, - endLine: annotationProperties.endLine, - col: annotationProperties.startColumn, - endColumn: annotationProperties.endColumn - }; -} -exports.toCommandProperties = toCommandProperties; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 5236: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getExecOutput = exports.exec = void 0; -const string_decoder_1 = __nccwpck_require__(3193); -const tr = __importStar(__nccwpck_require__(6665)); -/** - * Exec a command. - * Output will be streamed to the live console. - * Returns promise with return code - * - * @param commandLine command to execute (can include additional args). Must be correctly escaped. - * @param args optional arguments for tool. Escaping is handled by the lib. - * @param options optional exec options. See ExecOptions - * @returns Promise exit code - */ -function exec(commandLine, args, options) { - return __awaiter(this, void 0, void 0, function* () { - const commandArgs = tr.argStringToArray(commandLine); - if (commandArgs.length === 0) { - throw new Error(`Parameter 'commandLine' cannot be null or empty.`); - } - // Path to tool to execute should be first arg - const toolPath = commandArgs[0]; - args = commandArgs.slice(1).concat(args || []); - const runner = new tr.ToolRunner(toolPath, args, options); - return runner.exec(); - }); -} -exports.exec = exec; -/** - * Exec a command and get the output. - * Output will be streamed to the live console. - * Returns promise with the exit code and collected stdout and stderr - * - * @param commandLine command to execute (can include additional args). Must be correctly escaped. - * @param args optional arguments for tool. Escaping is handled by the lib. - * @param options optional exec options. See ExecOptions - * @returns Promise exit code, stdout, and stderr - */ -function getExecOutput(commandLine, args, options) { - var _a, _b; - return __awaiter(this, void 0, void 0, function* () { - let stdout = ''; - let stderr = ''; - //Using string decoder covers the case where a mult-byte character is split - const stdoutDecoder = new string_decoder_1.StringDecoder('utf8'); - const stderrDecoder = new string_decoder_1.StringDecoder('utf8'); - const originalStdoutListener = (_a = options === null || options === void 0 ? void 0 : options.listeners) === null || _a === void 0 ? void 0 : _a.stdout; - const originalStdErrListener = (_b = options === null || options === void 0 ? void 0 : options.listeners) === null || _b === void 0 ? void 0 : _b.stderr; - const stdErrListener = (data) => { - stderr += stderrDecoder.write(data); - if (originalStdErrListener) { - originalStdErrListener(data); - } - }; - const stdOutListener = (data) => { - stdout += stdoutDecoder.write(data); - if (originalStdoutListener) { - originalStdoutListener(data); - } - }; - const listeners = Object.assign(Object.assign({}, options === null || options === void 0 ? void 0 : options.listeners), { stdout: stdOutListener, stderr: stdErrListener }); - const exitCode = yield exec(commandLine, args, Object.assign(Object.assign({}, options), { listeners })); - //flush any remaining characters - stdout += stdoutDecoder.end(); - stderr += stderrDecoder.end(); - return { - exitCode, - stdout, - stderr - }; - }); -} -exports.getExecOutput = getExecOutput; -//# sourceMappingURL=exec.js.map - -/***/ }), - -/***/ 6665: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.argStringToArray = exports.ToolRunner = void 0; -const os = __importStar(__nccwpck_require__(857)); -const events = __importStar(__nccwpck_require__(4434)); -const child = __importStar(__nccwpck_require__(5317)); -const path = __importStar(__nccwpck_require__(6928)); -const io = __importStar(__nccwpck_require__(4994)); -const ioUtil = __importStar(__nccwpck_require__(5207)); -const timers_1 = __nccwpck_require__(3557); -/* eslint-disable @typescript-eslint/unbound-method */ -const IS_WINDOWS = process.platform === 'win32'; -/* - * Class for running command line tools. Handles quoting and arg parsing in a platform agnostic way. - */ -class ToolRunner extends events.EventEmitter { - constructor(toolPath, args, options) { - super(); - if (!toolPath) { - throw new Error("Parameter 'toolPath' cannot be null or empty."); - } - this.toolPath = toolPath; - this.args = args || []; - this.options = options || {}; - } - _debug(message) { - if (this.options.listeners && this.options.listeners.debug) { - this.options.listeners.debug(message); - } - } - _getCommandString(options, noPrefix) { - const toolPath = this._getSpawnFileName(); - const args = this._getSpawnArgs(options); - let cmd = noPrefix ? '' : '[command]'; // omit prefix when piped to a second tool - if (IS_WINDOWS) { - // Windows + cmd file - if (this._isCmdFile()) { - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - // Windows + verbatim - else if (options.windowsVerbatimArguments) { - cmd += `"${toolPath}"`; - for (const a of args) { - cmd += ` ${a}`; - } - } - // Windows (regular) - else { - cmd += this._windowsQuoteCmdArg(toolPath); - for (const a of args) { - cmd += ` ${this._windowsQuoteCmdArg(a)}`; - } - } - } - else { - // OSX/Linux - this can likely be improved with some form of quoting. - // creating processes on Unix is fundamentally different than Windows. - // on Unix, execvp() takes an arg array. - cmd += toolPath; - for (const a of args) { - cmd += ` ${a}`; - } - } - return cmd; - } - _processLineBuffer(data, strBuffer, onLine) { - try { - let s = strBuffer + data.toString(); - let n = s.indexOf(os.EOL); - while (n > -1) { - const line = s.substring(0, n); - onLine(line); - // the rest of the string ... - s = s.substring(n + os.EOL.length); - n = s.indexOf(os.EOL); - } - return s; - } - catch (err) { - // streaming lines to console is best effort. Don't fail a build. - this._debug(`error processing line. Failed with error ${err}`); - return ''; - } - } - _getSpawnFileName() { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - return process.env['COMSPEC'] || 'cmd.exe'; - } - } - return this.toolPath; - } - _getSpawnArgs(options) { - if (IS_WINDOWS) { - if (this._isCmdFile()) { - let argline = `/D /S /C "${this._windowsQuoteCmdArg(this.toolPath)}`; - for (const a of this.args) { - argline += ' '; - argline += options.windowsVerbatimArguments - ? a - : this._windowsQuoteCmdArg(a); - } - argline += '"'; - return [argline]; - } - } - return this.args; - } - _endsWith(str, end) { - return str.endsWith(end); - } - _isCmdFile() { - const upperToolPath = this.toolPath.toUpperCase(); - return (this._endsWith(upperToolPath, '.CMD') || - this._endsWith(upperToolPath, '.BAT')); - } - _windowsQuoteCmdArg(arg) { - // for .exe, apply the normal quoting rules that libuv applies - if (!this._isCmdFile()) { - return this._uvQuoteCmdArg(arg); - } - // otherwise apply quoting rules specific to the cmd.exe command line parser. - // the libuv rules are generic and are not designed specifically for cmd.exe - // command line parser. - // - // for a detailed description of the cmd.exe command line parser, refer to - // http://stackoverflow.com/questions/4094699/how-does-the-windows-command-interpreter-cmd-exe-parse-scripts/7970912#7970912 - // need quotes for empty arg - if (!arg) { - return '""'; - } - // determine whether the arg needs to be quoted - const cmdSpecialChars = [ - ' ', - '\t', - '&', - '(', - ')', - '[', - ']', - '{', - '}', - '^', - '=', - ';', - '!', - "'", - '+', - ',', - '`', - '~', - '|', - '<', - '>', - '"' - ]; - let needsQuotes = false; - for (const char of arg) { - if (cmdSpecialChars.some(x => x === char)) { - needsQuotes = true; - break; - } - } - // short-circuit if quotes not needed - if (!needsQuotes) { - return arg; - } - // the following quoting rules are very similar to the rules that by libuv applies. - // - // 1) wrap the string in quotes - // - // 2) double-up quotes - i.e. " => "" - // - // this is different from the libuv quoting rules. libuv replaces " with \", which unfortunately - // doesn't work well with a cmd.exe command line. - // - // note, replacing " with "" also works well if the arg is passed to a downstream .NET console app. - // for example, the command line: - // foo.exe "myarg:""my val""" - // is parsed by a .NET console app into an arg array: - // [ "myarg:\"my val\"" ] - // which is the same end result when applying libuv quoting rules. although the actual - // command line from libuv quoting rules would look like: - // foo.exe "myarg:\"my val\"" - // - // 3) double-up slashes that precede a quote, - // e.g. hello \world => "hello \world" - // hello\"world => "hello\\""world" - // hello\\"world => "hello\\\\""world" - // hello world\ => "hello world\\" - // - // technically this is not required for a cmd.exe command line, or the batch argument parser. - // the reasons for including this as a .cmd quoting rule are: - // - // a) this is optimized for the scenario where the argument is passed from the .cmd file to an - // external program. many programs (e.g. .NET console apps) rely on the slash-doubling rule. - // - // b) it's what we've been doing previously (by deferring to node default behavior) and we - // haven't heard any complaints about that aspect. - // - // note, a weakness of the quoting rules chosen here, is that % is not escaped. in fact, % cannot be - // escaped when used on the command line directly - even though within a .cmd file % can be escaped - // by using %%. - // - // the saving grace is, on the command line, %var% is left as-is if var is not defined. this contrasts - // the line parsing rules within a .cmd file, where if var is not defined it is replaced with nothing. - // - // one option that was explored was replacing % with ^% - i.e. %var% => ^%var^%. this hack would - // often work, since it is unlikely that var^ would exist, and the ^ character is removed when the - // variable is used. the problem, however, is that ^ is not removed when %* is used to pass the args - // to an external program. - // - // an unexplored potential solution for the % escaping problem, is to create a wrapper .cmd file. - // % can be escaped within a .cmd file. - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - // walk the string in reverse - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === '\\') { - reverse += '\\'; // double the slash - } - else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '"'; // double the quote - } - else { - quoteHit = false; - } - } - reverse += '"'; - return reverse - .split('') - .reverse() - .join(''); - } - _uvQuoteCmdArg(arg) { - // Tool runner wraps child_process.spawn() and needs to apply the same quoting as - // Node in certain cases where the undocumented spawn option windowsVerbatimArguments - // is used. - // - // Since this function is a port of quote_cmd_arg from Node 4.x (technically, lib UV, - // see https://github.com/nodejs/node/blob/v4.x/deps/uv/src/win/process.c for details), - // pasting copyright notice from Node within this function: - // - // Copyright Joyent, Inc. and other Node contributors. All rights reserved. - // - // Permission is hereby granted, free of charge, to any person obtaining a copy - // of this software and associated documentation files (the "Software"), to - // deal in the Software without restriction, including without limitation the - // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - // sell copies of the Software, and to permit persons to whom the Software is - // furnished to do so, subject to the following conditions: - // - // The above copyright notice and this permission notice shall be included in - // all copies or substantial portions of the Software. - // - // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - // IN THE SOFTWARE. - if (!arg) { - // Need double quotation for empty argument - return '""'; - } - if (!arg.includes(' ') && !arg.includes('\t') && !arg.includes('"')) { - // No quotation needed - return arg; - } - if (!arg.includes('"') && !arg.includes('\\')) { - // No embedded double quotes or backslashes, so I can just wrap - // quote marks around the whole thing. - return `"${arg}"`; - } - // Expected input/output: - // input : hello"world - // output: "hello\"world" - // input : hello""world - // output: "hello\"\"world" - // input : hello\world - // output: hello\world - // input : hello\\world - // output: hello\\world - // input : hello\"world - // output: "hello\\\"world" - // input : hello\\"world - // output: "hello\\\\\"world" - // input : hello world\ - // output: "hello world\\" - note the comment in libuv actually reads "hello world\" - // but it appears the comment is wrong, it should be "hello world\\" - let reverse = '"'; - let quoteHit = true; - for (let i = arg.length; i > 0; i--) { - // walk the string in reverse - reverse += arg[i - 1]; - if (quoteHit && arg[i - 1] === '\\') { - reverse += '\\'; - } - else if (arg[i - 1] === '"') { - quoteHit = true; - reverse += '\\'; - } - else { - quoteHit = false; - } - } - reverse += '"'; - return reverse - .split('') - .reverse() - .join(''); - } - _cloneExecOptions(options) { - options = options || {}; - const result = { - cwd: options.cwd || process.cwd(), - env: options.env || process.env, - silent: options.silent || false, - windowsVerbatimArguments: options.windowsVerbatimArguments || false, - failOnStdErr: options.failOnStdErr || false, - ignoreReturnCode: options.ignoreReturnCode || false, - delay: options.delay || 10000 - }; - result.outStream = options.outStream || process.stdout; - result.errStream = options.errStream || process.stderr; - return result; - } - _getSpawnOptions(options, toolPath) { - options = options || {}; - const result = {}; - result.cwd = options.cwd; - result.env = options.env; - result['windowsVerbatimArguments'] = - options.windowsVerbatimArguments || this._isCmdFile(); - if (options.windowsVerbatimArguments) { - result.argv0 = `"${toolPath}"`; - } - return result; - } - /** - * Exec a tool. - * Output will be streamed to the live console. - * Returns promise with return code - * - * @param tool path to tool to exec - * @param options optional exec options. See ExecOptions - * @returns number - */ - exec() { - return __awaiter(this, void 0, void 0, function* () { - // root the tool path if it is unrooted and contains relative pathing - if (!ioUtil.isRooted(this.toolPath) && - (this.toolPath.includes('/') || - (IS_WINDOWS && this.toolPath.includes('\\')))) { - // prefer options.cwd if it is specified, however options.cwd may also need to be rooted - this.toolPath = path.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); - } - // if the tool is only a file name, then resolve it from the PATH - // otherwise verify it exists (add extension on Windows if necessary) - this.toolPath = yield io.which(this.toolPath, true); - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - this._debug(`exec tool: ${this.toolPath}`); - this._debug('arguments:'); - for (const arg of this.args) { - this._debug(` ${arg}`); - } - const optionsNonNull = this._cloneExecOptions(this.options); - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(this._getCommandString(optionsNonNull) + os.EOL); - } - const state = new ExecState(optionsNonNull, this.toolPath); - state.on('debug', (message) => { - this._debug(message); - }); - if (this.options.cwd && !(yield ioUtil.exists(this.options.cwd))) { - return reject(new Error(`The cwd: ${this.options.cwd} does not exist!`)); - } - const fileName = this._getSpawnFileName(); - const cp = child.spawn(fileName, this._getSpawnArgs(optionsNonNull), this._getSpawnOptions(this.options, fileName)); - let stdbuffer = ''; - if (cp.stdout) { - cp.stdout.on('data', (data) => { - if (this.options.listeners && this.options.listeners.stdout) { - this.options.listeners.stdout(data); - } - if (!optionsNonNull.silent && optionsNonNull.outStream) { - optionsNonNull.outStream.write(data); - } - stdbuffer = this._processLineBuffer(data, stdbuffer, (line) => { - if (this.options.listeners && this.options.listeners.stdline) { - this.options.listeners.stdline(line); - } - }); - }); - } - let errbuffer = ''; - if (cp.stderr) { - cp.stderr.on('data', (data) => { - state.processStderr = true; - if (this.options.listeners && this.options.listeners.stderr) { - this.options.listeners.stderr(data); - } - if (!optionsNonNull.silent && - optionsNonNull.errStream && - optionsNonNull.outStream) { - const s = optionsNonNull.failOnStdErr - ? optionsNonNull.errStream - : optionsNonNull.outStream; - s.write(data); - } - errbuffer = this._processLineBuffer(data, errbuffer, (line) => { - if (this.options.listeners && this.options.listeners.errline) { - this.options.listeners.errline(line); - } - }); - }); - } - cp.on('error', (err) => { - state.processError = err.message; - state.processExited = true; - state.processClosed = true; - state.CheckComplete(); - }); - cp.on('exit', (code) => { - state.processExitCode = code; - state.processExited = true; - this._debug(`Exit code ${code} received from tool '${this.toolPath}'`); - state.CheckComplete(); - }); - cp.on('close', (code) => { - state.processExitCode = code; - state.processExited = true; - state.processClosed = true; - this._debug(`STDIO streams have closed for tool '${this.toolPath}'`); - state.CheckComplete(); - }); - state.on('done', (error, exitCode) => { - if (stdbuffer.length > 0) { - this.emit('stdline', stdbuffer); - } - if (errbuffer.length > 0) { - this.emit('errline', errbuffer); - } - cp.removeAllListeners(); - if (error) { - reject(error); - } - else { - resolve(exitCode); - } - }); - if (this.options.input) { - if (!cp.stdin) { - throw new Error('child process missing stdin'); - } - cp.stdin.end(this.options.input); - } - })); - }); - } -} -exports.ToolRunner = ToolRunner; -/** - * Convert an arg string to an array of args. Handles escaping - * - * @param argString string of arguments - * @returns string[] array of arguments - */ -function argStringToArray(argString) { - const args = []; - let inQuotes = false; - let escaped = false; - let arg = ''; - function append(c) { - // we only escape double quotes. - if (escaped && c !== '"') { - arg += '\\'; - } - arg += c; - escaped = false; - } - for (let i = 0; i < argString.length; i++) { - const c = argString.charAt(i); - if (c === '"') { - if (!escaped) { - inQuotes = !inQuotes; - } - else { - append(c); - } - continue; - } - if (c === '\\' && escaped) { - append(c); - continue; - } - if (c === '\\' && inQuotes) { - escaped = true; - continue; - } - if (c === ' ' && !inQuotes) { - if (arg.length > 0) { - args.push(arg); - arg = ''; - } - continue; - } - append(c); - } - if (arg.length > 0) { - args.push(arg.trim()); - } - return args; -} -exports.argStringToArray = argStringToArray; -class ExecState extends events.EventEmitter { - constructor(options, toolPath) { - super(); - this.processClosed = false; // tracks whether the process has exited and stdio is closed - this.processError = ''; - this.processExitCode = 0; - this.processExited = false; // tracks whether the process has exited - this.processStderr = false; // tracks whether stderr was written to - this.delay = 10000; // 10 seconds - this.done = false; - this.timeout = null; - if (!toolPath) { - throw new Error('toolPath must not be empty'); - } - this.options = options; - this.toolPath = toolPath; - if (options.delay) { - this.delay = options.delay; - } - } - CheckComplete() { - if (this.done) { - return; - } - if (this.processClosed) { - this._setResult(); - } - else if (this.processExited) { - this.timeout = timers_1.setTimeout(ExecState.HandleTimeout, this.delay, this); - } - } - _debug(message) { - this.emit('debug', message); - } - _setResult() { - // determine whether there is an error - let error; - if (this.processExited) { - if (this.processError) { - error = new Error(`There was an error when attempting to execute the process '${this.toolPath}'. This may indicate the process failed to start. Error: ${this.processError}`); - } - else if (this.processExitCode !== 0 && !this.options.ignoreReturnCode) { - error = new Error(`The process '${this.toolPath}' failed with exit code ${this.processExitCode}`); - } - else if (this.processStderr && this.options.failOnStdErr) { - error = new Error(`The process '${this.toolPath}' failed because one or more lines were written to the STDERR stream`); - } - } - // clear the timeout - if (this.timeout) { - clearTimeout(this.timeout); - this.timeout = null; - } - this.done = true; - this.emit('done', error, this.processExitCode); - } - static HandleTimeout(state) { - if (state.done) { - return; - } - if (!state.processClosed && state.processExited) { - const message = `The STDIO streams did not close within ${state.delay / - 1000} seconds of the exit event from process '${state.toolPath}'. This may indicate a child process inherited the STDIO streams and has not yet exited.`; - state._debug(message); - } - state._setResult(); - } -} -//# sourceMappingURL=toolrunner.js.map - -/***/ }), - -/***/ 1648: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.Context = void 0; -const fs_1 = __nccwpck_require__(9896); -const os_1 = __nccwpck_require__(857); -class Context { - /** - * Hydrate the context from the environment - */ - constructor() { - var _a, _b, _c; - this.payload = {}; - if (process.env.GITHUB_EVENT_PATH) { - if ((0, fs_1.existsSync)(process.env.GITHUB_EVENT_PATH)) { - this.payload = JSON.parse((0, fs_1.readFileSync)(process.env.GITHUB_EVENT_PATH, { encoding: 'utf8' })); - } - else { - const path = process.env.GITHUB_EVENT_PATH; - process.stdout.write(`GITHUB_EVENT_PATH ${path} does not exist${os_1.EOL}`); - } - } - this.eventName = process.env.GITHUB_EVENT_NAME; - this.sha = process.env.GITHUB_SHA; - this.ref = process.env.GITHUB_REF; - this.workflow = process.env.GITHUB_WORKFLOW; - this.action = process.env.GITHUB_ACTION; - this.actor = process.env.GITHUB_ACTOR; - this.job = process.env.GITHUB_JOB; - this.runAttempt = parseInt(process.env.GITHUB_RUN_ATTEMPT, 10); - this.runNumber = parseInt(process.env.GITHUB_RUN_NUMBER, 10); - this.runId = parseInt(process.env.GITHUB_RUN_ID, 10); - this.apiUrl = (_a = process.env.GITHUB_API_URL) !== null && _a !== void 0 ? _a : `https://api.github.com`; - this.serverUrl = (_b = process.env.GITHUB_SERVER_URL) !== null && _b !== void 0 ? _b : `https://github.com`; - this.graphqlUrl = - (_c = process.env.GITHUB_GRAPHQL_URL) !== null && _c !== void 0 ? _c : `https://api.github.com/graphql`; - } - get issue() { - const payload = this.payload; - return Object.assign(Object.assign({}, this.repo), { number: (payload.issue || payload.pull_request || payload).number }); - } - get repo() { - if (process.env.GITHUB_REPOSITORY) { - const [owner, repo] = process.env.GITHUB_REPOSITORY.split('/'); - return { owner, repo }; - } - if (this.payload.repository) { - return { - owner: this.payload.repository.owner.login, - repo: this.payload.repository.name - }; - } - throw new Error("context.repo requires a GITHUB_REPOSITORY environment variable like 'owner/repo'"); - } -} -exports.Context = Context; -//# sourceMappingURL=context.js.map - -/***/ }), - -/***/ 3228: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokit = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(1648)); -const utils_1 = __nccwpck_require__(8006); -exports.context = new Context.Context(); -/** - * Returns a hydrated octokit ready to use for GitHub Actions - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokit(token, options, ...additionalPlugins) { - const GitHubWithPlugins = utils_1.GitHub.plugin(...additionalPlugins); - return new GitHubWithPlugins((0, utils_1.getOctokitOptions)(token, options)); -} -exports.getOctokit = getOctokit; -//# sourceMappingURL=github.js.map - -/***/ }), - -/***/ 5156: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getApiBaseUrl = exports.getProxyFetch = exports.getProxyAgentDispatcher = exports.getProxyAgent = exports.getAuthString = void 0; -const httpClient = __importStar(__nccwpck_require__(4844)); -const undici_1 = __nccwpck_require__(6752); -function getAuthString(token, options) { - if (!token && !options.auth) { - throw new Error('Parameter token or opts.auth is required'); - } - else if (token && options.auth) { - throw new Error('Parameters token and opts.auth may not both be specified'); - } - return typeof options.auth === 'string' ? options.auth : `token ${token}`; -} -exports.getAuthString = getAuthString; -function getProxyAgent(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgent(destinationUrl); -} -exports.getProxyAgent = getProxyAgent; -function getProxyAgentDispatcher(destinationUrl) { - const hc = new httpClient.HttpClient(); - return hc.getAgentDispatcher(destinationUrl); -} -exports.getProxyAgentDispatcher = getProxyAgentDispatcher; -function getProxyFetch(destinationUrl) { - const httpDispatcher = getProxyAgentDispatcher(destinationUrl); - const proxyFetch = (url, opts) => __awaiter(this, void 0, void 0, function* () { - return (0, undici_1.fetch)(url, Object.assign(Object.assign({}, opts), { dispatcher: httpDispatcher })); - }); - return proxyFetch; -} -exports.getProxyFetch = getProxyFetch; -function getApiBaseUrl() { - return process.env['GITHUB_API_URL'] || 'https://api.github.com'; -} -exports.getApiBaseUrl = getApiBaseUrl; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 8006: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getOctokitOptions = exports.GitHub = exports.defaults = exports.context = void 0; -const Context = __importStar(__nccwpck_require__(1648)); -const Utils = __importStar(__nccwpck_require__(5156)); -// octokit + plugins -const core_1 = __nccwpck_require__(1897); -const plugin_rest_endpoint_methods_1 = __nccwpck_require__(4935); -const plugin_paginate_rest_1 = __nccwpck_require__(8082); -exports.context = new Context.Context(); -const baseUrl = Utils.getApiBaseUrl(); -exports.defaults = { - baseUrl, - request: { - agent: Utils.getProxyAgent(baseUrl), - fetch: Utils.getProxyFetch(baseUrl) - } -}; -exports.GitHub = core_1.Octokit.plugin(plugin_rest_endpoint_methods_1.restEndpointMethods, plugin_paginate_rest_1.paginateRest).defaults(exports.defaults); -/** - * Convience function to correctly format Octokit Options to pass into the constructor. - * - * @param token the repo PAT or GITHUB_TOKEN - * @param options other options to set - */ -function getOctokitOptions(token, options) { - const opts = Object.assign({}, options || {}); // Shallow clone - don't mutate the object provided by the caller - // Auth - const auth = Utils.getAuthString(token, opts); - if (auth) { - opts.auth = auth; - } - return opts; -} -exports.getOctokitOptions = getOctokitOptions; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 4552: -/***/ (function(__unused_webpack_module, exports) { - - -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.PersonalAccessTokenCredentialHandler = exports.BearerCredentialHandler = exports.BasicCredentialHandler = void 0; -class BasicCredentialHandler { - constructor(username, password) { - this.username = username; - this.password = password; - } - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`${this.username}:${this.password}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.BasicCredentialHandler = BasicCredentialHandler; -class BearerCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Bearer ${this.token}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.BearerCredentialHandler = BearerCredentialHandler; -class PersonalAccessTokenCredentialHandler { - constructor(token) { - this.token = token; - } - // currently implements pre-authorization - // TODO: support preAuth = false where it hooks on 401 - prepareRequest(options) { - if (!options.headers) { - throw Error('The request has no headers'); - } - options.headers['Authorization'] = `Basic ${Buffer.from(`PAT:${this.token}`).toString('base64')}`; - } - // This handler cannot handle 401 - canHandleAuthentication() { - return false; - } - handleAuthentication() { - return __awaiter(this, void 0, void 0, function* () { - throw new Error('not implemented'); - }); - } -} -exports.PersonalAccessTokenCredentialHandler = PersonalAccessTokenCredentialHandler; -//# sourceMappingURL=auth.js.map - -/***/ }), - -/***/ 4844: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -/* eslint-disable @typescript-eslint/no-explicit-any */ -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - var desc = Object.getOwnPropertyDescriptor(m, k); - if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { - desc = { enumerable: true, get: function() { return m[k]; } }; - } - Object.defineProperty(o, k2, desc); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.HttpClient = exports.isHttps = exports.HttpClientResponse = exports.HttpClientError = exports.getProxyUrl = exports.MediaTypes = exports.Headers = exports.HttpCodes = void 0; -const http = __importStar(__nccwpck_require__(8611)); -const https = __importStar(__nccwpck_require__(5692)); -const pm = __importStar(__nccwpck_require__(4988)); -const tunnel = __importStar(__nccwpck_require__(770)); -const undici_1 = __nccwpck_require__(6752); -var HttpCodes; -(function (HttpCodes) { - HttpCodes[HttpCodes["OK"] = 200] = "OK"; - HttpCodes[HttpCodes["MultipleChoices"] = 300] = "MultipleChoices"; - HttpCodes[HttpCodes["MovedPermanently"] = 301] = "MovedPermanently"; - HttpCodes[HttpCodes["ResourceMoved"] = 302] = "ResourceMoved"; - HttpCodes[HttpCodes["SeeOther"] = 303] = "SeeOther"; - HttpCodes[HttpCodes["NotModified"] = 304] = "NotModified"; - HttpCodes[HttpCodes["UseProxy"] = 305] = "UseProxy"; - HttpCodes[HttpCodes["SwitchProxy"] = 306] = "SwitchProxy"; - HttpCodes[HttpCodes["TemporaryRedirect"] = 307] = "TemporaryRedirect"; - HttpCodes[HttpCodes["PermanentRedirect"] = 308] = "PermanentRedirect"; - HttpCodes[HttpCodes["BadRequest"] = 400] = "BadRequest"; - HttpCodes[HttpCodes["Unauthorized"] = 401] = "Unauthorized"; - HttpCodes[HttpCodes["PaymentRequired"] = 402] = "PaymentRequired"; - HttpCodes[HttpCodes["Forbidden"] = 403] = "Forbidden"; - HttpCodes[HttpCodes["NotFound"] = 404] = "NotFound"; - HttpCodes[HttpCodes["MethodNotAllowed"] = 405] = "MethodNotAllowed"; - HttpCodes[HttpCodes["NotAcceptable"] = 406] = "NotAcceptable"; - HttpCodes[HttpCodes["ProxyAuthenticationRequired"] = 407] = "ProxyAuthenticationRequired"; - HttpCodes[HttpCodes["RequestTimeout"] = 408] = "RequestTimeout"; - HttpCodes[HttpCodes["Conflict"] = 409] = "Conflict"; - HttpCodes[HttpCodes["Gone"] = 410] = "Gone"; - HttpCodes[HttpCodes["TooManyRequests"] = 429] = "TooManyRequests"; - HttpCodes[HttpCodes["InternalServerError"] = 500] = "InternalServerError"; - HttpCodes[HttpCodes["NotImplemented"] = 501] = "NotImplemented"; - HttpCodes[HttpCodes["BadGateway"] = 502] = "BadGateway"; - HttpCodes[HttpCodes["ServiceUnavailable"] = 503] = "ServiceUnavailable"; - HttpCodes[HttpCodes["GatewayTimeout"] = 504] = "GatewayTimeout"; -})(HttpCodes || (exports.HttpCodes = HttpCodes = {})); -var Headers; -(function (Headers) { - Headers["Accept"] = "accept"; - Headers["ContentType"] = "content-type"; -})(Headers || (exports.Headers = Headers = {})); -var MediaTypes; -(function (MediaTypes) { - MediaTypes["ApplicationJson"] = "application/json"; -})(MediaTypes || (exports.MediaTypes = MediaTypes = {})); -/** - * Returns the proxy URL, depending upon the supplied url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ -function getProxyUrl(serverUrl) { - const proxyUrl = pm.getProxyUrl(new URL(serverUrl)); - return proxyUrl ? proxyUrl.href : ''; -} -exports.getProxyUrl = getProxyUrl; -const HttpRedirectCodes = [ - HttpCodes.MovedPermanently, - HttpCodes.ResourceMoved, - HttpCodes.SeeOther, - HttpCodes.TemporaryRedirect, - HttpCodes.PermanentRedirect -]; -const HttpResponseRetryCodes = [ - HttpCodes.BadGateway, - HttpCodes.ServiceUnavailable, - HttpCodes.GatewayTimeout -]; -const RetryableHttpVerbs = ['OPTIONS', 'GET', 'DELETE', 'HEAD']; -const ExponentialBackoffCeiling = 10; -const ExponentialBackoffTimeSlice = 5; -class HttpClientError extends Error { - constructor(message, statusCode) { - super(message); - this.name = 'HttpClientError'; - this.statusCode = statusCode; - Object.setPrototypeOf(this, HttpClientError.prototype); - } -} -exports.HttpClientError = HttpClientError; -class HttpClientResponse { - constructor(message) { - this.message = message; - } - readBody() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - let output = Buffer.alloc(0); - this.message.on('data', (chunk) => { - output = Buffer.concat([output, chunk]); - }); - this.message.on('end', () => { - resolve(output.toString()); - }); - })); - }); - } - readBodyBuffer() { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve) => __awaiter(this, void 0, void 0, function* () { - const chunks = []; - this.message.on('data', (chunk) => { - chunks.push(chunk); - }); - this.message.on('end', () => { - resolve(Buffer.concat(chunks)); - }); - })); - }); - } -} -exports.HttpClientResponse = HttpClientResponse; -function isHttps(requestUrl) { - const parsedUrl = new URL(requestUrl); - return parsedUrl.protocol === 'https:'; -} -exports.isHttps = isHttps; -class HttpClient { - constructor(userAgent, handlers, requestOptions) { - this._ignoreSslError = false; - this._allowRedirects = true; - this._allowRedirectDowngrade = false; - this._maxRedirects = 50; - this._allowRetries = false; - this._maxRetries = 1; - this._keepAlive = false; - this._disposed = false; - this.userAgent = userAgent; - this.handlers = handlers || []; - this.requestOptions = requestOptions; - if (requestOptions) { - if (requestOptions.ignoreSslError != null) { - this._ignoreSslError = requestOptions.ignoreSslError; - } - this._socketTimeout = requestOptions.socketTimeout; - if (requestOptions.allowRedirects != null) { - this._allowRedirects = requestOptions.allowRedirects; - } - if (requestOptions.allowRedirectDowngrade != null) { - this._allowRedirectDowngrade = requestOptions.allowRedirectDowngrade; - } - if (requestOptions.maxRedirects != null) { - this._maxRedirects = Math.max(requestOptions.maxRedirects, 0); - } - if (requestOptions.keepAlive != null) { - this._keepAlive = requestOptions.keepAlive; - } - if (requestOptions.allowRetries != null) { - this._allowRetries = requestOptions.allowRetries; - } - if (requestOptions.maxRetries != null) { - this._maxRetries = requestOptions.maxRetries; - } - } - } - options(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('OPTIONS', requestUrl, null, additionalHeaders || {}); - }); - } - get(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('GET', requestUrl, null, additionalHeaders || {}); - }); - } - del(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('DELETE', requestUrl, null, additionalHeaders || {}); - }); - } - post(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('POST', requestUrl, data, additionalHeaders || {}); - }); - } - patch(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PATCH', requestUrl, data, additionalHeaders || {}); - }); - } - put(requestUrl, data, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('PUT', requestUrl, data, additionalHeaders || {}); - }); - } - head(requestUrl, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request('HEAD', requestUrl, null, additionalHeaders || {}); - }); - } - sendStream(verb, requestUrl, stream, additionalHeaders) { - return __awaiter(this, void 0, void 0, function* () { - return this.request(verb, requestUrl, stream, additionalHeaders); - }); - } - /** - * Gets a typed object from an endpoint - * Be aware that not found returns a null. Other errors (4xx, 5xx) reject the promise - */ - getJson(requestUrl, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - const res = yield this.get(requestUrl, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - postJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.post(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - putJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.put(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - patchJson(requestUrl, obj, additionalHeaders = {}) { - return __awaiter(this, void 0, void 0, function* () { - const data = JSON.stringify(obj, null, 2); - additionalHeaders[Headers.Accept] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.Accept, MediaTypes.ApplicationJson); - additionalHeaders[Headers.ContentType] = this._getExistingOrDefaultHeader(additionalHeaders, Headers.ContentType, MediaTypes.ApplicationJson); - const res = yield this.patch(requestUrl, data, additionalHeaders); - return this._processResponse(res, this.requestOptions); - }); - } - /** - * Makes a raw http request. - * All other methods such as get, post, patch, and request ultimately call this. - * Prefer get, del, post and patch - */ - request(verb, requestUrl, data, headers) { - return __awaiter(this, void 0, void 0, function* () { - if (this._disposed) { - throw new Error('Client has already been disposed.'); - } - const parsedUrl = new URL(requestUrl); - let info = this._prepareRequest(verb, parsedUrl, headers); - // Only perform retries on reads since writes may not be idempotent. - const maxTries = this._allowRetries && RetryableHttpVerbs.includes(verb) - ? this._maxRetries + 1 - : 1; - let numTries = 0; - let response; - do { - response = yield this.requestRaw(info, data); - // Check if it's an authentication challenge - if (response && - response.message && - response.message.statusCode === HttpCodes.Unauthorized) { - let authenticationHandler; - for (const handler of this.handlers) { - if (handler.canHandleAuthentication(response)) { - authenticationHandler = handler; - break; - } - } - if (authenticationHandler) { - return authenticationHandler.handleAuthentication(this, info, data); - } - else { - // We have received an unauthorized response but have no handlers to handle it. - // Let the response return to the caller. - return response; - } - } - let redirectsRemaining = this._maxRedirects; - while (response.message.statusCode && - HttpRedirectCodes.includes(response.message.statusCode) && - this._allowRedirects && - redirectsRemaining > 0) { - const redirectUrl = response.message.headers['location']; - if (!redirectUrl) { - // if there's no location to redirect to, we won't - break; - } - const parsedRedirectUrl = new URL(redirectUrl); - if (parsedUrl.protocol === 'https:' && - parsedUrl.protocol !== parsedRedirectUrl.protocol && - !this._allowRedirectDowngrade) { - throw new Error('Redirect from HTTPS to HTTP protocol. This downgrade is not allowed for security reasons. If you want to allow this behavior, set the allowRedirectDowngrade option to true.'); - } - // we need to finish reading the response before reassigning response - // which will leak the open socket. - yield response.readBody(); - // strip authorization header if redirected to a different hostname - if (parsedRedirectUrl.hostname !== parsedUrl.hostname) { - for (const header in headers) { - // header names are case insensitive - if (header.toLowerCase() === 'authorization') { - delete headers[header]; - } - } - } - // let's make the request with the new redirectUrl - info = this._prepareRequest(verb, parsedRedirectUrl, headers); - response = yield this.requestRaw(info, data); - redirectsRemaining--; - } - if (!response.message.statusCode || - !HttpResponseRetryCodes.includes(response.message.statusCode)) { - // If not a retry code, return immediately instead of retrying - return response; - } - numTries += 1; - if (numTries < maxTries) { - yield response.readBody(); - yield this._performExponentialBackoff(numTries); - } - } while (numTries < maxTries); - return response; - }); - } - /** - * Needs to be called if keepAlive is set to true in request options. - */ - dispose() { - if (this._agent) { - this._agent.destroy(); - } - this._disposed = true; - } - /** - * Raw request. - * @param info - * @param data - */ - requestRaw(info, data) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => { - function callbackForResult(err, res) { - if (err) { - reject(err); - } - else if (!res) { - // If `err` is not passed, then `res` must be passed. - reject(new Error('Unknown error')); - } - else { - resolve(res); - } - } - this.requestRawWithCallback(info, data, callbackForResult); - }); - }); - } - /** - * Raw request with callback. - * @param info - * @param data - * @param onResult - */ - requestRawWithCallback(info, data, onResult) { - if (typeof data === 'string') { - if (!info.options.headers) { - info.options.headers = {}; - } - info.options.headers['Content-Length'] = Buffer.byteLength(data, 'utf8'); - } - let callbackCalled = false; - function handleResult(err, res) { - if (!callbackCalled) { - callbackCalled = true; - onResult(err, res); - } - } - const req = info.httpModule.request(info.options, (msg) => { - const res = new HttpClientResponse(msg); - handleResult(undefined, res); - }); - let socket; - req.on('socket', sock => { - socket = sock; - }); - // If we ever get disconnected, we want the socket to timeout eventually - req.setTimeout(this._socketTimeout || 3 * 60000, () => { - if (socket) { - socket.end(); - } - handleResult(new Error(`Request timeout: ${info.options.path}`)); - }); - req.on('error', function (err) { - // err has statusCode property - // res should have headers - handleResult(err); - }); - if (data && typeof data === 'string') { - req.write(data, 'utf8'); - } - if (data && typeof data !== 'string') { - data.on('close', function () { - req.end(); - }); - data.pipe(req); - } - else { - req.end(); - } - } - /** - * Gets an http agent. This function is useful when you need an http agent that handles - * routing through a proxy server - depending upon the url and proxy environment variables. - * @param serverUrl The server URL where the request will be sent. For example, https://api.github.com - */ - getAgent(serverUrl) { - const parsedUrl = new URL(serverUrl); - return this._getAgent(parsedUrl); - } - getAgentDispatcher(serverUrl) { - const parsedUrl = new URL(serverUrl); - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (!useProxy) { - return; - } - return this._getProxyAgentDispatcher(parsedUrl, proxyUrl); - } - _prepareRequest(method, requestUrl, headers) { - const info = {}; - info.parsedUrl = requestUrl; - const usingSsl = info.parsedUrl.protocol === 'https:'; - info.httpModule = usingSsl ? https : http; - const defaultPort = usingSsl ? 443 : 80; - info.options = {}; - info.options.host = info.parsedUrl.hostname; - info.options.port = info.parsedUrl.port - ? parseInt(info.parsedUrl.port) - : defaultPort; - info.options.path = - (info.parsedUrl.pathname || '') + (info.parsedUrl.search || ''); - info.options.method = method; - info.options.headers = this._mergeHeaders(headers); - if (this.userAgent != null) { - info.options.headers['user-agent'] = this.userAgent; - } - info.options.agent = this._getAgent(info.parsedUrl); - // gives handlers an opportunity to participate - if (this.handlers) { - for (const handler of this.handlers) { - handler.prepareRequest(info.options); - } - } - return info; - } - _mergeHeaders(headers) { - if (this.requestOptions && this.requestOptions.headers) { - return Object.assign({}, lowercaseKeys(this.requestOptions.headers), lowercaseKeys(headers || {})); - } - return lowercaseKeys(headers || {}); - } - _getExistingOrDefaultHeader(additionalHeaders, header, _default) { - let clientHeader; - if (this.requestOptions && this.requestOptions.headers) { - clientHeader = lowercaseKeys(this.requestOptions.headers)[header]; - } - return additionalHeaders[header] || clientHeader || _default; - } - _getAgent(parsedUrl) { - let agent; - const proxyUrl = pm.getProxyUrl(parsedUrl); - const useProxy = proxyUrl && proxyUrl.hostname; - if (this._keepAlive && useProxy) { - agent = this._proxyAgent; - } - if (!useProxy) { - agent = this._agent; - } - // if agent is already assigned use that agent. - if (agent) { - return agent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - let maxSockets = 100; - if (this.requestOptions) { - maxSockets = this.requestOptions.maxSockets || http.globalAgent.maxSockets; - } - // This is `useProxy` again, but we need to check `proxyURl` directly for TypeScripts's flow analysis. - if (proxyUrl && proxyUrl.hostname) { - const agentOptions = { - maxSockets, - keepAlive: this._keepAlive, - proxy: Object.assign(Object.assign({}, ((proxyUrl.username || proxyUrl.password) && { - proxyAuth: `${proxyUrl.username}:${proxyUrl.password}` - })), { host: proxyUrl.hostname, port: proxyUrl.port }) - }; - let tunnelAgent; - const overHttps = proxyUrl.protocol === 'https:'; - if (usingSsl) { - tunnelAgent = overHttps ? tunnel.httpsOverHttps : tunnel.httpsOverHttp; - } - else { - tunnelAgent = overHttps ? tunnel.httpOverHttps : tunnel.httpOverHttp; - } - agent = tunnelAgent(agentOptions); - this._proxyAgent = agent; - } - // if tunneling agent isn't assigned create a new agent - if (!agent) { - const options = { keepAlive: this._keepAlive, maxSockets }; - agent = usingSsl ? new https.Agent(options) : new http.Agent(options); - this._agent = agent; - } - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - agent.options = Object.assign(agent.options || {}, { - rejectUnauthorized: false - }); - } - return agent; - } - _getProxyAgentDispatcher(parsedUrl, proxyUrl) { - let proxyAgent; - if (this._keepAlive) { - proxyAgent = this._proxyAgentDispatcher; - } - // if agent is already assigned use that agent. - if (proxyAgent) { - return proxyAgent; - } - const usingSsl = parsedUrl.protocol === 'https:'; - proxyAgent = new undici_1.ProxyAgent(Object.assign({ uri: proxyUrl.href, pipelining: !this._keepAlive ? 0 : 1 }, ((proxyUrl.username || proxyUrl.password) && { - token: `Basic ${Buffer.from(`${proxyUrl.username}:${proxyUrl.password}`).toString('base64')}` - }))); - this._proxyAgentDispatcher = proxyAgent; - if (usingSsl && this._ignoreSslError) { - // we don't want to set NODE_TLS_REJECT_UNAUTHORIZED=0 since that will affect request for entire process - // http.RequestOptions doesn't expose a way to modify RequestOptions.agent.options - // we have to cast it to any and change it directly - proxyAgent.options = Object.assign(proxyAgent.options.requestTls || {}, { - rejectUnauthorized: false - }); - } - return proxyAgent; - } - _performExponentialBackoff(retryNumber) { - return __awaiter(this, void 0, void 0, function* () { - retryNumber = Math.min(ExponentialBackoffCeiling, retryNumber); - const ms = ExponentialBackoffTimeSlice * Math.pow(2, retryNumber); - return new Promise(resolve => setTimeout(() => resolve(), ms)); - }); - } - _processResponse(res, options) { - return __awaiter(this, void 0, void 0, function* () { - return new Promise((resolve, reject) => __awaiter(this, void 0, void 0, function* () { - const statusCode = res.message.statusCode || 0; - const response = { - statusCode, - result: null, - headers: {} - }; - // not found leads to null obj returned - if (statusCode === HttpCodes.NotFound) { - resolve(response); - } - // get the result from the body - function dateTimeDeserializer(key, value) { - if (typeof value === 'string') { - const a = new Date(value); - if (!isNaN(a.valueOf())) { - return a; - } - } - return value; - } - let obj; - let contents; - try { - contents = yield res.readBody(); - if (contents && contents.length > 0) { - if (options && options.deserializeDates) { - obj = JSON.parse(contents, dateTimeDeserializer); - } - else { - obj = JSON.parse(contents); - } - response.result = obj; - } - response.headers = res.message.headers; - } - catch (err) { - // Invalid resource (contents not json); leaving result obj null - } - // note that 3xx redirects are handled by the http layer. - if (statusCode > 299) { - let msg; - // if exception/error in body, attempt to get better error - if (obj && obj.message) { - msg = obj.message; - } - else if (contents && contents.length > 0) { - // it may be the case that the exception is in the body message as string - msg = contents; - } - else { - msg = `Failed request: (${statusCode})`; - } - const err = new HttpClientError(msg, statusCode); - err.result = response.result; - reject(err); - } - else { - resolve(response); - } - })); - }); - } -} -exports.HttpClient = HttpClient; -const lowercaseKeys = (obj) => Object.keys(obj).reduce((c, k) => ((c[k.toLowerCase()] = obj[k]), c), {}); -//# sourceMappingURL=index.js.map - -/***/ }), - -/***/ 4988: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.checkBypass = exports.getProxyUrl = void 0; -function getProxyUrl(reqUrl) { - const usingSsl = reqUrl.protocol === 'https:'; - if (checkBypass(reqUrl)) { - return undefined; - } - const proxyVar = (() => { - if (usingSsl) { - return process.env['https_proxy'] || process.env['HTTPS_PROXY']; - } - else { - return process.env['http_proxy'] || process.env['HTTP_PROXY']; - } - })(); - if (proxyVar) { - try { - return new DecodedURL(proxyVar); - } - catch (_a) { - if (!proxyVar.startsWith('http://') && !proxyVar.startsWith('https://')) - return new DecodedURL(`http://${proxyVar}`); - } - } - else { - return undefined; - } -} -exports.getProxyUrl = getProxyUrl; -function checkBypass(reqUrl) { - if (!reqUrl.hostname) { - return false; - } - const reqHost = reqUrl.hostname; - if (isLoopbackAddress(reqHost)) { - return true; - } - const noProxy = process.env['no_proxy'] || process.env['NO_PROXY'] || ''; - if (!noProxy) { - return false; - } - // Determine the request port - let reqPort; - if (reqUrl.port) { - reqPort = Number(reqUrl.port); - } - else if (reqUrl.protocol === 'http:') { - reqPort = 80; - } - else if (reqUrl.protocol === 'https:') { - reqPort = 443; - } - // Format the request hostname and hostname with port - const upperReqHosts = [reqUrl.hostname.toUpperCase()]; - if (typeof reqPort === 'number') { - upperReqHosts.push(`${upperReqHosts[0]}:${reqPort}`); - } - // Compare request host against noproxy - for (const upperNoProxyItem of noProxy - .split(',') - .map(x => x.trim().toUpperCase()) - .filter(x => x)) { - if (upperNoProxyItem === '*' || - upperReqHosts.some(x => x === upperNoProxyItem || - x.endsWith(`.${upperNoProxyItem}`) || - (upperNoProxyItem.startsWith('.') && - x.endsWith(`${upperNoProxyItem}`)))) { - return true; - } - } - return false; -} -exports.checkBypass = checkBypass; -function isLoopbackAddress(host) { - const hostLower = host.toLowerCase(); - return (hostLower === 'localhost' || - hostLower.startsWith('127.') || - hostLower.startsWith('[::1]') || - hostLower.startsWith('[0:0:0:0:0:0:0:1]')); -} -class DecodedURL extends URL { - constructor(url, base) { - super(url, base); - this._decodedUsername = decodeURIComponent(super.username); - this._decodedPassword = decodeURIComponent(super.password); - } - get username() { - return this._decodedUsername; - } - get password() { - return this._decodedPassword; - } -} -//# sourceMappingURL=proxy.js.map - -/***/ }), - -/***/ 5207: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -var _a; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; -const fs = __importStar(__nccwpck_require__(9896)); -const path = __importStar(__nccwpck_require__(6928)); -_a = fs.promises -// export const {open} = 'fs' -, exports.chmod = _a.chmod, exports.copyFile = _a.copyFile, exports.lstat = _a.lstat, exports.mkdir = _a.mkdir, exports.open = _a.open, exports.readdir = _a.readdir, exports.readlink = _a.readlink, exports.rename = _a.rename, exports.rm = _a.rm, exports.rmdir = _a.rmdir, exports.stat = _a.stat, exports.symlink = _a.symlink, exports.unlink = _a.unlink; -// export const {open} = 'fs' -exports.IS_WINDOWS = process.platform === 'win32'; -// See https://github.com/nodejs/node/blob/d0153aee367422d0858105abec186da4dff0a0c5/deps/uv/include/uv/win.h#L691 -exports.UV_FS_O_EXLOCK = 0x10000000; -exports.READONLY = fs.constants.O_RDONLY; -function exists(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - try { - yield exports.stat(fsPath); - } - catch (err) { - if (err.code === 'ENOENT') { - return false; - } - throw err; - } - return true; - }); -} -exports.exists = exists; -function isDirectory(fsPath, useStat = false) { - return __awaiter(this, void 0, void 0, function* () { - const stats = useStat ? yield exports.stat(fsPath) : yield exports.lstat(fsPath); - return stats.isDirectory(); - }); -} -exports.isDirectory = isDirectory; -/** - * On OSX/Linux, true if path starts with '/'. On Windows, true for paths like: - * \, \hello, \\hello\share, C:, and C:\hello (and corresponding alternate separator cases). - */ -function isRooted(p) { - p = normalizeSeparators(p); - if (!p) { - throw new Error('isRooted() parameter "p" cannot be empty'); - } - if (exports.IS_WINDOWS) { - return (p.startsWith('\\') || /^[A-Z]:/i.test(p) // e.g. \ or \hello or \\hello - ); // e.g. C: or C:\hello - } - return p.startsWith('/'); -} -exports.isRooted = isRooted; -/** - * Best effort attempt to determine whether a file exists and is executable. - * @param filePath file path to check - * @param extensions additional file extensions to try - * @return if file exists and is executable, returns the file path. otherwise empty string. - */ -function tryGetExecutablePath(filePath, extensions) { - return __awaiter(this, void 0, void 0, function* () { - let stats = undefined; - try { - // test file exists - stats = yield exports.stat(filePath); - } - catch (err) { - if (err.code !== 'ENOENT') { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports.IS_WINDOWS) { - // on Windows, test for valid extension - const upperExt = path.extname(filePath).toUpperCase(); - if (extensions.some(validExt => validExt.toUpperCase() === upperExt)) { - return filePath; - } - } - else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - // try each extension - const originalFilePath = filePath; - for (const extension of extensions) { - filePath = originalFilePath + extension; - stats = undefined; - try { - stats = yield exports.stat(filePath); - } - catch (err) { - if (err.code !== 'ENOENT') { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine if executable file exists '${filePath}': ${err}`); - } - } - if (stats && stats.isFile()) { - if (exports.IS_WINDOWS) { - // preserve the case of the actual file (since an extension was appended) - try { - const directory = path.dirname(filePath); - const upperName = path.basename(filePath).toUpperCase(); - for (const actualName of yield exports.readdir(directory)) { - if (upperName === actualName.toUpperCase()) { - filePath = path.join(directory, actualName); - break; - } - } - } - catch (err) { - // eslint-disable-next-line no-console - console.log(`Unexpected error attempting to determine the actual case of the file '${filePath}': ${err}`); - } - return filePath; - } - else { - if (isUnixExecutable(stats)) { - return filePath; - } - } - } - } - return ''; - }); -} -exports.tryGetExecutablePath = tryGetExecutablePath; -function normalizeSeparators(p) { - p = p || ''; - if (exports.IS_WINDOWS) { - // convert slashes on Windows - p = p.replace(/\//g, '\\'); - // remove redundant slashes - return p.replace(/\\\\+/g, '\\'); - } - // remove redundant slashes - return p.replace(/\/\/+/g, '/'); -} -// on Mac/Linux, test the execute bit -// R W X R W X R W X -// 256 128 64 32 16 8 4 2 1 -function isUnixExecutable(stats) { - return ((stats.mode & 1) > 0 || - ((stats.mode & 8) > 0 && stats.gid === process.getgid()) || - ((stats.mode & 64) > 0 && stats.uid === process.getuid())); -} -// Get the path of cmd.exe in windows -function getCmdPath() { - var _a; - return (_a = process.env['COMSPEC']) !== null && _a !== void 0 ? _a : `cmd.exe`; -} -exports.getCmdPath = getCmdPath; -//# sourceMappingURL=io-util.js.map - -/***/ }), - -/***/ 4994: -/***/ (function(__unused_webpack_module, exports, __nccwpck_require__) { - - -var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - Object.defineProperty(o, k2, { enumerable: true, get: function() { return m[k]; } }); -}) : (function(o, m, k, k2) { - if (k2 === undefined) k2 = k; - o[k2] = m[k]; -})); -var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { - Object.defineProperty(o, "default", { enumerable: true, value: v }); -}) : function(o, v) { - o["default"] = v; -}); -var __importStar = (this && this.__importStar) || function (mod) { - if (mod && mod.__esModule) return mod; - var result = {}; - if (mod != null) for (var k in mod) if (k !== "default" && Object.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k); - __setModuleDefault(result, mod); - return result; -}; -var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) { - function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } - return new (P || (P = Promise))(function (resolve, reject) { - function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } - function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } - function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } - step((generator = generator.apply(thisArg, _arguments || [])).next()); - }); -}; -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; -const assert_1 = __nccwpck_require__(2613); -const path = __importStar(__nccwpck_require__(6928)); -const ioUtil = __importStar(__nccwpck_require__(5207)); -/** - * Copies a file or folder. - * Based off of shelljs - https://github.com/shelljs/shelljs/blob/9237f66c52e5daa40458f94f9565e18e8132f5a6/src/cp.js - * - * @param source source path - * @param dest destination path - * @param options optional. See CopyOptions. - */ -function cp(source, dest, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - const { force, recursive, copySourceDirectory } = readCopyOptions(options); - const destStat = (yield ioUtil.exists(dest)) ? yield ioUtil.stat(dest) : null; - // Dest is an existing file, but not forcing - if (destStat && destStat.isFile() && !force) { - return; - } - // If dest is an existing directory, should copy inside. - const newDest = destStat && destStat.isDirectory() && copySourceDirectory - ? path.join(dest, path.basename(source)) - : dest; - if (!(yield ioUtil.exists(source))) { - throw new Error(`no such file or directory: ${source}`); - } - const sourceStat = yield ioUtil.stat(source); - if (sourceStat.isDirectory()) { - if (!recursive) { - throw new Error(`Failed to copy. ${source} is a directory, but tried to copy without recursive flag.`); - } - else { - yield cpDirRecursive(source, newDest, 0, force); - } - } - else { - if (path.relative(source, newDest) === '') { - // a file cannot be copied to itself - throw new Error(`'${newDest}' and '${source}' are the same file`); - } - yield copyFile(source, newDest, force); - } - }); -} -exports.cp = cp; -/** - * Moves a path. - * - * @param source source path - * @param dest destination path - * @param options optional. See MoveOptions. - */ -function mv(source, dest, options = {}) { - return __awaiter(this, void 0, void 0, function* () { - if (yield ioUtil.exists(dest)) { - let destExists = true; - if (yield ioUtil.isDirectory(dest)) { - // If dest is directory copy src into dest - dest = path.join(dest, path.basename(source)); - destExists = yield ioUtil.exists(dest); - } - if (destExists) { - if (options.force == null || options.force) { - yield rmRF(dest); - } - else { - throw new Error('Destination already exists'); - } - } - } - yield mkdirP(path.dirname(dest)); - yield ioUtil.rename(source, dest); - }); -} -exports.mv = mv; -/** - * Remove a path recursively with force - * - * @param inputPath path to remove - */ -function rmRF(inputPath) { - return __awaiter(this, void 0, void 0, function* () { - if (ioUtil.IS_WINDOWS) { - // Check for invalid characters - // https://docs.microsoft.com/en-us/windows/win32/fileio/naming-a-file - if (/[*"<>|]/.test(inputPath)) { - throw new Error('File path must not contain `*`, `"`, `<`, `>` or `|` on Windows'); - } - } - try { - // note if path does not exist, error is silent - yield ioUtil.rm(inputPath, { - force: true, - maxRetries: 3, - recursive: true, - retryDelay: 300 - }); - } - catch (err) { - throw new Error(`File was unable to be removed ${err}`); - } - }); -} -exports.rmRF = rmRF; -/** - * Make a directory. Creates the full path with folders in between - * Will throw if it fails - * - * @param fsPath path to create - * @returns Promise - */ -function mkdirP(fsPath) { - return __awaiter(this, void 0, void 0, function* () { - assert_1.ok(fsPath, 'a path argument must be provided'); - yield ioUtil.mkdir(fsPath, { recursive: true }); - }); -} -exports.mkdirP = mkdirP; -/** - * Returns path of a tool had the tool actually been invoked. Resolves via paths. - * If you check and the tool does not exist, it will throw. - * - * @param tool name of the tool - * @param check whether to check if tool exists - * @returns Promise path to tool - */ -function which(tool, check) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - // recursive when check=true - if (check) { - const result = yield which(tool, false); - if (!result) { - if (ioUtil.IS_WINDOWS) { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also verify the file has a valid extension for an executable file.`); - } - else { - throw new Error(`Unable to locate executable file: ${tool}. Please verify either the file path exists or the file can be found within a directory specified by the PATH environment variable. Also check the file mode to verify the file is executable.`); - } - } - return result; - } - const matches = yield findInPath(tool); - if (matches && matches.length > 0) { - return matches[0]; - } - return ''; - }); -} -exports.which = which; -/** - * Returns a list of all occurrences of the given tool on the system path. - * - * @returns Promise the paths of the tool - */ -function findInPath(tool) { - return __awaiter(this, void 0, void 0, function* () { - if (!tool) { - throw new Error("parameter 'tool' is required"); - } - // build the list of extensions to try - const extensions = []; - if (ioUtil.IS_WINDOWS && process.env['PATHEXT']) { - for (const extension of process.env['PATHEXT'].split(path.delimiter)) { - if (extension) { - extensions.push(extension); - } - } - } - // if it's rooted, return it if exists. otherwise return empty. - if (ioUtil.isRooted(tool)) { - const filePath = yield ioUtil.tryGetExecutablePath(tool, extensions); - if (filePath) { - return [filePath]; - } - return []; - } - // if any path separators, return empty - if (tool.includes(path.sep)) { - return []; - } - // build the list of directories - // - // Note, technically "where" checks the current directory on Windows. From a toolkit perspective, - // it feels like we should not do this. Checking the current directory seems like more of a use - // case of a shell, and the which() function exposed by the toolkit should strive for consistency - // across platforms. - const directories = []; - if (process.env.PATH) { - for (const p of process.env.PATH.split(path.delimiter)) { - if (p) { - directories.push(p); - } - } - } - // find all matches - const matches = []; - for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path.join(directory, tool), extensions); - if (filePath) { - matches.push(filePath); - } - } - return matches; - }); -} -exports.findInPath = findInPath; -function readCopyOptions(options) { - const force = options.force == null ? true : options.force; - const recursive = Boolean(options.recursive); - const copySourceDirectory = options.copySourceDirectory == null - ? true - : Boolean(options.copySourceDirectory); - return { force, recursive, copySourceDirectory }; -} -function cpDirRecursive(sourceDir, destDir, currentDepth, force) { - return __awaiter(this, void 0, void 0, function* () { - // Ensure there is not a run away recursive copy - if (currentDepth >= 255) - return; - currentDepth++; - yield mkdirP(destDir); - const files = yield ioUtil.readdir(sourceDir); - for (const fileName of files) { - const srcFile = `${sourceDir}/${fileName}`; - const destFile = `${destDir}/${fileName}`; - const srcFileStat = yield ioUtil.lstat(srcFile); - if (srcFileStat.isDirectory()) { - // Recurse - yield cpDirRecursive(srcFile, destFile, currentDepth, force); - } - else { - yield copyFile(srcFile, destFile, force); - } - } - // Change the mode for the newly created directory - yield ioUtil.chmod(destDir, (yield ioUtil.stat(sourceDir)).mode); - }); -} -// Buffered file copy -function copyFile(srcFile, destFile, force) { - return __awaiter(this, void 0, void 0, function* () { - if ((yield ioUtil.lstat(srcFile)).isSymbolicLink()) { - // unlink/re-link it - try { - yield ioUtil.lstat(destFile); - yield ioUtil.unlink(destFile); - } - catch (e) { - // Try to override file permission - if (e.code === 'EPERM') { - yield ioUtil.chmod(destFile, '0666'); - yield ioUtil.unlink(destFile); - } - // other errors = it doesn't exist, no work to do - } - // Copy over symlink - const symlinkFull = yield ioUtil.readlink(srcFile); - yield ioUtil.symlink(symlinkFull, destFile, ioUtil.IS_WINDOWS ? 'junction' : null); - } - else if (!(yield ioUtil.exists(destFile)) || force) { - yield ioUtil.copyFile(srcFile, destFile); - } - }); -} -//# sourceMappingURL=io.js.map - -/***/ }), - -/***/ 7864: -/***/ ((module) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - createTokenAuth: () => createTokenAuth -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/auth.js -var REGEX_IS_INSTALLATION_LEGACY = /^v1\./; -var REGEX_IS_INSTALLATION = /^ghs_/; -var REGEX_IS_USER_TO_SERVER = /^ghu_/; -async function auth(token) { - const isApp = token.split(/\./).length === 3; - const isInstallation = REGEX_IS_INSTALLATION_LEGACY.test(token) || REGEX_IS_INSTALLATION.test(token); - const isUserToServer = REGEX_IS_USER_TO_SERVER.test(token); - const tokenType = isApp ? "app" : isInstallation ? "installation" : isUserToServer ? "user-to-server" : "oauth"; - return { - type: "token", - token, - tokenType - }; -} - -// pkg/dist-src/with-authorization-prefix.js -function withAuthorizationPrefix(token) { - if (token.split(/\./).length === 3) { - return `bearer ${token}`; - } - return `token ${token}`; -} - -// pkg/dist-src/hook.js -async function hook(token, request, route, parameters) { - const endpoint = request.endpoint.merge( - route, - parameters - ); - endpoint.headers.authorization = withAuthorizationPrefix(token); - return request(endpoint); -} - -// pkg/dist-src/index.js -var createTokenAuth = function createTokenAuth2(token) { - if (!token) { - throw new Error("[@octokit/auth-token] No token passed to createTokenAuth"); - } - if (typeof token !== "string") { - throw new Error( - "[@octokit/auth-token] Token passed to createTokenAuth is not a string" - ); - } - token = token.replace(/^(token|bearer) +/i, ""); - return Object.assign(auth.bind(null, token), { - hook: hook.bind(null, token) - }); -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 1897: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var index_exports = {}; -__export(index_exports, { - Octokit: () => Octokit -}); -module.exports = __toCommonJS(index_exports); -var import_universal_user_agent = __nccwpck_require__(3843); -var import_before_after_hook = __nccwpck_require__(2732); -var import_request = __nccwpck_require__(8636); -var import_graphql = __nccwpck_require__(7); -var import_auth_token = __nccwpck_require__(7864); - -// pkg/dist-src/version.js -var VERSION = "5.2.2"; - -// pkg/dist-src/index.js -var noop = () => { -}; -var consoleWarn = console.warn.bind(console); -var consoleError = console.error.bind(console); -function createLogger(logger = {}) { - if (typeof logger.debug !== "function") { - logger.debug = noop; - } - if (typeof logger.info !== "function") { - logger.info = noop; - } - if (typeof logger.warn !== "function") { - logger.warn = consoleWarn; - } - if (typeof logger.error !== "function") { - logger.error = consoleError; - } - return logger; -} -var userAgentTrail = `octokit-core.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; -var Octokit = class { - static { - this.VERSION = VERSION; - } - static defaults(defaults) { - const OctokitWithDefaults = class extends this { - constructor(...args) { - const options = args[0] || {}; - if (typeof defaults === "function") { - super(defaults(options)); - return; - } - super( - Object.assign( - {}, - defaults, - options, - options.userAgent && defaults.userAgent ? { - userAgent: `${options.userAgent} ${defaults.userAgent}` - } : null - ) - ); - } - }; - return OctokitWithDefaults; - } - static { - this.plugins = []; - } - /** - * Attach a plugin (or many) to your Octokit instance. - * - * @example - * const API = Octokit.plugin(plugin1, plugin2, plugin3, ...) - */ - static plugin(...newPlugins) { - const currentPlugins = this.plugins; - const NewOctokit = class extends this { - static { - this.plugins = currentPlugins.concat( - newPlugins.filter((plugin) => !currentPlugins.includes(plugin)) - ); - } - }; - return NewOctokit; - } - constructor(options = {}) { - const hook = new import_before_after_hook.Collection(); - const requestDefaults = { - baseUrl: import_request.request.endpoint.DEFAULTS.baseUrl, - headers: {}, - request: Object.assign({}, options.request, { - // @ts-ignore internal usage only, no need to type - hook: hook.bind(null, "request") - }), - mediaType: { - previews: [], - format: "" - } - }; - requestDefaults.headers["user-agent"] = options.userAgent ? `${options.userAgent} ${userAgentTrail}` : userAgentTrail; - if (options.baseUrl) { - requestDefaults.baseUrl = options.baseUrl; - } - if (options.previews) { - requestDefaults.mediaType.previews = options.previews; - } - if (options.timeZone) { - requestDefaults.headers["time-zone"] = options.timeZone; - } - this.request = import_request.request.defaults(requestDefaults); - this.graphql = (0, import_graphql.withCustomRequest)(this.request).defaults(requestDefaults); - this.log = createLogger(options.log); - this.hook = hook; - if (!options.authStrategy) { - if (!options.auth) { - this.auth = async () => ({ - type: "unauthenticated" - }); - } else { - const auth = (0, import_auth_token.createTokenAuth)(options.auth); - hook.wrap("request", auth.hook); - this.auth = auth; - } - } else { - const { authStrategy, ...otherOptions } = options; - const auth = authStrategy( - Object.assign( - { - request: this.request, - log: this.log, - // we pass the current octokit instance as well as its constructor options - // to allow for authentication strategies that return a new octokit instance - // that shares the same internal state as the current one. The original - // requirement for this was the "event-octokit" authentication strategy - // of https://github.com/probot/octokit-auth-probot. - octokit: this, - octokitOptions: otherOptions - }, - options.auth - ) - ); - hook.wrap("request", auth.hook); - this.auth = auth; - } - const classConstructor = this.constructor; - for (let i = 0; i < classConstructor.plugins.length; ++i) { - Object.assign(this, classConstructor.plugins[i](this, options)); - } - } -}; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 4471: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - endpoint: () => endpoint -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/defaults.js -var import_universal_user_agent = __nccwpck_require__(3843); - -// pkg/dist-src/version.js -var VERSION = "9.0.6"; - -// pkg/dist-src/defaults.js -var userAgent = `octokit-endpoint.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}`; -var DEFAULTS = { - method: "GET", - baseUrl: "https://api.github.com", - headers: { - accept: "application/vnd.github.v3+json", - "user-agent": userAgent - }, - mediaType: { - format: "" - } -}; - -// pkg/dist-src/util/lowercase-keys.js -function lowercaseKeys(object) { - if (!object) { - return {}; - } - return Object.keys(object).reduce((newObj, key) => { - newObj[key.toLowerCase()] = object[key]; - return newObj; - }, {}); -} - -// pkg/dist-src/util/is-plain-object.js -function isPlainObject(value) { - if (typeof value !== "object" || value === null) - return false; - if (Object.prototype.toString.call(value) !== "[object Object]") - return false; - const proto = Object.getPrototypeOf(value); - if (proto === null) - return true; - const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); -} - -// pkg/dist-src/util/merge-deep.js -function mergeDeep(defaults, options) { - const result = Object.assign({}, defaults); - Object.keys(options).forEach((key) => { - if (isPlainObject(options[key])) { - if (!(key in defaults)) - Object.assign(result, { [key]: options[key] }); - else - result[key] = mergeDeep(defaults[key], options[key]); - } else { - Object.assign(result, { [key]: options[key] }); - } - }); - return result; -} - -// pkg/dist-src/util/remove-undefined-properties.js -function removeUndefinedProperties(obj) { - for (const key in obj) { - if (obj[key] === void 0) { - delete obj[key]; - } - } - return obj; -} - -// pkg/dist-src/merge.js -function merge(defaults, route, options) { - if (typeof route === "string") { - let [method, url] = route.split(" "); - options = Object.assign(url ? { method, url } : { url: method }, options); - } else { - options = Object.assign({}, route); - } - options.headers = lowercaseKeys(options.headers); - removeUndefinedProperties(options); - removeUndefinedProperties(options.headers); - const mergedOptions = mergeDeep(defaults || {}, options); - if (options.url === "/graphql") { - if (defaults && defaults.mediaType.previews?.length) { - mergedOptions.mediaType.previews = defaults.mediaType.previews.filter( - (preview) => !mergedOptions.mediaType.previews.includes(preview) - ).concat(mergedOptions.mediaType.previews); - } - mergedOptions.mediaType.previews = (mergedOptions.mediaType.previews || []).map((preview) => preview.replace(/-preview/, "")); - } - return mergedOptions; -} - -// pkg/dist-src/util/add-query-parameters.js -function addQueryParameters(url, parameters) { - const separator = /\?/.test(url) ? "&" : "?"; - const names = Object.keys(parameters); - if (names.length === 0) { - return url; - } - return url + separator + names.map((name) => { - if (name === "q") { - return "q=" + parameters.q.split("+").map(encodeURIComponent).join("+"); - } - return `${name}=${encodeURIComponent(parameters[name])}`; - }).join("&"); -} - -// pkg/dist-src/util/extract-url-variable-names.js -var urlVariableRegex = /\{[^{}}]+\}/g; -function removeNonChars(variableName) { - return variableName.replace(/(?:^\W+)|(?:(? a.concat(b), []); -} - -// pkg/dist-src/util/omit.js -function omit(object, keysToOmit) { - const result = { __proto__: null }; - for (const key of Object.keys(object)) { - if (keysToOmit.indexOf(key) === -1) { - result[key] = object[key]; - } - } - return result; -} - -// pkg/dist-src/util/url-template.js -function encodeReserved(str) { - return str.split(/(%[0-9A-Fa-f]{2})/g).map(function(part) { - if (!/%[0-9A-Fa-f]/.test(part)) { - part = encodeURI(part).replace(/%5B/g, "[").replace(/%5D/g, "]"); - } - return part; - }).join(""); -} -function encodeUnreserved(str) { - return encodeURIComponent(str).replace(/[!'()*]/g, function(c) { - return "%" + c.charCodeAt(0).toString(16).toUpperCase(); - }); -} -function encodeValue(operator, value, key) { - value = operator === "+" || operator === "#" ? encodeReserved(value) : encodeUnreserved(value); - if (key) { - return encodeUnreserved(key) + "=" + value; - } else { - return value; - } -} -function isDefined(value) { - return value !== void 0 && value !== null; -} -function isKeyOperator(operator) { - return operator === ";" || operator === "&" || operator === "?"; -} -function getValues(context, operator, key, modifier) { - var value = context[key], result = []; - if (isDefined(value) && value !== "") { - if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") { - value = value.toString(); - if (modifier && modifier !== "*") { - value = value.substring(0, parseInt(modifier, 10)); - } - result.push( - encodeValue(operator, value, isKeyOperator(operator) ? key : "") - ); - } else { - if (modifier === "*") { - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - result.push( - encodeValue(operator, value2, isKeyOperator(operator) ? key : "") - ); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - result.push(encodeValue(operator, value[k], k)); - } - }); - } - } else { - const tmp = []; - if (Array.isArray(value)) { - value.filter(isDefined).forEach(function(value2) { - tmp.push(encodeValue(operator, value2)); - }); - } else { - Object.keys(value).forEach(function(k) { - if (isDefined(value[k])) { - tmp.push(encodeUnreserved(k)); - tmp.push(encodeValue(operator, value[k].toString())); - } - }); - } - if (isKeyOperator(operator)) { - result.push(encodeUnreserved(key) + "=" + tmp.join(",")); - } else if (tmp.length !== 0) { - result.push(tmp.join(",")); - } - } - } - } else { - if (operator === ";") { - if (isDefined(value)) { - result.push(encodeUnreserved(key)); - } - } else if (value === "" && (operator === "&" || operator === "?")) { - result.push(encodeUnreserved(key) + "="); - } else if (value === "") { - result.push(""); - } - } - return result; -} -function parseUrl(template) { - return { - expand: expand.bind(null, template) - }; -} -function expand(template, context) { - var operators = ["+", "#", ".", "/", ";", "?", "&"]; - template = template.replace( - /\{([^\{\}]+)\}|([^\{\}]+)/g, - function(_, expression, literal) { - if (expression) { - let operator = ""; - const values = []; - if (operators.indexOf(expression.charAt(0)) !== -1) { - operator = expression.charAt(0); - expression = expression.substr(1); - } - expression.split(/,/g).forEach(function(variable) { - var tmp = /([^:\*]*)(?::(\d+)|(\*))?/.exec(variable); - values.push(getValues(context, operator, tmp[1], tmp[2] || tmp[3])); - }); - if (operator && operator !== "+") { - var separator = ","; - if (operator === "?") { - separator = "&"; - } else if (operator !== "#") { - separator = operator; - } - return (values.length !== 0 ? operator : "") + values.join(separator); - } else { - return values.join(","); - } - } else { - return encodeReserved(literal); - } - } - ); - if (template === "/") { - return template; - } else { - return template.replace(/\/$/, ""); - } -} - -// pkg/dist-src/parse.js -function parse(options) { - let method = options.method.toUpperCase(); - let url = (options.url || "/").replace(/:([a-z]\w+)/g, "{$1}"); - let headers = Object.assign({}, options.headers); - let body; - let parameters = omit(options, [ - "method", - "baseUrl", - "url", - "headers", - "request", - "mediaType" - ]); - const urlVariableNames = extractUrlVariableNames(url); - url = parseUrl(url).expand(parameters); - if (!/^http/.test(url)) { - url = options.baseUrl + url; - } - const omittedParameters = Object.keys(options).filter((option) => urlVariableNames.includes(option)).concat("baseUrl"); - const remainingParameters = omit(parameters, omittedParameters); - const isBinaryRequest = /application\/octet-stream/i.test(headers.accept); - if (!isBinaryRequest) { - if (options.mediaType.format) { - headers.accept = headers.accept.split(/,/).map( - (format) => format.replace( - /application\/vnd(\.\w+)(\.v3)?(\.\w+)?(\+json)?$/, - `application/vnd$1$2.${options.mediaType.format}` - ) - ).join(","); - } - if (url.endsWith("/graphql")) { - if (options.mediaType.previews?.length) { - const previewsFromAcceptHeader = headers.accept.match(/(? { - const format = options.mediaType.format ? `.${options.mediaType.format}` : "+json"; - return `application/vnd.github.${preview}-preview${format}`; - }).join(","); - } - } - } - if (["GET", "HEAD"].includes(method)) { - url = addQueryParameters(url, remainingParameters); - } else { - if ("data" in remainingParameters) { - body = remainingParameters.data; - } else { - if (Object.keys(remainingParameters).length) { - body = remainingParameters; - } - } - } - if (!headers["content-type"] && typeof body !== "undefined") { - headers["content-type"] = "application/json; charset=utf-8"; - } - if (["PATCH", "PUT"].includes(method) && typeof body === "undefined") { - body = ""; - } - return Object.assign( - { method, url, headers }, - typeof body !== "undefined" ? { body } : null, - options.request ? { request: options.request } : null - ); -} - -// pkg/dist-src/endpoint-with-defaults.js -function endpointWithDefaults(defaults, route, options) { - return parse(merge(defaults, route, options)); -} - -// pkg/dist-src/with-defaults.js -function withDefaults(oldDefaults, newDefaults) { - const DEFAULTS2 = merge(oldDefaults, newDefaults); - const endpoint2 = endpointWithDefaults.bind(null, DEFAULTS2); - return Object.assign(endpoint2, { - DEFAULTS: DEFAULTS2, - defaults: withDefaults.bind(null, DEFAULTS2), - merge: merge.bind(null, DEFAULTS2), - parse - }); -} - -// pkg/dist-src/index.js -var endpoint = withDefaults(null, DEFAULTS); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 7: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var index_exports = {}; -__export(index_exports, { - GraphqlResponseError: () => GraphqlResponseError, - graphql: () => graphql2, - withCustomRequest: () => withCustomRequest -}); -module.exports = __toCommonJS(index_exports); -var import_request3 = __nccwpck_require__(8636); -var import_universal_user_agent = __nccwpck_require__(3843); - -// pkg/dist-src/version.js -var VERSION = "7.1.1"; - -// pkg/dist-src/with-defaults.js -var import_request2 = __nccwpck_require__(8636); - -// pkg/dist-src/graphql.js -var import_request = __nccwpck_require__(8636); - -// pkg/dist-src/error.js -function _buildMessageForResponseErrors(data) { - return `Request failed due to following response errors: -` + data.errors.map((e) => ` - ${e.message}`).join("\n"); -} -var GraphqlResponseError = class extends Error { - constructor(request2, headers, response) { - super(_buildMessageForResponseErrors(response)); - this.request = request2; - this.headers = headers; - this.response = response; - this.name = "GraphqlResponseError"; - this.errors = response.errors; - this.data = response.data; - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - } -}; - -// pkg/dist-src/graphql.js -var NON_VARIABLE_OPTIONS = [ - "method", - "baseUrl", - "url", - "headers", - "request", - "query", - "mediaType" -]; -var FORBIDDEN_VARIABLE_OPTIONS = ["query", "method", "url"]; -var GHES_V3_SUFFIX_REGEX = /\/api\/v3\/?$/; -function graphql(request2, query, options) { - if (options) { - if (typeof query === "string" && "query" in options) { - return Promise.reject( - new Error(`[@octokit/graphql] "query" cannot be used as variable name`) - ); - } - for (const key in options) { - if (!FORBIDDEN_VARIABLE_OPTIONS.includes(key)) continue; - return Promise.reject( - new Error( - `[@octokit/graphql] "${key}" cannot be used as variable name` - ) - ); - } - } - const parsedOptions = typeof query === "string" ? Object.assign({ query }, options) : query; - const requestOptions = Object.keys( - parsedOptions - ).reduce((result, key) => { - if (NON_VARIABLE_OPTIONS.includes(key)) { - result[key] = parsedOptions[key]; - return result; - } - if (!result.variables) { - result.variables = {}; - } - result.variables[key] = parsedOptions[key]; - return result; - }, {}); - const baseUrl = parsedOptions.baseUrl || request2.endpoint.DEFAULTS.baseUrl; - if (GHES_V3_SUFFIX_REGEX.test(baseUrl)) { - requestOptions.url = baseUrl.replace(GHES_V3_SUFFIX_REGEX, "/api/graphql"); - } - return request2(requestOptions).then((response) => { - if (response.data.errors) { - const headers = {}; - for (const key of Object.keys(response.headers)) { - headers[key] = response.headers[key]; - } - throw new GraphqlResponseError( - requestOptions, - headers, - response.data - ); - } - return response.data.data; - }); -} - -// pkg/dist-src/with-defaults.js -function withDefaults(request2, newDefaults) { - const newRequest = request2.defaults(newDefaults); - const newApi = (query, options) => { - return graphql(newRequest, query, options); - }; - return Object.assign(newApi, { - defaults: withDefaults.bind(null, newRequest), - endpoint: newRequest.endpoint - }); -} - -// pkg/dist-src/index.js -var graphql2 = withDefaults(import_request3.request, { - headers: { - "user-agent": `octokit-graphql.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - }, - method: "POST", - url: "/graphql" -}); -function withCustomRequest(customRequest) { - return withDefaults(customRequest, { - method: "POST", - url: "/graphql" - }); -} -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 8082: -/***/ ((module) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - composePaginateRest: () => composePaginateRest, - isPaginatingEndpoint: () => isPaginatingEndpoint, - paginateRest: () => paginateRest, - paginatingEndpoints: () => paginatingEndpoints -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/version.js -var VERSION = "9.2.2"; - -// pkg/dist-src/normalize-paginated-list-response.js -function normalizePaginatedListResponse(response) { - if (!response.data) { - return { - ...response, - data: [] - }; - } - const responseNeedsNormalization = "total_count" in response.data && !("url" in response.data); - if (!responseNeedsNormalization) - return response; - const incompleteResults = response.data.incomplete_results; - const repositorySelection = response.data.repository_selection; - const totalCount = response.data.total_count; - delete response.data.incomplete_results; - delete response.data.repository_selection; - delete response.data.total_count; - const namespaceKey = Object.keys(response.data)[0]; - const data = response.data[namespaceKey]; - response.data = data; - if (typeof incompleteResults !== "undefined") { - response.data.incomplete_results = incompleteResults; - } - if (typeof repositorySelection !== "undefined") { - response.data.repository_selection = repositorySelection; - } - response.data.total_count = totalCount; - return response; -} - -// pkg/dist-src/iterator.js -function iterator(octokit, route, parameters) { - const options = typeof route === "function" ? route.endpoint(parameters) : octokit.request.endpoint(route, parameters); - const requestMethod = typeof route === "function" ? route : octokit.request; - const method = options.method; - const headers = options.headers; - let url = options.url; - return { - [Symbol.asyncIterator]: () => ({ - async next() { - if (!url) - return { done: true }; - try { - const response = await requestMethod({ method, url, headers }); - const normalizedResponse = normalizePaginatedListResponse(response); - url = ((normalizedResponse.headers.link || "").match( - /<([^<>]+)>;\s*rel="next"/ - ) || [])[1]; - return { value: normalizedResponse }; - } catch (error) { - if (error.status !== 409) - throw error; - url = ""; - return { - value: { - status: 200, - headers: {}, - data: [] - } - }; - } - } - }) - }; -} - -// pkg/dist-src/paginate.js -function paginate(octokit, route, parameters, mapFn) { - if (typeof parameters === "function") { - mapFn = parameters; - parameters = void 0; - } - return gather( - octokit, - [], - iterator(octokit, route, parameters)[Symbol.asyncIterator](), - mapFn - ); -} -function gather(octokit, results, iterator2, mapFn) { - return iterator2.next().then((result) => { - if (result.done) { - return results; - } - let earlyExit = false; - function done() { - earlyExit = true; - } - results = results.concat( - mapFn ? mapFn(result.value, done) : result.value.data - ); - if (earlyExit) { - return results; - } - return gather(octokit, results, iterator2, mapFn); - }); -} - -// pkg/dist-src/compose-paginate.js -var composePaginateRest = Object.assign(paginate, { - iterator -}); - -// pkg/dist-src/generated/paginating-endpoints.js -var paginatingEndpoints = [ - "GET /advisories", - "GET /app/hook/deliveries", - "GET /app/installation-requests", - "GET /app/installations", - "GET /assignments/{assignment_id}/accepted_assignments", - "GET /classrooms", - "GET /classrooms/{classroom_id}/assignments", - "GET /enterprises/{enterprise}/dependabot/alerts", - "GET /enterprises/{enterprise}/secret-scanning/alerts", - "GET /events", - "GET /gists", - "GET /gists/public", - "GET /gists/starred", - "GET /gists/{gist_id}/comments", - "GET /gists/{gist_id}/commits", - "GET /gists/{gist_id}/forks", - "GET /installation/repositories", - "GET /issues", - "GET /licenses", - "GET /marketplace_listing/plans", - "GET /marketplace_listing/plans/{plan_id}/accounts", - "GET /marketplace_listing/stubbed/plans", - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts", - "GET /networks/{owner}/{repo}/events", - "GET /notifications", - "GET /organizations", - "GET /orgs/{org}/actions/cache/usage-by-repository", - "GET /orgs/{org}/actions/permissions/repositories", - "GET /orgs/{org}/actions/runners", - "GET /orgs/{org}/actions/secrets", - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories", - "GET /orgs/{org}/actions/variables", - "GET /orgs/{org}/actions/variables/{name}/repositories", - "GET /orgs/{org}/blocks", - "GET /orgs/{org}/code-scanning/alerts", - "GET /orgs/{org}/codespaces", - "GET /orgs/{org}/codespaces/secrets", - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories", - "GET /orgs/{org}/copilot/billing/seats", - "GET /orgs/{org}/dependabot/alerts", - "GET /orgs/{org}/dependabot/secrets", - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories", - "GET /orgs/{org}/events", - "GET /orgs/{org}/failed_invitations", - "GET /orgs/{org}/hooks", - "GET /orgs/{org}/hooks/{hook_id}/deliveries", - "GET /orgs/{org}/installations", - "GET /orgs/{org}/invitations", - "GET /orgs/{org}/invitations/{invitation_id}/teams", - "GET /orgs/{org}/issues", - "GET /orgs/{org}/members", - "GET /orgs/{org}/members/{username}/codespaces", - "GET /orgs/{org}/migrations", - "GET /orgs/{org}/migrations/{migration_id}/repositories", - "GET /orgs/{org}/organization-roles/{role_id}/teams", - "GET /orgs/{org}/organization-roles/{role_id}/users", - "GET /orgs/{org}/outside_collaborators", - "GET /orgs/{org}/packages", - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - "GET /orgs/{org}/personal-access-token-requests", - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories", - "GET /orgs/{org}/personal-access-tokens", - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories", - "GET /orgs/{org}/projects", - "GET /orgs/{org}/properties/values", - "GET /orgs/{org}/public_members", - "GET /orgs/{org}/repos", - "GET /orgs/{org}/rulesets", - "GET /orgs/{org}/rulesets/rule-suites", - "GET /orgs/{org}/secret-scanning/alerts", - "GET /orgs/{org}/security-advisories", - "GET /orgs/{org}/teams", - "GET /orgs/{org}/teams/{team_slug}/discussions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions", - "GET /orgs/{org}/teams/{team_slug}/invitations", - "GET /orgs/{org}/teams/{team_slug}/members", - "GET /orgs/{org}/teams/{team_slug}/projects", - "GET /orgs/{org}/teams/{team_slug}/repos", - "GET /orgs/{org}/teams/{team_slug}/teams", - "GET /projects/columns/{column_id}/cards", - "GET /projects/{project_id}/collaborators", - "GET /projects/{project_id}/columns", - "GET /repos/{owner}/{repo}/actions/artifacts", - "GET /repos/{owner}/{repo}/actions/caches", - "GET /repos/{owner}/{repo}/actions/organization-secrets", - "GET /repos/{owner}/{repo}/actions/organization-variables", - "GET /repos/{owner}/{repo}/actions/runners", - "GET /repos/{owner}/{repo}/actions/runs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs", - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs", - "GET /repos/{owner}/{repo}/actions/secrets", - "GET /repos/{owner}/{repo}/actions/variables", - "GET /repos/{owner}/{repo}/actions/workflows", - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs", - "GET /repos/{owner}/{repo}/activity", - "GET /repos/{owner}/{repo}/assignees", - "GET /repos/{owner}/{repo}/branches", - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations", - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs", - "GET /repos/{owner}/{repo}/code-scanning/alerts", - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - "GET /repos/{owner}/{repo}/code-scanning/analyses", - "GET /repos/{owner}/{repo}/codespaces", - "GET /repos/{owner}/{repo}/codespaces/devcontainers", - "GET /repos/{owner}/{repo}/codespaces/secrets", - "GET /repos/{owner}/{repo}/collaborators", - "GET /repos/{owner}/{repo}/comments", - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/commits", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments", - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls", - "GET /repos/{owner}/{repo}/commits/{ref}/check-runs", - "GET /repos/{owner}/{repo}/commits/{ref}/check-suites", - "GET /repos/{owner}/{repo}/commits/{ref}/status", - "GET /repos/{owner}/{repo}/commits/{ref}/statuses", - "GET /repos/{owner}/{repo}/contributors", - "GET /repos/{owner}/{repo}/dependabot/alerts", - "GET /repos/{owner}/{repo}/dependabot/secrets", - "GET /repos/{owner}/{repo}/deployments", - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses", - "GET /repos/{owner}/{repo}/environments", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies", - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps", - "GET /repos/{owner}/{repo}/events", - "GET /repos/{owner}/{repo}/forks", - "GET /repos/{owner}/{repo}/hooks", - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries", - "GET /repos/{owner}/{repo}/invitations", - "GET /repos/{owner}/{repo}/issues", - "GET /repos/{owner}/{repo}/issues/comments", - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/issues/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/comments", - "GET /repos/{owner}/{repo}/issues/{issue_number}/events", - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels", - "GET /repos/{owner}/{repo}/issues/{issue_number}/reactions", - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline", - "GET /repos/{owner}/{repo}/keys", - "GET /repos/{owner}/{repo}/labels", - "GET /repos/{owner}/{repo}/milestones", - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels", - "GET /repos/{owner}/{repo}/notifications", - "GET /repos/{owner}/{repo}/pages/builds", - "GET /repos/{owner}/{repo}/projects", - "GET /repos/{owner}/{repo}/pulls", - "GET /repos/{owner}/{repo}/pulls/comments", - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/commits", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/files", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews", - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments", - "GET /repos/{owner}/{repo}/releases", - "GET /repos/{owner}/{repo}/releases/{release_id}/assets", - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions", - "GET /repos/{owner}/{repo}/rules/branches/{branch}", - "GET /repos/{owner}/{repo}/rulesets", - "GET /repos/{owner}/{repo}/rulesets/rule-suites", - "GET /repos/{owner}/{repo}/secret-scanning/alerts", - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations", - "GET /repos/{owner}/{repo}/security-advisories", - "GET /repos/{owner}/{repo}/stargazers", - "GET /repos/{owner}/{repo}/subscribers", - "GET /repos/{owner}/{repo}/tags", - "GET /repos/{owner}/{repo}/teams", - "GET /repos/{owner}/{repo}/topics", - "GET /repositories", - "GET /repositories/{repository_id}/environments/{environment_name}/secrets", - "GET /repositories/{repository_id}/environments/{environment_name}/variables", - "GET /search/code", - "GET /search/commits", - "GET /search/issues", - "GET /search/labels", - "GET /search/repositories", - "GET /search/topics", - "GET /search/users", - "GET /teams/{team_id}/discussions", - "GET /teams/{team_id}/discussions/{discussion_number}/comments", - "GET /teams/{team_id}/discussions/{discussion_number}/comments/{comment_number}/reactions", - "GET /teams/{team_id}/discussions/{discussion_number}/reactions", - "GET /teams/{team_id}/invitations", - "GET /teams/{team_id}/members", - "GET /teams/{team_id}/projects", - "GET /teams/{team_id}/repos", - "GET /teams/{team_id}/teams", - "GET /user/blocks", - "GET /user/codespaces", - "GET /user/codespaces/secrets", - "GET /user/emails", - "GET /user/followers", - "GET /user/following", - "GET /user/gpg_keys", - "GET /user/installations", - "GET /user/installations/{installation_id}/repositories", - "GET /user/issues", - "GET /user/keys", - "GET /user/marketplace_purchases", - "GET /user/marketplace_purchases/stubbed", - "GET /user/memberships/orgs", - "GET /user/migrations", - "GET /user/migrations/{migration_id}/repositories", - "GET /user/orgs", - "GET /user/packages", - "GET /user/packages/{package_type}/{package_name}/versions", - "GET /user/public_emails", - "GET /user/repos", - "GET /user/repository_invitations", - "GET /user/social_accounts", - "GET /user/ssh_signing_keys", - "GET /user/starred", - "GET /user/subscriptions", - "GET /user/teams", - "GET /users", - "GET /users/{username}/events", - "GET /users/{username}/events/orgs/{org}", - "GET /users/{username}/events/public", - "GET /users/{username}/followers", - "GET /users/{username}/following", - "GET /users/{username}/gists", - "GET /users/{username}/gpg_keys", - "GET /users/{username}/keys", - "GET /users/{username}/orgs", - "GET /users/{username}/packages", - "GET /users/{username}/projects", - "GET /users/{username}/received_events", - "GET /users/{username}/received_events/public", - "GET /users/{username}/repos", - "GET /users/{username}/social_accounts", - "GET /users/{username}/ssh_signing_keys", - "GET /users/{username}/starred", - "GET /users/{username}/subscriptions" -]; - -// pkg/dist-src/paginating-endpoints.js -function isPaginatingEndpoint(arg) { - if (typeof arg === "string") { - return paginatingEndpoints.includes(arg); - } else { - return false; - } -} - -// pkg/dist-src/index.js -function paginateRest(octokit) { - return { - paginate: Object.assign(paginate.bind(null, octokit), { - iterator: iterator.bind(null, octokit) - }) - }; -} -paginateRest.VERSION = VERSION; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 4935: -/***/ ((module) => { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - legacyRestEndpointMethods: () => legacyRestEndpointMethods, - restEndpointMethods: () => restEndpointMethods -}); -module.exports = __toCommonJS(dist_src_exports); - -// pkg/dist-src/version.js -var VERSION = "10.4.1"; - -// pkg/dist-src/generated/endpoints.js -var Endpoints = { - actions: { - addCustomLabelsToSelfHostedRunnerForOrg: [ - "POST /orgs/{org}/actions/runners/{runner_id}/labels" - ], - addCustomLabelsToSelfHostedRunnerForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - approveWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/approve" - ], - cancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/cancel" - ], - createEnvironmentVariable: [ - "POST /repositories/{repository_id}/environments/{environment_name}/variables" - ], - createOrUpdateEnvironmentSecret: [ - "PUT /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - createOrUpdateOrgSecret: ["PUT /orgs/{org}/actions/secrets/{secret_name}"], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - createOrgVariable: ["POST /orgs/{org}/actions/variables"], - createRegistrationTokenForOrg: [ - "POST /orgs/{org}/actions/runners/registration-token" - ], - createRegistrationTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/registration-token" - ], - createRemoveTokenForOrg: ["POST /orgs/{org}/actions/runners/remove-token"], - createRemoveTokenForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/remove-token" - ], - createRepoVariable: ["POST /repos/{owner}/{repo}/actions/variables"], - createWorkflowDispatch: [ - "POST /repos/{owner}/{repo}/actions/workflows/{workflow_id}/dispatches" - ], - deleteActionsCacheById: [ - "DELETE /repos/{owner}/{repo}/actions/caches/{cache_id}" - ], - deleteActionsCacheByKey: [ - "DELETE /repos/{owner}/{repo}/actions/caches{?key,ref}" - ], - deleteArtifact: [ - "DELETE /repos/{owner}/{repo}/actions/artifacts/{artifact_id}" - ], - deleteEnvironmentSecret: [ - "DELETE /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - deleteEnvironmentVariable: [ - "DELETE /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/actions/secrets/{secret_name}"], - deleteOrgVariable: ["DELETE /orgs/{org}/actions/variables/{name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/actions/secrets/{secret_name}" - ], - deleteRepoVariable: [ - "DELETE /repos/{owner}/{repo}/actions/variables/{name}" - ], - deleteSelfHostedRunnerFromOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}" - ], - deleteSelfHostedRunnerFromRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - deleteWorkflowRun: ["DELETE /repos/{owner}/{repo}/actions/runs/{run_id}"], - deleteWorkflowRunLogs: [ - "DELETE /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - disableSelectedRepositoryGithubActionsOrganization: [ - "DELETE /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - disableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/disable" - ], - downloadArtifact: [ - "GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}/{archive_format}" - ], - downloadJobLogsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/jobs/{job_id}/logs" - ], - downloadWorkflowRunAttemptLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/logs" - ], - downloadWorkflowRunLogs: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/logs" - ], - enableSelectedRepositoryGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories/{repository_id}" - ], - enableWorkflow: [ - "PUT /repos/{owner}/{repo}/actions/workflows/{workflow_id}/enable" - ], - forceCancelWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/force-cancel" - ], - generateRunnerJitconfigForOrg: [ - "POST /orgs/{org}/actions/runners/generate-jitconfig" - ], - generateRunnerJitconfigForRepo: [ - "POST /repos/{owner}/{repo}/actions/runners/generate-jitconfig" - ], - getActionsCacheList: ["GET /repos/{owner}/{repo}/actions/caches"], - getActionsCacheUsage: ["GET /repos/{owner}/{repo}/actions/cache/usage"], - getActionsCacheUsageByRepoForOrg: [ - "GET /orgs/{org}/actions/cache/usage-by-repository" - ], - getActionsCacheUsageForOrg: ["GET /orgs/{org}/actions/cache/usage"], - getAllowedActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/selected-actions" - ], - getAllowedActionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - getArtifact: ["GET /repos/{owner}/{repo}/actions/artifacts/{artifact_id}"], - getCustomOidcSubClaimForRepo: [ - "GET /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - getEnvironmentPublicKey: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets/public-key" - ], - getEnvironmentSecret: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets/{secret_name}" - ], - getEnvironmentVariable: [ - "GET /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - getGithubActionsDefaultWorkflowPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions/workflow" - ], - getGithubActionsDefaultWorkflowPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/workflow" - ], - getGithubActionsPermissionsOrganization: [ - "GET /orgs/{org}/actions/permissions" - ], - getGithubActionsPermissionsRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions" - ], - getJobForWorkflowRun: ["GET /repos/{owner}/{repo}/actions/jobs/{job_id}"], - getOrgPublicKey: ["GET /orgs/{org}/actions/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/actions/secrets/{secret_name}"], - getOrgVariable: ["GET /orgs/{org}/actions/variables/{name}"], - getPendingDeploymentsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - getRepoPermissions: [ - "GET /repos/{owner}/{repo}/actions/permissions", - {}, - { renamed: ["actions", "getGithubActionsPermissionsRepository"] } - ], - getRepoPublicKey: ["GET /repos/{owner}/{repo}/actions/secrets/public-key"], - getRepoSecret: ["GET /repos/{owner}/{repo}/actions/secrets/{secret_name}"], - getRepoVariable: ["GET /repos/{owner}/{repo}/actions/variables/{name}"], - getReviewsForRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/approvals" - ], - getSelfHostedRunnerForOrg: ["GET /orgs/{org}/actions/runners/{runner_id}"], - getSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}" - ], - getWorkflow: ["GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}"], - getWorkflowAccessToRepository: [ - "GET /repos/{owner}/{repo}/actions/permissions/access" - ], - getWorkflowRun: ["GET /repos/{owner}/{repo}/actions/runs/{run_id}"], - getWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}" - ], - getWorkflowRunUsage: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/timing" - ], - getWorkflowUsage: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/timing" - ], - listArtifactsForRepo: ["GET /repos/{owner}/{repo}/actions/artifacts"], - listEnvironmentSecrets: [ - "GET /repositories/{repository_id}/environments/{environment_name}/secrets" - ], - listEnvironmentVariables: [ - "GET /repositories/{repository_id}/environments/{environment_name}/variables" - ], - listJobsForWorkflowRun: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/jobs" - ], - listJobsForWorkflowRunAttempt: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/attempts/{attempt_number}/jobs" - ], - listLabelsForSelfHostedRunnerForOrg: [ - "GET /orgs/{org}/actions/runners/{runner_id}/labels" - ], - listLabelsForSelfHostedRunnerForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - listOrgSecrets: ["GET /orgs/{org}/actions/secrets"], - listOrgVariables: ["GET /orgs/{org}/actions/variables"], - listRepoOrganizationSecrets: [ - "GET /repos/{owner}/{repo}/actions/organization-secrets" - ], - listRepoOrganizationVariables: [ - "GET /repos/{owner}/{repo}/actions/organization-variables" - ], - listRepoSecrets: ["GET /repos/{owner}/{repo}/actions/secrets"], - listRepoVariables: ["GET /repos/{owner}/{repo}/actions/variables"], - listRepoWorkflows: ["GET /repos/{owner}/{repo}/actions/workflows"], - listRunnerApplicationsForOrg: ["GET /orgs/{org}/actions/runners/downloads"], - listRunnerApplicationsForRepo: [ - "GET /repos/{owner}/{repo}/actions/runners/downloads" - ], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - listSelectedReposForOrgVariable: [ - "GET /orgs/{org}/actions/variables/{name}/repositories" - ], - listSelectedRepositoriesEnabledGithubActionsOrganization: [ - "GET /orgs/{org}/actions/permissions/repositories" - ], - listSelfHostedRunnersForOrg: ["GET /orgs/{org}/actions/runners"], - listSelfHostedRunnersForRepo: ["GET /repos/{owner}/{repo}/actions/runners"], - listWorkflowRunArtifacts: [ - "GET /repos/{owner}/{repo}/actions/runs/{run_id}/artifacts" - ], - listWorkflowRuns: [ - "GET /repos/{owner}/{repo}/actions/workflows/{workflow_id}/runs" - ], - listWorkflowRunsForRepo: ["GET /repos/{owner}/{repo}/actions/runs"], - reRunJobForWorkflowRun: [ - "POST /repos/{owner}/{repo}/actions/jobs/{job_id}/rerun" - ], - reRunWorkflow: ["POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun"], - reRunWorkflowFailedJobs: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/rerun-failed-jobs" - ], - removeAllCustomLabelsFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels" - ], - removeAllCustomLabelsFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - removeCustomLabelFromSelfHostedRunnerForOrg: [ - "DELETE /orgs/{org}/actions/runners/{runner_id}/labels/{name}" - ], - removeCustomLabelFromSelfHostedRunnerForRepo: [ - "DELETE /repos/{owner}/{repo}/actions/runners/{runner_id}/labels/{name}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/actions/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgVariable: [ - "DELETE /orgs/{org}/actions/variables/{name}/repositories/{repository_id}" - ], - reviewCustomGatesForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/deployment_protection_rule" - ], - reviewPendingDeploymentsForRun: [ - "POST /repos/{owner}/{repo}/actions/runs/{run_id}/pending_deployments" - ], - setAllowedActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/selected-actions" - ], - setAllowedActionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/selected-actions" - ], - setCustomLabelsForSelfHostedRunnerForOrg: [ - "PUT /orgs/{org}/actions/runners/{runner_id}/labels" - ], - setCustomLabelsForSelfHostedRunnerForRepo: [ - "PUT /repos/{owner}/{repo}/actions/runners/{runner_id}/labels" - ], - setCustomOidcSubClaimForRepo: [ - "PUT /repos/{owner}/{repo}/actions/oidc/customization/sub" - ], - setGithubActionsDefaultWorkflowPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/workflow" - ], - setGithubActionsDefaultWorkflowPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/workflow" - ], - setGithubActionsPermissionsOrganization: [ - "PUT /orgs/{org}/actions/permissions" - ], - setGithubActionsPermissionsRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/actions/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgVariable: [ - "PUT /orgs/{org}/actions/variables/{name}/repositories" - ], - setSelectedRepositoriesEnabledGithubActionsOrganization: [ - "PUT /orgs/{org}/actions/permissions/repositories" - ], - setWorkflowAccessToRepository: [ - "PUT /repos/{owner}/{repo}/actions/permissions/access" - ], - updateEnvironmentVariable: [ - "PATCH /repositories/{repository_id}/environments/{environment_name}/variables/{name}" - ], - updateOrgVariable: ["PATCH /orgs/{org}/actions/variables/{name}"], - updateRepoVariable: [ - "PATCH /repos/{owner}/{repo}/actions/variables/{name}" - ] - }, - activity: { - checkRepoIsStarredByAuthenticatedUser: ["GET /user/starred/{owner}/{repo}"], - deleteRepoSubscription: ["DELETE /repos/{owner}/{repo}/subscription"], - deleteThreadSubscription: [ - "DELETE /notifications/threads/{thread_id}/subscription" - ], - getFeeds: ["GET /feeds"], - getRepoSubscription: ["GET /repos/{owner}/{repo}/subscription"], - getThread: ["GET /notifications/threads/{thread_id}"], - getThreadSubscriptionForAuthenticatedUser: [ - "GET /notifications/threads/{thread_id}/subscription" - ], - listEventsForAuthenticatedUser: ["GET /users/{username}/events"], - listNotificationsForAuthenticatedUser: ["GET /notifications"], - listOrgEventsForAuthenticatedUser: [ - "GET /users/{username}/events/orgs/{org}" - ], - listPublicEvents: ["GET /events"], - listPublicEventsForRepoNetwork: ["GET /networks/{owner}/{repo}/events"], - listPublicEventsForUser: ["GET /users/{username}/events/public"], - listPublicOrgEvents: ["GET /orgs/{org}/events"], - listReceivedEventsForUser: ["GET /users/{username}/received_events"], - listReceivedPublicEventsForUser: [ - "GET /users/{username}/received_events/public" - ], - listRepoEvents: ["GET /repos/{owner}/{repo}/events"], - listRepoNotificationsForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/notifications" - ], - listReposStarredByAuthenticatedUser: ["GET /user/starred"], - listReposStarredByUser: ["GET /users/{username}/starred"], - listReposWatchedByUser: ["GET /users/{username}/subscriptions"], - listStargazersForRepo: ["GET /repos/{owner}/{repo}/stargazers"], - listWatchedReposForAuthenticatedUser: ["GET /user/subscriptions"], - listWatchersForRepo: ["GET /repos/{owner}/{repo}/subscribers"], - markNotificationsAsRead: ["PUT /notifications"], - markRepoNotificationsAsRead: ["PUT /repos/{owner}/{repo}/notifications"], - markThreadAsDone: ["DELETE /notifications/threads/{thread_id}"], - markThreadAsRead: ["PATCH /notifications/threads/{thread_id}"], - setRepoSubscription: ["PUT /repos/{owner}/{repo}/subscription"], - setThreadSubscription: [ - "PUT /notifications/threads/{thread_id}/subscription" - ], - starRepoForAuthenticatedUser: ["PUT /user/starred/{owner}/{repo}"], - unstarRepoForAuthenticatedUser: ["DELETE /user/starred/{owner}/{repo}"] - }, - apps: { - addRepoToInstallation: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "addRepoToInstallationForAuthenticatedUser"] } - ], - addRepoToInstallationForAuthenticatedUser: [ - "PUT /user/installations/{installation_id}/repositories/{repository_id}" - ], - checkToken: ["POST /applications/{client_id}/token"], - createFromManifest: ["POST /app-manifests/{code}/conversions"], - createInstallationAccessToken: [ - "POST /app/installations/{installation_id}/access_tokens" - ], - deleteAuthorization: ["DELETE /applications/{client_id}/grant"], - deleteInstallation: ["DELETE /app/installations/{installation_id}"], - deleteToken: ["DELETE /applications/{client_id}/token"], - getAuthenticated: ["GET /app"], - getBySlug: ["GET /apps/{app_slug}"], - getInstallation: ["GET /app/installations/{installation_id}"], - getOrgInstallation: ["GET /orgs/{org}/installation"], - getRepoInstallation: ["GET /repos/{owner}/{repo}/installation"], - getSubscriptionPlanForAccount: [ - "GET /marketplace_listing/accounts/{account_id}" - ], - getSubscriptionPlanForAccountStubbed: [ - "GET /marketplace_listing/stubbed/accounts/{account_id}" - ], - getUserInstallation: ["GET /users/{username}/installation"], - getWebhookConfigForApp: ["GET /app/hook/config"], - getWebhookDelivery: ["GET /app/hook/deliveries/{delivery_id}"], - listAccountsForPlan: ["GET /marketplace_listing/plans/{plan_id}/accounts"], - listAccountsForPlanStubbed: [ - "GET /marketplace_listing/stubbed/plans/{plan_id}/accounts" - ], - listInstallationReposForAuthenticatedUser: [ - "GET /user/installations/{installation_id}/repositories" - ], - listInstallationRequestsForAuthenticatedApp: [ - "GET /app/installation-requests" - ], - listInstallations: ["GET /app/installations"], - listInstallationsForAuthenticatedUser: ["GET /user/installations"], - listPlans: ["GET /marketplace_listing/plans"], - listPlansStubbed: ["GET /marketplace_listing/stubbed/plans"], - listReposAccessibleToInstallation: ["GET /installation/repositories"], - listSubscriptionsForAuthenticatedUser: ["GET /user/marketplace_purchases"], - listSubscriptionsForAuthenticatedUserStubbed: [ - "GET /user/marketplace_purchases/stubbed" - ], - listWebhookDeliveries: ["GET /app/hook/deliveries"], - redeliverWebhookDelivery: [ - "POST /app/hook/deliveries/{delivery_id}/attempts" - ], - removeRepoFromInstallation: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}", - {}, - { renamed: ["apps", "removeRepoFromInstallationForAuthenticatedUser"] } - ], - removeRepoFromInstallationForAuthenticatedUser: [ - "DELETE /user/installations/{installation_id}/repositories/{repository_id}" - ], - resetToken: ["PATCH /applications/{client_id}/token"], - revokeInstallationAccessToken: ["DELETE /installation/token"], - scopeToken: ["POST /applications/{client_id}/token/scoped"], - suspendInstallation: ["PUT /app/installations/{installation_id}/suspended"], - unsuspendInstallation: [ - "DELETE /app/installations/{installation_id}/suspended" - ], - updateWebhookConfigForApp: ["PATCH /app/hook/config"] - }, - billing: { - getGithubActionsBillingOrg: ["GET /orgs/{org}/settings/billing/actions"], - getGithubActionsBillingUser: [ - "GET /users/{username}/settings/billing/actions" - ], - getGithubPackagesBillingOrg: ["GET /orgs/{org}/settings/billing/packages"], - getGithubPackagesBillingUser: [ - "GET /users/{username}/settings/billing/packages" - ], - getSharedStorageBillingOrg: [ - "GET /orgs/{org}/settings/billing/shared-storage" - ], - getSharedStorageBillingUser: [ - "GET /users/{username}/settings/billing/shared-storage" - ] - }, - checks: { - create: ["POST /repos/{owner}/{repo}/check-runs"], - createSuite: ["POST /repos/{owner}/{repo}/check-suites"], - get: ["GET /repos/{owner}/{repo}/check-runs/{check_run_id}"], - getSuite: ["GET /repos/{owner}/{repo}/check-suites/{check_suite_id}"], - listAnnotations: [ - "GET /repos/{owner}/{repo}/check-runs/{check_run_id}/annotations" - ], - listForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-runs"], - listForSuite: [ - "GET /repos/{owner}/{repo}/check-suites/{check_suite_id}/check-runs" - ], - listSuitesForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/check-suites"], - rerequestRun: [ - "POST /repos/{owner}/{repo}/check-runs/{check_run_id}/rerequest" - ], - rerequestSuite: [ - "POST /repos/{owner}/{repo}/check-suites/{check_suite_id}/rerequest" - ], - setSuitesPreferences: [ - "PATCH /repos/{owner}/{repo}/check-suites/preferences" - ], - update: ["PATCH /repos/{owner}/{repo}/check-runs/{check_run_id}"] - }, - codeScanning: { - deleteAnalysis: [ - "DELETE /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}{?confirm_delete}" - ], - getAlert: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}", - {}, - { renamedParameters: { alert_id: "alert_number" } } - ], - getAnalysis: [ - "GET /repos/{owner}/{repo}/code-scanning/analyses/{analysis_id}" - ], - getCodeqlDatabase: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases/{language}" - ], - getDefaultSetup: ["GET /repos/{owner}/{repo}/code-scanning/default-setup"], - getSarif: ["GET /repos/{owner}/{repo}/code-scanning/sarifs/{sarif_id}"], - listAlertInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances" - ], - listAlertsForOrg: ["GET /orgs/{org}/code-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/code-scanning/alerts"], - listAlertsInstances: [ - "GET /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}/instances", - {}, - { renamed: ["codeScanning", "listAlertInstances"] } - ], - listCodeqlDatabases: [ - "GET /repos/{owner}/{repo}/code-scanning/codeql/databases" - ], - listRecentAnalyses: ["GET /repos/{owner}/{repo}/code-scanning/analyses"], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/code-scanning/alerts/{alert_number}" - ], - updateDefaultSetup: [ - "PATCH /repos/{owner}/{repo}/code-scanning/default-setup" - ], - uploadSarif: ["POST /repos/{owner}/{repo}/code-scanning/sarifs"] - }, - codesOfConduct: { - getAllCodesOfConduct: ["GET /codes_of_conduct"], - getConductCode: ["GET /codes_of_conduct/{key}"] - }, - codespaces: { - addRepositoryForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - checkPermissionsForDevcontainer: [ - "GET /repos/{owner}/{repo}/codespaces/permissions_check" - ], - codespaceMachinesForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/machines" - ], - createForAuthenticatedUser: ["POST /user/codespaces"], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - createOrUpdateSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}" - ], - createWithPrForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/codespaces" - ], - createWithRepoForAuthenticatedUser: [ - "POST /repos/{owner}/{repo}/codespaces" - ], - deleteForAuthenticatedUser: ["DELETE /user/codespaces/{codespace_name}"], - deleteFromOrganization: [ - "DELETE /orgs/{org}/members/{username}/codespaces/{codespace_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/codespaces/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - deleteSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}" - ], - exportForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/exports" - ], - getCodespacesForUserInOrg: [ - "GET /orgs/{org}/members/{username}/codespaces" - ], - getExportDetailsForAuthenticatedUser: [ - "GET /user/codespaces/{codespace_name}/exports/{export_id}" - ], - getForAuthenticatedUser: ["GET /user/codespaces/{codespace_name}"], - getOrgPublicKey: ["GET /orgs/{org}/codespaces/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/codespaces/secrets/{secret_name}"], - getPublicKeyForAuthenticatedUser: [ - "GET /user/codespaces/secrets/public-key" - ], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/codespaces/secrets/{secret_name}" - ], - getSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}" - ], - listDevcontainersInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/devcontainers" - ], - listForAuthenticatedUser: ["GET /user/codespaces"], - listInOrganization: [ - "GET /orgs/{org}/codespaces", - {}, - { renamedParameters: { org_id: "org" } } - ], - listInRepositoryForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces" - ], - listOrgSecrets: ["GET /orgs/{org}/codespaces/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/codespaces/secrets"], - listRepositoriesForSecretForAuthenticatedUser: [ - "GET /user/codespaces/secrets/{secret_name}/repositories" - ], - listSecretsForAuthenticatedUser: ["GET /user/codespaces/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - preFlightWithRepoForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/new" - ], - publishForAuthenticatedUser: [ - "POST /user/codespaces/{codespace_name}/publish" - ], - removeRepositoryForSecretForAuthenticatedUser: [ - "DELETE /user/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/codespaces/secrets/{secret_name}/repositories/{repository_id}" - ], - repoMachinesForAuthenticatedUser: [ - "GET /repos/{owner}/{repo}/codespaces/machines" - ], - setRepositoriesForSecretForAuthenticatedUser: [ - "PUT /user/codespaces/secrets/{secret_name}/repositories" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/codespaces/secrets/{secret_name}/repositories" - ], - startForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/start"], - stopForAuthenticatedUser: ["POST /user/codespaces/{codespace_name}/stop"], - stopInOrganization: [ - "POST /orgs/{org}/members/{username}/codespaces/{codespace_name}/stop" - ], - updateForAuthenticatedUser: ["PATCH /user/codespaces/{codespace_name}"] - }, - copilot: { - addCopilotSeatsForTeams: [ - "POST /orgs/{org}/copilot/billing/selected_teams" - ], - addCopilotSeatsForUsers: [ - "POST /orgs/{org}/copilot/billing/selected_users" - ], - cancelCopilotSeatAssignmentForTeams: [ - "DELETE /orgs/{org}/copilot/billing/selected_teams" - ], - cancelCopilotSeatAssignmentForUsers: [ - "DELETE /orgs/{org}/copilot/billing/selected_users" - ], - getCopilotOrganizationDetails: ["GET /orgs/{org}/copilot/billing"], - getCopilotSeatDetailsForUser: [ - "GET /orgs/{org}/members/{username}/copilot" - ], - listCopilotSeats: ["GET /orgs/{org}/copilot/billing/seats"] - }, - dependabot: { - addSelectedRepoToOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - createOrUpdateOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}" - ], - createOrUpdateRepoSecret: [ - "PUT /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - deleteOrgSecret: ["DELETE /orgs/{org}/dependabot/secrets/{secret_name}"], - deleteRepoSecret: [ - "DELETE /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - getAlert: ["GET /repos/{owner}/{repo}/dependabot/alerts/{alert_number}"], - getOrgPublicKey: ["GET /orgs/{org}/dependabot/secrets/public-key"], - getOrgSecret: ["GET /orgs/{org}/dependabot/secrets/{secret_name}"], - getRepoPublicKey: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/public-key" - ], - getRepoSecret: [ - "GET /repos/{owner}/{repo}/dependabot/secrets/{secret_name}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/dependabot/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/dependabot/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/dependabot/alerts"], - listOrgSecrets: ["GET /orgs/{org}/dependabot/secrets"], - listRepoSecrets: ["GET /repos/{owner}/{repo}/dependabot/secrets"], - listSelectedReposForOrgSecret: [ - "GET /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - removeSelectedRepoFromOrgSecret: [ - "DELETE /orgs/{org}/dependabot/secrets/{secret_name}/repositories/{repository_id}" - ], - setSelectedReposForOrgSecret: [ - "PUT /orgs/{org}/dependabot/secrets/{secret_name}/repositories" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/dependabot/alerts/{alert_number}" - ] - }, - dependencyGraph: { - createRepositorySnapshot: [ - "POST /repos/{owner}/{repo}/dependency-graph/snapshots" - ], - diffRange: [ - "GET /repos/{owner}/{repo}/dependency-graph/compare/{basehead}" - ], - exportSbom: ["GET /repos/{owner}/{repo}/dependency-graph/sbom"] - }, - emojis: { get: ["GET /emojis"] }, - gists: { - checkIsStarred: ["GET /gists/{gist_id}/star"], - create: ["POST /gists"], - createComment: ["POST /gists/{gist_id}/comments"], - delete: ["DELETE /gists/{gist_id}"], - deleteComment: ["DELETE /gists/{gist_id}/comments/{comment_id}"], - fork: ["POST /gists/{gist_id}/forks"], - get: ["GET /gists/{gist_id}"], - getComment: ["GET /gists/{gist_id}/comments/{comment_id}"], - getRevision: ["GET /gists/{gist_id}/{sha}"], - list: ["GET /gists"], - listComments: ["GET /gists/{gist_id}/comments"], - listCommits: ["GET /gists/{gist_id}/commits"], - listForUser: ["GET /users/{username}/gists"], - listForks: ["GET /gists/{gist_id}/forks"], - listPublic: ["GET /gists/public"], - listStarred: ["GET /gists/starred"], - star: ["PUT /gists/{gist_id}/star"], - unstar: ["DELETE /gists/{gist_id}/star"], - update: ["PATCH /gists/{gist_id}"], - updateComment: ["PATCH /gists/{gist_id}/comments/{comment_id}"] - }, - git: { - createBlob: ["POST /repos/{owner}/{repo}/git/blobs"], - createCommit: ["POST /repos/{owner}/{repo}/git/commits"], - createRef: ["POST /repos/{owner}/{repo}/git/refs"], - createTag: ["POST /repos/{owner}/{repo}/git/tags"], - createTree: ["POST /repos/{owner}/{repo}/git/trees"], - deleteRef: ["DELETE /repos/{owner}/{repo}/git/refs/{ref}"], - getBlob: ["GET /repos/{owner}/{repo}/git/blobs/{file_sha}"], - getCommit: ["GET /repos/{owner}/{repo}/git/commits/{commit_sha}"], - getRef: ["GET /repos/{owner}/{repo}/git/ref/{ref}"], - getTag: ["GET /repos/{owner}/{repo}/git/tags/{tag_sha}"], - getTree: ["GET /repos/{owner}/{repo}/git/trees/{tree_sha}"], - listMatchingRefs: ["GET /repos/{owner}/{repo}/git/matching-refs/{ref}"], - updateRef: ["PATCH /repos/{owner}/{repo}/git/refs/{ref}"] - }, - gitignore: { - getAllTemplates: ["GET /gitignore/templates"], - getTemplate: ["GET /gitignore/templates/{name}"] - }, - interactions: { - getRestrictionsForAuthenticatedUser: ["GET /user/interaction-limits"], - getRestrictionsForOrg: ["GET /orgs/{org}/interaction-limits"], - getRestrictionsForRepo: ["GET /repos/{owner}/{repo}/interaction-limits"], - getRestrictionsForYourPublicRepos: [ - "GET /user/interaction-limits", - {}, - { renamed: ["interactions", "getRestrictionsForAuthenticatedUser"] } - ], - removeRestrictionsForAuthenticatedUser: ["DELETE /user/interaction-limits"], - removeRestrictionsForOrg: ["DELETE /orgs/{org}/interaction-limits"], - removeRestrictionsForRepo: [ - "DELETE /repos/{owner}/{repo}/interaction-limits" - ], - removeRestrictionsForYourPublicRepos: [ - "DELETE /user/interaction-limits", - {}, - { renamed: ["interactions", "removeRestrictionsForAuthenticatedUser"] } - ], - setRestrictionsForAuthenticatedUser: ["PUT /user/interaction-limits"], - setRestrictionsForOrg: ["PUT /orgs/{org}/interaction-limits"], - setRestrictionsForRepo: ["PUT /repos/{owner}/{repo}/interaction-limits"], - setRestrictionsForYourPublicRepos: [ - "PUT /user/interaction-limits", - {}, - { renamed: ["interactions", "setRestrictionsForAuthenticatedUser"] } - ] - }, - issues: { - addAssignees: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - addLabels: ["POST /repos/{owner}/{repo}/issues/{issue_number}/labels"], - checkUserCanBeAssigned: ["GET /repos/{owner}/{repo}/assignees/{assignee}"], - checkUserCanBeAssignedToIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/assignees/{assignee}" - ], - create: ["POST /repos/{owner}/{repo}/issues"], - createComment: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/comments" - ], - createLabel: ["POST /repos/{owner}/{repo}/labels"], - createMilestone: ["POST /repos/{owner}/{repo}/milestones"], - deleteComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}" - ], - deleteLabel: ["DELETE /repos/{owner}/{repo}/labels/{name}"], - deleteMilestone: [ - "DELETE /repos/{owner}/{repo}/milestones/{milestone_number}" - ], - get: ["GET /repos/{owner}/{repo}/issues/{issue_number}"], - getComment: ["GET /repos/{owner}/{repo}/issues/comments/{comment_id}"], - getEvent: ["GET /repos/{owner}/{repo}/issues/events/{event_id}"], - getLabel: ["GET /repos/{owner}/{repo}/labels/{name}"], - getMilestone: ["GET /repos/{owner}/{repo}/milestones/{milestone_number}"], - list: ["GET /issues"], - listAssignees: ["GET /repos/{owner}/{repo}/assignees"], - listComments: ["GET /repos/{owner}/{repo}/issues/{issue_number}/comments"], - listCommentsForRepo: ["GET /repos/{owner}/{repo}/issues/comments"], - listEvents: ["GET /repos/{owner}/{repo}/issues/{issue_number}/events"], - listEventsForRepo: ["GET /repos/{owner}/{repo}/issues/events"], - listEventsForTimeline: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/timeline" - ], - listForAuthenticatedUser: ["GET /user/issues"], - listForOrg: ["GET /orgs/{org}/issues"], - listForRepo: ["GET /repos/{owner}/{repo}/issues"], - listLabelsForMilestone: [ - "GET /repos/{owner}/{repo}/milestones/{milestone_number}/labels" - ], - listLabelsForRepo: ["GET /repos/{owner}/{repo}/labels"], - listLabelsOnIssue: [ - "GET /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - listMilestones: ["GET /repos/{owner}/{repo}/milestones"], - lock: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/lock"], - removeAllLabels: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels" - ], - removeAssignees: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/assignees" - ], - removeLabel: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/labels/{name}" - ], - setLabels: ["PUT /repos/{owner}/{repo}/issues/{issue_number}/labels"], - unlock: ["DELETE /repos/{owner}/{repo}/issues/{issue_number}/lock"], - update: ["PATCH /repos/{owner}/{repo}/issues/{issue_number}"], - updateComment: ["PATCH /repos/{owner}/{repo}/issues/comments/{comment_id}"], - updateLabel: ["PATCH /repos/{owner}/{repo}/labels/{name}"], - updateMilestone: [ - "PATCH /repos/{owner}/{repo}/milestones/{milestone_number}" - ] - }, - licenses: { - get: ["GET /licenses/{license}"], - getAllCommonlyUsed: ["GET /licenses"], - getForRepo: ["GET /repos/{owner}/{repo}/license"] - }, - markdown: { - render: ["POST /markdown"], - renderRaw: [ - "POST /markdown/raw", - { headers: { "content-type": "text/plain; charset=utf-8" } } - ] - }, - meta: { - get: ["GET /meta"], - getAllVersions: ["GET /versions"], - getOctocat: ["GET /octocat"], - getZen: ["GET /zen"], - root: ["GET /"] - }, - migrations: { - cancelImport: [ - "DELETE /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.cancelImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#cancel-an-import" - } - ], - deleteArchiveForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/archive" - ], - deleteArchiveForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/archive" - ], - downloadArchiveForOrg: [ - "GET /orgs/{org}/migrations/{migration_id}/archive" - ], - getArchiveForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/archive" - ], - getCommitAuthors: [ - "GET /repos/{owner}/{repo}/import/authors", - {}, - { - deprecated: "octokit.rest.migrations.getCommitAuthors() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-commit-authors" - } - ], - getImportStatus: [ - "GET /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.getImportStatus() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-an-import-status" - } - ], - getLargeFiles: [ - "GET /repos/{owner}/{repo}/import/large_files", - {}, - { - deprecated: "octokit.rest.migrations.getLargeFiles() is deprecated, see https://docs.github.com/rest/migrations/source-imports#get-large-files" - } - ], - getStatusForAuthenticatedUser: ["GET /user/migrations/{migration_id}"], - getStatusForOrg: ["GET /orgs/{org}/migrations/{migration_id}"], - listForAuthenticatedUser: ["GET /user/migrations"], - listForOrg: ["GET /orgs/{org}/migrations"], - listReposForAuthenticatedUser: [ - "GET /user/migrations/{migration_id}/repositories" - ], - listReposForOrg: ["GET /orgs/{org}/migrations/{migration_id}/repositories"], - listReposForUser: [ - "GET /user/migrations/{migration_id}/repositories", - {}, - { renamed: ["migrations", "listReposForAuthenticatedUser"] } - ], - mapCommitAuthor: [ - "PATCH /repos/{owner}/{repo}/import/authors/{author_id}", - {}, - { - deprecated: "octokit.rest.migrations.mapCommitAuthor() is deprecated, see https://docs.github.com/rest/migrations/source-imports#map-a-commit-author" - } - ], - setLfsPreference: [ - "PATCH /repos/{owner}/{repo}/import/lfs", - {}, - { - deprecated: "octokit.rest.migrations.setLfsPreference() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-git-lfs-preference" - } - ], - startForAuthenticatedUser: ["POST /user/migrations"], - startForOrg: ["POST /orgs/{org}/migrations"], - startImport: [ - "PUT /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.startImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#start-an-import" - } - ], - unlockRepoForAuthenticatedUser: [ - "DELETE /user/migrations/{migration_id}/repos/{repo_name}/lock" - ], - unlockRepoForOrg: [ - "DELETE /orgs/{org}/migrations/{migration_id}/repos/{repo_name}/lock" - ], - updateImport: [ - "PATCH /repos/{owner}/{repo}/import", - {}, - { - deprecated: "octokit.rest.migrations.updateImport() is deprecated, see https://docs.github.com/rest/migrations/source-imports#update-an-import" - } - ] - }, - oidc: { - getOidcCustomSubTemplateForOrg: [ - "GET /orgs/{org}/actions/oidc/customization/sub" - ], - updateOidcCustomSubTemplateForOrg: [ - "PUT /orgs/{org}/actions/oidc/customization/sub" - ] - }, - orgs: { - addSecurityManagerTeam: [ - "PUT /orgs/{org}/security-managers/teams/{team_slug}" - ], - assignTeamToOrgRole: [ - "PUT /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - assignUserToOrgRole: [ - "PUT /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - blockUser: ["PUT /orgs/{org}/blocks/{username}"], - cancelInvitation: ["DELETE /orgs/{org}/invitations/{invitation_id}"], - checkBlockedUser: ["GET /orgs/{org}/blocks/{username}"], - checkMembershipForUser: ["GET /orgs/{org}/members/{username}"], - checkPublicMembershipForUser: ["GET /orgs/{org}/public_members/{username}"], - convertMemberToOutsideCollaborator: [ - "PUT /orgs/{org}/outside_collaborators/{username}" - ], - createCustomOrganizationRole: ["POST /orgs/{org}/organization-roles"], - createInvitation: ["POST /orgs/{org}/invitations"], - createOrUpdateCustomProperties: ["PATCH /orgs/{org}/properties/schema"], - createOrUpdateCustomPropertiesValuesForRepos: [ - "PATCH /orgs/{org}/properties/values" - ], - createOrUpdateCustomProperty: [ - "PUT /orgs/{org}/properties/schema/{custom_property_name}" - ], - createWebhook: ["POST /orgs/{org}/hooks"], - delete: ["DELETE /orgs/{org}"], - deleteCustomOrganizationRole: [ - "DELETE /orgs/{org}/organization-roles/{role_id}" - ], - deleteWebhook: ["DELETE /orgs/{org}/hooks/{hook_id}"], - enableOrDisableSecurityProductOnAllOrgRepos: [ - "POST /orgs/{org}/{security_product}/{enablement}" - ], - get: ["GET /orgs/{org}"], - getAllCustomProperties: ["GET /orgs/{org}/properties/schema"], - getCustomProperty: [ - "GET /orgs/{org}/properties/schema/{custom_property_name}" - ], - getMembershipForAuthenticatedUser: ["GET /user/memberships/orgs/{org}"], - getMembershipForUser: ["GET /orgs/{org}/memberships/{username}"], - getOrgRole: ["GET /orgs/{org}/organization-roles/{role_id}"], - getWebhook: ["GET /orgs/{org}/hooks/{hook_id}"], - getWebhookConfigForOrg: ["GET /orgs/{org}/hooks/{hook_id}/config"], - getWebhookDelivery: [ - "GET /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - list: ["GET /organizations"], - listAppInstallations: ["GET /orgs/{org}/installations"], - listBlockedUsers: ["GET /orgs/{org}/blocks"], - listCustomPropertiesValuesForRepos: ["GET /orgs/{org}/properties/values"], - listFailedInvitations: ["GET /orgs/{org}/failed_invitations"], - listForAuthenticatedUser: ["GET /user/orgs"], - listForUser: ["GET /users/{username}/orgs"], - listInvitationTeams: ["GET /orgs/{org}/invitations/{invitation_id}/teams"], - listMembers: ["GET /orgs/{org}/members"], - listMembershipsForAuthenticatedUser: ["GET /user/memberships/orgs"], - listOrgRoleTeams: ["GET /orgs/{org}/organization-roles/{role_id}/teams"], - listOrgRoleUsers: ["GET /orgs/{org}/organization-roles/{role_id}/users"], - listOrgRoles: ["GET /orgs/{org}/organization-roles"], - listOrganizationFineGrainedPermissions: [ - "GET /orgs/{org}/organization-fine-grained-permissions" - ], - listOutsideCollaborators: ["GET /orgs/{org}/outside_collaborators"], - listPatGrantRepositories: [ - "GET /orgs/{org}/personal-access-tokens/{pat_id}/repositories" - ], - listPatGrantRequestRepositories: [ - "GET /orgs/{org}/personal-access-token-requests/{pat_request_id}/repositories" - ], - listPatGrantRequests: ["GET /orgs/{org}/personal-access-token-requests"], - listPatGrants: ["GET /orgs/{org}/personal-access-tokens"], - listPendingInvitations: ["GET /orgs/{org}/invitations"], - listPublicMembers: ["GET /orgs/{org}/public_members"], - listSecurityManagerTeams: ["GET /orgs/{org}/security-managers"], - listWebhookDeliveries: ["GET /orgs/{org}/hooks/{hook_id}/deliveries"], - listWebhooks: ["GET /orgs/{org}/hooks"], - patchCustomOrganizationRole: [ - "PATCH /orgs/{org}/organization-roles/{role_id}" - ], - pingWebhook: ["POST /orgs/{org}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /orgs/{org}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeCustomProperty: [ - "DELETE /orgs/{org}/properties/schema/{custom_property_name}" - ], - removeMember: ["DELETE /orgs/{org}/members/{username}"], - removeMembershipForUser: ["DELETE /orgs/{org}/memberships/{username}"], - removeOutsideCollaborator: [ - "DELETE /orgs/{org}/outside_collaborators/{username}" - ], - removePublicMembershipForAuthenticatedUser: [ - "DELETE /orgs/{org}/public_members/{username}" - ], - removeSecurityManagerTeam: [ - "DELETE /orgs/{org}/security-managers/teams/{team_slug}" - ], - reviewPatGrantRequest: [ - "POST /orgs/{org}/personal-access-token-requests/{pat_request_id}" - ], - reviewPatGrantRequestsInBulk: [ - "POST /orgs/{org}/personal-access-token-requests" - ], - revokeAllOrgRolesTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}" - ], - revokeAllOrgRolesUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}" - ], - revokeOrgRoleTeam: [ - "DELETE /orgs/{org}/organization-roles/teams/{team_slug}/{role_id}" - ], - revokeOrgRoleUser: [ - "DELETE /orgs/{org}/organization-roles/users/{username}/{role_id}" - ], - setMembershipForUser: ["PUT /orgs/{org}/memberships/{username}"], - setPublicMembershipForAuthenticatedUser: [ - "PUT /orgs/{org}/public_members/{username}" - ], - unblockUser: ["DELETE /orgs/{org}/blocks/{username}"], - update: ["PATCH /orgs/{org}"], - updateMembershipForAuthenticatedUser: [ - "PATCH /user/memberships/orgs/{org}" - ], - updatePatAccess: ["POST /orgs/{org}/personal-access-tokens/{pat_id}"], - updatePatAccesses: ["POST /orgs/{org}/personal-access-tokens"], - updateWebhook: ["PATCH /orgs/{org}/hooks/{hook_id}"], - updateWebhookConfigForOrg: ["PATCH /orgs/{org}/hooks/{hook_id}/config"] - }, - packages: { - deletePackageForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}" - ], - deletePackageForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}" - ], - deletePackageForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}" - ], - deletePackageVersionForAuthenticatedUser: [ - "DELETE /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForOrg: [ - "DELETE /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - deletePackageVersionForUser: [ - "DELETE /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getAllPackageVersionsForAPackageOwnedByAnOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions", - {}, - { renamed: ["packages", "getAllPackageVersionsForPackageOwnedByOrg"] } - ], - getAllPackageVersionsForAPackageOwnedByTheAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions", - {}, - { - renamed: [ - "packages", - "getAllPackageVersionsForPackageOwnedByAuthenticatedUser" - ] - } - ], - getAllPackageVersionsForPackageOwnedByAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByOrg: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions" - ], - getAllPackageVersionsForPackageOwnedByUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions" - ], - getPackageForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}" - ], - getPackageForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}" - ], - getPackageForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}" - ], - getPackageVersionForAuthenticatedUser: [ - "GET /user/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForOrganization: [ - "GET /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - getPackageVersionForUser: [ - "GET /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}" - ], - listDockerMigrationConflictingPackagesForAuthenticatedUser: [ - "GET /user/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForOrganization: [ - "GET /orgs/{org}/docker/conflicts" - ], - listDockerMigrationConflictingPackagesForUser: [ - "GET /users/{username}/docker/conflicts" - ], - listPackagesForAuthenticatedUser: ["GET /user/packages"], - listPackagesForOrganization: ["GET /orgs/{org}/packages"], - listPackagesForUser: ["GET /users/{username}/packages"], - restorePackageForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/restore{?token}" - ], - restorePackageVersionForAuthenticatedUser: [ - "POST /user/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForOrg: [ - "POST /orgs/{org}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ], - restorePackageVersionForUser: [ - "POST /users/{username}/packages/{package_type}/{package_name}/versions/{package_version_id}/restore" - ] - }, - projects: { - addCollaborator: ["PUT /projects/{project_id}/collaborators/{username}"], - createCard: ["POST /projects/columns/{column_id}/cards"], - createColumn: ["POST /projects/{project_id}/columns"], - createForAuthenticatedUser: ["POST /user/projects"], - createForOrg: ["POST /orgs/{org}/projects"], - createForRepo: ["POST /repos/{owner}/{repo}/projects"], - delete: ["DELETE /projects/{project_id}"], - deleteCard: ["DELETE /projects/columns/cards/{card_id}"], - deleteColumn: ["DELETE /projects/columns/{column_id}"], - get: ["GET /projects/{project_id}"], - getCard: ["GET /projects/columns/cards/{card_id}"], - getColumn: ["GET /projects/columns/{column_id}"], - getPermissionForUser: [ - "GET /projects/{project_id}/collaborators/{username}/permission" - ], - listCards: ["GET /projects/columns/{column_id}/cards"], - listCollaborators: ["GET /projects/{project_id}/collaborators"], - listColumns: ["GET /projects/{project_id}/columns"], - listForOrg: ["GET /orgs/{org}/projects"], - listForRepo: ["GET /repos/{owner}/{repo}/projects"], - listForUser: ["GET /users/{username}/projects"], - moveCard: ["POST /projects/columns/cards/{card_id}/moves"], - moveColumn: ["POST /projects/columns/{column_id}/moves"], - removeCollaborator: [ - "DELETE /projects/{project_id}/collaborators/{username}" - ], - update: ["PATCH /projects/{project_id}"], - updateCard: ["PATCH /projects/columns/cards/{card_id}"], - updateColumn: ["PATCH /projects/columns/{column_id}"] - }, - pulls: { - checkIfMerged: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - create: ["POST /repos/{owner}/{repo}/pulls"], - createReplyForReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments/{comment_id}/replies" - ], - createReview: ["POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - createReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - deletePendingReview: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - deleteReviewComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ], - dismissReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/dismissals" - ], - get: ["GET /repos/{owner}/{repo}/pulls/{pull_number}"], - getReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - getReviewComment: ["GET /repos/{owner}/{repo}/pulls/comments/{comment_id}"], - list: ["GET /repos/{owner}/{repo}/pulls"], - listCommentsForReview: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/comments" - ], - listCommits: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/commits"], - listFiles: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/files"], - listRequestedReviewers: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - listReviewComments: [ - "GET /repos/{owner}/{repo}/pulls/{pull_number}/comments" - ], - listReviewCommentsForRepo: ["GET /repos/{owner}/{repo}/pulls/comments"], - listReviews: ["GET /repos/{owner}/{repo}/pulls/{pull_number}/reviews"], - merge: ["PUT /repos/{owner}/{repo}/pulls/{pull_number}/merge"], - removeRequestedReviewers: [ - "DELETE /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - requestReviewers: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/requested_reviewers" - ], - submitReview: [ - "POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}/events" - ], - update: ["PATCH /repos/{owner}/{repo}/pulls/{pull_number}"], - updateBranch: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/update-branch" - ], - updateReview: [ - "PUT /repos/{owner}/{repo}/pulls/{pull_number}/reviews/{review_id}" - ], - updateReviewComment: [ - "PATCH /repos/{owner}/{repo}/pulls/comments/{comment_id}" - ] - }, - rateLimit: { get: ["GET /rate_limit"] }, - reactions: { - createForCommitComment: [ - "POST /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - createForIssue: [ - "POST /repos/{owner}/{repo}/issues/{issue_number}/reactions" - ], - createForIssueComment: [ - "POST /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - createForPullRequestReviewComment: [ - "POST /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - createForRelease: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - createForTeamDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - createForTeamDiscussionInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ], - deleteForCommitComment: [ - "DELETE /repos/{owner}/{repo}/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForIssue: [ - "DELETE /repos/{owner}/{repo}/issues/{issue_number}/reactions/{reaction_id}" - ], - deleteForIssueComment: [ - "DELETE /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForPullRequestComment: [ - "DELETE /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions/{reaction_id}" - ], - deleteForRelease: [ - "DELETE /repos/{owner}/{repo}/releases/{release_id}/reactions/{reaction_id}" - ], - deleteForTeamDiscussion: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions/{reaction_id}" - ], - deleteForTeamDiscussionComment: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions/{reaction_id}" - ], - listForCommitComment: [ - "GET /repos/{owner}/{repo}/comments/{comment_id}/reactions" - ], - listForIssue: ["GET /repos/{owner}/{repo}/issues/{issue_number}/reactions"], - listForIssueComment: [ - "GET /repos/{owner}/{repo}/issues/comments/{comment_id}/reactions" - ], - listForPullRequestReviewComment: [ - "GET /repos/{owner}/{repo}/pulls/comments/{comment_id}/reactions" - ], - listForRelease: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/reactions" - ], - listForTeamDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}/reactions" - ], - listForTeamDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/reactions" - ] - }, - repos: { - acceptInvitation: [ - "PATCH /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "acceptInvitationForAuthenticatedUser"] } - ], - acceptInvitationForAuthenticatedUser: [ - "PATCH /user/repository_invitations/{invitation_id}" - ], - addAppAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - addCollaborator: ["PUT /repos/{owner}/{repo}/collaborators/{username}"], - addStatusCheckContexts: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - addTeamAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - addUserAccessRestrictions: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - cancelPagesDeployment: [ - "POST /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}/cancel" - ], - checkAutomatedSecurityFixes: [ - "GET /repos/{owner}/{repo}/automated-security-fixes" - ], - checkCollaborator: ["GET /repos/{owner}/{repo}/collaborators/{username}"], - checkVulnerabilityAlerts: [ - "GET /repos/{owner}/{repo}/vulnerability-alerts" - ], - codeownersErrors: ["GET /repos/{owner}/{repo}/codeowners/errors"], - compareCommits: ["GET /repos/{owner}/{repo}/compare/{base}...{head}"], - compareCommitsWithBasehead: [ - "GET /repos/{owner}/{repo}/compare/{basehead}" - ], - createAutolink: ["POST /repos/{owner}/{repo}/autolinks"], - createCommitComment: [ - "POST /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - createCommitSignatureProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - createCommitStatus: ["POST /repos/{owner}/{repo}/statuses/{sha}"], - createDeployKey: ["POST /repos/{owner}/{repo}/keys"], - createDeployment: ["POST /repos/{owner}/{repo}/deployments"], - createDeploymentBranchPolicy: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - createDeploymentProtectionRule: [ - "POST /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - createDeploymentStatus: [ - "POST /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - createDispatchEvent: ["POST /repos/{owner}/{repo}/dispatches"], - createForAuthenticatedUser: ["POST /user/repos"], - createFork: ["POST /repos/{owner}/{repo}/forks"], - createInOrg: ["POST /orgs/{org}/repos"], - createOrUpdateCustomPropertiesValues: [ - "PATCH /repos/{owner}/{repo}/properties/values" - ], - createOrUpdateEnvironment: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}" - ], - createOrUpdateFileContents: ["PUT /repos/{owner}/{repo}/contents/{path}"], - createOrgRuleset: ["POST /orgs/{org}/rulesets"], - createPagesDeployment: ["POST /repos/{owner}/{repo}/pages/deployments"], - createPagesSite: ["POST /repos/{owner}/{repo}/pages"], - createRelease: ["POST /repos/{owner}/{repo}/releases"], - createRepoRuleset: ["POST /repos/{owner}/{repo}/rulesets"], - createTagProtection: ["POST /repos/{owner}/{repo}/tags/protection"], - createUsingTemplate: [ - "POST /repos/{template_owner}/{template_repo}/generate" - ], - createWebhook: ["POST /repos/{owner}/{repo}/hooks"], - declineInvitation: [ - "DELETE /user/repository_invitations/{invitation_id}", - {}, - { renamed: ["repos", "declineInvitationForAuthenticatedUser"] } - ], - declineInvitationForAuthenticatedUser: [ - "DELETE /user/repository_invitations/{invitation_id}" - ], - delete: ["DELETE /repos/{owner}/{repo}"], - deleteAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - deleteAdminBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - deleteAnEnvironment: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}" - ], - deleteAutolink: ["DELETE /repos/{owner}/{repo}/autolinks/{autolink_id}"], - deleteBranchProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection" - ], - deleteCommitComment: ["DELETE /repos/{owner}/{repo}/comments/{comment_id}"], - deleteCommitSignatureProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - deleteDeployKey: ["DELETE /repos/{owner}/{repo}/keys/{key_id}"], - deleteDeployment: [ - "DELETE /repos/{owner}/{repo}/deployments/{deployment_id}" - ], - deleteDeploymentBranchPolicy: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - deleteFile: ["DELETE /repos/{owner}/{repo}/contents/{path}"], - deleteInvitation: [ - "DELETE /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - deleteOrgRuleset: ["DELETE /orgs/{org}/rulesets/{ruleset_id}"], - deletePagesSite: ["DELETE /repos/{owner}/{repo}/pages"], - deletePullRequestReviewProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - deleteRelease: ["DELETE /repos/{owner}/{repo}/releases/{release_id}"], - deleteReleaseAsset: [ - "DELETE /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - deleteRepoRuleset: ["DELETE /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - deleteTagProtection: [ - "DELETE /repos/{owner}/{repo}/tags/protection/{tag_protection_id}" - ], - deleteWebhook: ["DELETE /repos/{owner}/{repo}/hooks/{hook_id}"], - disableAutomatedSecurityFixes: [ - "DELETE /repos/{owner}/{repo}/automated-security-fixes" - ], - disableDeploymentProtectionRule: [ - "DELETE /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - disablePrivateVulnerabilityReporting: [ - "DELETE /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - disableVulnerabilityAlerts: [ - "DELETE /repos/{owner}/{repo}/vulnerability-alerts" - ], - downloadArchive: [ - "GET /repos/{owner}/{repo}/zipball/{ref}", - {}, - { renamed: ["repos", "downloadZipballArchive"] } - ], - downloadTarballArchive: ["GET /repos/{owner}/{repo}/tarball/{ref}"], - downloadZipballArchive: ["GET /repos/{owner}/{repo}/zipball/{ref}"], - enableAutomatedSecurityFixes: [ - "PUT /repos/{owner}/{repo}/automated-security-fixes" - ], - enablePrivateVulnerabilityReporting: [ - "PUT /repos/{owner}/{repo}/private-vulnerability-reporting" - ], - enableVulnerabilityAlerts: [ - "PUT /repos/{owner}/{repo}/vulnerability-alerts" - ], - generateReleaseNotes: [ - "POST /repos/{owner}/{repo}/releases/generate-notes" - ], - get: ["GET /repos/{owner}/{repo}"], - getAccessRestrictions: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions" - ], - getAdminBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - getAllDeploymentProtectionRules: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules" - ], - getAllEnvironments: ["GET /repos/{owner}/{repo}/environments"], - getAllStatusCheckContexts: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts" - ], - getAllTopics: ["GET /repos/{owner}/{repo}/topics"], - getAppsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps" - ], - getAutolink: ["GET /repos/{owner}/{repo}/autolinks/{autolink_id}"], - getBranch: ["GET /repos/{owner}/{repo}/branches/{branch}"], - getBranchProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection" - ], - getBranchRules: ["GET /repos/{owner}/{repo}/rules/branches/{branch}"], - getClones: ["GET /repos/{owner}/{repo}/traffic/clones"], - getCodeFrequencyStats: ["GET /repos/{owner}/{repo}/stats/code_frequency"], - getCollaboratorPermissionLevel: [ - "GET /repos/{owner}/{repo}/collaborators/{username}/permission" - ], - getCombinedStatusForRef: ["GET /repos/{owner}/{repo}/commits/{ref}/status"], - getCommit: ["GET /repos/{owner}/{repo}/commits/{ref}"], - getCommitActivityStats: ["GET /repos/{owner}/{repo}/stats/commit_activity"], - getCommitComment: ["GET /repos/{owner}/{repo}/comments/{comment_id}"], - getCommitSignatureProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_signatures" - ], - getCommunityProfileMetrics: ["GET /repos/{owner}/{repo}/community/profile"], - getContent: ["GET /repos/{owner}/{repo}/contents/{path}"], - getContributorsStats: ["GET /repos/{owner}/{repo}/stats/contributors"], - getCustomDeploymentProtectionRule: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/{protection_rule_id}" - ], - getCustomPropertiesValues: ["GET /repos/{owner}/{repo}/properties/values"], - getDeployKey: ["GET /repos/{owner}/{repo}/keys/{key_id}"], - getDeployment: ["GET /repos/{owner}/{repo}/deployments/{deployment_id}"], - getDeploymentBranchPolicy: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - getDeploymentStatus: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses/{status_id}" - ], - getEnvironment: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}" - ], - getLatestPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/latest"], - getLatestRelease: ["GET /repos/{owner}/{repo}/releases/latest"], - getOrgRuleSuite: ["GET /orgs/{org}/rulesets/rule-suites/{rule_suite_id}"], - getOrgRuleSuites: ["GET /orgs/{org}/rulesets/rule-suites"], - getOrgRuleset: ["GET /orgs/{org}/rulesets/{ruleset_id}"], - getOrgRulesets: ["GET /orgs/{org}/rulesets"], - getPages: ["GET /repos/{owner}/{repo}/pages"], - getPagesBuild: ["GET /repos/{owner}/{repo}/pages/builds/{build_id}"], - getPagesDeployment: [ - "GET /repos/{owner}/{repo}/pages/deployments/{pages_deployment_id}" - ], - getPagesHealthCheck: ["GET /repos/{owner}/{repo}/pages/health"], - getParticipationStats: ["GET /repos/{owner}/{repo}/stats/participation"], - getPullRequestReviewProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - getPunchCardStats: ["GET /repos/{owner}/{repo}/stats/punch_card"], - getReadme: ["GET /repos/{owner}/{repo}/readme"], - getReadmeInDirectory: ["GET /repos/{owner}/{repo}/readme/{dir}"], - getRelease: ["GET /repos/{owner}/{repo}/releases/{release_id}"], - getReleaseAsset: ["GET /repos/{owner}/{repo}/releases/assets/{asset_id}"], - getReleaseByTag: ["GET /repos/{owner}/{repo}/releases/tags/{tag}"], - getRepoRuleSuite: [ - "GET /repos/{owner}/{repo}/rulesets/rule-suites/{rule_suite_id}" - ], - getRepoRuleSuites: ["GET /repos/{owner}/{repo}/rulesets/rule-suites"], - getRepoRuleset: ["GET /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - getRepoRulesets: ["GET /repos/{owner}/{repo}/rulesets"], - getStatusChecksProtection: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - getTeamsWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams" - ], - getTopPaths: ["GET /repos/{owner}/{repo}/traffic/popular/paths"], - getTopReferrers: ["GET /repos/{owner}/{repo}/traffic/popular/referrers"], - getUsersWithAccessToProtectedBranch: [ - "GET /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users" - ], - getViews: ["GET /repos/{owner}/{repo}/traffic/views"], - getWebhook: ["GET /repos/{owner}/{repo}/hooks/{hook_id}"], - getWebhookConfigForRepo: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - getWebhookDelivery: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}" - ], - listActivities: ["GET /repos/{owner}/{repo}/activity"], - listAutolinks: ["GET /repos/{owner}/{repo}/autolinks"], - listBranches: ["GET /repos/{owner}/{repo}/branches"], - listBranchesForHeadCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/branches-where-head" - ], - listCollaborators: ["GET /repos/{owner}/{repo}/collaborators"], - listCommentsForCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/comments" - ], - listCommitCommentsForRepo: ["GET /repos/{owner}/{repo}/comments"], - listCommitStatusesForRef: [ - "GET /repos/{owner}/{repo}/commits/{ref}/statuses" - ], - listCommits: ["GET /repos/{owner}/{repo}/commits"], - listContributors: ["GET /repos/{owner}/{repo}/contributors"], - listCustomDeploymentRuleIntegrations: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment_protection_rules/apps" - ], - listDeployKeys: ["GET /repos/{owner}/{repo}/keys"], - listDeploymentBranchPolicies: [ - "GET /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies" - ], - listDeploymentStatuses: [ - "GET /repos/{owner}/{repo}/deployments/{deployment_id}/statuses" - ], - listDeployments: ["GET /repos/{owner}/{repo}/deployments"], - listForAuthenticatedUser: ["GET /user/repos"], - listForOrg: ["GET /orgs/{org}/repos"], - listForUser: ["GET /users/{username}/repos"], - listForks: ["GET /repos/{owner}/{repo}/forks"], - listInvitations: ["GET /repos/{owner}/{repo}/invitations"], - listInvitationsForAuthenticatedUser: ["GET /user/repository_invitations"], - listLanguages: ["GET /repos/{owner}/{repo}/languages"], - listPagesBuilds: ["GET /repos/{owner}/{repo}/pages/builds"], - listPublic: ["GET /repositories"], - listPullRequestsAssociatedWithCommit: [ - "GET /repos/{owner}/{repo}/commits/{commit_sha}/pulls" - ], - listReleaseAssets: [ - "GET /repos/{owner}/{repo}/releases/{release_id}/assets" - ], - listReleases: ["GET /repos/{owner}/{repo}/releases"], - listTagProtection: ["GET /repos/{owner}/{repo}/tags/protection"], - listTags: ["GET /repos/{owner}/{repo}/tags"], - listTeams: ["GET /repos/{owner}/{repo}/teams"], - listWebhookDeliveries: [ - "GET /repos/{owner}/{repo}/hooks/{hook_id}/deliveries" - ], - listWebhooks: ["GET /repos/{owner}/{repo}/hooks"], - merge: ["POST /repos/{owner}/{repo}/merges"], - mergeUpstream: ["POST /repos/{owner}/{repo}/merge-upstream"], - pingWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/pings"], - redeliverWebhookDelivery: [ - "POST /repos/{owner}/{repo}/hooks/{hook_id}/deliveries/{delivery_id}/attempts" - ], - removeAppAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - removeCollaborator: [ - "DELETE /repos/{owner}/{repo}/collaborators/{username}" - ], - removeStatusCheckContexts: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - removeStatusCheckProtection: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - removeTeamAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - removeUserAccessRestrictions: [ - "DELETE /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - renameBranch: ["POST /repos/{owner}/{repo}/branches/{branch}/rename"], - replaceAllTopics: ["PUT /repos/{owner}/{repo}/topics"], - requestPagesBuild: ["POST /repos/{owner}/{repo}/pages/builds"], - setAdminBranchProtection: [ - "POST /repos/{owner}/{repo}/branches/{branch}/protection/enforce_admins" - ], - setAppAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/apps", - {}, - { mapToData: "apps" } - ], - setStatusCheckContexts: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks/contexts", - {}, - { mapToData: "contexts" } - ], - setTeamAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/teams", - {}, - { mapToData: "teams" } - ], - setUserAccessRestrictions: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection/restrictions/users", - {}, - { mapToData: "users" } - ], - testPushWebhook: ["POST /repos/{owner}/{repo}/hooks/{hook_id}/tests"], - transfer: ["POST /repos/{owner}/{repo}/transfer"], - update: ["PATCH /repos/{owner}/{repo}"], - updateBranchProtection: [ - "PUT /repos/{owner}/{repo}/branches/{branch}/protection" - ], - updateCommitComment: ["PATCH /repos/{owner}/{repo}/comments/{comment_id}"], - updateDeploymentBranchPolicy: [ - "PUT /repos/{owner}/{repo}/environments/{environment_name}/deployment-branch-policies/{branch_policy_id}" - ], - updateInformationAboutPagesSite: ["PUT /repos/{owner}/{repo}/pages"], - updateInvitation: [ - "PATCH /repos/{owner}/{repo}/invitations/{invitation_id}" - ], - updateOrgRuleset: ["PUT /orgs/{org}/rulesets/{ruleset_id}"], - updatePullRequestReviewProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_pull_request_reviews" - ], - updateRelease: ["PATCH /repos/{owner}/{repo}/releases/{release_id}"], - updateReleaseAsset: [ - "PATCH /repos/{owner}/{repo}/releases/assets/{asset_id}" - ], - updateRepoRuleset: ["PUT /repos/{owner}/{repo}/rulesets/{ruleset_id}"], - updateStatusCheckPotection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks", - {}, - { renamed: ["repos", "updateStatusCheckProtection"] } - ], - updateStatusCheckProtection: [ - "PATCH /repos/{owner}/{repo}/branches/{branch}/protection/required_status_checks" - ], - updateWebhook: ["PATCH /repos/{owner}/{repo}/hooks/{hook_id}"], - updateWebhookConfigForRepo: [ - "PATCH /repos/{owner}/{repo}/hooks/{hook_id}/config" - ], - uploadReleaseAsset: [ - "POST /repos/{owner}/{repo}/releases/{release_id}/assets{?name,label}", - { baseUrl: "https://uploads.github.com" } - ] - }, - search: { - code: ["GET /search/code"], - commits: ["GET /search/commits"], - issuesAndPullRequests: ["GET /search/issues"], - labels: ["GET /search/labels"], - repos: ["GET /search/repositories"], - topics: ["GET /search/topics"], - users: ["GET /search/users"] - }, - secretScanning: { - getAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ], - listAlertsForEnterprise: [ - "GET /enterprises/{enterprise}/secret-scanning/alerts" - ], - listAlertsForOrg: ["GET /orgs/{org}/secret-scanning/alerts"], - listAlertsForRepo: ["GET /repos/{owner}/{repo}/secret-scanning/alerts"], - listLocationsForAlert: [ - "GET /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}/locations" - ], - updateAlert: [ - "PATCH /repos/{owner}/{repo}/secret-scanning/alerts/{alert_number}" - ] - }, - securityAdvisories: { - createFork: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/forks" - ], - createPrivateVulnerabilityReport: [ - "POST /repos/{owner}/{repo}/security-advisories/reports" - ], - createRepositoryAdvisory: [ - "POST /repos/{owner}/{repo}/security-advisories" - ], - createRepositoryAdvisoryCveRequest: [ - "POST /repos/{owner}/{repo}/security-advisories/{ghsa_id}/cve" - ], - getGlobalAdvisory: ["GET /advisories/{ghsa_id}"], - getRepositoryAdvisory: [ - "GET /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ], - listGlobalAdvisories: ["GET /advisories"], - listOrgRepositoryAdvisories: ["GET /orgs/{org}/security-advisories"], - listRepositoryAdvisories: ["GET /repos/{owner}/{repo}/security-advisories"], - updateRepositoryAdvisory: [ - "PATCH /repos/{owner}/{repo}/security-advisories/{ghsa_id}" - ] - }, - teams: { - addOrUpdateMembershipForUserInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - addOrUpdateProjectPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - addOrUpdateRepoPermissionsInOrg: [ - "PUT /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - checkPermissionsForProjectInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - checkPermissionsForRepoInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - create: ["POST /orgs/{org}/teams"], - createDiscussionCommentInOrg: [ - "POST /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - createDiscussionInOrg: ["POST /orgs/{org}/teams/{team_slug}/discussions"], - deleteDiscussionCommentInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - deleteDiscussionInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - deleteInOrg: ["DELETE /orgs/{org}/teams/{team_slug}"], - getByName: ["GET /orgs/{org}/teams/{team_slug}"], - getDiscussionCommentInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - getDiscussionInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - getMembershipForUserInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - list: ["GET /orgs/{org}/teams"], - listChildInOrg: ["GET /orgs/{org}/teams/{team_slug}/teams"], - listDiscussionCommentsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments" - ], - listDiscussionsInOrg: ["GET /orgs/{org}/teams/{team_slug}/discussions"], - listForAuthenticatedUser: ["GET /user/teams"], - listMembersInOrg: ["GET /orgs/{org}/teams/{team_slug}/members"], - listPendingInvitationsInOrg: [ - "GET /orgs/{org}/teams/{team_slug}/invitations" - ], - listProjectsInOrg: ["GET /orgs/{org}/teams/{team_slug}/projects"], - listReposInOrg: ["GET /orgs/{org}/teams/{team_slug}/repos"], - removeMembershipForUserInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/memberships/{username}" - ], - removeProjectInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/projects/{project_id}" - ], - removeRepoInOrg: [ - "DELETE /orgs/{org}/teams/{team_slug}/repos/{owner}/{repo}" - ], - updateDiscussionCommentInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}/comments/{comment_number}" - ], - updateDiscussionInOrg: [ - "PATCH /orgs/{org}/teams/{team_slug}/discussions/{discussion_number}" - ], - updateInOrg: ["PATCH /orgs/{org}/teams/{team_slug}"] - }, - users: { - addEmailForAuthenticated: [ - "POST /user/emails", - {}, - { renamed: ["users", "addEmailForAuthenticatedUser"] } - ], - addEmailForAuthenticatedUser: ["POST /user/emails"], - addSocialAccountForAuthenticatedUser: ["POST /user/social_accounts"], - block: ["PUT /user/blocks/{username}"], - checkBlocked: ["GET /user/blocks/{username}"], - checkFollowingForUser: ["GET /users/{username}/following/{target_user}"], - checkPersonIsFollowedByAuthenticated: ["GET /user/following/{username}"], - createGpgKeyForAuthenticated: [ - "POST /user/gpg_keys", - {}, - { renamed: ["users", "createGpgKeyForAuthenticatedUser"] } - ], - createGpgKeyForAuthenticatedUser: ["POST /user/gpg_keys"], - createPublicSshKeyForAuthenticated: [ - "POST /user/keys", - {}, - { renamed: ["users", "createPublicSshKeyForAuthenticatedUser"] } - ], - createPublicSshKeyForAuthenticatedUser: ["POST /user/keys"], - createSshSigningKeyForAuthenticatedUser: ["POST /user/ssh_signing_keys"], - deleteEmailForAuthenticated: [ - "DELETE /user/emails", - {}, - { renamed: ["users", "deleteEmailForAuthenticatedUser"] } - ], - deleteEmailForAuthenticatedUser: ["DELETE /user/emails"], - deleteGpgKeyForAuthenticated: [ - "DELETE /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "deleteGpgKeyForAuthenticatedUser"] } - ], - deleteGpgKeyForAuthenticatedUser: ["DELETE /user/gpg_keys/{gpg_key_id}"], - deletePublicSshKeyForAuthenticated: [ - "DELETE /user/keys/{key_id}", - {}, - { renamed: ["users", "deletePublicSshKeyForAuthenticatedUser"] } - ], - deletePublicSshKeyForAuthenticatedUser: ["DELETE /user/keys/{key_id}"], - deleteSocialAccountForAuthenticatedUser: ["DELETE /user/social_accounts"], - deleteSshSigningKeyForAuthenticatedUser: [ - "DELETE /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - follow: ["PUT /user/following/{username}"], - getAuthenticated: ["GET /user"], - getByUsername: ["GET /users/{username}"], - getContextForUser: ["GET /users/{username}/hovercard"], - getGpgKeyForAuthenticated: [ - "GET /user/gpg_keys/{gpg_key_id}", - {}, - { renamed: ["users", "getGpgKeyForAuthenticatedUser"] } - ], - getGpgKeyForAuthenticatedUser: ["GET /user/gpg_keys/{gpg_key_id}"], - getPublicSshKeyForAuthenticated: [ - "GET /user/keys/{key_id}", - {}, - { renamed: ["users", "getPublicSshKeyForAuthenticatedUser"] } - ], - getPublicSshKeyForAuthenticatedUser: ["GET /user/keys/{key_id}"], - getSshSigningKeyForAuthenticatedUser: [ - "GET /user/ssh_signing_keys/{ssh_signing_key_id}" - ], - list: ["GET /users"], - listBlockedByAuthenticated: [ - "GET /user/blocks", - {}, - { renamed: ["users", "listBlockedByAuthenticatedUser"] } - ], - listBlockedByAuthenticatedUser: ["GET /user/blocks"], - listEmailsForAuthenticated: [ - "GET /user/emails", - {}, - { renamed: ["users", "listEmailsForAuthenticatedUser"] } - ], - listEmailsForAuthenticatedUser: ["GET /user/emails"], - listFollowedByAuthenticated: [ - "GET /user/following", - {}, - { renamed: ["users", "listFollowedByAuthenticatedUser"] } - ], - listFollowedByAuthenticatedUser: ["GET /user/following"], - listFollowersForAuthenticatedUser: ["GET /user/followers"], - listFollowersForUser: ["GET /users/{username}/followers"], - listFollowingForUser: ["GET /users/{username}/following"], - listGpgKeysForAuthenticated: [ - "GET /user/gpg_keys", - {}, - { renamed: ["users", "listGpgKeysForAuthenticatedUser"] } - ], - listGpgKeysForAuthenticatedUser: ["GET /user/gpg_keys"], - listGpgKeysForUser: ["GET /users/{username}/gpg_keys"], - listPublicEmailsForAuthenticated: [ - "GET /user/public_emails", - {}, - { renamed: ["users", "listPublicEmailsForAuthenticatedUser"] } - ], - listPublicEmailsForAuthenticatedUser: ["GET /user/public_emails"], - listPublicKeysForUser: ["GET /users/{username}/keys"], - listPublicSshKeysForAuthenticated: [ - "GET /user/keys", - {}, - { renamed: ["users", "listPublicSshKeysForAuthenticatedUser"] } - ], - listPublicSshKeysForAuthenticatedUser: ["GET /user/keys"], - listSocialAccountsForAuthenticatedUser: ["GET /user/social_accounts"], - listSocialAccountsForUser: ["GET /users/{username}/social_accounts"], - listSshSigningKeysForAuthenticatedUser: ["GET /user/ssh_signing_keys"], - listSshSigningKeysForUser: ["GET /users/{username}/ssh_signing_keys"], - setPrimaryEmailVisibilityForAuthenticated: [ - "PATCH /user/email/visibility", - {}, - { renamed: ["users", "setPrimaryEmailVisibilityForAuthenticatedUser"] } - ], - setPrimaryEmailVisibilityForAuthenticatedUser: [ - "PATCH /user/email/visibility" - ], - unblock: ["DELETE /user/blocks/{username}"], - unfollow: ["DELETE /user/following/{username}"], - updateAuthenticated: ["PATCH /user"] - } -}; -var endpoints_default = Endpoints; - -// pkg/dist-src/endpoints-to-methods.js -var endpointMethodsMap = /* @__PURE__ */ new Map(); -for (const [scope, endpoints] of Object.entries(endpoints_default)) { - for (const [methodName, endpoint] of Object.entries(endpoints)) { - const [route, defaults, decorations] = endpoint; - const [method, url] = route.split(/ /); - const endpointDefaults = Object.assign( - { - method, - url - }, - defaults - ); - if (!endpointMethodsMap.has(scope)) { - endpointMethodsMap.set(scope, /* @__PURE__ */ new Map()); - } - endpointMethodsMap.get(scope).set(methodName, { - scope, - methodName, - endpointDefaults, - decorations - }); - } -} -var handler = { - has({ scope }, methodName) { - return endpointMethodsMap.get(scope).has(methodName); - }, - getOwnPropertyDescriptor(target, methodName) { - return { - value: this.get(target, methodName), - // ensures method is in the cache - configurable: true, - writable: true, - enumerable: true - }; - }, - defineProperty(target, methodName, descriptor) { - Object.defineProperty(target.cache, methodName, descriptor); - return true; - }, - deleteProperty(target, methodName) { - delete target.cache[methodName]; - return true; - }, - ownKeys({ scope }) { - return [...endpointMethodsMap.get(scope).keys()]; - }, - set(target, methodName, value) { - return target.cache[methodName] = value; - }, - get({ octokit, scope, cache }, methodName) { - if (cache[methodName]) { - return cache[methodName]; - } - const method = endpointMethodsMap.get(scope).get(methodName); - if (!method) { - return void 0; - } - const { endpointDefaults, decorations } = method; - if (decorations) { - cache[methodName] = decorate( - octokit, - scope, - methodName, - endpointDefaults, - decorations - ); - } else { - cache[methodName] = octokit.request.defaults(endpointDefaults); - } - return cache[methodName]; - } -}; -function endpointsToMethods(octokit) { - const newMethods = {}; - for (const scope of endpointMethodsMap.keys()) { - newMethods[scope] = new Proxy({ octokit, scope, cache: {} }, handler); - } - return newMethods; -} -function decorate(octokit, scope, methodName, defaults, decorations) { - const requestWithDefaults = octokit.request.defaults(defaults); - function withDecorations(...args) { - let options = requestWithDefaults.endpoint.merge(...args); - if (decorations.mapToData) { - options = Object.assign({}, options, { - data: options[decorations.mapToData], - [decorations.mapToData]: void 0 - }); - return requestWithDefaults(options); - } - if (decorations.renamed) { - const [newScope, newMethodName] = decorations.renamed; - octokit.log.warn( - `octokit.${scope}.${methodName}() has been renamed to octokit.${newScope}.${newMethodName}()` - ); - } - if (decorations.deprecated) { - octokit.log.warn(decorations.deprecated); - } - if (decorations.renamedParameters) { - const options2 = requestWithDefaults.endpoint.merge(...args); - for (const [name, alias] of Object.entries( - decorations.renamedParameters - )) { - if (name in options2) { - octokit.log.warn( - `"${name}" parameter is deprecated for "octokit.${scope}.${methodName}()". Use "${alias}" instead` - ); - if (!(alias in options2)) { - options2[alias] = options2[name]; - } - delete options2[name]; - } - } - return requestWithDefaults(options2); - } - return requestWithDefaults(...args); - } - return Object.assign(withDecorations, requestWithDefaults); -} - -// pkg/dist-src/index.js -function restEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - rest: api - }; -} -restEndpointMethods.VERSION = VERSION; -function legacyRestEndpointMethods(octokit) { - const api = endpointsToMethods(octokit); - return { - ...api, - rest: api - }; -} -legacyRestEndpointMethods.VERSION = VERSION; -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 3708: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - -var __create = Object.create; -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __getProtoOf = Object.getPrototypeOf; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( - // If the importer is in node compatibility mode or this is not an ESM - // file that has been converted to a CommonJS file using a Babel- - // compatible transform (i.e. "__esModule" has not been set), then set - // "default" to the CommonJS "module.exports" for node compatibility. - isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, - mod -)); -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - RequestError: () => RequestError -}); -module.exports = __toCommonJS(dist_src_exports); -var import_deprecation = __nccwpck_require__(4150); -var import_once = __toESM(__nccwpck_require__(5560)); -var logOnceCode = (0, import_once.default)((deprecation) => console.warn(deprecation)); -var logOnceHeaders = (0, import_once.default)((deprecation) => console.warn(deprecation)); -var RequestError = class extends Error { - constructor(message, statusCode, options) { - super(message); - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - this.name = "HttpError"; - this.status = statusCode; - let headers; - if ("headers" in options && typeof options.headers !== "undefined") { - headers = options.headers; - } - if ("response" in options) { - this.response = options.response; - headers = options.response.headers; - } - const requestCopy = Object.assign({}, options.request); - if (options.request.headers.authorization) { - requestCopy.headers = Object.assign({}, options.request.headers, { - authorization: options.request.headers.authorization.replace( - /(? { - - -var __defProp = Object.defineProperty; -var __getOwnPropDesc = Object.getOwnPropertyDescriptor; -var __getOwnPropNames = Object.getOwnPropertyNames; -var __hasOwnProp = Object.prototype.hasOwnProperty; -var __export = (target, all) => { - for (var name in all) - __defProp(target, name, { get: all[name], enumerable: true }); -}; -var __copyProps = (to, from, except, desc) => { - if (from && typeof from === "object" || typeof from === "function") { - for (let key of __getOwnPropNames(from)) - if (!__hasOwnProp.call(to, key) && key !== except) - __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); - } - return to; -}; -var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); - -// pkg/dist-src/index.js -var dist_src_exports = {}; -__export(dist_src_exports, { - request: () => request -}); -module.exports = __toCommonJS(dist_src_exports); -var import_endpoint = __nccwpck_require__(4471); -var import_universal_user_agent = __nccwpck_require__(3843); - -// pkg/dist-src/version.js -var VERSION = "8.4.1"; - -// pkg/dist-src/is-plain-object.js -function isPlainObject(value) { - if (typeof value !== "object" || value === null) - return false; - if (Object.prototype.toString.call(value) !== "[object Object]") - return false; - const proto = Object.getPrototypeOf(value); - if (proto === null) - return true; - const Ctor = Object.prototype.hasOwnProperty.call(proto, "constructor") && proto.constructor; - return typeof Ctor === "function" && Ctor instanceof Ctor && Function.prototype.call(Ctor) === Function.prototype.call(value); -} - -// pkg/dist-src/fetch-wrapper.js -var import_request_error = __nccwpck_require__(3708); - -// pkg/dist-src/get-buffer-response.js -function getBufferResponse(response) { - return response.arrayBuffer(); -} - -// pkg/dist-src/fetch-wrapper.js -function fetchWrapper(requestOptions) { - var _a, _b, _c, _d; - const log = requestOptions.request && requestOptions.request.log ? requestOptions.request.log : console; - const parseSuccessResponseBody = ((_a = requestOptions.request) == null ? void 0 : _a.parseSuccessResponseBody) !== false; - if (isPlainObject(requestOptions.body) || Array.isArray(requestOptions.body)) { - requestOptions.body = JSON.stringify(requestOptions.body); - } - let headers = {}; - let status; - let url; - let { fetch } = globalThis; - if ((_b = requestOptions.request) == null ? void 0 : _b.fetch) { - fetch = requestOptions.request.fetch; - } - if (!fetch) { - throw new Error( - "fetch is not set. Please pass a fetch implementation as new Octokit({ request: { fetch }}). Learn more at https://github.com/octokit/octokit.js/#fetch-missing" - ); - } - return fetch(requestOptions.url, { - method: requestOptions.method, - body: requestOptions.body, - redirect: (_c = requestOptions.request) == null ? void 0 : _c.redirect, - headers: requestOptions.headers, - signal: (_d = requestOptions.request) == null ? void 0 : _d.signal, - // duplex must be set if request.body is ReadableStream or Async Iterables. - // See https://fetch.spec.whatwg.org/#dom-requestinit-duplex. - ...requestOptions.body && { duplex: "half" } - }).then(async (response) => { - url = response.url; - status = response.status; - for (const keyAndValue of response.headers) { - headers[keyAndValue[0]] = keyAndValue[1]; - } - if ("deprecation" in headers) { - const matches = headers.link && headers.link.match(/<([^<>]+)>; rel="deprecation"/); - const deprecationLink = matches && matches.pop(); - log.warn( - `[@octokit/request] "${requestOptions.method} ${requestOptions.url}" is deprecated. It is scheduled to be removed on ${headers.sunset}${deprecationLink ? `. See ${deprecationLink}` : ""}` - ); - } - if (status === 204 || status === 205) { - return; - } - if (requestOptions.method === "HEAD") { - if (status < 400) { - return; - } - throw new import_request_error.RequestError(response.statusText, status, { - response: { - url, - status, - headers, - data: void 0 - }, - request: requestOptions - }); - } - if (status === 304) { - throw new import_request_error.RequestError("Not modified", status, { - response: { - url, - status, - headers, - data: await getResponseData(response) - }, - request: requestOptions - }); - } - if (status >= 400) { - const data = await getResponseData(response); - const error = new import_request_error.RequestError(toErrorMessage(data), status, { - response: { - url, - status, - headers, - data - }, - request: requestOptions - }); - throw error; - } - return parseSuccessResponseBody ? await getResponseData(response) : response.body; - }).then((data) => { - return { - status, - url, - headers, - data - }; - }).catch((error) => { - if (error instanceof import_request_error.RequestError) - throw error; - else if (error.name === "AbortError") - throw error; - let message = error.message; - if (error.name === "TypeError" && "cause" in error) { - if (error.cause instanceof Error) { - message = error.cause.message; - } else if (typeof error.cause === "string") { - message = error.cause; - } - } - throw new import_request_error.RequestError(message, 500, { - request: requestOptions - }); - }); -} -async function getResponseData(response) { - const contentType = response.headers.get("content-type"); - if (/application\/json/.test(contentType)) { - return response.json().catch(() => response.text()).catch(() => ""); - } - if (!contentType || /^text\/|charset=utf-8$/.test(contentType)) { - return response.text(); - } - return getBufferResponse(response); -} -function toErrorMessage(data) { - if (typeof data === "string") - return data; - let suffix; - if ("documentation_url" in data) { - suffix = ` - ${data.documentation_url}`; - } else { - suffix = ""; - } - if ("message" in data) { - if (Array.isArray(data.errors)) { - return `${data.message}: ${data.errors.map(JSON.stringify).join(", ")}${suffix}`; - } - return `${data.message}${suffix}`; - } - return `Unknown error: ${JSON.stringify(data)}`; -} - -// pkg/dist-src/with-defaults.js -function withDefaults(oldEndpoint, newDefaults) { - const endpoint2 = oldEndpoint.defaults(newDefaults); - const newApi = function(route, parameters) { - const endpointOptions = endpoint2.merge(route, parameters); - if (!endpointOptions.request || !endpointOptions.request.hook) { - return fetchWrapper(endpoint2.parse(endpointOptions)); - } - const request2 = (route2, parameters2) => { - return fetchWrapper( - endpoint2.parse(endpoint2.merge(route2, parameters2)) - ); - }; - Object.assign(request2, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); - return endpointOptions.request.hook(request2, endpointOptions); - }; - return Object.assign(newApi, { - endpoint: endpoint2, - defaults: withDefaults.bind(null, endpoint2) - }); -} - -// pkg/dist-src/index.js -var request = withDefaults(import_endpoint.endpoint, { - headers: { - "user-agent": `octokit-request.js/${VERSION} ${(0, import_universal_user_agent.getUserAgent)()}` - } -}); -// Annotate the CommonJS export names for ESM import in node: -0 && (0); - - -/***/ }), - -/***/ 4412: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* module decorator */ module = __nccwpck_require__.nmd(module); - - -const ANSI_BACKGROUND_OFFSET = 10; - -const wrapAnsi256 = (offset = 0) => code => `\u001B[${38 + offset};5;${code}m`; - -const wrapAnsi16m = (offset = 0) => (red, green, blue) => `\u001B[${38 + offset};2;${red};${green};${blue}m`; - -function assembleStyles() { - const codes = new Map(); - const styles = { - modifier: { - reset: [0, 0], - // 21 isn't widely supported and 22 does the same thing - bold: [1, 22], - dim: [2, 22], - italic: [3, 23], - underline: [4, 24], - overline: [53, 55], - inverse: [7, 27], - hidden: [8, 28], - strikethrough: [9, 29] - }, - color: { - black: [30, 39], - red: [31, 39], - green: [32, 39], - yellow: [33, 39], - blue: [34, 39], - magenta: [35, 39], - cyan: [36, 39], - white: [37, 39], - - // Bright color - blackBright: [90, 39], - redBright: [91, 39], - greenBright: [92, 39], - yellowBright: [93, 39], - blueBright: [94, 39], - magentaBright: [95, 39], - cyanBright: [96, 39], - whiteBright: [97, 39] - }, - bgColor: { - bgBlack: [40, 49], - bgRed: [41, 49], - bgGreen: [42, 49], - bgYellow: [43, 49], - bgBlue: [44, 49], - bgMagenta: [45, 49], - bgCyan: [46, 49], - bgWhite: [47, 49], - - // Bright color - bgBlackBright: [100, 49], - bgRedBright: [101, 49], - bgGreenBright: [102, 49], - bgYellowBright: [103, 49], - bgBlueBright: [104, 49], - bgMagentaBright: [105, 49], - bgCyanBright: [106, 49], - bgWhiteBright: [107, 49] - } - }; - - // Alias bright black as gray (and grey) - styles.color.gray = styles.color.blackBright; - styles.bgColor.bgGray = styles.bgColor.bgBlackBright; - styles.color.grey = styles.color.blackBright; - styles.bgColor.bgGrey = styles.bgColor.bgBlackBright; - - for (const [groupName, group] of Object.entries(styles)) { - for (const [styleName, style] of Object.entries(group)) { - styles[styleName] = { - open: `\u001B[${style[0]}m`, - close: `\u001B[${style[1]}m` - }; - - group[styleName] = styles[styleName]; - - codes.set(style[0], style[1]); - } - - Object.defineProperty(styles, groupName, { - value: group, - enumerable: false - }); - } - - Object.defineProperty(styles, 'codes', { - value: codes, - enumerable: false - }); - - styles.color.close = '\u001B[39m'; - styles.bgColor.close = '\u001B[49m'; - - styles.color.ansi256 = wrapAnsi256(); - styles.color.ansi16m = wrapAnsi16m(); - styles.bgColor.ansi256 = wrapAnsi256(ANSI_BACKGROUND_OFFSET); - styles.bgColor.ansi16m = wrapAnsi16m(ANSI_BACKGROUND_OFFSET); - - // From https://github.com/Qix-/color-convert/blob/3f0e0d4e92e235796ccb17f6e85c72094a651f49/conversions.js - Object.defineProperties(styles, { - rgbToAnsi256: { - value: (red, green, blue) => { - // We use the extended greyscale palette here, with the exception of - // black and white. normal palette only has 4 greyscale shades. - if (red === green && green === blue) { - if (red < 8) { - return 16; - } - - if (red > 248) { - return 231; - } - - return Math.round(((red - 8) / 247) * 24) + 232; - } - - return 16 + - (36 * Math.round(red / 255 * 5)) + - (6 * Math.round(green / 255 * 5)) + - Math.round(blue / 255 * 5); - }, - enumerable: false - }, - hexToRgb: { - value: hex => { - const matches = /(?[a-f\d]{6}|[a-f\d]{3})/i.exec(hex.toString(16)); - if (!matches) { - return [0, 0, 0]; - } - - let {colorString} = matches.groups; - - if (colorString.length === 3) { - colorString = colorString.split('').map(character => character + character).join(''); - } - - const integer = Number.parseInt(colorString, 16); - - return [ - (integer >> 16) & 0xFF, - (integer >> 8) & 0xFF, - integer & 0xFF - ]; - }, - enumerable: false - }, - hexToAnsi256: { - value: hex => styles.rgbToAnsi256(...styles.hexToRgb(hex)), - enumerable: false - } - }); - - return styles; -} - -// Make the export immutable -Object.defineProperty(module, 'exports', { - enumerable: true, - get: assembleStyles -}); - - -/***/ }), - -/***/ 8793: -/***/ ((__unused_webpack_module, exports) => { - - - -exports.byteLength = byteLength -exports.toByteArray = toByteArray -exports.fromByteArray = fromByteArray - -var lookup = [] -var revLookup = [] -var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array - -var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' -for (var i = 0, len = code.length; i < len; ++i) { - lookup[i] = code[i] - revLookup[code.charCodeAt(i)] = i -} - -// Support decoding URL-safe base64 strings, as Node.js does. -// See: https://en.wikipedia.org/wiki/Base64#URL_applications -revLookup['-'.charCodeAt(0)] = 62 -revLookup['_'.charCodeAt(0)] = 63 - -function getLens (b64) { - var len = b64.length - - if (len % 4 > 0) { - throw new Error('Invalid string. Length must be a multiple of 4') - } - - // Trim off extra bytes after placeholder bytes are found - // See: https://github.com/beatgammit/base64-js/issues/42 - var validLen = b64.indexOf('=') - if (validLen === -1) validLen = len - - var placeHoldersLen = validLen === len - ? 0 - : 4 - (validLen % 4) - - return [validLen, placeHoldersLen] -} - -// base64 is 4/3 + up to two characters of the original data -function byteLength (b64) { - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function _byteLength (b64, validLen, placeHoldersLen) { - return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen -} - -function toByteArray (b64) { - var tmp - var lens = getLens(b64) - var validLen = lens[0] - var placeHoldersLen = lens[1] - - var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)) - - var curByte = 0 - - // if there are placeholders, only get up to the last complete 4 chars - var len = placeHoldersLen > 0 - ? validLen - 4 - : validLen - - var i - for (i = 0; i < len; i += 4) { - tmp = - (revLookup[b64.charCodeAt(i)] << 18) | - (revLookup[b64.charCodeAt(i + 1)] << 12) | - (revLookup[b64.charCodeAt(i + 2)] << 6) | - revLookup[b64.charCodeAt(i + 3)] - arr[curByte++] = (tmp >> 16) & 0xFF - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 2) { - tmp = - (revLookup[b64.charCodeAt(i)] << 2) | - (revLookup[b64.charCodeAt(i + 1)] >> 4) - arr[curByte++] = tmp & 0xFF - } - - if (placeHoldersLen === 1) { - tmp = - (revLookup[b64.charCodeAt(i)] << 10) | - (revLookup[b64.charCodeAt(i + 1)] << 4) | - (revLookup[b64.charCodeAt(i + 2)] >> 2) - arr[curByte++] = (tmp >> 8) & 0xFF - arr[curByte++] = tmp & 0xFF - } - - return arr -} - -function tripletToBase64 (num) { - return lookup[num >> 18 & 0x3F] + - lookup[num >> 12 & 0x3F] + - lookup[num >> 6 & 0x3F] + - lookup[num & 0x3F] -} - -function encodeChunk (uint8, start, end) { - var tmp - var output = [] - for (var i = start; i < end; i += 3) { - tmp = - ((uint8[i] << 16) & 0xFF0000) + - ((uint8[i + 1] << 8) & 0xFF00) + - (uint8[i + 2] & 0xFF) - output.push(tripletToBase64(tmp)) - } - return output.join('') -} - -function fromByteArray (uint8) { - var tmp - var len = uint8.length - var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes - var parts = [] - var maxChunkLength = 16383 // must be multiple of 3 - - // go through the array every three bytes, we'll deal with trailing stuff later - for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { - parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) - } - - // pad the end with zeros, but make sure to not forget the extra bytes - if (extraBytes === 1) { - tmp = uint8[len - 1] - parts.push( - lookup[tmp >> 2] + - lookup[(tmp << 4) & 0x3F] + - '==' - ) - } else if (extraBytes === 2) { - tmp = (uint8[len - 2] << 8) + uint8[len - 1] - parts.push( - lookup[tmp >> 10] + - lookup[(tmp >> 4) & 0x3F] + - lookup[(tmp << 2) & 0x3F] + - '=' - ) - } - - return parts.join('') -} - - -/***/ }), - -/***/ 2732: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var register = __nccwpck_require__(1063); -var addHook = __nccwpck_require__(2027); -var removeHook = __nccwpck_require__(9934); - -// bind with array of arguments: https://stackoverflow.com/a/21792913 -var bind = Function.bind; -var bindable = bind.bind(bind); - -function bindApi(hook, state, name) { - var removeHookRef = bindable(removeHook, null).apply( - null, - name ? [state, name] : [state] - ); - hook.api = { remove: removeHookRef }; - hook.remove = removeHookRef; - ["before", "error", "after", "wrap"].forEach(function (kind) { - var args = name ? [state, kind, name] : [state, kind]; - hook[kind] = hook.api[kind] = bindable(addHook, null).apply(null, args); - }); -} - -function HookSingular() { - var singularHookName = "h"; - var singularHookState = { - registry: {}, - }; - var singularHook = register.bind(null, singularHookState, singularHookName); - bindApi(singularHook, singularHookState, singularHookName); - return singularHook; -} - -function HookCollection() { - var state = { - registry: {}, - }; - - var hook = register.bind(null, state); - bindApi(hook, state); - - return hook; -} - -var collectionHookDeprecationMessageDisplayed = false; -function Hook() { - if (!collectionHookDeprecationMessageDisplayed) { - console.warn( - '[before-after-hook]: "Hook()" repurposing warning, use "Hook.Collection()". Read more: https://git.io/upgrade-before-after-hook-to-1.4' - ); - collectionHookDeprecationMessageDisplayed = true; - } - return HookCollection(); -} - -Hook.Singular = HookSingular.bind(); -Hook.Collection = HookCollection.bind(); - -module.exports = Hook; -// expose constructors as a named property for TypeScript -module.exports.Hook = Hook; -module.exports.Singular = Hook.Singular; -module.exports.Collection = Hook.Collection; - - -/***/ }), - -/***/ 2027: -/***/ ((module) => { - -module.exports = addHook; - -function addHook(state, kind, name, hook) { - var orig = hook; - if (!state.registry[name]) { - state.registry[name] = []; - } - - if (kind === "before") { - hook = function (method, options) { - return Promise.resolve() - .then(orig.bind(null, options)) - .then(method.bind(null, options)); - }; - } - - if (kind === "after") { - hook = function (method, options) { - var result; - return Promise.resolve() - .then(method.bind(null, options)) - .then(function (result_) { - result = result_; - return orig(result, options); - }) - .then(function () { - return result; - }); - }; - } - - if (kind === "error") { - hook = function (method, options) { - return Promise.resolve() - .then(method.bind(null, options)) - .catch(function (error) { - return orig(error, options); - }); - }; - } - - state.registry[name].push({ - hook: hook, - orig: orig, - }); -} - - -/***/ }), - -/***/ 1063: -/***/ ((module) => { - -module.exports = register; - -function register(state, name, method, options) { - if (typeof method !== "function") { - throw new Error("method for before hook must be a function"); - } - - if (!options) { - options = {}; - } - - if (Array.isArray(name)) { - return name.reverse().reduce(function (callback, name) { - return register.bind(null, state, name, callback, options); - }, method)(); - } - - return Promise.resolve().then(function () { - if (!state.registry[name]) { - return method(options); - } - - return state.registry[name].reduce(function (method, registered) { - return registered.hook.bind(null, method, options); - }, method)(); - }); -} - - -/***/ }), - -/***/ 9934: -/***/ ((module) => { - -module.exports = removeHook; - -function removeHook(state, name, method) { - if (!state.registry[name]) { - return; - } - - var index = state.registry[name] - .map(function (registered) { - return registered.orig; - }) - .indexOf(method); - - if (index === -1) { - return; - } - - state.registry[name].splice(index, 1); -} - - -/***/ }), - -/***/ 9890: -/***/ ((module) => { - - - -const UPPERCASE = /[\p{Lu}]/u; -const LOWERCASE = /[\p{Ll}]/u; -const LEADING_CAPITAL = /^[\p{Lu}](?![\p{Lu}])/gu; -const IDENTIFIER = /([\p{Alpha}\p{N}_]|$)/u; -const SEPARATORS = /[_.\- ]+/; - -const LEADING_SEPARATORS = new RegExp('^' + SEPARATORS.source); -const SEPARATORS_AND_IDENTIFIER = new RegExp(SEPARATORS.source + IDENTIFIER.source, 'gu'); -const NUMBERS_AND_IDENTIFIER = new RegExp('\\d+' + IDENTIFIER.source, 'gu'); - -const preserveCamelCase = (string, toLowerCase, toUpperCase) => { - let isLastCharLower = false; - let isLastCharUpper = false; - let isLastLastCharUpper = false; - - for (let i = 0; i < string.length; i++) { - const character = string[i]; - - if (isLastCharLower && UPPERCASE.test(character)) { - string = string.slice(0, i) + '-' + string.slice(i); - isLastCharLower = false; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = true; - i++; - } else if (isLastCharUpper && isLastLastCharUpper && LOWERCASE.test(character)) { - string = string.slice(0, i - 1) + '-' + string.slice(i - 1); - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = false; - isLastCharLower = true; - } else { - isLastCharLower = toLowerCase(character) === character && toUpperCase(character) !== character; - isLastLastCharUpper = isLastCharUpper; - isLastCharUpper = toUpperCase(character) === character && toLowerCase(character) !== character; - } - } - - return string; -}; - -const preserveConsecutiveUppercase = (input, toLowerCase) => { - LEADING_CAPITAL.lastIndex = 0; - - return input.replace(LEADING_CAPITAL, m1 => toLowerCase(m1)); -}; - -const postProcess = (input, toUpperCase) => { - SEPARATORS_AND_IDENTIFIER.lastIndex = 0; - NUMBERS_AND_IDENTIFIER.lastIndex = 0; - - return input.replace(SEPARATORS_AND_IDENTIFIER, (_, identifier) => toUpperCase(identifier)) - .replace(NUMBERS_AND_IDENTIFIER, m => toUpperCase(m)); -}; - -const camelCase = (input, options) => { - if (!(typeof input === 'string' || Array.isArray(input))) { - throw new TypeError('Expected the input to be `string | string[]`'); - } - - options = { - pascalCase: false, - preserveConsecutiveUppercase: false, - ...options - }; - - if (Array.isArray(input)) { - input = input.map(x => x.trim()) - .filter(x => x.length) - .join('-'); - } else { - input = input.trim(); - } - - if (input.length === 0) { - return ''; - } - - const toLowerCase = options.locale === false ? - string => string.toLowerCase() : - string => string.toLocaleLowerCase(options.locale); - const toUpperCase = options.locale === false ? - string => string.toUpperCase() : - string => string.toLocaleUpperCase(options.locale); - - if (input.length === 1) { - return options.pascalCase ? toUpperCase(input) : toLowerCase(input); - } - - const hasUpperCase = input !== toLowerCase(input); - - if (hasUpperCase) { - input = preserveCamelCase(input, toLowerCase, toUpperCase); - } - - input = input.replace(LEADING_SEPARATORS, ''); - - if (options.preserveConsecutiveUppercase) { - input = preserveConsecutiveUppercase(input, toLowerCase); - } else { - input = toLowerCase(input); - } - - if (options.pascalCase) { - input = toUpperCase(input.charAt(0)) + input.slice(1); - } - - return postProcess(input, toUpperCase); -}; - -module.exports = camelCase; -// TODO: Remove this for the next major release -module.exports["default"] = camelCase; - - -/***/ }), - -/***/ 8203: -/***/ ((module) => { - - -module.exports = function (str, sep) { - if (typeof str !== 'string') { - throw new TypeError('Expected a string'); - } - - sep = typeof sep === 'undefined' ? '_' : sep; - - return str - .replace(/([a-z\d])([A-Z])/g, '$1' + sep + '$2') - .replace(/([A-Z]+)([A-Z][a-z\d]+)/g, '$1' + sep + '$2') - .toLowerCase(); -}; - - -/***/ }), - -/***/ 4150: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -class Deprecation extends Error { - constructor(message) { - super(message); // Maintains proper stack trace (only available on V8) - - /* istanbul ignore next */ - - if (Error.captureStackTrace) { - Error.captureStackTrace(this, this.constructor); - } - - this.name = 'Deprecation'; - } - -} - -exports.Deprecation = Deprecation; - - -/***/ }), - -/***/ 2415: -/***/ ((module) => { - - - -var has = Object.prototype.hasOwnProperty - , prefix = '~'; - -/** - * Constructor to create a storage for our `EE` objects. - * An `Events` instance is a plain object whose properties are event names. - * - * @constructor - * @private - */ -function Events() {} - -// -// We try to not inherit from `Object.prototype`. In some engines creating an -// instance in this way is faster than calling `Object.create(null)` directly. -// If `Object.create(null)` is not supported we prefix the event names with a -// character to make sure that the built-in object properties are not -// overridden or used as an attack vector. -// -if (Object.create) { - Events.prototype = Object.create(null); - - // - // This hack is needed because the `__proto__` property is still inherited in - // some old browsers like Android 4, iPhone 5.1, Opera 11 and Safari 5. - // - if (!new Events().__proto__) prefix = false; -} - -/** - * Representation of a single event listener. - * - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} [once=false] Specify if the listener is a one-time listener. - * @constructor - * @private - */ -function EE(fn, context, once) { - this.fn = fn; - this.context = context; - this.once = once || false; -} - -/** - * Add a listener for a given event. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} context The context to invoke the listener with. - * @param {Boolean} once Specify if the listener is a one-time listener. - * @returns {EventEmitter} - * @private - */ -function addListener(emitter, event, fn, context, once) { - if (typeof fn !== 'function') { - throw new TypeError('The listener must be a function'); - } - - var listener = new EE(fn, context || emitter, once) - , evt = prefix ? prefix + event : event; - - if (!emitter._events[evt]) emitter._events[evt] = listener, emitter._eventsCount++; - else if (!emitter._events[evt].fn) emitter._events[evt].push(listener); - else emitter._events[evt] = [emitter._events[evt], listener]; - - return emitter; -} - -/** - * Clear event by name. - * - * @param {EventEmitter} emitter Reference to the `EventEmitter` instance. - * @param {(String|Symbol)} evt The Event name. - * @private - */ -function clearEvent(emitter, evt) { - if (--emitter._eventsCount === 0) emitter._events = new Events(); - else delete emitter._events[evt]; -} - -/** - * Minimal `EventEmitter` interface that is molded against the Node.js - * `EventEmitter` interface. - * - * @constructor - * @public - */ -function EventEmitter() { - this._events = new Events(); - this._eventsCount = 0; -} - -/** - * Return an array listing the events for which the emitter has registered - * listeners. - * - * @returns {Array} - * @public - */ -EventEmitter.prototype.eventNames = function eventNames() { - var names = [] - , events - , name; - - if (this._eventsCount === 0) return names; - - for (name in (events = this._events)) { - if (has.call(events, name)) names.push(prefix ? name.slice(1) : name); - } - - if (Object.getOwnPropertySymbols) { - return names.concat(Object.getOwnPropertySymbols(events)); - } - - return names; -}; - -/** - * Return the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Array} The registered listeners. - * @public - */ -EventEmitter.prototype.listeners = function listeners(event) { - var evt = prefix ? prefix + event : event - , handlers = this._events[evt]; - - if (!handlers) return []; - if (handlers.fn) return [handlers.fn]; - - for (var i = 0, l = handlers.length, ee = new Array(l); i < l; i++) { - ee[i] = handlers[i].fn; - } - - return ee; -}; - -/** - * Return the number of listeners listening to a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Number} The number of listeners. - * @public - */ -EventEmitter.prototype.listenerCount = function listenerCount(event) { - var evt = prefix ? prefix + event : event - , listeners = this._events[evt]; - - if (!listeners) return 0; - if (listeners.fn) return 1; - return listeners.length; -}; - -/** - * Calls each of the listeners registered for a given event. - * - * @param {(String|Symbol)} event The event name. - * @returns {Boolean} `true` if the event had listeners, else `false`. - * @public - */ -EventEmitter.prototype.emit = function emit(event, a1, a2, a3, a4, a5) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return false; - - var listeners = this._events[evt] - , len = arguments.length - , args - , i; - - if (listeners.fn) { - if (listeners.once) this.removeListener(event, listeners.fn, undefined, true); - - switch (len) { - case 1: return listeners.fn.call(listeners.context), true; - case 2: return listeners.fn.call(listeners.context, a1), true; - case 3: return listeners.fn.call(listeners.context, a1, a2), true; - case 4: return listeners.fn.call(listeners.context, a1, a2, a3), true; - case 5: return listeners.fn.call(listeners.context, a1, a2, a3, a4), true; - case 6: return listeners.fn.call(listeners.context, a1, a2, a3, a4, a5), true; - } - - for (i = 1, args = new Array(len -1); i < len; i++) { - args[i - 1] = arguments[i]; - } - - listeners.fn.apply(listeners.context, args); - } else { - var length = listeners.length - , j; - - for (i = 0; i < length; i++) { - if (listeners[i].once) this.removeListener(event, listeners[i].fn, undefined, true); - - switch (len) { - case 1: listeners[i].fn.call(listeners[i].context); break; - case 2: listeners[i].fn.call(listeners[i].context, a1); break; - case 3: listeners[i].fn.call(listeners[i].context, a1, a2); break; - case 4: listeners[i].fn.call(listeners[i].context, a1, a2, a3); break; - default: - if (!args) for (j = 1, args = new Array(len -1); j < len; j++) { - args[j - 1] = arguments[j]; - } - - listeners[i].fn.apply(listeners[i].context, args); - } - } - } - - return true; -}; - -/** - * Add a listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.on = function on(event, fn, context) { - return addListener(this, event, fn, context, false); -}; - -/** - * Add a one-time listener for a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn The listener function. - * @param {*} [context=this] The context to invoke the listener with. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.once = function once(event, fn, context) { - return addListener(this, event, fn, context, true); -}; - -/** - * Remove the listeners of a given event. - * - * @param {(String|Symbol)} event The event name. - * @param {Function} fn Only remove the listeners that match this function. - * @param {*} context Only remove the listeners that have this context. - * @param {Boolean} once Only remove one-time listeners. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeListener = function removeListener(event, fn, context, once) { - var evt = prefix ? prefix + event : event; - - if (!this._events[evt]) return this; - if (!fn) { - clearEvent(this, evt); - return this; - } - - var listeners = this._events[evt]; - - if (listeners.fn) { - if ( - listeners.fn === fn && - (!once || listeners.once) && - (!context || listeners.context === context) - ) { - clearEvent(this, evt); - } - } else { - for (var i = 0, events = [], length = listeners.length; i < length; i++) { - if ( - listeners[i].fn !== fn || - (once && !listeners[i].once) || - (context && listeners[i].context !== context) - ) { - events.push(listeners[i]); - } - } - - // - // Reset the array, or remove it completely if we have no more listeners. - // - if (events.length) this._events[evt] = events.length === 1 ? events[0] : events; - else clearEvent(this, evt); - } - - return this; -}; - -/** - * Remove all listeners, or those of the specified event. - * - * @param {(String|Symbol)} [event] The event name. - * @returns {EventEmitter} `this`. - * @public - */ -EventEmitter.prototype.removeAllListeners = function removeAllListeners(event) { - var evt; - - if (event) { - evt = prefix ? prefix + event : event; - if (this._events[evt]) clearEvent(this, evt); - } else { - this._events = new Events(); - this._eventsCount = 0; - } - - return this; -}; - -// -// Alias methods names because people roll like that. -// -EventEmitter.prototype.off = EventEmitter.prototype.removeListener; -EventEmitter.prototype.addListener = EventEmitter.prototype.on; - -// -// Expose the prefix. -// -EventEmitter.prefixed = prefix; - -// -// Allow `EventEmitter` to be imported as module namespace. -// -EventEmitter.EventEmitter = EventEmitter; - -// -// Expose the module. -// -if (true) { - module.exports = EventEmitter; -} - - -/***/ }), - -/***/ 9018: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const ANY = Symbol('SemVer ANY') -// hoisted class for cyclic dependency -class Comparator { - static get ANY () { - return ANY - } - - constructor (comp, options) { - options = parseOptions(options) - - if (comp instanceof Comparator) { - if (comp.loose === !!options.loose) { - return comp - } else { - comp = comp.value - } - } - - comp = comp.trim().split(/\s+/).join(' ') - debug('comparator', comp, options) - this.options = options - this.loose = !!options.loose - this.parse(comp) - - if (this.semver === ANY) { - this.value = '' - } else { - this.value = this.operator + this.semver.version - } - - debug('comp', this) - } - - parse (comp) { - const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR] - const m = comp.match(r) - - if (!m) { - throw new TypeError(`Invalid comparator: ${comp}`) - } - - this.operator = m[1] !== undefined ? m[1] : '' - if (this.operator === '=') { - this.operator = '' - } - - // if it literally is just '>' or '' then allow anything. - if (!m[2]) { - this.semver = ANY - } else { - this.semver = new SemVer(m[2], this.options.loose) - } - } - - toString () { - return this.value - } - - test (version) { - debug('Comparator.test', version, this.options.loose) - - if (this.semver === ANY || version === ANY) { - return true - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - - return cmp(version, this.operator, this.semver, this.options) - } - - intersects (comp, options) { - if (!(comp instanceof Comparator)) { - throw new TypeError('a Comparator is required') - } - - if (this.operator === '') { - if (this.value === '') { - return true - } - return new Range(comp.value, options).test(this.value) - } else if (comp.operator === '') { - if (comp.value === '') { - return true - } - return new Range(this.value, options).test(comp.semver) - } - - options = parseOptions(options) - - // Special cases where nothing can possibly be lower - if (options.includePrerelease && - (this.value === '<0.0.0-0' || comp.value === '<0.0.0-0')) { - return false - } - if (!options.includePrerelease && - (this.value.startsWith('<0.0.0') || comp.value.startsWith('<0.0.0'))) { - return false - } - - // Same direction increasing (> or >=) - if (this.operator.startsWith('>') && comp.operator.startsWith('>')) { - return true - } - // Same direction decreasing (< or <=) - if (this.operator.startsWith('<') && comp.operator.startsWith('<')) { - return true - } - // same SemVer and both sides are inclusive (<= or >=) - if ( - (this.semver.version === comp.semver.version) && - this.operator.includes('=') && comp.operator.includes('=')) { - return true - } - // opposite directions less than - if (cmp(this.semver, '<', comp.semver, options) && - this.operator.startsWith('>') && comp.operator.startsWith('<')) { - return true - } - // opposite directions greater than - if (cmp(this.semver, '>', comp.semver, options) && - this.operator.startsWith('<') && comp.operator.startsWith('>')) { - return true - } - return false - } -} - -module.exports = Comparator - -const parseOptions = __nccwpck_require__(741) -const { safeRe: re, t } = __nccwpck_require__(3744) -const cmp = __nccwpck_require__(6845) -const debug = __nccwpck_require__(1370) -const SemVer = __nccwpck_require__(3542) -const Range = __nccwpck_require__(9005) - - -/***/ }), - -/***/ 9005: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SPACE_CHARACTERS = /\s+/g - -// hoisted class for cyclic dependency -class Range { - constructor (range, options) { - options = parseOptions(options) - - if (range instanceof Range) { - if ( - range.loose === !!options.loose && - range.includePrerelease === !!options.includePrerelease - ) { - return range - } else { - return new Range(range.raw, options) - } - } - - if (range instanceof Comparator) { - // just put it in the set and return - this.raw = range.value - this.set = [[range]] - this.formatted = undefined - return this - } - - this.options = options - this.loose = !!options.loose - this.includePrerelease = !!options.includePrerelease - - // First reduce all whitespace as much as possible so we do not have to rely - // on potentially slow regexes like \s*. This is then stored and used for - // future error messages as well. - this.raw = range.trim().replace(SPACE_CHARACTERS, ' ') - - // First, split on || - this.set = this.raw - .split('||') - // map the range to a 2d array of comparators - .map(r => this.parseRange(r.trim())) - // throw out any comparator lists that are empty - // this generally means that it was not a valid range, which is allowed - // in loose mode, but will still throw if the WHOLE range is invalid. - .filter(c => c.length) - - if (!this.set.length) { - throw new TypeError(`Invalid SemVer Range: ${this.raw}`) - } - - // if we have any that are not the null set, throw out null sets. - if (this.set.length > 1) { - // keep the first one, in case they're all null sets - const first = this.set[0] - this.set = this.set.filter(c => !isNullSet(c[0])) - if (this.set.length === 0) { - this.set = [first] - } else if (this.set.length > 1) { - // if we have any that are *, then the range is just * - for (const c of this.set) { - if (c.length === 1 && isAny(c[0])) { - this.set = [c] - break - } - } - } - } - - this.formatted = undefined - } - - get range () { - if (this.formatted === undefined) { - this.formatted = '' - for (let i = 0; i < this.set.length; i++) { - if (i > 0) { - this.formatted += '||' - } - const comps = this.set[i] - for (let k = 0; k < comps.length; k++) { - if (k > 0) { - this.formatted += ' ' - } - this.formatted += comps[k].toString().trim() - } - } - } - return this.formatted - } - - format () { - return this.range - } - - toString () { - return this.range - } - - parseRange (range) { - // memoize range parsing for performance. - // this is a very hot path, and fully deterministic. - const memoOpts = - (this.options.includePrerelease && FLAG_INCLUDE_PRERELEASE) | - (this.options.loose && FLAG_LOOSE) - const memoKey = memoOpts + ':' + range - const cached = cache.get(memoKey) - if (cached) { - return cached - } - - const loose = this.options.loose - // `1.2.3 - 1.2.4` => `>=1.2.3 <=1.2.4` - const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE] - range = range.replace(hr, hyphenReplace(this.options.includePrerelease)) - debug('hyphen replace', range) - - // `> 1.2.3 < 1.2.5` => `>1.2.3 <1.2.5` - range = range.replace(re[t.COMPARATORTRIM], comparatorTrimReplace) - debug('comparator trim', range) - - // `~ 1.2.3` => `~1.2.3` - range = range.replace(re[t.TILDETRIM], tildeTrimReplace) - debug('tilde trim', range) - - // `^ 1.2.3` => `^1.2.3` - range = range.replace(re[t.CARETTRIM], caretTrimReplace) - debug('caret trim', range) - - // At this point, the range is completely trimmed and - // ready to be split into comparators. - - let rangeList = range - .split(' ') - .map(comp => parseComparator(comp, this.options)) - .join(' ') - .split(/\s+/) - // >=0.0.0 is equivalent to * - .map(comp => replaceGTE0(comp, this.options)) - - if (loose) { - // in loose mode, throw out any that are not valid comparators - rangeList = rangeList.filter(comp => { - debug('loose invalid filter', comp, this.options) - return !!comp.match(re[t.COMPARATORLOOSE]) - }) - } - debug('range list', rangeList) - - // if any comparators are the null set, then replace with JUST null set - // if more than one comparator, remove any * comparators - // also, don't include the same comparator more than once - const rangeMap = new Map() - const comparators = rangeList.map(comp => new Comparator(comp, this.options)) - for (const comp of comparators) { - if (isNullSet(comp)) { - return [comp] - } - rangeMap.set(comp.value, comp) - } - if (rangeMap.size > 1 && rangeMap.has('')) { - rangeMap.delete('') - } - - const result = [...rangeMap.values()] - cache.set(memoKey, result) - return result - } - - intersects (range, options) { - if (!(range instanceof Range)) { - throw new TypeError('a Range is required') - } - - return this.set.some((thisComparators) => { - return ( - isSatisfiable(thisComparators, options) && - range.set.some((rangeComparators) => { - return ( - isSatisfiable(rangeComparators, options) && - thisComparators.every((thisComparator) => { - return rangeComparators.every((rangeComparator) => { - return thisComparator.intersects(rangeComparator, options) - }) - }) - ) - }) - ) - }) - } - - // if ANY of the sets match ALL of its comparators, then pass - test (version) { - if (!version) { - return false - } - - if (typeof version === 'string') { - try { - version = new SemVer(version, this.options) - } catch (er) { - return false - } - } - - for (let i = 0; i < this.set.length; i++) { - if (testSet(this.set[i], version, this.options)) { - return true - } - } - return false - } -} - -module.exports = Range - -const LRU = __nccwpck_require__(9508) -const cache = new LRU() - -const parseOptions = __nccwpck_require__(741) -const Comparator = __nccwpck_require__(9018) -const debug = __nccwpck_require__(1370) -const SemVer = __nccwpck_require__(3542) -const { - safeRe: re, - t, - comparatorTrimReplace, - tildeTrimReplace, - caretTrimReplace, -} = __nccwpck_require__(3744) -const { FLAG_INCLUDE_PRERELEASE, FLAG_LOOSE } = __nccwpck_require__(2780) - -const isNullSet = c => c.value === '<0.0.0-0' -const isAny = c => c.value === '' - -// take a set of comparators and determine whether there -// exists a version which can satisfy it -const isSatisfiable = (comparators, options) => { - let result = true - const remainingComparators = comparators.slice() - let testComparator = remainingComparators.pop() - - while (result && remainingComparators.length) { - result = remainingComparators.every((otherComparator) => { - return testComparator.intersects(otherComparator, options) - }) - - testComparator = remainingComparators.pop() - } - - return result -} - -// comprised of xranges, tildes, stars, and gtlt's at this point. -// already replaced the hyphen ranges -// turn into a set of JUST comparators. -const parseComparator = (comp, options) => { - comp = comp.replace(re[t.BUILD], '') - debug('comp', comp, options) - comp = replaceCarets(comp, options) - debug('caret', comp) - comp = replaceTildes(comp, options) - debug('tildes', comp) - comp = replaceXRanges(comp, options) - debug('xrange', comp) - comp = replaceStars(comp, options) - debug('stars', comp) - return comp -} - -const isX = id => !id || id.toLowerCase() === 'x' || id === '*' - -// ~, ~> --> * (any, kinda silly) -// ~2, ~2.x, ~2.x.x, ~>2, ~>2.x ~>2.x.x --> >=2.0.0 <3.0.0-0 -// ~2.0, ~2.0.x, ~>2.0, ~>2.0.x --> >=2.0.0 <2.1.0-0 -// ~1.2, ~1.2.x, ~>1.2, ~>1.2.x --> >=1.2.0 <1.3.0-0 -// ~1.2.3, ~>1.2.3 --> >=1.2.3 <1.3.0-0 -// ~1.2.0, ~>1.2.0 --> >=1.2.0 <1.3.0-0 -// ~0.0.1 --> >=0.0.1 <0.1.0-0 -const replaceTildes = (comp, options) => { - return comp - .trim() - .split(/\s+/) - .map((c) => replaceTilde(c, options)) - .join(' ') -} - -const replaceTilde = (comp, options) => { - const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE] - return comp.replace(r, (_, M, m, p, pr) => { - debug('tilde', comp, _, M, m, p, pr) - let ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0 <${+M + 1}.0.0-0` - } else if (isX(p)) { - // ~1.2 == >=1.2.0 <1.3.0-0 - ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0` - } else if (pr) { - debug('replaceTilde pr', pr) - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } else { - // ~1.2.3 == >=1.2.3 <1.3.0-0 - ret = `>=${M}.${m}.${p - } <${M}.${+m + 1}.0-0` - } - - debug('tilde return', ret) - return ret - }) -} - -// ^ --> * (any, kinda silly) -// ^2, ^2.x, ^2.x.x --> >=2.0.0 <3.0.0-0 -// ^2.0, ^2.0.x --> >=2.0.0 <3.0.0-0 -// ^1.2, ^1.2.x --> >=1.2.0 <2.0.0-0 -// ^1.2.3 --> >=1.2.3 <2.0.0-0 -// ^1.2.0 --> >=1.2.0 <2.0.0-0 -// ^0.0.1 --> >=0.0.1 <0.0.2-0 -// ^0.1.0 --> >=0.1.0 <0.2.0-0 -const replaceCarets = (comp, options) => { - return comp - .trim() - .split(/\s+/) - .map((c) => replaceCaret(c, options)) - .join(' ') -} - -const replaceCaret = (comp, options) => { - debug('caret', comp, options) - const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET] - const z = options.includePrerelease ? '-0' : '' - return comp.replace(r, (_, M, m, p, pr) => { - debug('caret', comp, _, M, m, p, pr) - let ret - - if (isX(M)) { - ret = '' - } else if (isX(m)) { - ret = `>=${M}.0.0${z} <${+M + 1}.0.0-0` - } else if (isX(p)) { - if (M === '0') { - ret = `>=${M}.${m}.0${z} <${M}.${+m + 1}.0-0` - } else { - ret = `>=${M}.${m}.0${z} <${+M + 1}.0.0-0` - } - } else if (pr) { - debug('replaceCaret pr', pr) - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p}-${pr - } <${+M + 1}.0.0-0` - } - } else { - debug('no pr') - if (M === '0') { - if (m === '0') { - ret = `>=${M}.${m}.${p - }${z} <${M}.${m}.${+p + 1}-0` - } else { - ret = `>=${M}.${m}.${p - }${z} <${M}.${+m + 1}.0-0` - } - } else { - ret = `>=${M}.${m}.${p - } <${+M + 1}.0.0-0` - } - } - - debug('caret return', ret) - return ret - }) -} - -const replaceXRanges = (comp, options) => { - debug('replaceXRanges', comp, options) - return comp - .split(/\s+/) - .map((c) => replaceXRange(c, options)) - .join(' ') -} - -const replaceXRange = (comp, options) => { - comp = comp.trim() - const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE] - return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug('xRange', comp, ret, gtlt, M, m, p, pr) - const xM = isX(M) - const xm = xM || isX(m) - const xp = xm || isX(p) - const anyX = xp - - if (gtlt === '=' && anyX) { - gtlt = '' - } - - // if we're including prereleases in the match, then we need - // to fix this to -0, the lowest possible prerelease value - pr = options.includePrerelease ? '-0' : '' - - if (xM) { - if (gtlt === '>' || gtlt === '<') { - // nothing is allowed - ret = '<0.0.0-0' - } else { - // nothing is forbidden - ret = '*' - } - } else if (gtlt && anyX) { - // we know patch is an x, because we have any x at all. - // replace X with 0 - if (xm) { - m = 0 - } - p = 0 - - if (gtlt === '>') { - // >1 => >=2.0.0 - // >1.2 => >=1.3.0 - gtlt = '>=' - if (xm) { - M = +M + 1 - m = 0 - p = 0 - } else { - m = +m + 1 - p = 0 - } - } else if (gtlt === '<=') { - // <=0.7.x is actually <0.8.0, since any 0.7.x should - // pass. Similarly, <=7.x is actually <8.0.0, etc. - gtlt = '<' - if (xm) { - M = +M + 1 - } else { - m = +m + 1 - } - } - - if (gtlt === '<') { - pr = '-0' - } - - ret = `${gtlt + M}.${m}.${p}${pr}` - } else if (xm) { - ret = `>=${M}.0.0${pr} <${+M + 1}.0.0-0` - } else if (xp) { - ret = `>=${M}.${m}.0${pr - } <${M}.${+m + 1}.0-0` - } - - debug('xRange return', ret) - - return ret - }) -} - -// Because * is AND-ed with everything else in the comparator, -// and '' means "any version", just remove the *s entirely. -const replaceStars = (comp, options) => { - debug('replaceStars', comp, options) - // Looseness is ignored here. star is always as loose as it gets! - return comp - .trim() - .replace(re[t.STAR], '') -} - -const replaceGTE0 = (comp, options) => { - debug('replaceGTE0', comp, options) - return comp - .trim() - .replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], '') -} - -// This function is passed to string.replace(re[t.HYPHENRANGE]) -// M, m, patch, prerelease, build -// 1.2 - 3.4.5 => >=1.2.0 <=3.4.5 -// 1.2.3 - 3.4 => >=1.2.0 <3.5.0-0 Any 3.4.x will do -// 1.2 - 3.4 => >=1.2.0 <3.5.0-0 -// TODO build? -const hyphenReplace = incPr => ($0, - from, fM, fm, fp, fpr, fb, - to, tM, tm, tp, tpr) => { - if (isX(fM)) { - from = '' - } else if (isX(fm)) { - from = `>=${fM}.0.0${incPr ? '-0' : ''}` - } else if (isX(fp)) { - from = `>=${fM}.${fm}.0${incPr ? '-0' : ''}` - } else if (fpr) { - from = `>=${from}` - } else { - from = `>=${from}${incPr ? '-0' : ''}` - } - - if (isX(tM)) { - to = '' - } else if (isX(tm)) { - to = `<${+tM + 1}.0.0-0` - } else if (isX(tp)) { - to = `<${tM}.${+tm + 1}.0-0` - } else if (tpr) { - to = `<=${tM}.${tm}.${tp}-${tpr}` - } else if (incPr) { - to = `<${tM}.${tm}.${+tp + 1}-0` - } else { - to = `<=${to}` - } - - return `${from} ${to}`.trim() -} - -const testSet = (set, version, options) => { - for (let i = 0; i < set.length; i++) { - if (!set[i].test(version)) { - return false - } - } - - if (version.prerelease.length && !options.includePrerelease) { - // Find the set of versions that are allowed to have prereleases - // For example, ^1.2.3-pr.1 desugars to >=1.2.3-pr.1 <2.0.0 - // That should allow `1.2.3-pr.2` to pass. - // However, `1.2.4-alpha.notready` should NOT be allowed, - // even though it's within the range set by the comparators. - for (let i = 0; i < set.length; i++) { - debug(set[i].semver) - if (set[i].semver === Comparator.ANY) { - continue - } - - if (set[i].semver.prerelease.length > 0) { - const allowed = set[i].semver - if (allowed.major === version.major && - allowed.minor === version.minor && - allowed.patch === version.patch) { - return true - } - } - } - - // Version has a -pre, but it's not one of the ones we like. - return false - } - - return true -} - - -/***/ }), - -/***/ 3542: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const debug = __nccwpck_require__(1370) -const { MAX_LENGTH, MAX_SAFE_INTEGER } = __nccwpck_require__(2780) -const { safeRe: re, t } = __nccwpck_require__(3744) - -const parseOptions = __nccwpck_require__(741) -const { compareIdentifiers } = __nccwpck_require__(5397) -class SemVer { - constructor (version, options) { - options = parseOptions(options) - - if (version instanceof SemVer) { - if (version.loose === !!options.loose && - version.includePrerelease === !!options.includePrerelease) { - return version - } else { - version = version.version - } - } else if (typeof version !== 'string') { - throw new TypeError(`Invalid version. Must be a string. Got type "${typeof version}".`) - } - - if (version.length > MAX_LENGTH) { - throw new TypeError( - `version is longer than ${MAX_LENGTH} characters` - ) - } - - debug('SemVer', version, options) - this.options = options - this.loose = !!options.loose - // this isn't actually relevant for versions, but keep it so that we - // don't run into trouble passing this.options around. - this.includePrerelease = !!options.includePrerelease - - const m = version.trim().match(options.loose ? re[t.LOOSE] : re[t.FULL]) - - if (!m) { - throw new TypeError(`Invalid Version: ${version}`) - } - - this.raw = version - - // these are actually numbers - this.major = +m[1] - this.minor = +m[2] - this.patch = +m[3] - - if (this.major > MAX_SAFE_INTEGER || this.major < 0) { - throw new TypeError('Invalid major version') - } - - if (this.minor > MAX_SAFE_INTEGER || this.minor < 0) { - throw new TypeError('Invalid minor version') - } - - if (this.patch > MAX_SAFE_INTEGER || this.patch < 0) { - throw new TypeError('Invalid patch version') - } - - // numberify any prerelease numeric ids - if (!m[4]) { - this.prerelease = [] - } else { - this.prerelease = m[4].split('.').map((id) => { - if (/^[0-9]+$/.test(id)) { - const num = +id - if (num >= 0 && num < MAX_SAFE_INTEGER) { - return num - } - } - return id - }) - } - - this.build = m[5] ? m[5].split('.') : [] - this.format() - } - - format () { - this.version = `${this.major}.${this.minor}.${this.patch}` - if (this.prerelease.length) { - this.version += `-${this.prerelease.join('.')}` - } - return this.version - } - - toString () { - return this.version - } - - compare (other) { - debug('SemVer.compare', this.version, this.options, other) - if (!(other instanceof SemVer)) { - if (typeof other === 'string' && other === this.version) { - return 0 - } - other = new SemVer(other, this.options) - } - - if (other.version === this.version) { - return 0 - } - - return this.compareMain(other) || this.comparePre(other) - } - - compareMain (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - if (this.major < other.major) { - return -1 - } - if (this.major > other.major) { - return 1 - } - if (this.minor < other.minor) { - return -1 - } - if (this.minor > other.minor) { - return 1 - } - if (this.patch < other.patch) { - return -1 - } - if (this.patch > other.patch) { - return 1 - } - return 0 - } - - comparePre (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - // NOT having a prerelease is > having one - if (this.prerelease.length && !other.prerelease.length) { - return -1 - } else if (!this.prerelease.length && other.prerelease.length) { - return 1 - } else if (!this.prerelease.length && !other.prerelease.length) { - return 0 - } - - let i = 0 - do { - const a = this.prerelease[i] - const b = other.prerelease[i] - debug('prerelease compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - compareBuild (other) { - if (!(other instanceof SemVer)) { - other = new SemVer(other, this.options) - } - - let i = 0 - do { - const a = this.build[i] - const b = other.build[i] - debug('build compare', i, a, b) - if (a === undefined && b === undefined) { - return 0 - } else if (b === undefined) { - return 1 - } else if (a === undefined) { - return -1 - } else if (a === b) { - continue - } else { - return compareIdentifiers(a, b) - } - } while (++i) - } - - // preminor will bump the version up to the next minor release, and immediately - // down to pre-release. premajor and prepatch work the same way. - inc (release, identifier, identifierBase) { - if (release.startsWith('pre')) { - if (!identifier && identifierBase === false) { - throw new Error('invalid increment argument: identifier is empty') - } - // Avoid an invalid semver results - if (identifier) { - const match = `-${identifier}`.match(this.options.loose ? re[t.PRERELEASELOOSE] : re[t.PRERELEASE]) - if (!match || match[1] !== identifier) { - throw new Error(`invalid identifier: ${identifier}`) - } - } - } - - switch (release) { - case 'premajor': - this.prerelease.length = 0 - this.patch = 0 - this.minor = 0 - this.major++ - this.inc('pre', identifier, identifierBase) - break - case 'preminor': - this.prerelease.length = 0 - this.patch = 0 - this.minor++ - this.inc('pre', identifier, identifierBase) - break - case 'prepatch': - // If this is already a prerelease, it will bump to the next version - // drop any prereleases that might already exist, since they are not - // relevant at this point. - this.prerelease.length = 0 - this.inc('patch', identifier, identifierBase) - this.inc('pre', identifier, identifierBase) - break - // If the input is a non-prerelease version, this acts the same as - // prepatch. - case 'prerelease': - if (this.prerelease.length === 0) { - this.inc('patch', identifier, identifierBase) - } - this.inc('pre', identifier, identifierBase) - break - case 'release': - if (this.prerelease.length === 0) { - throw new Error(`version ${this.raw} is not a prerelease`) - } - this.prerelease.length = 0 - break - - case 'major': - // If this is a pre-major version, bump up to the same major version. - // Otherwise increment major. - // 1.0.0-5 bumps to 1.0.0 - // 1.1.0 bumps to 2.0.0 - if ( - this.minor !== 0 || - this.patch !== 0 || - this.prerelease.length === 0 - ) { - this.major++ - } - this.minor = 0 - this.patch = 0 - this.prerelease = [] - break - case 'minor': - // If this is a pre-minor version, bump up to the same minor version. - // Otherwise increment minor. - // 1.2.0-5 bumps to 1.2.0 - // 1.2.1 bumps to 1.3.0 - if (this.patch !== 0 || this.prerelease.length === 0) { - this.minor++ - } - this.patch = 0 - this.prerelease = [] - break - case 'patch': - // If this is not a pre-release version, it will increment the patch. - // If it is a pre-release it will bump up to the same patch version. - // 1.2.0-5 patches to 1.2.0 - // 1.2.0 patches to 1.2.1 - if (this.prerelease.length === 0) { - this.patch++ - } - this.prerelease = [] - break - // This probably shouldn't be used publicly. - // 1.0.0 'pre' would become 1.0.0-0 which is the wrong direction. - case 'pre': { - const base = Number(identifierBase) ? 1 : 0 - - if (this.prerelease.length === 0) { - this.prerelease = [base] - } else { - let i = this.prerelease.length - while (--i >= 0) { - if (typeof this.prerelease[i] === 'number') { - this.prerelease[i]++ - i = -2 - } - } - if (i === -1) { - // didn't increment anything - if (identifier === this.prerelease.join('.') && identifierBase === false) { - throw new Error('invalid increment argument: identifier already exists') - } - this.prerelease.push(base) - } - } - if (identifier) { - // 1.2.0-beta.1 bumps to 1.2.0-beta.2, - // 1.2.0-beta.fooblz or 1.2.0-beta bumps to 1.2.0-beta.0 - let prerelease = [identifier, base] - if (identifierBase === false) { - prerelease = [identifier] - } - if (compareIdentifiers(this.prerelease[0], identifier) === 0) { - if (isNaN(this.prerelease[1])) { - this.prerelease = prerelease - } - } else { - this.prerelease = prerelease - } - } - break - } - default: - throw new Error(`invalid increment argument: ${release}`) - } - this.raw = this.format() - if (this.build.length) { - this.raw += `+${this.build.join('.')}` - } - return this - } -} - -module.exports = SemVer - - -/***/ }), - -/***/ 4944: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const parse = __nccwpck_require__(9354) -const clean = (version, options) => { - const s = parse(version.trim().replace(/^[=v]+/, ''), options) - return s ? s.version : null -} -module.exports = clean - - -/***/ }), - -/***/ 6845: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const eq = __nccwpck_require__(1095) -const neq = __nccwpck_require__(5) -const gt = __nccwpck_require__(4430) -const gte = __nccwpck_require__(4167) -const lt = __nccwpck_require__(401) -const lte = __nccwpck_require__(6162) - -const cmp = (a, op, b, loose) => { - switch (op) { - case '===': - if (typeof a === 'object') { - a = a.version - } - if (typeof b === 'object') { - b = b.version - } - return a === b - - case '!==': - if (typeof a === 'object') { - a = a.version - } - if (typeof b === 'object') { - b = b.version - } - return a !== b - - case '': - case '=': - case '==': - return eq(a, b, loose) - - case '!=': - return neq(a, b, loose) - - case '>': - return gt(a, b, loose) - - case '>=': - return gte(a, b, loose) - - case '<': - return lt(a, b, loose) - - case '<=': - return lte(a, b, loose) - - default: - throw new TypeError(`Invalid operator: ${op}`) - } -} -module.exports = cmp - - -/***/ }), - -/***/ 9376: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) -const parse = __nccwpck_require__(9354) -const { safeRe: re, t } = __nccwpck_require__(3744) - -const coerce = (version, options) => { - if (version instanceof SemVer) { - return version - } - - if (typeof version === 'number') { - version = String(version) - } - - if (typeof version !== 'string') { - return null - } - - options = options || {} - - let match = null - if (!options.rtl) { - match = version.match(options.includePrerelease ? re[t.COERCEFULL] : re[t.COERCE]) - } else { - // Find the right-most coercible string that does not share - // a terminus with a more left-ward coercible string. - // Eg, '1.2.3.4' wants to coerce '2.3.4', not '3.4' or '4' - // With includePrerelease option set, '1.2.3.4-rc' wants to coerce '2.3.4-rc', not '2.3.4' - // - // Walk through the string checking with a /g regexp - // Manually set the index so as to pick up overlapping matches. - // Stop when we get a match that ends at the string end, since no - // coercible string can be more right-ward without the same terminus. - const coerceRtlRegex = options.includePrerelease ? re[t.COERCERTLFULL] : re[t.COERCERTL] - let next - while ((next = coerceRtlRegex.exec(version)) && - (!match || match.index + match[0].length !== version.length) - ) { - if (!match || - next.index + next[0].length !== match.index + match[0].length) { - match = next - } - coerceRtlRegex.lastIndex = next.index + next[1].length + next[2].length - } - // leave it in a clean state - coerceRtlRegex.lastIndex = -1 - } - - if (match === null) { - return null - } - - const major = match[2] - const minor = match[3] || '0' - const patch = match[4] || '0' - const prerelease = options.includePrerelease && match[5] ? `-${match[5]}` : '' - const build = options.includePrerelease && match[6] ? `+${match[6]}` : '' - - return parse(`${major}.${minor}.${patch}${prerelease}${build}`, options) -} -module.exports = coerce - - -/***/ }), - -/***/ 5271: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) -const compareBuild = (a, b, loose) => { - const versionA = new SemVer(a, loose) - const versionB = new SemVer(b, loose) - return versionA.compare(versionB) || versionA.compareBuild(versionB) -} -module.exports = compareBuild - - -/***/ }), - -/***/ 5354: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8534) -const compareLoose = (a, b) => compare(a, b, true) -module.exports = compareLoose - - -/***/ }), - -/***/ 8534: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) -const compare = (a, b, loose) => - new SemVer(a, loose).compare(new SemVer(b, loose)) - -module.exports = compare - - -/***/ }), - -/***/ 9670: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const parse = __nccwpck_require__(9354) - -const diff = (version1, version2) => { - const v1 = parse(version1, null, true) - const v2 = parse(version2, null, true) - const comparison = v1.compare(v2) - - if (comparison === 0) { - return null - } - - const v1Higher = comparison > 0 - const highVersion = v1Higher ? v1 : v2 - const lowVersion = v1Higher ? v2 : v1 - const highHasPre = !!highVersion.prerelease.length - const lowHasPre = !!lowVersion.prerelease.length - - if (lowHasPre && !highHasPre) { - // Going from prerelease -> no prerelease requires some special casing - - // If the low version has only a major, then it will always be a major - // Some examples: - // 1.0.0-1 -> 1.0.0 - // 1.0.0-1 -> 1.1.1 - // 1.0.0-1 -> 2.0.0 - if (!lowVersion.patch && !lowVersion.minor) { - return 'major' - } - - // If the main part has no difference - if (lowVersion.compareMain(highVersion) === 0) { - if (lowVersion.minor && !lowVersion.patch) { - return 'minor' - } - return 'patch' - } - } - - // add the `pre` prefix if we are going to a prerelease version - const prefix = highHasPre ? 'pre' : '' - - if (v1.major !== v2.major) { - return prefix + 'major' - } - - if (v1.minor !== v2.minor) { - return prefix + 'minor' - } - - if (v1.patch !== v2.patch) { - return prefix + 'patch' - } - - // high and low are preleases - return 'prerelease' -} - -module.exports = diff - - -/***/ }), - -/***/ 1095: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8534) -const eq = (a, b, loose) => compare(a, b, loose) === 0 -module.exports = eq - - -/***/ }), - -/***/ 4430: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8534) -const gt = (a, b, loose) => compare(a, b, loose) > 0 -module.exports = gt - - -/***/ }), - -/***/ 4167: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8534) -const gte = (a, b, loose) => compare(a, b, loose) >= 0 -module.exports = gte - - -/***/ }), - -/***/ 1745: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) - -const inc = (version, release, options, identifier, identifierBase) => { - if (typeof (options) === 'string') { - identifierBase = identifier - identifier = options - options = undefined - } - - try { - return new SemVer( - version instanceof SemVer ? version.version : version, - options - ).inc(release, identifier, identifierBase).version - } catch (er) { - return null - } -} -module.exports = inc - - -/***/ }), - -/***/ 401: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8534) -const lt = (a, b, loose) => compare(a, b, loose) < 0 -module.exports = lt - - -/***/ }), - -/***/ 6162: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8534) -const lte = (a, b, loose) => compare(a, b, loose) <= 0 -module.exports = lte - - -/***/ }), - -/***/ 6264: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) -const major = (a, loose) => new SemVer(a, loose).major -module.exports = major - - -/***/ }), - -/***/ 8084: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) -const minor = (a, loose) => new SemVer(a, loose).minor -module.exports = minor - - -/***/ }), - -/***/ 5: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8534) -const neq = (a, b, loose) => compare(a, b, loose) !== 0 -module.exports = neq - - -/***/ }), - -/***/ 9354: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) -const parse = (version, options, throwErrors = false) => { - if (version instanceof SemVer) { - return version - } - try { - return new SemVer(version, options) - } catch (er) { - if (!throwErrors) { - return null - } - throw er - } -} - -module.exports = parse - - -/***/ }), - -/***/ 955: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) -const patch = (a, loose) => new SemVer(a, loose).patch -module.exports = patch - - -/***/ }), - -/***/ 7451: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const parse = __nccwpck_require__(9354) -const prerelease = (version, options) => { - const parsed = parse(version, options) - return (parsed && parsed.prerelease.length) ? parsed.prerelease : null -} -module.exports = prerelease - - -/***/ }), - -/***/ 1184: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compare = __nccwpck_require__(8534) -const rcompare = (a, b, loose) => compare(b, a, loose) -module.exports = rcompare - - -/***/ }), - -/***/ 7895: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compareBuild = __nccwpck_require__(5271) -const rsort = (list, loose) => list.sort((a, b) => compareBuild(b, a, loose)) -module.exports = rsort - - -/***/ }), - -/***/ 5344: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Range = __nccwpck_require__(9005) -const satisfies = (version, range, options) => { - try { - range = new Range(range, options) - } catch (er) { - return false - } - return range.test(version) -} -module.exports = satisfies - - -/***/ }), - -/***/ 6425: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const compareBuild = __nccwpck_require__(5271) -const sort = (list, loose) => list.sort((a, b) => compareBuild(a, b, loose)) -module.exports = sort - - -/***/ }), - -/***/ 8799: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const parse = __nccwpck_require__(9354) -const valid = (version, options) => { - const v = parse(version, options) - return v ? v.version : null -} -module.exports = valid - - -/***/ }), - -/***/ 1727: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// just pre-load all the stuff that index.js lazily exports -const internalRe = __nccwpck_require__(3744) -const constants = __nccwpck_require__(2780) -const SemVer = __nccwpck_require__(3542) -const identifiers = __nccwpck_require__(5397) -const parse = __nccwpck_require__(9354) -const valid = __nccwpck_require__(8799) -const clean = __nccwpck_require__(4944) -const inc = __nccwpck_require__(1745) -const diff = __nccwpck_require__(9670) -const major = __nccwpck_require__(6264) -const minor = __nccwpck_require__(8084) -const patch = __nccwpck_require__(955) -const prerelease = __nccwpck_require__(7451) -const compare = __nccwpck_require__(8534) -const rcompare = __nccwpck_require__(1184) -const compareLoose = __nccwpck_require__(5354) -const compareBuild = __nccwpck_require__(5271) -const sort = __nccwpck_require__(6425) -const rsort = __nccwpck_require__(7895) -const gt = __nccwpck_require__(4430) -const lt = __nccwpck_require__(401) -const eq = __nccwpck_require__(1095) -const neq = __nccwpck_require__(5) -const gte = __nccwpck_require__(4167) -const lte = __nccwpck_require__(6162) -const cmp = __nccwpck_require__(6845) -const coerce = __nccwpck_require__(9376) -const Comparator = __nccwpck_require__(9018) -const Range = __nccwpck_require__(9005) -const satisfies = __nccwpck_require__(5344) -const toComparators = __nccwpck_require__(6493) -const maxSatisfying = __nccwpck_require__(7890) -const minSatisfying = __nccwpck_require__(5320) -const minVersion = __nccwpck_require__(2067) -const validRange = __nccwpck_require__(8340) -const outside = __nccwpck_require__(2382) -const gtr = __nccwpck_require__(761) -const ltr = __nccwpck_require__(4624) -const intersects = __nccwpck_require__(7978) -const simplifyRange = __nccwpck_require__(9615) -const subset = __nccwpck_require__(7710) -module.exports = { - parse, - valid, - clean, - inc, - diff, - major, - minor, - patch, - prerelease, - compare, - rcompare, - compareLoose, - compareBuild, - sort, - rsort, - gt, - lt, - eq, - neq, - gte, - lte, - cmp, - coerce, - Comparator, - Range, - satisfies, - toComparators, - maxSatisfying, - minSatisfying, - minVersion, - validRange, - outside, - gtr, - ltr, - intersects, - simplifyRange, - subset, - SemVer, - re: internalRe.re, - src: internalRe.src, - tokens: internalRe.t, - SEMVER_SPEC_VERSION: constants.SEMVER_SPEC_VERSION, - RELEASE_TYPES: constants.RELEASE_TYPES, - compareIdentifiers: identifiers.compareIdentifiers, - rcompareIdentifiers: identifiers.rcompareIdentifiers, -} - - -/***/ }), - -/***/ 2780: -/***/ ((module) => { - - - -// Note: this is the semver.org version of the spec that it implements -// Not necessarily the package version of this code. -const SEMVER_SPEC_VERSION = '2.0.0' - -const MAX_LENGTH = 256 -const MAX_SAFE_INTEGER = Number.MAX_SAFE_INTEGER || -/* istanbul ignore next */ 9007199254740991 - -// Max safe segment length for coercion. -const MAX_SAFE_COMPONENT_LENGTH = 16 - -// Max safe length for a build identifier. The max length minus 6 characters for -// the shortest version with a build 0.0.0+BUILD. -const MAX_SAFE_BUILD_LENGTH = MAX_LENGTH - 6 - -const RELEASE_TYPES = [ - 'major', - 'premajor', - 'minor', - 'preminor', - 'patch', - 'prepatch', - 'prerelease', -] - -module.exports = { - MAX_LENGTH, - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_SAFE_INTEGER, - RELEASE_TYPES, - SEMVER_SPEC_VERSION, - FLAG_INCLUDE_PRERELEASE: 0b001, - FLAG_LOOSE: 0b010, -} - - -/***/ }), - -/***/ 1370: -/***/ ((module) => { - - - -const debug = ( - typeof process === 'object' && - process.env && - process.env.NODE_DEBUG && - /\bsemver\b/i.test(process.env.NODE_DEBUG) -) ? (...args) => console.error('SEMVER', ...args) - : () => {} - -module.exports = debug - - -/***/ }), - -/***/ 5397: -/***/ ((module) => { - - - -const numeric = /^[0-9]+$/ -const compareIdentifiers = (a, b) => { - if (typeof a === 'number' && typeof b === 'number') { - return a === b ? 0 : a < b ? -1 : 1 - } - - const anum = numeric.test(a) - const bnum = numeric.test(b) - - if (anum && bnum) { - a = +a - b = +b - } - - return a === b ? 0 - : (anum && !bnum) ? -1 - : (bnum && !anum) ? 1 - : a < b ? -1 - : 1 -} - -const rcompareIdentifiers = (a, b) => compareIdentifiers(b, a) - -module.exports = { - compareIdentifiers, - rcompareIdentifiers, -} - - -/***/ }), - -/***/ 9508: -/***/ ((module) => { - - - -class LRUCache { - constructor () { - this.max = 1000 - this.map = new Map() - } - - get (key) { - const value = this.map.get(key) - if (value === undefined) { - return undefined - } else { - // Remove the key from the map and add it to the end - this.map.delete(key) - this.map.set(key, value) - return value - } - } - - delete (key) { - return this.map.delete(key) - } - - set (key, value) { - const deleted = this.delete(key) - - if (!deleted && value !== undefined) { - // If cache is full, delete the least recently used item - if (this.map.size >= this.max) { - const firstKey = this.map.keys().next().value - this.delete(firstKey) - } - - this.map.set(key, value) - } - - return this - } -} - -module.exports = LRUCache - - -/***/ }), - -/***/ 741: -/***/ ((module) => { - - - -// parse out just the options we care about -const looseOption = Object.freeze({ loose: true }) -const emptyOpts = Object.freeze({ }) -const parseOptions = options => { - if (!options) { - return emptyOpts - } - - if (typeof options !== 'object') { - return looseOption - } - - return options -} -module.exports = parseOptions - - -/***/ }), - -/***/ 3744: -/***/ ((module, exports, __nccwpck_require__) => { - - - -const { - MAX_SAFE_COMPONENT_LENGTH, - MAX_SAFE_BUILD_LENGTH, - MAX_LENGTH, -} = __nccwpck_require__(2780) -const debug = __nccwpck_require__(1370) -exports = module.exports = {} - -// The actual regexps go on exports.re -const re = exports.re = [] -const safeRe = exports.safeRe = [] -const src = exports.src = [] -const safeSrc = exports.safeSrc = [] -const t = exports.t = {} -let R = 0 - -const LETTERDASHNUMBER = '[a-zA-Z0-9-]' - -// Replace some greedy regex tokens to prevent regex dos issues. These regex are -// used internally via the safeRe object since all inputs in this library get -// normalized first to trim and collapse all extra whitespace. The original -// regexes are exported for userland consumption and lower level usage. A -// future breaking change could export the safer regex only with a note that -// all input should have extra whitespace removed. -const safeRegexReplacements = [ - ['\\s', 1], - ['\\d', MAX_LENGTH], - [LETTERDASHNUMBER, MAX_SAFE_BUILD_LENGTH], -] - -const makeSafeRegex = (value) => { - for (const [token, max] of safeRegexReplacements) { - value = value - .split(`${token}*`).join(`${token}{0,${max}}`) - .split(`${token}+`).join(`${token}{1,${max}}`) - } - return value -} - -const createToken = (name, value, isGlobal) => { - const safe = makeSafeRegex(value) - const index = R++ - debug(name, index, value) - t[name] = index - src[index] = value - safeSrc[index] = safe - re[index] = new RegExp(value, isGlobal ? 'g' : undefined) - safeRe[index] = new RegExp(safe, isGlobal ? 'g' : undefined) -} - -// The following Regular Expressions can be used for tokenizing, -// validating, and parsing SemVer version strings. - -// ## Numeric Identifier -// A single `0`, or a non-zero digit followed by zero or more digits. - -createToken('NUMERICIDENTIFIER', '0|[1-9]\\d*') -createToken('NUMERICIDENTIFIERLOOSE', '\\d+') - -// ## Non-numeric Identifier -// Zero or more digits, followed by a letter or hyphen, and then zero or -// more letters, digits, or hyphens. - -createToken('NONNUMERICIDENTIFIER', `\\d*[a-zA-Z-]${LETTERDASHNUMBER}*`) - -// ## Main Version -// Three dot-separated numeric identifiers. - -createToken('MAINVERSION', `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})\\.` + - `(${src[t.NUMERICIDENTIFIER]})`) - -createToken('MAINVERSIONLOOSE', `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})\\.` + - `(${src[t.NUMERICIDENTIFIERLOOSE]})`) - -// ## Pre-release Version Identifier -// A numeric identifier, or a non-numeric identifier. -// Non-numberic identifiers include numberic identifiers but can be longer. -// Therefore non-numberic identifiers must go first. - -createToken('PRERELEASEIDENTIFIER', `(?:${src[t.NONNUMERICIDENTIFIER] -}|${src[t.NUMERICIDENTIFIER]})`) - -createToken('PRERELEASEIDENTIFIERLOOSE', `(?:${src[t.NONNUMERICIDENTIFIER] -}|${src[t.NUMERICIDENTIFIERLOOSE]})`) - -// ## Pre-release Version -// Hyphen, followed by one or more dot-separated pre-release version -// identifiers. - -createToken('PRERELEASE', `(?:-(${src[t.PRERELEASEIDENTIFIER] -}(?:\\.${src[t.PRERELEASEIDENTIFIER]})*))`) - -createToken('PRERELEASELOOSE', `(?:-?(${src[t.PRERELEASEIDENTIFIERLOOSE] -}(?:\\.${src[t.PRERELEASEIDENTIFIERLOOSE]})*))`) - -// ## Build Metadata Identifier -// Any combination of digits, letters, or hyphens. - -createToken('BUILDIDENTIFIER', `${LETTERDASHNUMBER}+`) - -// ## Build Metadata -// Plus sign, followed by one or more period-separated build metadata -// identifiers. - -createToken('BUILD', `(?:\\+(${src[t.BUILDIDENTIFIER] -}(?:\\.${src[t.BUILDIDENTIFIER]})*))`) - -// ## Full Version String -// A main version, followed optionally by a pre-release version and -// build metadata. - -// Note that the only major, minor, patch, and pre-release sections of -// the version string are capturing groups. The build metadata is not a -// capturing group, because it should not ever be used in version -// comparison. - -createToken('FULLPLAIN', `v?${src[t.MAINVERSION] -}${src[t.PRERELEASE]}?${ - src[t.BUILD]}?`) - -createToken('FULL', `^${src[t.FULLPLAIN]}$`) - -// like full, but allows v1.2.3 and =1.2.3, which people do sometimes. -// also, 1.0.0alpha1 (prerelease without the hyphen) which is pretty -// common in the npm registry. -createToken('LOOSEPLAIN', `[v=\\s]*${src[t.MAINVERSIONLOOSE] -}${src[t.PRERELEASELOOSE]}?${ - src[t.BUILD]}?`) - -createToken('LOOSE', `^${src[t.LOOSEPLAIN]}$`) - -createToken('GTLT', '((?:<|>)?=?)') - -// Something like "2.*" or "1.2.x". -// Note that "x.x" is a valid xRange identifer, meaning "any version" -// Only the first item is strictly required. -createToken('XRANGEIDENTIFIERLOOSE', `${src[t.NUMERICIDENTIFIERLOOSE]}|x|X|\\*`) -createToken('XRANGEIDENTIFIER', `${src[t.NUMERICIDENTIFIER]}|x|X|\\*`) - -createToken('XRANGEPLAIN', `[v=\\s]*(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIER]})` + - `(?:${src[t.PRERELEASE]})?${ - src[t.BUILD]}?` + - `)?)?`) - -createToken('XRANGEPLAINLOOSE', `[v=\\s]*(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:\\.(${src[t.XRANGEIDENTIFIERLOOSE]})` + - `(?:${src[t.PRERELEASELOOSE]})?${ - src[t.BUILD]}?` + - `)?)?`) - -createToken('XRANGE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAIN]}$`) -createToken('XRANGELOOSE', `^${src[t.GTLT]}\\s*${src[t.XRANGEPLAINLOOSE]}$`) - -// Coercion. -// Extract anything that could conceivably be a part of a valid semver -createToken('COERCEPLAIN', `${'(^|[^\\d])' + - '(\\d{1,'}${MAX_SAFE_COMPONENT_LENGTH}})` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?` + - `(?:\\.(\\d{1,${MAX_SAFE_COMPONENT_LENGTH}}))?`) -createToken('COERCE', `${src[t.COERCEPLAIN]}(?:$|[^\\d])`) -createToken('COERCEFULL', src[t.COERCEPLAIN] + - `(?:${src[t.PRERELEASE]})?` + - `(?:${src[t.BUILD]})?` + - `(?:$|[^\\d])`) -createToken('COERCERTL', src[t.COERCE], true) -createToken('COERCERTLFULL', src[t.COERCEFULL], true) - -// Tilde ranges. -// Meaning is "reasonably at or greater than" -createToken('LONETILDE', '(?:~>?)') - -createToken('TILDETRIM', `(\\s*)${src[t.LONETILDE]}\\s+`, true) -exports.tildeTrimReplace = '$1~' - -createToken('TILDE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAIN]}$`) -createToken('TILDELOOSE', `^${src[t.LONETILDE]}${src[t.XRANGEPLAINLOOSE]}$`) - -// Caret ranges. -// Meaning is "at least and backwards compatible with" -createToken('LONECARET', '(?:\\^)') - -createToken('CARETTRIM', `(\\s*)${src[t.LONECARET]}\\s+`, true) -exports.caretTrimReplace = '$1^' - -createToken('CARET', `^${src[t.LONECARET]}${src[t.XRANGEPLAIN]}$`) -createToken('CARETLOOSE', `^${src[t.LONECARET]}${src[t.XRANGEPLAINLOOSE]}$`) - -// A simple gt/lt/eq thing, or just "" to indicate "any version" -createToken('COMPARATORLOOSE', `^${src[t.GTLT]}\\s*(${src[t.LOOSEPLAIN]})$|^$`) -createToken('COMPARATOR', `^${src[t.GTLT]}\\s*(${src[t.FULLPLAIN]})$|^$`) - -// An expression to strip any whitespace between the gtlt and the thing -// it modifies, so that `> 1.2.3` ==> `>1.2.3` -createToken('COMPARATORTRIM', `(\\s*)${src[t.GTLT] -}\\s*(${src[t.LOOSEPLAIN]}|${src[t.XRANGEPLAIN]})`, true) -exports.comparatorTrimReplace = '$1$2$3' - -// Something like `1.2.3 - 1.2.4` -// Note that these all use the loose form, because they'll be -// checked against either the strict or loose comparator form -// later. -createToken('HYPHENRANGE', `^\\s*(${src[t.XRANGEPLAIN]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAIN]})` + - `\\s*$`) - -createToken('HYPHENRANGELOOSE', `^\\s*(${src[t.XRANGEPLAINLOOSE]})` + - `\\s+-\\s+` + - `(${src[t.XRANGEPLAINLOOSE]})` + - `\\s*$`) - -// Star ranges basically just allow anything at all. -createToken('STAR', '(<|>)?=?\\s*\\*') -// >=0.0.0 is like a star -createToken('GTE0', '^\\s*>=\\s*0\\.0\\.0\\s*$') -createToken('GTE0PRE', '^\\s*>=\\s*0\\.0\\.0-0\\s*$') - - -/***/ }), - -/***/ 761: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// Determine if version is greater than all the versions possible in the range. -const outside = __nccwpck_require__(2382) -const gtr = (version, range, options) => outside(version, range, '>', options) -module.exports = gtr - - -/***/ }), - -/***/ 7978: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Range = __nccwpck_require__(9005) -const intersects = (r1, r2, options) => { - r1 = new Range(r1, options) - r2 = new Range(r2, options) - return r1.intersects(r2, options) -} -module.exports = intersects - - -/***/ }), - -/***/ 4624: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const outside = __nccwpck_require__(2382) -// Determine if version is less than all the versions possible in the range -const ltr = (version, range, options) => outside(version, range, '<', options) -module.exports = ltr - - -/***/ }), - -/***/ 7890: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) -const Range = __nccwpck_require__(9005) - -const maxSatisfying = (versions, range, options) => { - let max = null - let maxSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!max || maxSV.compare(v) === -1) { - // compare(max, v, true) - max = v - maxSV = new SemVer(max, options) - } - } - }) - return max -} -module.exports = maxSatisfying - - -/***/ }), - -/***/ 5320: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) -const Range = __nccwpck_require__(9005) -const minSatisfying = (versions, range, options) => { - let min = null - let minSV = null - let rangeObj = null - try { - rangeObj = new Range(range, options) - } catch (er) { - return null - } - versions.forEach((v) => { - if (rangeObj.test(v)) { - // satisfies(v, range, options) - if (!min || minSV.compare(v) === 1) { - // compare(min, v, true) - min = v - minSV = new SemVer(min, options) - } - } - }) - return min -} -module.exports = minSatisfying - - -/***/ }), - -/***/ 2067: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) -const Range = __nccwpck_require__(9005) -const gt = __nccwpck_require__(4430) - -const minVersion = (range, loose) => { - range = new Range(range, loose) - - let minver = new SemVer('0.0.0') - if (range.test(minver)) { - return minver - } - - minver = new SemVer('0.0.0-0') - if (range.test(minver)) { - return minver - } - - minver = null - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] - - let setMin = null - comparators.forEach((comparator) => { - // Clone to avoid manipulating the comparator's semver object. - const compver = new SemVer(comparator.semver.version) - switch (comparator.operator) { - case '>': - if (compver.prerelease.length === 0) { - compver.patch++ - } else { - compver.prerelease.push(0) - } - compver.raw = compver.format() - /* fallthrough */ - case '': - case '>=': - if (!setMin || gt(compver, setMin)) { - setMin = compver - } - break - case '<': - case '<=': - /* Ignore maximum versions */ - break - /* istanbul ignore next */ - default: - throw new Error(`Unexpected operation: ${comparator.operator}`) - } - }) - if (setMin && (!minver || gt(minver, setMin))) { - minver = setMin - } - } - - if (minver && range.test(minver)) { - return minver - } - - return null -} -module.exports = minVersion - - -/***/ }), - -/***/ 2382: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const SemVer = __nccwpck_require__(3542) -const Comparator = __nccwpck_require__(9018) -const { ANY } = Comparator -const Range = __nccwpck_require__(9005) -const satisfies = __nccwpck_require__(5344) -const gt = __nccwpck_require__(4430) -const lt = __nccwpck_require__(401) -const lte = __nccwpck_require__(6162) -const gte = __nccwpck_require__(4167) - -const outside = (version, range, hilo, options) => { - version = new SemVer(version, options) - range = new Range(range, options) - - let gtfn, ltefn, ltfn, comp, ecomp - switch (hilo) { - case '>': - gtfn = gt - ltefn = lte - ltfn = lt - comp = '>' - ecomp = '>=' - break - case '<': - gtfn = lt - ltefn = gte - ltfn = gt - comp = '<' - ecomp = '<=' - break - default: - throw new TypeError('Must provide a hilo val of "<" or ">"') - } - - // If it satisfies the range it is not outside - if (satisfies(version, range, options)) { - return false - } - - // From now on, variable terms are as if we're in "gtr" mode. - // but note that everything is flipped for the "ltr" function. - - for (let i = 0; i < range.set.length; ++i) { - const comparators = range.set[i] - - let high = null - let low = null - - comparators.forEach((comparator) => { - if (comparator.semver === ANY) { - comparator = new Comparator('>=0.0.0') - } - high = high || comparator - low = low || comparator - if (gtfn(comparator.semver, high.semver, options)) { - high = comparator - } else if (ltfn(comparator.semver, low.semver, options)) { - low = comparator - } - }) - - // If the edge version comparator has a operator then our version - // isn't outside it - if (high.operator === comp || high.operator === ecomp) { - return false - } - - // If the lowest version comparator has an operator and our version - // is less than it then it isn't higher than the range - if ((!low.operator || low.operator === comp) && - ltefn(version, low.semver)) { - return false - } else if (low.operator === ecomp && ltfn(version, low.semver)) { - return false - } - } - return true -} - -module.exports = outside - - -/***/ }), - -/***/ 9615: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// given a set of versions and a range, create a "simplified" range -// that includes the same versions that the original range does -// If the original range is shorter than the simplified one, return that. -const satisfies = __nccwpck_require__(5344) -const compare = __nccwpck_require__(8534) -module.exports = (versions, range, options) => { - const set = [] - let first = null - let prev = null - const v = versions.sort((a, b) => compare(a, b, options)) - for (const version of v) { - const included = satisfies(version, range, options) - if (included) { - prev = version - if (!first) { - first = version - } - } else { - if (prev) { - set.push([first, prev]) - } - prev = null - first = null - } - } - if (first) { - set.push([first, null]) - } - - const ranges = [] - for (const [min, max] of set) { - if (min === max) { - ranges.push(min) - } else if (!max && min === v[0]) { - ranges.push('*') - } else if (!max) { - ranges.push(`>=${min}`) - } else if (min === v[0]) { - ranges.push(`<=${max}`) - } else { - ranges.push(`${min} - ${max}`) - } - } - const simplified = ranges.join(' || ') - const original = typeof range.raw === 'string' ? range.raw : String(range) - return simplified.length < original.length ? simplified : range -} - - -/***/ }), - -/***/ 7710: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Range = __nccwpck_require__(9005) -const Comparator = __nccwpck_require__(9018) -const { ANY } = Comparator -const satisfies = __nccwpck_require__(5344) -const compare = __nccwpck_require__(8534) - -// Complex range `r1 || r2 || ...` is a subset of `R1 || R2 || ...` iff: -// - Every simple range `r1, r2, ...` is a null set, OR -// - Every simple range `r1, r2, ...` which is not a null set is a subset of -// some `R1, R2, ...` -// -// Simple range `c1 c2 ...` is a subset of simple range `C1 C2 ...` iff: -// - If c is only the ANY comparator -// - If C is only the ANY comparator, return true -// - Else if in prerelease mode, return false -// - else replace c with `[>=0.0.0]` -// - If C is only the ANY comparator -// - if in prerelease mode, return true -// - else replace C with `[>=0.0.0]` -// - Let EQ be the set of = comparators in c -// - If EQ is more than one, return true (null set) -// - Let GT be the highest > or >= comparator in c -// - Let LT be the lowest < or <= comparator in c -// - If GT and LT, and GT.semver > LT.semver, return true (null set) -// - If any C is a = range, and GT or LT are set, return false -// - If EQ -// - If GT, and EQ does not satisfy GT, return true (null set) -// - If LT, and EQ does not satisfy LT, return true (null set) -// - If EQ satisfies every C, return true -// - Else return false -// - If GT -// - If GT.semver is lower than any > or >= comp in C, return false -// - If GT is >=, and GT.semver does not satisfy every C, return false -// - If GT.semver has a prerelease, and not in prerelease mode -// - If no C has a prerelease and the GT.semver tuple, return false -// - If LT -// - If LT.semver is greater than any < or <= comp in C, return false -// - If LT is <=, and LT.semver does not satisfy every C, return false -// - If GT.semver has a prerelease, and not in prerelease mode -// - If no C has a prerelease and the LT.semver tuple, return false -// - Else return true - -const subset = (sub, dom, options = {}) => { - if (sub === dom) { - return true - } - - sub = new Range(sub, options) - dom = new Range(dom, options) - let sawNonNull = false - - OUTER: for (const simpleSub of sub.set) { - for (const simpleDom of dom.set) { - const isSub = simpleSubset(simpleSub, simpleDom, options) - sawNonNull = sawNonNull || isSub !== null - if (isSub) { - continue OUTER - } - } - // the null set is a subset of everything, but null simple ranges in - // a complex range should be ignored. so if we saw a non-null range, - // then we know this isn't a subset, but if EVERY simple range was null, - // then it is a subset. - if (sawNonNull) { - return false - } - } - return true -} - -const minimumVersionWithPreRelease = [new Comparator('>=0.0.0-0')] -const minimumVersion = [new Comparator('>=0.0.0')] - -const simpleSubset = (sub, dom, options) => { - if (sub === dom) { - return true - } - - if (sub.length === 1 && sub[0].semver === ANY) { - if (dom.length === 1 && dom[0].semver === ANY) { - return true - } else if (options.includePrerelease) { - sub = minimumVersionWithPreRelease - } else { - sub = minimumVersion - } - } - - if (dom.length === 1 && dom[0].semver === ANY) { - if (options.includePrerelease) { - return true - } else { - dom = minimumVersion - } - } - - const eqSet = new Set() - let gt, lt - for (const c of sub) { - if (c.operator === '>' || c.operator === '>=') { - gt = higherGT(gt, c, options) - } else if (c.operator === '<' || c.operator === '<=') { - lt = lowerLT(lt, c, options) - } else { - eqSet.add(c.semver) - } - } - - if (eqSet.size > 1) { - return null - } - - let gtltComp - if (gt && lt) { - gtltComp = compare(gt.semver, lt.semver, options) - if (gtltComp > 0) { - return null - } else if (gtltComp === 0 && (gt.operator !== '>=' || lt.operator !== '<=')) { - return null - } - } - - // will iterate one or zero times - for (const eq of eqSet) { - if (gt && !satisfies(eq, String(gt), options)) { - return null - } - - if (lt && !satisfies(eq, String(lt), options)) { - return null - } - - for (const c of dom) { - if (!satisfies(eq, String(c), options)) { - return false - } - } - - return true - } - - let higher, lower - let hasDomLT, hasDomGT - // if the subset has a prerelease, we need a comparator in the superset - // with the same tuple and a prerelease, or it's not a subset - let needDomLTPre = lt && - !options.includePrerelease && - lt.semver.prerelease.length ? lt.semver : false - let needDomGTPre = gt && - !options.includePrerelease && - gt.semver.prerelease.length ? gt.semver : false - // exception: <1.2.3-0 is the same as <1.2.3 - if (needDomLTPre && needDomLTPre.prerelease.length === 1 && - lt.operator === '<' && needDomLTPre.prerelease[0] === 0) { - needDomLTPre = false - } - - for (const c of dom) { - hasDomGT = hasDomGT || c.operator === '>' || c.operator === '>=' - hasDomLT = hasDomLT || c.operator === '<' || c.operator === '<=' - if (gt) { - if (needDomGTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomGTPre.major && - c.semver.minor === needDomGTPre.minor && - c.semver.patch === needDomGTPre.patch) { - needDomGTPre = false - } - } - if (c.operator === '>' || c.operator === '>=') { - higher = higherGT(gt, c, options) - if (higher === c && higher !== gt) { - return false - } - } else if (gt.operator === '>=' && !satisfies(gt.semver, String(c), options)) { - return false - } - } - if (lt) { - if (needDomLTPre) { - if (c.semver.prerelease && c.semver.prerelease.length && - c.semver.major === needDomLTPre.major && - c.semver.minor === needDomLTPre.minor && - c.semver.patch === needDomLTPre.patch) { - needDomLTPre = false - } - } - if (c.operator === '<' || c.operator === '<=') { - lower = lowerLT(lt, c, options) - if (lower === c && lower !== lt) { - return false - } - } else if (lt.operator === '<=' && !satisfies(lt.semver, String(c), options)) { - return false - } - } - if (!c.operator && (lt || gt) && gtltComp !== 0) { - return false - } - } - - // if there was a < or >, and nothing in the dom, then must be false - // UNLESS it was limited by another range in the other direction. - // Eg, >1.0.0 <1.0.1 is still a subset of <2.0.0 - if (gt && hasDomLT && !lt && gtltComp !== 0) { - return false - } - - if (lt && hasDomGT && !gt && gtltComp !== 0) { - return false - } - - // we needed a prerelease range in a specific tuple, but didn't get one - // then this isn't a subset. eg >=1.2.3-pre is not a subset of >=1.0.0, - // because it includes prereleases in the 1.2.3 tuple - if (needDomGTPre || needDomLTPre) { - return false - } - - return true -} - -// >=1.2.3 is lower than >1.2.3 -const higherGT = (a, b, options) => { - if (!a) { - return b - } - const comp = compare(a.semver, b.semver, options) - return comp > 0 ? a - : comp < 0 ? b - : b.operator === '>' && a.operator === '>=' ? b - : a -} - -// <=1.2.3 is higher than <1.2.3 -const lowerLT = (a, b, options) => { - if (!a) { - return b - } - const comp = compare(a.semver, b.semver, options) - return comp < 0 ? a - : comp > 0 ? b - : b.operator === '<' && a.operator === '<=' ? b - : a -} - -module.exports = subset - - -/***/ }), - -/***/ 6493: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Range = __nccwpck_require__(9005) - -// Mostly just for testing and legacy API reasons -const toComparators = (range, options) => - new Range(range, options).set - .map(comp => comp.map(c => c.value).join(' ').trim().split(' ')) - -module.exports = toComparators - - -/***/ }), - -/***/ 8340: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Range = __nccwpck_require__(9005) -const validRange = (range, options) => { - try { - // Return '*' instead of '' so that truthiness works. - // This will throw if it's invalid anyway - return new Range(range, options).range || '*' - } catch (er) { - return null - } -} -module.exports = validRange - - -/***/ }), - -/***/ 5560: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -var wrappy = __nccwpck_require__(8264) -module.exports = wrappy(once) -module.exports.strict = wrappy(onceStrict) - -once.proto = once(function () { - Object.defineProperty(Function.prototype, 'once', { - value: function () { - return once(this) - }, - configurable: true - }) - - Object.defineProperty(Function.prototype, 'onceStrict', { - value: function () { - return onceStrict(this) - }, - configurable: true - }) -}) - -function once (fn) { - var f = function () { - if (f.called) return f.value - f.called = true - return f.value = fn.apply(this, arguments) - } - f.called = false - return f -} - -function onceStrict (fn) { - var f = function () { - if (f.called) - throw new Error(f.onceError) - f.called = true - return f.value = fn.apply(this, arguments) - } - var name = fn.name || 'Function wrapped with `once`' - f.onceError = name + " shouldn't be called more than once" - f.called = false - return f -} - - -/***/ }), - -/***/ 2766: -/***/ ((module) => { - - -module.exports = (promise, onFinally) => { - onFinally = onFinally || (() => {}); - - return promise.then( - val => new Promise(resolve => { - resolve(onFinally()); - }).then(() => val), - err => new Promise(resolve => { - resolve(onFinally()); - }).then(() => { - throw err; - }) - ); -}; - - -/***/ }), - -/***/ 6459: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const EventEmitter = __nccwpck_require__(2415); -const p_timeout_1 = __nccwpck_require__(4802); -const priority_queue_1 = __nccwpck_require__(5905); -// eslint-disable-next-line @typescript-eslint/no-empty-function -const empty = () => { }; -const timeoutError = new p_timeout_1.TimeoutError(); -/** -Promise queue with concurrency control. -*/ -class PQueue extends EventEmitter { - constructor(options) { - var _a, _b, _c, _d; - super(); - this._intervalCount = 0; - this._intervalEnd = 0; - this._pendingCount = 0; - this._resolveEmpty = empty; - this._resolveIdle = empty; - // eslint-disable-next-line @typescript-eslint/consistent-type-assertions - options = Object.assign({ carryoverConcurrencyCount: false, intervalCap: Infinity, interval: 0, concurrency: Infinity, autoStart: true, queueClass: priority_queue_1.default }, options); - if (!(typeof options.intervalCap === 'number' && options.intervalCap >= 1)) { - throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${(_b = (_a = options.intervalCap) === null || _a === void 0 ? void 0 : _a.toString()) !== null && _b !== void 0 ? _b : ''}\` (${typeof options.intervalCap})`); - } - if (options.interval === undefined || !(Number.isFinite(options.interval) && options.interval >= 0)) { - throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${(_d = (_c = options.interval) === null || _c === void 0 ? void 0 : _c.toString()) !== null && _d !== void 0 ? _d : ''}\` (${typeof options.interval})`); - } - this._carryoverConcurrencyCount = options.carryoverConcurrencyCount; - this._isIntervalIgnored = options.intervalCap === Infinity || options.interval === 0; - this._intervalCap = options.intervalCap; - this._interval = options.interval; - this._queue = new options.queueClass(); - this._queueClass = options.queueClass; - this.concurrency = options.concurrency; - this._timeout = options.timeout; - this._throwOnTimeout = options.throwOnTimeout === true; - this._isPaused = options.autoStart === false; - } - get _doesIntervalAllowAnother() { - return this._isIntervalIgnored || this._intervalCount < this._intervalCap; - } - get _doesConcurrentAllowAnother() { - return this._pendingCount < this._concurrency; - } - _next() { - this._pendingCount--; - this._tryToStartAnother(); - this.emit('next'); - } - _resolvePromises() { - this._resolveEmpty(); - this._resolveEmpty = empty; - if (this._pendingCount === 0) { - this._resolveIdle(); - this._resolveIdle = empty; - this.emit('idle'); - } - } - _onResumeInterval() { - this._onInterval(); - this._initializeIntervalIfNeeded(); - this._timeoutId = undefined; - } - _isIntervalPaused() { - const now = Date.now(); - if (this._intervalId === undefined) { - const delay = this._intervalEnd - now; - if (delay < 0) { - // Act as the interval was done - // We don't need to resume it here because it will be resumed on line 160 - this._intervalCount = (this._carryoverConcurrencyCount) ? this._pendingCount : 0; - } - else { - // Act as the interval is pending - if (this._timeoutId === undefined) { - this._timeoutId = setTimeout(() => { - this._onResumeInterval(); - }, delay); - } - return true; - } - } - return false; - } - _tryToStartAnother() { - if (this._queue.size === 0) { - // We can clear the interval ("pause") - // Because we can redo it later ("resume") - if (this._intervalId) { - clearInterval(this._intervalId); - } - this._intervalId = undefined; - this._resolvePromises(); - return false; - } - if (!this._isPaused) { - const canInitializeInterval = !this._isIntervalPaused(); - if (this._doesIntervalAllowAnother && this._doesConcurrentAllowAnother) { - const job = this._queue.dequeue(); - if (!job) { - return false; - } - this.emit('active'); - job(); - if (canInitializeInterval) { - this._initializeIntervalIfNeeded(); - } - return true; - } - } - return false; - } - _initializeIntervalIfNeeded() { - if (this._isIntervalIgnored || this._intervalId !== undefined) { - return; - } - this._intervalId = setInterval(() => { - this._onInterval(); - }, this._interval); - this._intervalEnd = Date.now() + this._interval; - } - _onInterval() { - if (this._intervalCount === 0 && this._pendingCount === 0 && this._intervalId) { - clearInterval(this._intervalId); - this._intervalId = undefined; - } - this._intervalCount = this._carryoverConcurrencyCount ? this._pendingCount : 0; - this._processQueue(); - } - /** - Executes all queued functions until it reaches the limit. - */ - _processQueue() { - // eslint-disable-next-line no-empty - while (this._tryToStartAnother()) { } - } - get concurrency() { - return this._concurrency; - } - set concurrency(newConcurrency) { - if (!(typeof newConcurrency === 'number' && newConcurrency >= 1)) { - throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${newConcurrency}\` (${typeof newConcurrency})`); - } - this._concurrency = newConcurrency; - this._processQueue(); - } - /** - Adds a sync or async task to the queue. Always returns a promise. - */ - async add(fn, options = {}) { - return new Promise((resolve, reject) => { - const run = async () => { - this._pendingCount++; - this._intervalCount++; - try { - const operation = (this._timeout === undefined && options.timeout === undefined) ? fn() : p_timeout_1.default(Promise.resolve(fn()), (options.timeout === undefined ? this._timeout : options.timeout), () => { - if (options.throwOnTimeout === undefined ? this._throwOnTimeout : options.throwOnTimeout) { - reject(timeoutError); - } - return undefined; - }); - resolve(await operation); - } - catch (error) { - reject(error); - } - this._next(); - }; - this._queue.enqueue(run, options); - this._tryToStartAnother(); - this.emit('add'); - }); - } - /** - Same as `.add()`, but accepts an array of sync or async functions. - - @returns A promise that resolves when all functions are resolved. - */ - async addAll(functions, options) { - return Promise.all(functions.map(async (function_) => this.add(function_, options))); - } - /** - Start (or resume) executing enqueued tasks within concurrency limit. No need to call this if queue is not paused (via `options.autoStart = false` or by `.pause()` method.) - */ - start() { - if (!this._isPaused) { - return this; - } - this._isPaused = false; - this._processQueue(); - return this; - } - /** - Put queue execution on hold. - */ - pause() { - this._isPaused = true; - } - /** - Clear the queue. - */ - clear() { - this._queue = new this._queueClass(); - } - /** - Can be called multiple times. Useful if you for example add additional items at a later time. - - @returns A promise that settles when the queue becomes empty. - */ - async onEmpty() { - // Instantly resolve if the queue is empty - if (this._queue.size === 0) { - return; - } - return new Promise(resolve => { - const existingResolve = this._resolveEmpty; - this._resolveEmpty = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - The difference with `.onEmpty` is that `.onIdle` guarantees that all work from the queue has finished. `.onEmpty` merely signals that the queue is empty, but it could mean that some promises haven't completed yet. - - @returns A promise that settles when the queue becomes empty, and all promises have completed; `queue.size === 0 && queue.pending === 0`. - */ - async onIdle() { - // Instantly resolve if none pending and if nothing else is queued - if (this._pendingCount === 0 && this._queue.size === 0) { - return; - } - return new Promise(resolve => { - const existingResolve = this._resolveIdle; - this._resolveIdle = () => { - existingResolve(); - resolve(); - }; - }); - } - /** - Size of the queue. - */ - get size() { - return this._queue.size; - } - /** - Size of the queue, filtered by the given options. - - For example, this can be used to find the number of items remaining in the queue with a specific priority level. - */ - sizeBy(options) { - // eslint-disable-next-line unicorn/no-fn-reference-in-iterator - return this._queue.filter(options).length; - } - /** - Number of pending promises. - */ - get pending() { - return this._pendingCount; - } - /** - Whether the queue is currently paused. - */ - get isPaused() { - return this._isPaused; - } - get timeout() { - return this._timeout; - } - /** - Set the timeout for future operations. - */ - set timeout(milliseconds) { - this._timeout = milliseconds; - } -} -exports["default"] = PQueue; - - -/***/ }), - -/***/ 9015: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -// Port of lower_bound from https://en.cppreference.com/w/cpp/algorithm/lower_bound -// Used to compute insertion index to keep queue sorted after insertion -function lowerBound(array, value, comparator) { - let first = 0; - let count = array.length; - while (count > 0) { - const step = (count / 2) | 0; - let it = first + step; - if (comparator(array[it], value) <= 0) { - first = ++it; - count -= step + 1; - } - else { - count = step; - } - } - return first; -} -exports["default"] = lowerBound; - - -/***/ }), - -/***/ 5905: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -const lower_bound_1 = __nccwpck_require__(9015); -class PriorityQueue { - constructor() { - this._queue = []; - } - enqueue(run, options) { - options = Object.assign({ priority: 0 }, options); - const element = { - priority: options.priority, - run - }; - if (this.size && this._queue[this.size - 1].priority >= options.priority) { - this._queue.push(element); - return; - } - const index = lower_bound_1.default(this._queue, element, (a, b) => b.priority - a.priority); - this._queue.splice(index, 0, element); - } - dequeue() { - const item = this._queue.shift(); - return item === null || item === void 0 ? void 0 : item.run; - } - filter(options) { - return this._queue.filter((element) => element.priority === options.priority).map((element) => element.run); - } - get size() { - return this._queue.length; - } -} -exports["default"] = PriorityQueue; - - -/***/ }), - -/***/ 4802: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const pFinally = __nccwpck_require__(2766); - -class TimeoutError extends Error { - constructor(message) { - super(message); - this.name = 'TimeoutError'; - } -} - -const pTimeout = (promise, milliseconds, fallback) => new Promise((resolve, reject) => { - if (typeof milliseconds !== 'number' || milliseconds < 0) { - throw new TypeError('Expected `milliseconds` to be a positive number'); - } - - if (milliseconds === Infinity) { - resolve(promise); - return; - } - - const timer = setTimeout(() => { - if (typeof fallback === 'function') { - try { - resolve(fallback()); - } catch (error) { - reject(error); - } - - return; - } - - const message = typeof fallback === 'string' ? fallback : `Promise timed out after ${milliseconds} milliseconds`; - const timeoutError = fallback instanceof Error ? fallback : new TimeoutError(message); - - if (typeof promise.cancel === 'function') { - promise.cancel(); - } - - reject(timeoutError); - }, milliseconds); - - // TODO: Use native `finally` keyword when targeting Node.js 10 - pFinally( - // eslint-disable-next-line promise/prefer-await-to-then - promise.then(resolve, reject), - () => { - clearTimeout(timer); - } - ); -}); - -module.exports = pTimeout; -// TODO: Remove this for the next major release -module.exports["default"] = pTimeout; - -module.exports.TimeoutError = TimeoutError; - - -/***/ }), - -/***/ 770: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -module.exports = __nccwpck_require__(218); - - -/***/ }), - -/***/ 218: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -var net = __nccwpck_require__(9278); -var tls = __nccwpck_require__(4756); -var http = __nccwpck_require__(8611); -var https = __nccwpck_require__(5692); -var events = __nccwpck_require__(4434); -var assert = __nccwpck_require__(2613); -var util = __nccwpck_require__(9023); - - -exports.httpOverHttp = httpOverHttp; -exports.httpsOverHttp = httpsOverHttp; -exports.httpOverHttps = httpOverHttps; -exports.httpsOverHttps = httpsOverHttps; - - -function httpOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - return agent; -} - -function httpsOverHttp(options) { - var agent = new TunnelingAgent(options); - agent.request = http.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} - -function httpOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - return agent; -} - -function httpsOverHttps(options) { - var agent = new TunnelingAgent(options); - agent.request = https.request; - agent.createSocket = createSecureSocket; - agent.defaultPort = 443; - return agent; -} - - -function TunnelingAgent(options) { - var self = this; - self.options = options || {}; - self.proxyOptions = self.options.proxy || {}; - self.maxSockets = self.options.maxSockets || http.Agent.defaultMaxSockets; - self.requests = []; - self.sockets = []; - - self.on('free', function onFree(socket, host, port, localAddress) { - var options = toOptions(host, port, localAddress); - for (var i = 0, len = self.requests.length; i < len; ++i) { - var pending = self.requests[i]; - if (pending.host === options.host && pending.port === options.port) { - // Detect the request to connect same origin server, - // reuse the connection. - self.requests.splice(i, 1); - pending.request.onSocket(socket); - return; - } - } - socket.destroy(); - self.removeSocket(socket); - }); -} -util.inherits(TunnelingAgent, events.EventEmitter); - -TunnelingAgent.prototype.addRequest = function addRequest(req, host, port, localAddress) { - var self = this; - var options = mergeOptions({request: req}, self.options, toOptions(host, port, localAddress)); - - if (self.sockets.length >= this.maxSockets) { - // We are over limit so we'll add it to the queue. - self.requests.push(options); - return; - } - - // If we are under maxSockets create a new one. - self.createSocket(options, function(socket) { - socket.on('free', onFree); - socket.on('close', onCloseOrRemove); - socket.on('agentRemove', onCloseOrRemove); - req.onSocket(socket); - - function onFree() { - self.emit('free', socket, options); - } - - function onCloseOrRemove(err) { - self.removeSocket(socket); - socket.removeListener('free', onFree); - socket.removeListener('close', onCloseOrRemove); - socket.removeListener('agentRemove', onCloseOrRemove); - } - }); -}; - -TunnelingAgent.prototype.createSocket = function createSocket(options, cb) { - var self = this; - var placeholder = {}; - self.sockets.push(placeholder); - - var connectOptions = mergeOptions({}, self.proxyOptions, { - method: 'CONNECT', - path: options.host + ':' + options.port, - agent: false, - headers: { - host: options.host + ':' + options.port - } - }); - if (options.localAddress) { - connectOptions.localAddress = options.localAddress; - } - if (connectOptions.proxyAuth) { - connectOptions.headers = connectOptions.headers || {}; - connectOptions.headers['Proxy-Authorization'] = 'Basic ' + - new Buffer(connectOptions.proxyAuth).toString('base64'); - } - - debug('making CONNECT request'); - var connectReq = self.request(connectOptions); - connectReq.useChunkedEncodingByDefault = false; // for v0.6 - connectReq.once('response', onResponse); // for v0.6 - connectReq.once('upgrade', onUpgrade); // for v0.6 - connectReq.once('connect', onConnect); // for v0.7 or later - connectReq.once('error', onError); - connectReq.end(); - - function onResponse(res) { - // Very hacky. This is necessary to avoid http-parser leaks. - res.upgrade = true; - } - - function onUpgrade(res, socket, head) { - // Hacky. - process.nextTick(function() { - onConnect(res, socket, head); - }); - } - - function onConnect(res, socket, head) { - connectReq.removeAllListeners(); - socket.removeAllListeners(); - - if (res.statusCode !== 200) { - debug('tunneling socket could not be established, statusCode=%d', - res.statusCode); - socket.destroy(); - var error = new Error('tunneling socket could not be established, ' + - 'statusCode=' + res.statusCode); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - if (head.length > 0) { - debug('got illegal response body from proxy'); - socket.destroy(); - var error = new Error('got illegal response body from proxy'); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - return; - } - debug('tunneling connection has established'); - self.sockets[self.sockets.indexOf(placeholder)] = socket; - return cb(socket); - } - - function onError(cause) { - connectReq.removeAllListeners(); - - debug('tunneling socket could not be established, cause=%s\n', - cause.message, cause.stack); - var error = new Error('tunneling socket could not be established, ' + - 'cause=' + cause.message); - error.code = 'ECONNRESET'; - options.request.emit('error', error); - self.removeSocket(placeholder); - } -}; - -TunnelingAgent.prototype.removeSocket = function removeSocket(socket) { - var pos = this.sockets.indexOf(socket) - if (pos === -1) { - return; - } - this.sockets.splice(pos, 1); - - var pending = this.requests.shift(); - if (pending) { - // If we have pending requests and a socket gets closed a new one - // needs to be created to take over in the pool for the one that closed. - this.createSocket(pending, function(socket) { - pending.request.onSocket(socket); - }); - } -}; - -function createSecureSocket(options, cb) { - var self = this; - TunnelingAgent.prototype.createSocket.call(self, options, function(socket) { - var hostHeader = options.request.getHeader('host'); - var tlsOptions = mergeOptions({}, self.options, { - socket: socket, - servername: hostHeader ? hostHeader.replace(/:.*$/, '') : options.host - }); - - // 0 is dummy port for v0.6 - var secureSocket = tls.connect(0, tlsOptions); - self.sockets[self.sockets.indexOf(socket)] = secureSocket; - cb(secureSocket); - }); -} - - -function toOptions(host, port, localAddress) { - if (typeof host === 'string') { // since v0.10 - return { - host: host, - port: port, - localAddress: localAddress - }; - } - return host; // for v0.11 or later -} - -function mergeOptions(target) { - for (var i = 1, len = arguments.length; i < len; ++i) { - var overrides = arguments[i]; - if (typeof overrides === 'object') { - var keys = Object.keys(overrides); - for (var j = 0, keyLen = keys.length; j < keyLen; ++j) { - var k = keys[j]; - if (overrides[k] !== undefined) { - target[k] = overrides[k]; - } - } - } - } - return target; -} - - -var debug; -if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { - var args = Array.prototype.slice.call(arguments); - if (typeof args[0] === 'string') { - args[0] = 'TUNNEL: ' + args[0]; - } else { - args.unshift('TUNNEL:'); - } - console.error.apply(console, args); - } -} else { - debug = function() {}; -} -exports.debug = debug; // for test - - -/***/ }), - -/***/ 6752: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Client = __nccwpck_require__(6197) -const Dispatcher = __nccwpck_require__(992) -const errors = __nccwpck_require__(8707) -const Pool = __nccwpck_require__(5076) -const BalancedPool = __nccwpck_require__(1093) -const Agent = __nccwpck_require__(9965) -const util = __nccwpck_require__(3440) -const { InvalidArgumentError } = errors -const api = __nccwpck_require__(6615) -const buildConnector = __nccwpck_require__(9136) -const MockClient = __nccwpck_require__(7365) -const MockAgent = __nccwpck_require__(7501) -const MockPool = __nccwpck_require__(4004) -const mockErrors = __nccwpck_require__(2429) -const ProxyAgent = __nccwpck_require__(2720) -const RetryHandler = __nccwpck_require__(3573) -const { getGlobalDispatcher, setGlobalDispatcher } = __nccwpck_require__(2581) -const DecoratorHandler = __nccwpck_require__(8840) -const RedirectHandler = __nccwpck_require__(8299) -const createRedirectInterceptor = __nccwpck_require__(4415) - -let hasCrypto -try { - __nccwpck_require__(6982) - hasCrypto = true -} catch { - hasCrypto = false -} - -Object.assign(Dispatcher.prototype, api) - -module.exports.Dispatcher = Dispatcher -module.exports.Client = Client -module.exports.Pool = Pool -module.exports.BalancedPool = BalancedPool -module.exports.Agent = Agent -module.exports.ProxyAgent = ProxyAgent -module.exports.RetryHandler = RetryHandler - -module.exports.DecoratorHandler = DecoratorHandler -module.exports.RedirectHandler = RedirectHandler -module.exports.createRedirectInterceptor = createRedirectInterceptor - -module.exports.buildConnector = buildConnector -module.exports.errors = errors - -function makeDispatcher (fn) { - return (url, opts, handler) => { - if (typeof opts === 'function') { - handler = opts - opts = null - } - - if (!url || (typeof url !== 'string' && typeof url !== 'object' && !(url instanceof URL))) { - throw new InvalidArgumentError('invalid url') - } - - if (opts != null && typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - if (opts && opts.path != null) { - if (typeof opts.path !== 'string') { - throw new InvalidArgumentError('invalid opts.path') - } - - let path = opts.path - if (!opts.path.startsWith('/')) { - path = `/${path}` - } - - url = new URL(util.parseOrigin(url).origin + path) - } else { - if (!opts) { - opts = typeof url === 'object' ? url : {} - } - - url = util.parseURL(url) - } - - const { agent, dispatcher = getGlobalDispatcher() } = opts - - if (agent) { - throw new InvalidArgumentError('unsupported opts.agent. Did you mean opts.client?') - } - - return fn.call(dispatcher, { - ...opts, - origin: url.origin, - path: url.search ? `${url.pathname}${url.search}` : url.pathname, - method: opts.method || (opts.body ? 'PUT' : 'GET') - }, handler) - } -} - -module.exports.setGlobalDispatcher = setGlobalDispatcher -module.exports.getGlobalDispatcher = getGlobalDispatcher - -if (util.nodeMajor > 16 || (util.nodeMajor === 16 && util.nodeMinor >= 8)) { - let fetchImpl = null - module.exports.fetch = async function fetch (resource) { - if (!fetchImpl) { - fetchImpl = (__nccwpck_require__(2315).fetch) - } - - try { - return await fetchImpl(...arguments) - } catch (err) { - if (typeof err === 'object') { - Error.captureStackTrace(err, this) - } - - throw err - } - } - module.exports.Headers = __nccwpck_require__(6349).Headers - module.exports.Response = __nccwpck_require__(8676).Response - module.exports.Request = __nccwpck_require__(5194).Request - module.exports.FormData = __nccwpck_require__(3073).FormData - module.exports.File = __nccwpck_require__(3041).File - module.exports.FileReader = __nccwpck_require__(2160).FileReader - - const { setGlobalOrigin, getGlobalOrigin } = __nccwpck_require__(5628) - - module.exports.setGlobalOrigin = setGlobalOrigin - module.exports.getGlobalOrigin = getGlobalOrigin - - const { CacheStorage } = __nccwpck_require__(4738) - const { kConstruct } = __nccwpck_require__(296) - - // Cache & CacheStorage are tightly coupled with fetch. Even if it may run - // in an older version of Node, it doesn't have any use without fetch. - module.exports.caches = new CacheStorage(kConstruct) -} - -if (util.nodeMajor >= 16) { - const { deleteCookie, getCookies, getSetCookies, setCookie } = __nccwpck_require__(3168) - - module.exports.deleteCookie = deleteCookie - module.exports.getCookies = getCookies - module.exports.getSetCookies = getSetCookies - module.exports.setCookie = setCookie - - const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) - - module.exports.parseMIMEType = parseMIMEType - module.exports.serializeAMimeType = serializeAMimeType -} - -if (util.nodeMajor >= 18 && hasCrypto) { - const { WebSocket } = __nccwpck_require__(5171) - - module.exports.WebSocket = WebSocket -} - -module.exports.request = makeDispatcher(api.request) -module.exports.stream = makeDispatcher(api.stream) -module.exports.pipeline = makeDispatcher(api.pipeline) -module.exports.connect = makeDispatcher(api.connect) -module.exports.upgrade = makeDispatcher(api.upgrade) - -module.exports.MockClient = MockClient -module.exports.MockPool = MockPool -module.exports.MockAgent = MockAgent -module.exports.mockErrors = mockErrors - - -/***/ }), - -/***/ 9965: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { InvalidArgumentError } = __nccwpck_require__(8707) -const { kClients, kRunning, kClose, kDestroy, kDispatch, kInterceptors } = __nccwpck_require__(6443) -const DispatcherBase = __nccwpck_require__(1) -const Pool = __nccwpck_require__(5076) -const Client = __nccwpck_require__(6197) -const util = __nccwpck_require__(3440) -const createRedirectInterceptor = __nccwpck_require__(4415) -const { WeakRef, FinalizationRegistry } = __nccwpck_require__(3194)() - -const kOnConnect = Symbol('onConnect') -const kOnDisconnect = Symbol('onDisconnect') -const kOnConnectionError = Symbol('onConnectionError') -const kMaxRedirections = Symbol('maxRedirections') -const kOnDrain = Symbol('onDrain') -const kFactory = Symbol('factory') -const kFinalizer = Symbol('finalizer') -const kOptions = Symbol('options') - -function defaultFactory (origin, opts) { - return opts && opts.connections === 1 - ? new Client(origin, opts) - : new Pool(origin, opts) -} - -class Agent extends DispatcherBase { - constructor ({ factory = defaultFactory, maxRedirections = 0, connect, ...options } = {}) { - super() - - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } - - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') - } - - if (!Number.isInteger(maxRedirections) || maxRedirections < 0) { - throw new InvalidArgumentError('maxRedirections must be a positive number') - } - - if (connect && typeof connect !== 'function') { - connect = { ...connect } - } - - this[kInterceptors] = options.interceptors && options.interceptors.Agent && Array.isArray(options.interceptors.Agent) - ? options.interceptors.Agent - : [createRedirectInterceptor({ maxRedirections })] - - this[kOptions] = { ...util.deepClone(options), connect } - this[kOptions].interceptors = options.interceptors - ? { ...options.interceptors } - : undefined - this[kMaxRedirections] = maxRedirections - this[kFactory] = factory - this[kClients] = new Map() - this[kFinalizer] = new FinalizationRegistry(/* istanbul ignore next: gc is undeterministic */ key => { - const ref = this[kClients].get(key) - if (ref !== undefined && ref.deref() === undefined) { - this[kClients].delete(key) - } - }) - - const agent = this - - this[kOnDrain] = (origin, targets) => { - agent.emit('drain', origin, [agent, ...targets]) - } - - this[kOnConnect] = (origin, targets) => { - agent.emit('connect', origin, [agent, ...targets]) - } - - this[kOnDisconnect] = (origin, targets, err) => { - agent.emit('disconnect', origin, [agent, ...targets], err) - } - - this[kOnConnectionError] = (origin, targets, err) => { - agent.emit('connectionError', origin, [agent, ...targets], err) - } - } - - get [kRunning] () { - let ret = 0 - for (const ref of this[kClients].values()) { - const client = ref.deref() - /* istanbul ignore next: gc is undeterministic */ - if (client) { - ret += client[kRunning] - } - } - return ret - } - - [kDispatch] (opts, handler) { - let key - if (opts.origin && (typeof opts.origin === 'string' || opts.origin instanceof URL)) { - key = String(opts.origin) - } else { - throw new InvalidArgumentError('opts.origin must be a non-empty string or URL.') - } - - const ref = this[kClients].get(key) - - let dispatcher = ref ? ref.deref() : null - if (!dispatcher) { - dispatcher = this[kFactory](opts.origin, this[kOptions]) - .on('drain', this[kOnDrain]) - .on('connect', this[kOnConnect]) - .on('disconnect', this[kOnDisconnect]) - .on('connectionError', this[kOnConnectionError]) - - this[kClients].set(key, new WeakRef(dispatcher)) - this[kFinalizer].register(dispatcher, key) - } - - return dispatcher.dispatch(opts, handler) - } - - async [kClose] () { - const closePromises = [] - for (const ref of this[kClients].values()) { - const client = ref.deref() - /* istanbul ignore else: gc is undeterministic */ - if (client) { - closePromises.push(client.close()) - } - } - - await Promise.all(closePromises) - } - - async [kDestroy] (err) { - const destroyPromises = [] - for (const ref of this[kClients].values()) { - const client = ref.deref() - /* istanbul ignore else: gc is undeterministic */ - if (client) { - destroyPromises.push(client.destroy(err)) - } - } - - await Promise.all(destroyPromises) - } -} - -module.exports = Agent - - -/***/ }), - -/***/ 158: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { addAbortListener } = __nccwpck_require__(3440) -const { RequestAbortedError } = __nccwpck_require__(8707) - -const kListener = Symbol('kListener') -const kSignal = Symbol('kSignal') - -function abort (self) { - if (self.abort) { - self.abort() - } else { - self.onError(new RequestAbortedError()) - } -} - -function addSignal (self, signal) { - self[kSignal] = null - self[kListener] = null - - if (!signal) { - return - } - - if (signal.aborted) { - abort(self) - return - } - - self[kSignal] = signal - self[kListener] = () => { - abort(self) - } - - addAbortListener(self[kSignal], self[kListener]) -} - -function removeSignal (self) { - if (!self[kSignal]) { - return - } - - if ('removeEventListener' in self[kSignal]) { - self[kSignal].removeEventListener('abort', self[kListener]) - } else { - self[kSignal].removeListener('abort', self[kListener]) - } - - self[kSignal] = null - self[kListener] = null -} - -module.exports = { - addSignal, - removeSignal -} - - -/***/ }), - -/***/ 4660: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { AsyncResource } = __nccwpck_require__(290) -const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { addSignal, removeSignal } = __nccwpck_require__(158) - -class ConnectHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - const { signal, opaque, responseHeaders } = opts - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - - super('UNDICI_CONNECT') - - this.opaque = opaque || null - this.responseHeaders = responseHeaders || null - this.callback = callback - this.abort = null - - addSignal(this, signal) - } - - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } - - this.abort = abort - this.context = context - } - - onHeaders () { - throw new SocketError('bad connect', null) - } - - onUpgrade (statusCode, rawHeaders, socket) { - const { callback, opaque, context } = this - - removeSignal(this) - - this.callback = null - - let headers = rawHeaders - // Indicates is an HTTP2Session - if (headers != null) { - headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - } - - this.runInAsyncScope(callback, null, null, { - statusCode, - headers, - socket, - opaque, - context - }) - } - - onError (err) { - const { callback, opaque } = this - - removeSignal(this) - - if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } - } -} - -function connect (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - connect.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } - - try { - const connectHandler = new ConnectHandler(opts, callback) - this.dispatch({ ...opts, method: 'CONNECT' }, connectHandler) - } catch (err) { - if (typeof callback !== 'function') { - throw err - } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } -} - -module.exports = connect - - -/***/ }), - -/***/ 6862: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - Readable, - Duplex, - PassThrough -} = __nccwpck_require__(2203) -const { - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError -} = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { AsyncResource } = __nccwpck_require__(290) -const { addSignal, removeSignal } = __nccwpck_require__(158) -const assert = __nccwpck_require__(2613) - -const kResume = Symbol('resume') - -class PipelineRequest extends Readable { - constructor () { - super({ autoDestroy: true }) - - this[kResume] = null - } - - _read () { - const { [kResume]: resume } = this - - if (resume) { - this[kResume] = null - resume() - } - } - - _destroy (err, callback) { - this._read() - - callback(err) - } -} - -class PipelineResponse extends Readable { - constructor (resume) { - super({ autoDestroy: true }) - this[kResume] = resume - } - - _read () { - this[kResume]() - } - - _destroy (err, callback) { - if (!err && !this._readableState.endEmitted) { - err = new RequestAbortedError() - } - - callback(err) - } -} - -class PipelineHandler extends AsyncResource { - constructor (opts, handler) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - if (typeof handler !== 'function') { - throw new InvalidArgumentError('invalid handler') - } - - const { signal, method, opaque, onInfo, responseHeaders } = opts - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } - - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } - - super('UNDICI_PIPELINE') - - this.opaque = opaque || null - this.responseHeaders = responseHeaders || null - this.handler = handler - this.abort = null - this.context = null - this.onInfo = onInfo || null - - this.req = new PipelineRequest().on('error', util.nop) - - this.ret = new Duplex({ - readableObjectMode: opts.objectMode, - autoDestroy: true, - read: () => { - const { body } = this - - if (body && body.resume) { - body.resume() - } - }, - write: (chunk, encoding, callback) => { - const { req } = this - - if (req.push(chunk, encoding) || req._readableState.destroyed) { - callback() - } else { - req[kResume] = callback - } - }, - destroy: (err, callback) => { - const { body, req, res, ret, abort } = this - - if (!err && !ret._readableState.endEmitted) { - err = new RequestAbortedError() - } - - if (abort && err) { - abort() - } - - util.destroy(body, err) - util.destroy(req, err) - util.destroy(res, err) - - removeSignal(this) - - callback(err) - } - }).on('prefinish', () => { - const { req } = this - - // Node < 15 does not call _final in same tick. - req.push(null) - }) - - this.res = null - - addSignal(this, signal) - } - - onConnect (abort, context) { - const { ret, res } = this - - assert(!res, 'pipeline cannot be retried') - - if (ret.destroyed) { - throw new RequestAbortedError() - } - - this.abort = abort - this.context = context - } - - onHeaders (statusCode, rawHeaders, resume) { - const { opaque, handler, context } = this - - if (statusCode < 200) { - if (this.onInfo) { - const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - this.onInfo({ statusCode, headers }) - } - return - } - - this.res = new PipelineResponse(resume) - - let body - try { - this.handler = null - const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - body = this.runInAsyncScope(handler, null, { - statusCode, - headers, - opaque, - body: this.res, - context - }) - } catch (err) { - this.res.on('error', util.nop) - throw err - } - - if (!body || typeof body.on !== 'function') { - throw new InvalidReturnValueError('expected Readable') - } - - body - .on('data', (chunk) => { - const { ret, body } = this - - if (!ret.push(chunk) && body.pause) { - body.pause() - } - }) - .on('error', (err) => { - const { ret } = this - - util.destroy(ret, err) - }) - .on('end', () => { - const { ret } = this - - ret.push(null) - }) - .on('close', () => { - const { ret } = this - - if (!ret._readableState.ended) { - util.destroy(ret, new RequestAbortedError()) - } - }) - - this.body = body - } - - onData (chunk) { - const { res } = this - return res.push(chunk) - } - - onComplete (trailers) { - const { res } = this - res.push(null) - } - - onError (err) { - const { ret } = this - this.handler = null - util.destroy(ret, err) - } -} - -function pipeline (opts, handler) { - try { - const pipelineHandler = new PipelineHandler(opts, handler) - this.dispatch({ ...opts, body: pipelineHandler.req }, pipelineHandler) - return pipelineHandler.ret - } catch (err) { - return new PassThrough().destroy(err) - } -} - -module.exports = pipeline - - -/***/ }), - -/***/ 4043: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Readable = __nccwpck_require__(9927) -const { - InvalidArgumentError, - RequestAbortedError -} = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) -const { AsyncResource } = __nccwpck_require__(290) -const { addSignal, removeSignal } = __nccwpck_require__(158) - -class RequestHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError, highWaterMark } = opts - - try { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - if (highWaterMark && (typeof highWaterMark !== 'number' || highWaterMark < 0)) { - throw new InvalidArgumentError('invalid highWaterMark') - } - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } - - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } - - super('UNDICI_REQUEST') - } catch (err) { - if (util.isStream(body)) { - util.destroy(body.on('error', util.nop), err) - } - throw err - } - - this.responseHeaders = responseHeaders || null - this.opaque = opaque || null - this.callback = callback - this.res = null - this.abort = null - this.body = body - this.trailers = {} - this.context = null - this.onInfo = onInfo || null - this.throwOnError = throwOnError - this.highWaterMark = highWaterMark - - if (util.isStream(body)) { - body.on('error', (err) => { - this.onError(err) - }) - } - - addSignal(this, signal) - } - - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } - - this.abort = abort - this.context = context - } - - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const { callback, opaque, abort, context, responseHeaders, highWaterMark } = this - - const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - - if (statusCode < 200) { - if (this.onInfo) { - this.onInfo({ statusCode, headers }) - } - return - } - - const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers - const contentType = parsedHeaders['content-type'] - const body = new Readable({ resume, abort, contentType, highWaterMark }) - - this.callback = null - this.res = body - if (callback !== null) { - if (this.throwOnError && statusCode >= 400) { - this.runInAsyncScope(getResolveErrorBodyCallback, null, - { callback, body, contentType, statusCode, statusMessage, headers } - ) - } else { - this.runInAsyncScope(callback, null, null, { - statusCode, - headers, - trailers: this.trailers, - opaque, - body, - context - }) - } - } - } - - onData (chunk) { - const { res } = this - return res.push(chunk) - } - - onComplete (trailers) { - const { res } = this - - removeSignal(this) - - util.parseHeaders(trailers, this.trailers) - - res.push(null) - } - - onError (err) { - const { res, callback, body, opaque } = this - - removeSignal(this) - - if (callback) { - // TODO: Does this need queueMicrotask? - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } - - if (res) { - this.res = null - // Ensure all queued handlers are invoked before destroying res. - queueMicrotask(() => { - util.destroy(res, err) - }) - } - - if (body) { - this.body = null - util.destroy(body, err) - } - } -} - -function request (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - request.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } - - try { - this.dispatch(opts, new RequestHandler(opts, callback)) - } catch (err) { - if (typeof callback !== 'function') { - throw err - } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } -} - -module.exports = request -module.exports.RequestHandler = RequestHandler - - -/***/ }), - -/***/ 3560: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { finished, PassThrough } = __nccwpck_require__(2203) -const { - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError -} = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { getResolveErrorBodyCallback } = __nccwpck_require__(7655) -const { AsyncResource } = __nccwpck_require__(290) -const { addSignal, removeSignal } = __nccwpck_require__(158) - -class StreamHandler extends AsyncResource { - constructor (opts, factory, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - const { signal, method, opaque, body, onInfo, responseHeaders, throwOnError } = opts - - try { - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - if (typeof factory !== 'function') { - throw new InvalidArgumentError('invalid factory') - } - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - - if (method === 'CONNECT') { - throw new InvalidArgumentError('invalid method') - } - - if (onInfo && typeof onInfo !== 'function') { - throw new InvalidArgumentError('invalid onInfo callback') - } - - super('UNDICI_STREAM') - } catch (err) { - if (util.isStream(body)) { - util.destroy(body.on('error', util.nop), err) - } - throw err - } - - this.responseHeaders = responseHeaders || null - this.opaque = opaque || null - this.factory = factory - this.callback = callback - this.res = null - this.abort = null - this.context = null - this.trailers = null - this.body = body - this.onInfo = onInfo || null - this.throwOnError = throwOnError || false - - if (util.isStream(body)) { - body.on('error', (err) => { - this.onError(err) - }) - } - - addSignal(this, signal) - } - - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } - - this.abort = abort - this.context = context - } - - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const { factory, opaque, context, callback, responseHeaders } = this - - const headers = responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - - if (statusCode < 200) { - if (this.onInfo) { - this.onInfo({ statusCode, headers }) - } - return - } - - this.factory = null - - let res - - if (this.throwOnError && statusCode >= 400) { - const parsedHeaders = responseHeaders === 'raw' ? util.parseHeaders(rawHeaders) : headers - const contentType = parsedHeaders['content-type'] - res = new PassThrough() - - this.callback = null - this.runInAsyncScope(getResolveErrorBodyCallback, null, - { callback, body: res, contentType, statusCode, statusMessage, headers } - ) - } else { - if (factory === null) { - return - } - - res = this.runInAsyncScope(factory, null, { - statusCode, - headers, - opaque, - context - }) - - if ( - !res || - typeof res.write !== 'function' || - typeof res.end !== 'function' || - typeof res.on !== 'function' - ) { - throw new InvalidReturnValueError('expected Writable') - } - - // TODO: Avoid finished. It registers an unnecessary amount of listeners. - finished(res, { readable: false }, (err) => { - const { callback, res, opaque, trailers, abort } = this - - this.res = null - if (err || !res.readable) { - util.destroy(res, err) - } - - this.callback = null - this.runInAsyncScope(callback, null, err || null, { opaque, trailers }) - - if (err) { - abort() - } - }) - } - - res.on('drain', resume) - - this.res = res - - const needDrain = res.writableNeedDrain !== undefined - ? res.writableNeedDrain - : res._writableState && res._writableState.needDrain - - return needDrain !== true - } - - onData (chunk) { - const { res } = this - - return res ? res.write(chunk) : true - } - - onComplete (trailers) { - const { res } = this - - removeSignal(this) - - if (!res) { - return - } - - this.trailers = util.parseHeaders(trailers) - - res.end() - } - - onError (err) { - const { res, callback, opaque, body } = this - - removeSignal(this) - - this.factory = null - - if (res) { - this.res = null - util.destroy(res, err) - } else if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } - - if (body) { - this.body = null - util.destroy(body, err) - } - } -} - -function stream (opts, factory, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - stream.call(this, opts, factory, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } - - try { - this.dispatch(opts, new StreamHandler(opts, factory, callback)) - } catch (err) { - if (typeof callback !== 'function') { - throw err - } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } -} - -module.exports = stream - - -/***/ }), - -/***/ 1882: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { InvalidArgumentError, RequestAbortedError, SocketError } = __nccwpck_require__(8707) -const { AsyncResource } = __nccwpck_require__(290) -const util = __nccwpck_require__(3440) -const { addSignal, removeSignal } = __nccwpck_require__(158) -const assert = __nccwpck_require__(2613) - -class UpgradeHandler extends AsyncResource { - constructor (opts, callback) { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('invalid opts') - } - - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - const { signal, opaque, responseHeaders } = opts - - if (signal && typeof signal.on !== 'function' && typeof signal.addEventListener !== 'function') { - throw new InvalidArgumentError('signal must be an EventEmitter or EventTarget') - } - - super('UNDICI_UPGRADE') - - this.responseHeaders = responseHeaders || null - this.opaque = opaque || null - this.callback = callback - this.abort = null - this.context = null - - addSignal(this, signal) - } - - onConnect (abort, context) { - if (!this.callback) { - throw new RequestAbortedError() - } - - this.abort = abort - this.context = null - } - - onHeaders () { - throw new SocketError('bad upgrade', null) - } - - onUpgrade (statusCode, rawHeaders, socket) { - const { callback, opaque, context } = this - - assert.strictEqual(statusCode, 101) - - removeSignal(this) - - this.callback = null - const headers = this.responseHeaders === 'raw' ? util.parseRawHeaders(rawHeaders) : util.parseHeaders(rawHeaders) - this.runInAsyncScope(callback, null, null, { - headers, - socket, - opaque, - context - }) - } - - onError (err) { - const { callback, opaque } = this - - removeSignal(this) - - if (callback) { - this.callback = null - queueMicrotask(() => { - this.runInAsyncScope(callback, null, err, { opaque }) - }) - } - } -} - -function upgrade (opts, callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - upgrade.call(this, opts, (err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } - - try { - const upgradeHandler = new UpgradeHandler(opts, callback) - this.dispatch({ - ...opts, - method: opts.method || 'GET', - upgrade: opts.protocol || 'Websocket' - }, upgradeHandler) - } catch (err) { - if (typeof callback !== 'function') { - throw err - } - const opaque = opts && opts.opaque - queueMicrotask(() => callback(err, { opaque })) - } -} - -module.exports = upgrade - - -/***/ }), - -/***/ 6615: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -module.exports.request = __nccwpck_require__(4043) -module.exports.stream = __nccwpck_require__(3560) -module.exports.pipeline = __nccwpck_require__(6862) -module.exports.upgrade = __nccwpck_require__(1882) -module.exports.connect = __nccwpck_require__(4660) - - -/***/ }), - -/***/ 9927: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// Ported from https://github.com/nodejs/undici/pull/907 - - - -const assert = __nccwpck_require__(2613) -const { Readable } = __nccwpck_require__(2203) -const { RequestAbortedError, NotSupportedError, InvalidArgumentError } = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { ReadableStreamFrom, toUSVString } = __nccwpck_require__(3440) - -let Blob - -const kConsume = Symbol('kConsume') -const kReading = Symbol('kReading') -const kBody = Symbol('kBody') -const kAbort = Symbol('abort') -const kContentType = Symbol('kContentType') - -const noop = () => {} - -module.exports = class BodyReadable extends Readable { - constructor ({ - resume, - abort, - contentType = '', - highWaterMark = 64 * 1024 // Same as nodejs fs streams. - }) { - super({ - autoDestroy: true, - read: resume, - highWaterMark - }) - - this._readableState.dataEmitted = false - - this[kAbort] = abort - this[kConsume] = null - this[kBody] = null - this[kContentType] = contentType - - // Is stream being consumed through Readable API? - // This is an optimization so that we avoid checking - // for 'data' and 'readable' listeners in the hot path - // inside push(). - this[kReading] = false - } - - destroy (err) { - if (this.destroyed) { - // Node < 16 - return this - } - - if (!err && !this._readableState.endEmitted) { - err = new RequestAbortedError() - } - - if (err) { - this[kAbort]() - } - - return super.destroy(err) - } - - emit (ev, ...args) { - if (ev === 'data') { - // Node < 16.7 - this._readableState.dataEmitted = true - } else if (ev === 'error') { - // Node < 16 - this._readableState.errorEmitted = true - } - return super.emit(ev, ...args) - } - - on (ev, ...args) { - if (ev === 'data' || ev === 'readable') { - this[kReading] = true - } - return super.on(ev, ...args) - } - - addListener (ev, ...args) { - return this.on(ev, ...args) - } - - off (ev, ...args) { - const ret = super.off(ev, ...args) - if (ev === 'data' || ev === 'readable') { - this[kReading] = ( - this.listenerCount('data') > 0 || - this.listenerCount('readable') > 0 - ) - } - return ret - } - - removeListener (ev, ...args) { - return this.off(ev, ...args) - } - - push (chunk) { - if (this[kConsume] && chunk !== null && this.readableLength === 0) { - consumePush(this[kConsume], chunk) - return this[kReading] ? super.push(chunk) : true - } - return super.push(chunk) - } - - // https://fetch.spec.whatwg.org/#dom-body-text - async text () { - return consume(this, 'text') - } - - // https://fetch.spec.whatwg.org/#dom-body-json - async json () { - return consume(this, 'json') - } - - // https://fetch.spec.whatwg.org/#dom-body-blob - async blob () { - return consume(this, 'blob') - } - - // https://fetch.spec.whatwg.org/#dom-body-arraybuffer - async arrayBuffer () { - return consume(this, 'arrayBuffer') - } - - // https://fetch.spec.whatwg.org/#dom-body-formdata - async formData () { - // TODO: Implement. - throw new NotSupportedError() - } - - // https://fetch.spec.whatwg.org/#dom-body-bodyused - get bodyUsed () { - return util.isDisturbed(this) - } - - // https://fetch.spec.whatwg.org/#dom-body-body - get body () { - if (!this[kBody]) { - this[kBody] = ReadableStreamFrom(this) - if (this[kConsume]) { - // TODO: Is this the best way to force a lock? - this[kBody].getReader() // Ensure stream is locked. - assert(this[kBody].locked) - } - } - return this[kBody] - } - - dump (opts) { - let limit = opts && Number.isFinite(opts.limit) ? opts.limit : 262144 - const signal = opts && opts.signal - - if (signal) { - try { - if (typeof signal !== 'object' || !('aborted' in signal)) { - throw new InvalidArgumentError('signal must be an AbortSignal') - } - util.throwIfAborted(signal) - } catch (err) { - return Promise.reject(err) - } - } - - if (this.closed) { - return Promise.resolve(null) - } - - return new Promise((resolve, reject) => { - const signalListenerCleanup = signal - ? util.addAbortListener(signal, () => { - this.destroy() - }) - : noop - - this - .on('close', function () { - signalListenerCleanup() - if (signal && signal.aborted) { - reject(signal.reason || Object.assign(new Error('The operation was aborted'), { name: 'AbortError' })) - } else { - resolve(null) - } - }) - .on('error', noop) - .on('data', function (chunk) { - limit -= chunk.length - if (limit <= 0) { - this.destroy() - } - }) - .resume() - }) - } -} - -// https://streams.spec.whatwg.org/#readablestream-locked -function isLocked (self) { - // Consume is an implicit lock. - return (self[kBody] && self[kBody].locked === true) || self[kConsume] -} - -// https://fetch.spec.whatwg.org/#body-unusable -function isUnusable (self) { - return util.isDisturbed(self) || isLocked(self) -} - -async function consume (stream, type) { - if (isUnusable(stream)) { - throw new TypeError('unusable') - } - - assert(!stream[kConsume]) - - return new Promise((resolve, reject) => { - stream[kConsume] = { - type, - stream, - resolve, - reject, - length: 0, - body: [] - } - - stream - .on('error', function (err) { - consumeFinish(this[kConsume], err) - }) - .on('close', function () { - if (this[kConsume].body !== null) { - consumeFinish(this[kConsume], new RequestAbortedError()) - } - }) - - process.nextTick(consumeStart, stream[kConsume]) - }) -} - -function consumeStart (consume) { - if (consume.body === null) { - return - } - - const { _readableState: state } = consume.stream - - for (const chunk of state.buffer) { - consumePush(consume, chunk) - } - - if (state.endEmitted) { - consumeEnd(this[kConsume]) - } else { - consume.stream.on('end', function () { - consumeEnd(this[kConsume]) - }) - } - - consume.stream.resume() - - while (consume.stream.read() != null) { - // Loop - } -} - -function consumeEnd (consume) { - const { type, body, resolve, stream, length } = consume - - try { - if (type === 'text') { - resolve(toUSVString(Buffer.concat(body))) - } else if (type === 'json') { - resolve(JSON.parse(Buffer.concat(body))) - } else if (type === 'arrayBuffer') { - const dst = new Uint8Array(length) - - let pos = 0 - for (const buf of body) { - dst.set(buf, pos) - pos += buf.byteLength - } - - resolve(dst.buffer) - } else if (type === 'blob') { - if (!Blob) { - Blob = (__nccwpck_require__(181).Blob) - } - resolve(new Blob(body, { type: stream[kContentType] })) - } - - consumeFinish(consume) - } catch (err) { - stream.destroy(err) - } -} - -function consumePush (consume, chunk) { - consume.length += chunk.length - consume.body.push(chunk) -} - -function consumeFinish (consume, err) { - if (consume.body === null) { - return - } - - if (err) { - consume.reject(err) - } else { - consume.resolve() - } - - consume.type = null - consume.stream = null - consume.resolve = null - consume.reject = null - consume.length = 0 - consume.body = null -} - - -/***/ }), - -/***/ 7655: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const assert = __nccwpck_require__(2613) -const { - ResponseStatusCodeError -} = __nccwpck_require__(8707) -const { toUSVString } = __nccwpck_require__(3440) - -async function getResolveErrorBodyCallback ({ callback, body, contentType, statusCode, statusMessage, headers }) { - assert(body) - - let chunks = [] - let limit = 0 - - for await (const chunk of body) { - chunks.push(chunk) - limit += chunk.length - if (limit > 128 * 1024) { - chunks = null - break - } - } - - if (statusCode === 204 || !contentType || !chunks) { - process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) - return - } - - try { - if (contentType.startsWith('application/json')) { - const payload = JSON.parse(toUSVString(Buffer.concat(chunks))) - process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) - return - } - - if (contentType.startsWith('text/')) { - const payload = toUSVString(Buffer.concat(chunks)) - process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers, payload)) - return - } - } catch (err) { - // Process in a fallback if error - } - - process.nextTick(callback, new ResponseStatusCodeError(`Response status code ${statusCode}${statusMessage ? `: ${statusMessage}` : ''}`, statusCode, headers)) -} - -module.exports = { getResolveErrorBodyCallback } - - -/***/ }), - -/***/ 1093: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - BalancedPoolMissingUpstreamError, - InvalidArgumentError -} = __nccwpck_require__(8707) -const { - PoolBase, - kClients, - kNeedDrain, - kAddClient, - kRemoveClient, - kGetDispatcher -} = __nccwpck_require__(8640) -const Pool = __nccwpck_require__(5076) -const { kUrl, kInterceptors } = __nccwpck_require__(6443) -const { parseOrigin } = __nccwpck_require__(3440) -const kFactory = Symbol('factory') - -const kOptions = Symbol('options') -const kGreatestCommonDivisor = Symbol('kGreatestCommonDivisor') -const kCurrentWeight = Symbol('kCurrentWeight') -const kIndex = Symbol('kIndex') -const kWeight = Symbol('kWeight') -const kMaxWeightPerServer = Symbol('kMaxWeightPerServer') -const kErrorPenalty = Symbol('kErrorPenalty') - -function getGreatestCommonDivisor (a, b) { - if (b === 0) return a - return getGreatestCommonDivisor(b, a % b) -} - -function defaultFactory (origin, opts) { - return new Pool(origin, opts) -} - -class BalancedPool extends PoolBase { - constructor (upstreams = [], { factory = defaultFactory, ...opts } = {}) { - super() - - this[kOptions] = opts - this[kIndex] = -1 - this[kCurrentWeight] = 0 - - this[kMaxWeightPerServer] = this[kOptions].maxWeightPerServer || 100 - this[kErrorPenalty] = this[kOptions].errorPenalty || 15 - - if (!Array.isArray(upstreams)) { - upstreams = [upstreams] - } - - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } - - this[kInterceptors] = opts.interceptors && opts.interceptors.BalancedPool && Array.isArray(opts.interceptors.BalancedPool) - ? opts.interceptors.BalancedPool - : [] - this[kFactory] = factory - - for (const upstream of upstreams) { - this.addUpstream(upstream) - } - this._updateBalancedPoolStats() - } - - addUpstream (upstream) { - const upstreamOrigin = parseOrigin(upstream).origin - - if (this[kClients].find((pool) => ( - pool[kUrl].origin === upstreamOrigin && - pool.closed !== true && - pool.destroyed !== true - ))) { - return this - } - const pool = this[kFactory](upstreamOrigin, Object.assign({}, this[kOptions])) - - this[kAddClient](pool) - pool.on('connect', () => { - pool[kWeight] = Math.min(this[kMaxWeightPerServer], pool[kWeight] + this[kErrorPenalty]) - }) - - pool.on('connectionError', () => { - pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) - this._updateBalancedPoolStats() - }) - - pool.on('disconnect', (...args) => { - const err = args[2] - if (err && err.code === 'UND_ERR_SOCKET') { - // decrease the weight of the pool. - pool[kWeight] = Math.max(1, pool[kWeight] - this[kErrorPenalty]) - this._updateBalancedPoolStats() - } - }) - - for (const client of this[kClients]) { - client[kWeight] = this[kMaxWeightPerServer] - } - - this._updateBalancedPoolStats() - - return this - } - - _updateBalancedPoolStats () { - this[kGreatestCommonDivisor] = this[kClients].map(p => p[kWeight]).reduce(getGreatestCommonDivisor, 0) - } - - removeUpstream (upstream) { - const upstreamOrigin = parseOrigin(upstream).origin - - const pool = this[kClients].find((pool) => ( - pool[kUrl].origin === upstreamOrigin && - pool.closed !== true && - pool.destroyed !== true - )) - - if (pool) { - this[kRemoveClient](pool) - } - - return this - } - - get upstreams () { - return this[kClients] - .filter(dispatcher => dispatcher.closed !== true && dispatcher.destroyed !== true) - .map((p) => p[kUrl].origin) - } - - [kGetDispatcher] () { - // We validate that pools is greater than 0, - // otherwise we would have to wait until an upstream - // is added, which might never happen. - if (this[kClients].length === 0) { - throw new BalancedPoolMissingUpstreamError() - } - - const dispatcher = this[kClients].find(dispatcher => ( - !dispatcher[kNeedDrain] && - dispatcher.closed !== true && - dispatcher.destroyed !== true - )) - - if (!dispatcher) { - return - } - - const allClientsBusy = this[kClients].map(pool => pool[kNeedDrain]).reduce((a, b) => a && b, true) - - if (allClientsBusy) { - return - } - - let counter = 0 - - let maxWeightIndex = this[kClients].findIndex(pool => !pool[kNeedDrain]) - - while (counter++ < this[kClients].length) { - this[kIndex] = (this[kIndex] + 1) % this[kClients].length - const pool = this[kClients][this[kIndex]] - - // find pool index with the largest weight - if (pool[kWeight] > this[kClients][maxWeightIndex][kWeight] && !pool[kNeedDrain]) { - maxWeightIndex = this[kIndex] - } - - // decrease the current weight every `this[kClients].length`. - if (this[kIndex] === 0) { - // Set the current weight to the next lower weight. - this[kCurrentWeight] = this[kCurrentWeight] - this[kGreatestCommonDivisor] - - if (this[kCurrentWeight] <= 0) { - this[kCurrentWeight] = this[kMaxWeightPerServer] - } - } - if (pool[kWeight] >= this[kCurrentWeight] && (!pool[kNeedDrain])) { - return pool - } - } - - this[kCurrentWeight] = this[kClients][maxWeightIndex][kWeight] - this[kIndex] = maxWeightIndex - return this[kClients][maxWeightIndex] - } -} - -module.exports = BalancedPool - - -/***/ }), - -/***/ 479: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { kConstruct } = __nccwpck_require__(296) -const { urlEquals, fieldValues: getFieldValues } = __nccwpck_require__(3993) -const { kEnumerableProperty, isDisturbed } = __nccwpck_require__(3440) -const { kHeadersList } = __nccwpck_require__(6443) -const { webidl } = __nccwpck_require__(4222) -const { Response, cloneResponse } = __nccwpck_require__(8676) -const { Request } = __nccwpck_require__(5194) -const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) -const { fetching } = __nccwpck_require__(2315) -const { urlIsHttpHttpsScheme, createDeferredPromise, readAllBytes } = __nccwpck_require__(5523) -const assert = __nccwpck_require__(2613) -const { getGlobalDispatcher } = __nccwpck_require__(2581) - -/** - * @see https://w3c.github.io/ServiceWorker/#dfn-cache-batch-operation - * @typedef {Object} CacheBatchOperation - * @property {'delete' | 'put'} type - * @property {any} request - * @property {any} response - * @property {import('../../types/cache').CacheQueryOptions} options - */ - -/** - * @see https://w3c.github.io/ServiceWorker/#dfn-request-response-list - * @typedef {[any, any][]} requestResponseList - */ - -class Cache { - /** - * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-request-response-list - * @type {requestResponseList} - */ - #relevantRequestResponseList - - constructor () { - if (arguments[0] !== kConstruct) { - webidl.illegalConstructor() - } - - this.#relevantRequestResponseList = arguments[1] - } - - async match (request, options = {}) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.match' }) - - request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) - - const p = await this.matchAll(request, options) - - if (p.length === 0) { - return - } - - return p[0] - } - - async matchAll (request = undefined, options = {}) { - webidl.brandCheck(this, Cache) - - if (request !== undefined) request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) - - // 1. - let r = null - - // 2. - if (request !== undefined) { - if (request instanceof Request) { - // 2.1.1 - r = request[kState] - - // 2.1.2 - if (r.method !== 'GET' && !options.ignoreMethod) { - return [] - } - } else if (typeof request === 'string') { - // 2.2.1 - r = new Request(request)[kState] - } - } - - // 5. - // 5.1 - const responses = [] - - // 5.2 - if (request === undefined) { - // 5.2.1 - for (const requestResponse of this.#relevantRequestResponseList) { - responses.push(requestResponse[1]) - } - } else { // 5.3 - // 5.3.1 - const requestResponses = this.#queryCache(r, options) - - // 5.3.2 - for (const requestResponse of requestResponses) { - responses.push(requestResponse[1]) - } - } - - // 5.4 - // We don't implement CORs so we don't need to loop over the responses, yay! - - // 5.5.1 - const responseList = [] - - // 5.5.2 - for (const response of responses) { - // 5.5.2.1 - const responseObject = new Response(response.body?.source ?? null) - const body = responseObject[kState].body - responseObject[kState] = response - responseObject[kState].body = body - responseObject[kHeaders][kHeadersList] = response.headersList - responseObject[kHeaders][kGuard] = 'immutable' - - responseList.push(responseObject) - } - - // 6. - return Object.freeze(responseList) - } - - async add (request) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.add' }) - - request = webidl.converters.RequestInfo(request) - - // 1. - const requests = [request] - - // 2. - const responseArrayPromise = this.addAll(requests) - - // 3. - return await responseArrayPromise - } - - async addAll (requests) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.addAll' }) - - requests = webidl.converters['sequence'](requests) - - // 1. - const responsePromises = [] - - // 2. - const requestList = [] - - // 3. - for (const request of requests) { - if (typeof request === 'string') { - continue - } - - // 3.1 - const r = request[kState] - - // 3.2 - if (!urlIsHttpHttpsScheme(r.url) || r.method !== 'GET') { - throw webidl.errors.exception({ - header: 'Cache.addAll', - message: 'Expected http/s scheme when method is not GET.' - }) - } - } - - // 4. - /** @type {ReturnType[]} */ - const fetchControllers = [] - - // 5. - for (const request of requests) { - // 5.1 - const r = new Request(request)[kState] - - // 5.2 - if (!urlIsHttpHttpsScheme(r.url)) { - throw webidl.errors.exception({ - header: 'Cache.addAll', - message: 'Expected http/s scheme.' - }) - } - - // 5.4 - r.initiator = 'fetch' - r.destination = 'subresource' - - // 5.5 - requestList.push(r) - - // 5.6 - const responsePromise = createDeferredPromise() - - // 5.7 - fetchControllers.push(fetching({ - request: r, - dispatcher: getGlobalDispatcher(), - processResponse (response) { - // 1. - if (response.type === 'error' || response.status === 206 || response.status < 200 || response.status > 299) { - responsePromise.reject(webidl.errors.exception({ - header: 'Cache.addAll', - message: 'Received an invalid status code or the request failed.' - })) - } else if (response.headersList.contains('vary')) { // 2. - // 2.1 - const fieldValues = getFieldValues(response.headersList.get('vary')) - - // 2.2 - for (const fieldValue of fieldValues) { - // 2.2.1 - if (fieldValue === '*') { - responsePromise.reject(webidl.errors.exception({ - header: 'Cache.addAll', - message: 'invalid vary field value' - })) - - for (const controller of fetchControllers) { - controller.abort() - } - - return - } - } - } - }, - processResponseEndOfBody (response) { - // 1. - if (response.aborted) { - responsePromise.reject(new DOMException('aborted', 'AbortError')) - return - } - - // 2. - responsePromise.resolve(response) - } - })) - - // 5.8 - responsePromises.push(responsePromise.promise) - } - - // 6. - const p = Promise.all(responsePromises) - - // 7. - const responses = await p - - // 7.1 - const operations = [] - - // 7.2 - let index = 0 - - // 7.3 - for (const response of responses) { - // 7.3.1 - /** @type {CacheBatchOperation} */ - const operation = { - type: 'put', // 7.3.2 - request: requestList[index], // 7.3.3 - response // 7.3.4 - } - - operations.push(operation) // 7.3.5 - - index++ // 7.3.6 - } - - // 7.5 - const cacheJobPromise = createDeferredPromise() - - // 7.6.1 - let errorData = null - - // 7.6.2 - try { - this.#batchCacheOperations(operations) - } catch (e) { - errorData = e - } - - // 7.6.3 - queueMicrotask(() => { - // 7.6.3.1 - if (errorData === null) { - cacheJobPromise.resolve(undefined) - } else { - // 7.6.3.2 - cacheJobPromise.reject(errorData) - } - }) - - // 7.7 - return cacheJobPromise.promise - } - - async put (request, response) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 2, { header: 'Cache.put' }) - - request = webidl.converters.RequestInfo(request) - response = webidl.converters.Response(response) - - // 1. - let innerRequest = null - - // 2. - if (request instanceof Request) { - innerRequest = request[kState] - } else { // 3. - innerRequest = new Request(request)[kState] - } - - // 4. - if (!urlIsHttpHttpsScheme(innerRequest.url) || innerRequest.method !== 'GET') { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Expected an http/s scheme when method is not GET' - }) - } - - // 5. - const innerResponse = response[kState] - - // 6. - if (innerResponse.status === 206) { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Got 206 status' - }) - } - - // 7. - if (innerResponse.headersList.contains('vary')) { - // 7.1. - const fieldValues = getFieldValues(innerResponse.headersList.get('vary')) - - // 7.2. - for (const fieldValue of fieldValues) { - // 7.2.1 - if (fieldValue === '*') { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Got * vary field value' - }) - } - } - } - - // 8. - if (innerResponse.body && (isDisturbed(innerResponse.body.stream) || innerResponse.body.stream.locked)) { - throw webidl.errors.exception({ - header: 'Cache.put', - message: 'Response body is locked or disturbed' - }) - } - - // 9. - const clonedResponse = cloneResponse(innerResponse) - - // 10. - const bodyReadPromise = createDeferredPromise() - - // 11. - if (innerResponse.body != null) { - // 11.1 - const stream = innerResponse.body.stream - - // 11.2 - const reader = stream.getReader() - - // 11.3 - readAllBytes(reader).then(bodyReadPromise.resolve, bodyReadPromise.reject) - } else { - bodyReadPromise.resolve(undefined) - } - - // 12. - /** @type {CacheBatchOperation[]} */ - const operations = [] - - // 13. - /** @type {CacheBatchOperation} */ - const operation = { - type: 'put', // 14. - request: innerRequest, // 15. - response: clonedResponse // 16. - } - - // 17. - operations.push(operation) - - // 19. - const bytes = await bodyReadPromise.promise - - if (clonedResponse.body != null) { - clonedResponse.body.source = bytes - } - - // 19.1 - const cacheJobPromise = createDeferredPromise() - - // 19.2.1 - let errorData = null - - // 19.2.2 - try { - this.#batchCacheOperations(operations) - } catch (e) { - errorData = e - } - - // 19.2.3 - queueMicrotask(() => { - // 19.2.3.1 - if (errorData === null) { - cacheJobPromise.resolve() - } else { // 19.2.3.2 - cacheJobPromise.reject(errorData) - } - }) - - return cacheJobPromise.promise - } - - async delete (request, options = {}) { - webidl.brandCheck(this, Cache) - webidl.argumentLengthCheck(arguments, 1, { header: 'Cache.delete' }) - - request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) - - /** - * @type {Request} - */ - let r = null - - if (request instanceof Request) { - r = request[kState] - - if (r.method !== 'GET' && !options.ignoreMethod) { - return false - } - } else { - assert(typeof request === 'string') - - r = new Request(request)[kState] - } - - /** @type {CacheBatchOperation[]} */ - const operations = [] - - /** @type {CacheBatchOperation} */ - const operation = { - type: 'delete', - request: r, - options - } - - operations.push(operation) - - const cacheJobPromise = createDeferredPromise() - - let errorData = null - let requestResponses - - try { - requestResponses = this.#batchCacheOperations(operations) - } catch (e) { - errorData = e - } - - queueMicrotask(() => { - if (errorData === null) { - cacheJobPromise.resolve(!!requestResponses?.length) - } else { - cacheJobPromise.reject(errorData) - } - }) - - return cacheJobPromise.promise - } - - /** - * @see https://w3c.github.io/ServiceWorker/#dom-cache-keys - * @param {any} request - * @param {import('../../types/cache').CacheQueryOptions} options - * @returns {readonly Request[]} - */ - async keys (request = undefined, options = {}) { - webidl.brandCheck(this, Cache) - - if (request !== undefined) request = webidl.converters.RequestInfo(request) - options = webidl.converters.CacheQueryOptions(options) - - // 1. - let r = null - - // 2. - if (request !== undefined) { - // 2.1 - if (request instanceof Request) { - // 2.1.1 - r = request[kState] - - // 2.1.2 - if (r.method !== 'GET' && !options.ignoreMethod) { - return [] - } - } else if (typeof request === 'string') { // 2.2 - r = new Request(request)[kState] - } - } - - // 4. - const promise = createDeferredPromise() - - // 5. - // 5.1 - const requests = [] - - // 5.2 - if (request === undefined) { - // 5.2.1 - for (const requestResponse of this.#relevantRequestResponseList) { - // 5.2.1.1 - requests.push(requestResponse[0]) - } - } else { // 5.3 - // 5.3.1 - const requestResponses = this.#queryCache(r, options) - - // 5.3.2 - for (const requestResponse of requestResponses) { - // 5.3.2.1 - requests.push(requestResponse[0]) - } - } - - // 5.4 - queueMicrotask(() => { - // 5.4.1 - const requestList = [] - - // 5.4.2 - for (const request of requests) { - const requestObject = new Request('https://a') - requestObject[kState] = request - requestObject[kHeaders][kHeadersList] = request.headersList - requestObject[kHeaders][kGuard] = 'immutable' - requestObject[kRealm] = request.client - - // 5.4.2.1 - requestList.push(requestObject) - } - - // 5.4.3 - promise.resolve(Object.freeze(requestList)) - }) - - return promise.promise - } - - /** - * @see https://w3c.github.io/ServiceWorker/#batch-cache-operations-algorithm - * @param {CacheBatchOperation[]} operations - * @returns {requestResponseList} - */ - #batchCacheOperations (operations) { - // 1. - const cache = this.#relevantRequestResponseList - - // 2. - const backupCache = [...cache] - - // 3. - const addedItems = [] - - // 4.1 - const resultList = [] - - try { - // 4.2 - for (const operation of operations) { - // 4.2.1 - if (operation.type !== 'delete' && operation.type !== 'put') { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'operation type does not match "delete" or "put"' - }) - } - - // 4.2.2 - if (operation.type === 'delete' && operation.response != null) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'delete operation should not have an associated response' - }) - } - - // 4.2.3 - if (this.#queryCache(operation.request, operation.options, addedItems).length) { - throw new DOMException('???', 'InvalidStateError') - } - - // 4.2.4 - let requestResponses - - // 4.2.5 - if (operation.type === 'delete') { - // 4.2.5.1 - requestResponses = this.#queryCache(operation.request, operation.options) - - // TODO: the spec is wrong, this is needed to pass WPTs - if (requestResponses.length === 0) { - return [] - } - - // 4.2.5.2 - for (const requestResponse of requestResponses) { - const idx = cache.indexOf(requestResponse) - assert(idx !== -1) - - // 4.2.5.2.1 - cache.splice(idx, 1) - } - } else if (operation.type === 'put') { // 4.2.6 - // 4.2.6.1 - if (operation.response == null) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'put operation should have an associated response' - }) - } - - // 4.2.6.2 - const r = operation.request - - // 4.2.6.3 - if (!urlIsHttpHttpsScheme(r.url)) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'expected http or https scheme' - }) - } - - // 4.2.6.4 - if (r.method !== 'GET') { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'not get method' - }) - } - - // 4.2.6.5 - if (operation.options != null) { - throw webidl.errors.exception({ - header: 'Cache.#batchCacheOperations', - message: 'options must not be defined' - }) - } - - // 4.2.6.6 - requestResponses = this.#queryCache(operation.request) - - // 4.2.6.7 - for (const requestResponse of requestResponses) { - const idx = cache.indexOf(requestResponse) - assert(idx !== -1) - - // 4.2.6.7.1 - cache.splice(idx, 1) - } - - // 4.2.6.8 - cache.push([operation.request, operation.response]) - - // 4.2.6.10 - addedItems.push([operation.request, operation.response]) - } - - // 4.2.7 - resultList.push([operation.request, operation.response]) - } - - // 4.3 - return resultList - } catch (e) { // 5. - // 5.1 - this.#relevantRequestResponseList.length = 0 - - // 5.2 - this.#relevantRequestResponseList = backupCache - - // 5.3 - throw e - } - } - - /** - * @see https://w3c.github.io/ServiceWorker/#query-cache - * @param {any} requestQuery - * @param {import('../../types/cache').CacheQueryOptions} options - * @param {requestResponseList} targetStorage - * @returns {requestResponseList} - */ - #queryCache (requestQuery, options, targetStorage) { - /** @type {requestResponseList} */ - const resultList = [] - - const storage = targetStorage ?? this.#relevantRequestResponseList - - for (const requestResponse of storage) { - const [cachedRequest, cachedResponse] = requestResponse - if (this.#requestMatchesCachedItem(requestQuery, cachedRequest, cachedResponse, options)) { - resultList.push(requestResponse) - } - } - - return resultList - } - - /** - * @see https://w3c.github.io/ServiceWorker/#request-matches-cached-item-algorithm - * @param {any} requestQuery - * @param {any} request - * @param {any | null} response - * @param {import('../../types/cache').CacheQueryOptions | undefined} options - * @returns {boolean} - */ - #requestMatchesCachedItem (requestQuery, request, response = null, options) { - // if (options?.ignoreMethod === false && request.method === 'GET') { - // return false - // } - - const queryURL = new URL(requestQuery.url) - - const cachedURL = new URL(request.url) - - if (options?.ignoreSearch) { - cachedURL.search = '' - - queryURL.search = '' - } - - if (!urlEquals(queryURL, cachedURL, true)) { - return false - } - - if ( - response == null || - options?.ignoreVary || - !response.headersList.contains('vary') - ) { - return true - } - - const fieldValues = getFieldValues(response.headersList.get('vary')) - - for (const fieldValue of fieldValues) { - if (fieldValue === '*') { - return false - } - - const requestValue = request.headersList.get(fieldValue) - const queryValue = requestQuery.headersList.get(fieldValue) - - // If one has the header and the other doesn't, or one has - // a different value than the other, return false - if (requestValue !== queryValue) { - return false - } - } - - return true - } -} - -Object.defineProperties(Cache.prototype, { - [Symbol.toStringTag]: { - value: 'Cache', - configurable: true - }, - match: kEnumerableProperty, - matchAll: kEnumerableProperty, - add: kEnumerableProperty, - addAll: kEnumerableProperty, - put: kEnumerableProperty, - delete: kEnumerableProperty, - keys: kEnumerableProperty -}) - -const cacheQueryOptionConverters = [ - { - key: 'ignoreSearch', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'ignoreMethod', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'ignoreVary', - converter: webidl.converters.boolean, - defaultValue: false - } -] - -webidl.converters.CacheQueryOptions = webidl.dictionaryConverter(cacheQueryOptionConverters) - -webidl.converters.MultiCacheQueryOptions = webidl.dictionaryConverter([ - ...cacheQueryOptionConverters, - { - key: 'cacheName', - converter: webidl.converters.DOMString - } -]) - -webidl.converters.Response = webidl.interfaceConverter(Response) - -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.RequestInfo -) - -module.exports = { - Cache -} - - -/***/ }), - -/***/ 4738: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { kConstruct } = __nccwpck_require__(296) -const { Cache } = __nccwpck_require__(479) -const { webidl } = __nccwpck_require__(4222) -const { kEnumerableProperty } = __nccwpck_require__(3440) - -class CacheStorage { - /** - * @see https://w3c.github.io/ServiceWorker/#dfn-relevant-name-to-cache-map - * @type {Map} - */ - async has (cacheName) { - webidl.brandCheck(this, CacheStorage) - webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.has' }) - - cacheName = webidl.converters.DOMString(cacheName) - - // 2.1.1 - // 2.2 - return this.#caches.has(cacheName) - } - - /** - * @see https://w3c.github.io/ServiceWorker/#dom-cachestorage-open - * @param {string} cacheName - * @returns {Promise} - */ - async open (cacheName) { - webidl.brandCheck(this, CacheStorage) - webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.open' }) - - cacheName = webidl.converters.DOMString(cacheName) - - // 2.1 - if (this.#caches.has(cacheName)) { - // await caches.open('v1') !== await caches.open('v1') - - // 2.1.1 - const cache = this.#caches.get(cacheName) - - // 2.1.1.1 - return new Cache(kConstruct, cache) - } - - // 2.2 - const cache = [] - - // 2.3 - this.#caches.set(cacheName, cache) - - // 2.4 - return new Cache(kConstruct, cache) - } - - /** - * @see https://w3c.github.io/ServiceWorker/#cache-storage-delete - * @param {string} cacheName - * @returns {Promise} - */ - async delete (cacheName) { - webidl.brandCheck(this, CacheStorage) - webidl.argumentLengthCheck(arguments, 1, { header: 'CacheStorage.delete' }) - - cacheName = webidl.converters.DOMString(cacheName) - - return this.#caches.delete(cacheName) - } - - /** - * @see https://w3c.github.io/ServiceWorker/#cache-storage-keys - * @returns {string[]} - */ - async keys () { - webidl.brandCheck(this, CacheStorage) - - // 2.1 - const keys = this.#caches.keys() - - // 2.2 - return [...keys] - } -} - -Object.defineProperties(CacheStorage.prototype, { - [Symbol.toStringTag]: { - value: 'CacheStorage', - configurable: true - }, - match: kEnumerableProperty, - has: kEnumerableProperty, - open: kEnumerableProperty, - delete: kEnumerableProperty, - keys: kEnumerableProperty -}) - -module.exports = { - CacheStorage -} - - -/***/ }), - -/***/ 296: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -module.exports = { - kConstruct: (__nccwpck_require__(6443).kConstruct) -} - - -/***/ }), - -/***/ 3993: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const assert = __nccwpck_require__(2613) -const { URLSerializer } = __nccwpck_require__(4322) -const { isValidHeaderName } = __nccwpck_require__(5523) - -/** - * @see https://url.spec.whatwg.org/#concept-url-equals - * @param {URL} A - * @param {URL} B - * @param {boolean | undefined} excludeFragment - * @returns {boolean} - */ -function urlEquals (A, B, excludeFragment = false) { - const serializedA = URLSerializer(A, excludeFragment) - - const serializedB = URLSerializer(B, excludeFragment) - - return serializedA === serializedB -} - -/** - * @see https://github.com/chromium/chromium/blob/694d20d134cb553d8d89e5500b9148012b1ba299/content/browser/cache_storage/cache_storage_cache.cc#L260-L262 - * @param {string} header - */ -function fieldValues (header) { - assert(header !== null) - - const values = [] - - for (let value of header.split(',')) { - value = value.trim() - - if (!value.length) { - continue - } else if (!isValidHeaderName(value)) { - continue - } - - values.push(value) - } - - return values -} - -module.exports = { - urlEquals, - fieldValues -} - - -/***/ }), - -/***/ 6197: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// @ts-check - - - -/* global WebAssembly */ - -const assert = __nccwpck_require__(2613) -const net = __nccwpck_require__(9278) -const http = __nccwpck_require__(8611) -const { pipeline } = __nccwpck_require__(2203) -const util = __nccwpck_require__(3440) -const timers = __nccwpck_require__(8804) -const Request = __nccwpck_require__(4655) -const DispatcherBase = __nccwpck_require__(1) -const { - RequestContentLengthMismatchError, - ResponseContentLengthMismatchError, - InvalidArgumentError, - RequestAbortedError, - HeadersTimeoutError, - HeadersOverflowError, - SocketError, - InformationalError, - BodyTimeoutError, - HTTPParserError, - ResponseExceededMaxSizeError, - ClientDestroyedError -} = __nccwpck_require__(8707) -const buildConnector = __nccwpck_require__(9136) -const { - kUrl, - kReset, - kServerName, - kClient, - kBusy, - kParser, - kConnect, - kBlocking, - kResuming, - kRunning, - kPending, - kSize, - kWriting, - kQueue, - kConnected, - kConnecting, - kNeedDrain, - kNoRef, - kKeepAliveDefaultTimeout, - kHostHeader, - kPendingIdx, - kRunningIdx, - kError, - kPipelining, - kSocket, - kKeepAliveTimeoutValue, - kMaxHeadersSize, - kKeepAliveMaxTimeout, - kKeepAliveTimeoutThreshold, - kHeadersTimeout, - kBodyTimeout, - kStrictContentLength, - kConnector, - kMaxRedirections, - kMaxRequests, - kCounter, - kClose, - kDestroy, - kDispatch, - kInterceptors, - kLocalAddress, - kMaxResponseSize, - kHTTPConnVersion, - // HTTP2 - kHost, - kHTTP2Session, - kHTTP2SessionState, - kHTTP2BuildRequest, - kHTTP2CopyHeaders, - kHTTP1BuildRequest -} = __nccwpck_require__(6443) - -/** @type {import('http2')} */ -let http2 -try { - http2 = __nccwpck_require__(5675) -} catch { - // @ts-ignore - http2 = { constants: {} } -} - -const { - constants: { - HTTP2_HEADER_AUTHORITY, - HTTP2_HEADER_METHOD, - HTTP2_HEADER_PATH, - HTTP2_HEADER_SCHEME, - HTTP2_HEADER_CONTENT_LENGTH, - HTTP2_HEADER_EXPECT, - HTTP2_HEADER_STATUS - } -} = http2 - -// Experimental -let h2ExperimentalWarned = false - -const FastBuffer = Buffer[Symbol.species] - -const kClosedResolve = Symbol('kClosedResolve') - -const channels = {} - -try { - const diagnosticsChannel = __nccwpck_require__(1637) - channels.sendHeaders = diagnosticsChannel.channel('undici:client:sendHeaders') - channels.beforeConnect = diagnosticsChannel.channel('undici:client:beforeConnect') - channels.connectError = diagnosticsChannel.channel('undici:client:connectError') - channels.connected = diagnosticsChannel.channel('undici:client:connected') -} catch { - channels.sendHeaders = { hasSubscribers: false } - channels.beforeConnect = { hasSubscribers: false } - channels.connectError = { hasSubscribers: false } - channels.connected = { hasSubscribers: false } -} - -/** - * @type {import('../types/client').default} - */ -class Client extends DispatcherBase { - /** - * - * @param {string|URL} url - * @param {import('../types/client').Client.Options} options - */ - constructor (url, { - interceptors, - maxHeaderSize, - headersTimeout, - socketTimeout, - requestTimeout, - connectTimeout, - bodyTimeout, - idleTimeout, - keepAlive, - keepAliveTimeout, - maxKeepAliveTimeout, - keepAliveMaxTimeout, - keepAliveTimeoutThreshold, - socketPath, - pipelining, - tls, - strictContentLength, - maxCachedSessions, - maxRedirections, - connect, - maxRequestsPerClient, - localAddress, - maxResponseSize, - autoSelectFamily, - autoSelectFamilyAttemptTimeout, - // h2 - allowH2, - maxConcurrentStreams - } = {}) { - super() - - if (keepAlive !== undefined) { - throw new InvalidArgumentError('unsupported keepAlive, use pipelining=0 instead') - } - - if (socketTimeout !== undefined) { - throw new InvalidArgumentError('unsupported socketTimeout, use headersTimeout & bodyTimeout instead') - } - - if (requestTimeout !== undefined) { - throw new InvalidArgumentError('unsupported requestTimeout, use headersTimeout & bodyTimeout instead') - } - - if (idleTimeout !== undefined) { - throw new InvalidArgumentError('unsupported idleTimeout, use keepAliveTimeout instead') - } - - if (maxKeepAliveTimeout !== undefined) { - throw new InvalidArgumentError('unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead') - } - - if (maxHeaderSize != null && !Number.isFinite(maxHeaderSize)) { - throw new InvalidArgumentError('invalid maxHeaderSize') - } - - if (socketPath != null && typeof socketPath !== 'string') { - throw new InvalidArgumentError('invalid socketPath') - } - - if (connectTimeout != null && (!Number.isFinite(connectTimeout) || connectTimeout < 0)) { - throw new InvalidArgumentError('invalid connectTimeout') - } - - if (keepAliveTimeout != null && (!Number.isFinite(keepAliveTimeout) || keepAliveTimeout <= 0)) { - throw new InvalidArgumentError('invalid keepAliveTimeout') - } - - if (keepAliveMaxTimeout != null && (!Number.isFinite(keepAliveMaxTimeout) || keepAliveMaxTimeout <= 0)) { - throw new InvalidArgumentError('invalid keepAliveMaxTimeout') - } - - if (keepAliveTimeoutThreshold != null && !Number.isFinite(keepAliveTimeoutThreshold)) { - throw new InvalidArgumentError('invalid keepAliveTimeoutThreshold') - } - - if (headersTimeout != null && (!Number.isInteger(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError('headersTimeout must be a positive integer or zero') - } - - if (bodyTimeout != null && (!Number.isInteger(bodyTimeout) || bodyTimeout < 0)) { - throw new InvalidArgumentError('bodyTimeout must be a positive integer or zero') - } - - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') - } - - if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { - throw new InvalidArgumentError('maxRedirections must be a positive number') - } - - if (maxRequestsPerClient != null && (!Number.isInteger(maxRequestsPerClient) || maxRequestsPerClient < 0)) { - throw new InvalidArgumentError('maxRequestsPerClient must be a positive number') - } - - if (localAddress != null && (typeof localAddress !== 'string' || net.isIP(localAddress) === 0)) { - throw new InvalidArgumentError('localAddress must be valid string IP address') - } - - if (maxResponseSize != null && (!Number.isInteger(maxResponseSize) || maxResponseSize < -1)) { - throw new InvalidArgumentError('maxResponseSize must be a positive number') - } - - if ( - autoSelectFamilyAttemptTimeout != null && - (!Number.isInteger(autoSelectFamilyAttemptTimeout) || autoSelectFamilyAttemptTimeout < -1) - ) { - throw new InvalidArgumentError('autoSelectFamilyAttemptTimeout must be a positive number') - } - - // h2 - if (allowH2 != null && typeof allowH2 !== 'boolean') { - throw new InvalidArgumentError('allowH2 must be a valid boolean value') - } - - if (maxConcurrentStreams != null && (typeof maxConcurrentStreams !== 'number' || maxConcurrentStreams < 1)) { - throw new InvalidArgumentError('maxConcurrentStreams must be a possitive integer, greater than 0') - } - - if (typeof connect !== 'function') { - connect = buildConnector({ - ...tls, - maxCachedSessions, - allowH2, - socketPath, - timeout: connectTimeout, - ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), - ...connect - }) - } - - this[kInterceptors] = interceptors && interceptors.Client && Array.isArray(interceptors.Client) - ? interceptors.Client - : [createRedirectInterceptor({ maxRedirections })] - this[kUrl] = util.parseOrigin(url) - this[kConnector] = connect - this[kSocket] = null - this[kPipelining] = pipelining != null ? pipelining : 1 - this[kMaxHeadersSize] = maxHeaderSize || http.maxHeaderSize - this[kKeepAliveDefaultTimeout] = keepAliveTimeout == null ? 4e3 : keepAliveTimeout - this[kKeepAliveMaxTimeout] = keepAliveMaxTimeout == null ? 600e3 : keepAliveMaxTimeout - this[kKeepAliveTimeoutThreshold] = keepAliveTimeoutThreshold == null ? 1e3 : keepAliveTimeoutThreshold - this[kKeepAliveTimeoutValue] = this[kKeepAliveDefaultTimeout] - this[kServerName] = null - this[kLocalAddress] = localAddress != null ? localAddress : null - this[kResuming] = 0 // 0, idle, 1, scheduled, 2 resuming - this[kNeedDrain] = 0 // 0, idle, 1, scheduled, 2 resuming - this[kHostHeader] = `host: ${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}\r\n` - this[kBodyTimeout] = bodyTimeout != null ? bodyTimeout : 300e3 - this[kHeadersTimeout] = headersTimeout != null ? headersTimeout : 300e3 - this[kStrictContentLength] = strictContentLength == null ? true : strictContentLength - this[kMaxRedirections] = maxRedirections - this[kMaxRequests] = maxRequestsPerClient - this[kClosedResolve] = null - this[kMaxResponseSize] = maxResponseSize > -1 ? maxResponseSize : -1 - this[kHTTPConnVersion] = 'h1' - - // HTTP/2 - this[kHTTP2Session] = null - this[kHTTP2SessionState] = !allowH2 - ? null - : { - // streams: null, // Fixed queue of streams - For future support of `push` - openStreams: 0, // Keep track of them to decide wether or not unref the session - maxConcurrentStreams: maxConcurrentStreams != null ? maxConcurrentStreams : 100 // Max peerConcurrentStreams for a Node h2 server - } - this[kHost] = `${this[kUrl].hostname}${this[kUrl].port ? `:${this[kUrl].port}` : ''}` - - // kQueue is built up of 3 sections separated by - // the kRunningIdx and kPendingIdx indices. - // | complete | running | pending | - // ^ kRunningIdx ^ kPendingIdx ^ kQueue.length - // kRunningIdx points to the first running element. - // kPendingIdx points to the first pending element. - // This implements a fast queue with an amortized - // time of O(1). - - this[kQueue] = [] - this[kRunningIdx] = 0 - this[kPendingIdx] = 0 - } - - get pipelining () { - return this[kPipelining] - } - - set pipelining (value) { - this[kPipelining] = value - resume(this, true) - } - - get [kPending] () { - return this[kQueue].length - this[kPendingIdx] - } - - get [kRunning] () { - return this[kPendingIdx] - this[kRunningIdx] - } - - get [kSize] () { - return this[kQueue].length - this[kRunningIdx] - } - - get [kConnected] () { - return !!this[kSocket] && !this[kConnecting] && !this[kSocket].destroyed - } - - get [kBusy] () { - const socket = this[kSocket] - return ( - (socket && (socket[kReset] || socket[kWriting] || socket[kBlocking])) || - (this[kSize] >= (this[kPipelining] || 1)) || - this[kPending] > 0 - ) - } - - /* istanbul ignore: only used for test */ - [kConnect] (cb) { - connect(this) - this.once('connect', cb) - } - - [kDispatch] (opts, handler) { - const origin = opts.origin || this[kUrl].origin - - const request = this[kHTTPConnVersion] === 'h2' - ? Request[kHTTP2BuildRequest](origin, opts, handler) - : Request[kHTTP1BuildRequest](origin, opts, handler) - - this[kQueue].push(request) - if (this[kResuming]) { - // Do nothing. - } else if (util.bodyLength(request.body) == null && util.isIterable(request.body)) { - // Wait a tick in case stream/iterator is ended in the same tick. - this[kResuming] = 1 - process.nextTick(resume, this) - } else { - resume(this, true) - } - - if (this[kResuming] && this[kNeedDrain] !== 2 && this[kBusy]) { - this[kNeedDrain] = 2 - } - - return this[kNeedDrain] < 2 - } - - async [kClose] () { - // TODO: for H2 we need to gracefully flush the remaining enqueued - // request and close each stream. - return new Promise((resolve) => { - if (!this[kSize]) { - resolve(null) - } else { - this[kClosedResolve] = resolve - } - }) - } - - async [kDestroy] (err) { - return new Promise((resolve) => { - const requests = this[kQueue].splice(this[kPendingIdx]) - for (let i = 0; i < requests.length; i++) { - const request = requests[i] - errorRequest(this, request, err) - } - - const callback = () => { - if (this[kClosedResolve]) { - // TODO (fix): Should we error here with ClientDestroyedError? - this[kClosedResolve]() - this[kClosedResolve] = null - } - resolve() - } - - if (this[kHTTP2Session] != null) { - util.destroy(this[kHTTP2Session], err) - this[kHTTP2Session] = null - this[kHTTP2SessionState] = null - } - - if (!this[kSocket]) { - queueMicrotask(callback) - } else { - util.destroy(this[kSocket].on('close', callback), err) - } - - resume(this) - }) - } -} - -function onHttp2SessionError (err) { - assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - - this[kSocket][kError] = err - - onError(this[kClient], err) -} - -function onHttp2FrameError (type, code, id) { - const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) - - if (id === 0) { - this[kSocket][kError] = err - onError(this[kClient], err) - } -} - -function onHttp2SessionEnd () { - util.destroy(this, new SocketError('other side closed')) - util.destroy(this[kSocket], new SocketError('other side closed')) -} - -function onHTTP2GoAway (code) { - const client = this[kClient] - const err = new InformationalError(`HTTP/2: "GOAWAY" frame received with code ${code}`) - client[kSocket] = null - client[kHTTP2Session] = null - - if (client.destroyed) { - assert(this[kPending] === 0) - - // Fail entire queue. - const requests = client[kQueue].splice(client[kRunningIdx]) - for (let i = 0; i < requests.length; i++) { - const request = requests[i] - errorRequest(this, request, err) - } - } else if (client[kRunning] > 0) { - // Fail head of pipeline. - const request = client[kQueue][client[kRunningIdx]] - client[kQueue][client[kRunningIdx]++] = null - - errorRequest(client, request, err) - } - - client[kPendingIdx] = client[kRunningIdx] - - assert(client[kRunning] === 0) - - client.emit('disconnect', - client[kUrl], - [client], - err - ) - - resume(client) -} - -const constants = __nccwpck_require__(2824) -const createRedirectInterceptor = __nccwpck_require__(4415) -const EMPTY_BUF = Buffer.alloc(0) - -async function lazyllhttp () { - const llhttpWasmData = process.env.JEST_WORKER_ID ? __nccwpck_require__(3870) : undefined - - let mod - try { - mod = await WebAssembly.compile(Buffer.from(__nccwpck_require__(3434), 'base64')) - } catch (e) { - /* istanbul ignore next */ - - // We could check if the error was caused by the simd option not - // being enabled, but the occurring of this other error - // * https://github.com/emscripten-core/emscripten/issues/11495 - // got me to remove that check to avoid breaking Node 12. - mod = await WebAssembly.compile(Buffer.from(llhttpWasmData || __nccwpck_require__(3870), 'base64')) - } - - return await WebAssembly.instantiate(mod, { - env: { - /* eslint-disable camelcase */ - - wasm_on_url: (p, at, len) => { - /* istanbul ignore next */ - return 0 - }, - wasm_on_status: (p, at, len) => { - assert.strictEqual(currentParser.ptr, p) - const start = at - currentBufferPtr + currentBufferRef.byteOffset - return currentParser.onStatus(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 - }, - wasm_on_message_begin: (p) => { - assert.strictEqual(currentParser.ptr, p) - return currentParser.onMessageBegin() || 0 - }, - wasm_on_header_field: (p, at, len) => { - assert.strictEqual(currentParser.ptr, p) - const start = at - currentBufferPtr + currentBufferRef.byteOffset - return currentParser.onHeaderField(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 - }, - wasm_on_header_value: (p, at, len) => { - assert.strictEqual(currentParser.ptr, p) - const start = at - currentBufferPtr + currentBufferRef.byteOffset - return currentParser.onHeaderValue(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 - }, - wasm_on_headers_complete: (p, statusCode, upgrade, shouldKeepAlive) => { - assert.strictEqual(currentParser.ptr, p) - return currentParser.onHeadersComplete(statusCode, Boolean(upgrade), Boolean(shouldKeepAlive)) || 0 - }, - wasm_on_body: (p, at, len) => { - assert.strictEqual(currentParser.ptr, p) - const start = at - currentBufferPtr + currentBufferRef.byteOffset - return currentParser.onBody(new FastBuffer(currentBufferRef.buffer, start, len)) || 0 - }, - wasm_on_message_complete: (p) => { - assert.strictEqual(currentParser.ptr, p) - return currentParser.onMessageComplete() || 0 - } - - /* eslint-enable camelcase */ - } - }) -} - -let llhttpInstance = null -let llhttpPromise = lazyllhttp() -llhttpPromise.catch() - -let currentParser = null -let currentBufferRef = null -let currentBufferSize = 0 -let currentBufferPtr = null - -const TIMEOUT_HEADERS = 1 -const TIMEOUT_BODY = 2 -const TIMEOUT_IDLE = 3 - -class Parser { - constructor (client, socket, { exports }) { - assert(Number.isFinite(client[kMaxHeadersSize]) && client[kMaxHeadersSize] > 0) - - this.llhttp = exports - this.ptr = this.llhttp.llhttp_alloc(constants.TYPE.RESPONSE) - this.client = client - this.socket = socket - this.timeout = null - this.timeoutValue = null - this.timeoutType = null - this.statusCode = null - this.statusText = '' - this.upgrade = false - this.headers = [] - this.headersSize = 0 - this.headersMaxSize = client[kMaxHeadersSize] - this.shouldKeepAlive = false - this.paused = false - this.resume = this.resume.bind(this) - - this.bytesRead = 0 - - this.keepAlive = '' - this.contentLength = '' - this.connection = '' - this.maxResponseSize = client[kMaxResponseSize] - } - - setTimeout (value, type) { - this.timeoutType = type - if (value !== this.timeoutValue) { - timers.clearTimeout(this.timeout) - if (value) { - this.timeout = timers.setTimeout(onParserTimeout, value, this) - // istanbul ignore else: only for jest - if (this.timeout.unref) { - this.timeout.unref() - } - } else { - this.timeout = null - } - this.timeoutValue = value - } else if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() - } - } - } - - resume () { - if (this.socket.destroyed || !this.paused) { - return - } - - assert(this.ptr != null) - assert(currentParser == null) - - this.llhttp.llhttp_resume(this.ptr) - - assert(this.timeoutType === TIMEOUT_BODY) - if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() - } - } - - this.paused = false - this.execute(this.socket.read() || EMPTY_BUF) // Flush parser. - this.readMore() - } - - readMore () { - while (!this.paused && this.ptr) { - const chunk = this.socket.read() - if (chunk === null) { - break - } - this.execute(chunk) - } - } - - execute (data) { - assert(this.ptr != null) - assert(currentParser == null) - assert(!this.paused) - - const { socket, llhttp } = this - - if (data.length > currentBufferSize) { - if (currentBufferPtr) { - llhttp.free(currentBufferPtr) - } - currentBufferSize = Math.ceil(data.length / 4096) * 4096 - currentBufferPtr = llhttp.malloc(currentBufferSize) - } - - new Uint8Array(llhttp.memory.buffer, currentBufferPtr, currentBufferSize).set(data) - - // Call `execute` on the wasm parser. - // We pass the `llhttp_parser` pointer address, the pointer address of buffer view data, - // and finally the length of bytes to parse. - // The return value is an error code or `constants.ERROR.OK`. - try { - let ret - - try { - currentBufferRef = data - currentParser = this - ret = llhttp.llhttp_execute(this.ptr, currentBufferPtr, data.length) - /* eslint-disable-next-line no-useless-catch */ - } catch (err) { - /* istanbul ignore next: difficult to make a test case for */ - throw err - } finally { - currentParser = null - currentBufferRef = null - } - - const offset = llhttp.llhttp_get_error_pos(this.ptr) - currentBufferPtr - - if (ret === constants.ERROR.PAUSED_UPGRADE) { - this.onUpgrade(data.slice(offset)) - } else if (ret === constants.ERROR.PAUSED) { - this.paused = true - socket.unshift(data.slice(offset)) - } else if (ret !== constants.ERROR.OK) { - const ptr = llhttp.llhttp_get_error_reason(this.ptr) - let message = '' - /* istanbul ignore else: difficult to make a test case for */ - if (ptr) { - const len = new Uint8Array(llhttp.memory.buffer, ptr).indexOf(0) - message = - 'Response does not match the HTTP/1.1 protocol (' + - Buffer.from(llhttp.memory.buffer, ptr, len).toString() + - ')' - } - throw new HTTPParserError(message, constants.ERROR[ret], data.slice(offset)) - } - } catch (err) { - util.destroy(socket, err) - } - } - - destroy () { - assert(this.ptr != null) - assert(currentParser == null) - - this.llhttp.llhttp_free(this.ptr) - this.ptr = null - - timers.clearTimeout(this.timeout) - this.timeout = null - this.timeoutValue = null - this.timeoutType = null - - this.paused = false - } - - onStatus (buf) { - this.statusText = buf.toString() - } - - onMessageBegin () { - const { socket, client } = this - - /* istanbul ignore next: difficult to make a test case for */ - if (socket.destroyed) { - return -1 - } - - const request = client[kQueue][client[kRunningIdx]] - if (!request) { - return -1 - } - } - - onHeaderField (buf) { - const len = this.headers.length - - if ((len & 1) === 0) { - this.headers.push(buf) - } else { - this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) - } - - this.trackHeader(buf.length) - } - - onHeaderValue (buf) { - let len = this.headers.length - - if ((len & 1) === 1) { - this.headers.push(buf) - len += 1 - } else { - this.headers[len - 1] = Buffer.concat([this.headers[len - 1], buf]) - } - - const key = this.headers[len - 2] - if (key.length === 10 && key.toString().toLowerCase() === 'keep-alive') { - this.keepAlive += buf.toString() - } else if (key.length === 10 && key.toString().toLowerCase() === 'connection') { - this.connection += buf.toString() - } else if (key.length === 14 && key.toString().toLowerCase() === 'content-length') { - this.contentLength += buf.toString() - } - - this.trackHeader(buf.length) - } - - trackHeader (len) { - this.headersSize += len - if (this.headersSize >= this.headersMaxSize) { - util.destroy(this.socket, new HeadersOverflowError()) - } - } - - onUpgrade (head) { - const { upgrade, client, socket, headers, statusCode } = this - - assert(upgrade) - - const request = client[kQueue][client[kRunningIdx]] - assert(request) - - assert(!socket.destroyed) - assert(socket === client[kSocket]) - assert(!this.paused) - assert(request.upgrade || request.method === 'CONNECT') - - this.statusCode = null - this.statusText = '' - this.shouldKeepAlive = null - - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 - - socket.unshift(head) - - socket[kParser].destroy() - socket[kParser] = null - - socket[kClient] = null - socket[kError] = null - socket - .removeListener('error', onSocketError) - .removeListener('readable', onSocketReadable) - .removeListener('end', onSocketEnd) - .removeListener('close', onSocketClose) - - client[kSocket] = null - client[kQueue][client[kRunningIdx]++] = null - client.emit('disconnect', client[kUrl], [client], new InformationalError('upgrade')) - - try { - request.onUpgrade(statusCode, headers, socket) - } catch (err) { - util.destroy(socket, err) - } - - resume(client) - } - - onHeadersComplete (statusCode, upgrade, shouldKeepAlive) { - const { client, socket, headers, statusText } = this - - /* istanbul ignore next: difficult to make a test case for */ - if (socket.destroyed) { - return -1 - } - - const request = client[kQueue][client[kRunningIdx]] - - /* istanbul ignore next: difficult to make a test case for */ - if (!request) { - return -1 - } - - assert(!this.upgrade) - assert(this.statusCode < 200) - - if (statusCode === 100) { - util.destroy(socket, new SocketError('bad response', util.getSocketInfo(socket))) - return -1 - } - - /* this can only happen if server is misbehaving */ - if (upgrade && !request.upgrade) { - util.destroy(socket, new SocketError('bad upgrade', util.getSocketInfo(socket))) - return -1 - } - - assert.strictEqual(this.timeoutType, TIMEOUT_HEADERS) - - this.statusCode = statusCode - this.shouldKeepAlive = ( - shouldKeepAlive || - // Override llhttp value which does not allow keepAlive for HEAD. - (request.method === 'HEAD' && !socket[kReset] && this.connection.toLowerCase() === 'keep-alive') - ) - - if (this.statusCode >= 200) { - const bodyTimeout = request.bodyTimeout != null - ? request.bodyTimeout - : client[kBodyTimeout] - this.setTimeout(bodyTimeout, TIMEOUT_BODY) - } else if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() - } - } - - if (request.method === 'CONNECT') { - assert(client[kRunning] === 1) - this.upgrade = true - return 2 - } - - if (upgrade) { - assert(client[kRunning] === 1) - this.upgrade = true - return 2 - } - - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 - - if (this.shouldKeepAlive && client[kPipelining]) { - const keepAliveTimeout = this.keepAlive ? util.parseKeepAliveTimeout(this.keepAlive) : null - - if (keepAliveTimeout != null) { - const timeout = Math.min( - keepAliveTimeout - client[kKeepAliveTimeoutThreshold], - client[kKeepAliveMaxTimeout] - ) - if (timeout <= 0) { - socket[kReset] = true - } else { - client[kKeepAliveTimeoutValue] = timeout - } - } else { - client[kKeepAliveTimeoutValue] = client[kKeepAliveDefaultTimeout] - } - } else { - // Stop more requests from being dispatched. - socket[kReset] = true - } - - const pause = request.onHeaders(statusCode, headers, this.resume, statusText) === false - - if (request.aborted) { - return -1 - } - - if (request.method === 'HEAD') { - return 1 - } - - if (statusCode < 200) { - return 1 - } - - if (socket[kBlocking]) { - socket[kBlocking] = false - resume(client) - } - - return pause ? constants.ERROR.PAUSED : 0 - } - - onBody (buf) { - const { client, socket, statusCode, maxResponseSize } = this - - if (socket.destroyed) { - return -1 - } - - const request = client[kQueue][client[kRunningIdx]] - assert(request) - - assert.strictEqual(this.timeoutType, TIMEOUT_BODY) - if (this.timeout) { - // istanbul ignore else: only for jest - if (this.timeout.refresh) { - this.timeout.refresh() - } - } - - assert(statusCode >= 200) - - if (maxResponseSize > -1 && this.bytesRead + buf.length > maxResponseSize) { - util.destroy(socket, new ResponseExceededMaxSizeError()) - return -1 - } - - this.bytesRead += buf.length - - if (request.onData(buf) === false) { - return constants.ERROR.PAUSED - } - } - - onMessageComplete () { - const { client, socket, statusCode, upgrade, headers, contentLength, bytesRead, shouldKeepAlive } = this - - if (socket.destroyed && (!statusCode || shouldKeepAlive)) { - return -1 - } - - if (upgrade) { - return - } - - const request = client[kQueue][client[kRunningIdx]] - assert(request) - - assert(statusCode >= 100) - - this.statusCode = null - this.statusText = '' - this.bytesRead = 0 - this.contentLength = '' - this.keepAlive = '' - this.connection = '' - - assert(this.headers.length % 2 === 0) - this.headers = [] - this.headersSize = 0 - - if (statusCode < 200) { - return - } - - /* istanbul ignore next: should be handled by llhttp? */ - if (request.method !== 'HEAD' && contentLength && bytesRead !== parseInt(contentLength, 10)) { - util.destroy(socket, new ResponseContentLengthMismatchError()) - return -1 - } - - request.onComplete(headers) - - client[kQueue][client[kRunningIdx]++] = null - - if (socket[kWriting]) { - assert.strictEqual(client[kRunning], 0) - // Response completed before request. - util.destroy(socket, new InformationalError('reset')) - return constants.ERROR.PAUSED - } else if (!shouldKeepAlive) { - util.destroy(socket, new InformationalError('reset')) - return constants.ERROR.PAUSED - } else if (socket[kReset] && client[kRunning] === 0) { - // Destroy socket once all requests have completed. - // The request at the tail of the pipeline is the one - // that requested reset and no further requests should - // have been queued since then. - util.destroy(socket, new InformationalError('reset')) - return constants.ERROR.PAUSED - } else if (client[kPipelining] === 1) { - // We must wait a full event loop cycle to reuse this socket to make sure - // that non-spec compliant servers are not closing the connection even if they - // said they won't. - setImmediate(resume, client) - } else { - resume(client) - } - } -} - -function onParserTimeout (parser) { - const { socket, timeoutType, client } = parser - - /* istanbul ignore else */ - if (timeoutType === TIMEOUT_HEADERS) { - if (!socket[kWriting] || socket.writableNeedDrain || client[kRunning] > 1) { - assert(!parser.paused, 'cannot be paused while waiting for headers') - util.destroy(socket, new HeadersTimeoutError()) - } - } else if (timeoutType === TIMEOUT_BODY) { - if (!parser.paused) { - util.destroy(socket, new BodyTimeoutError()) - } - } else if (timeoutType === TIMEOUT_IDLE) { - assert(client[kRunning] === 0 && client[kKeepAliveTimeoutValue]) - util.destroy(socket, new InformationalError('socket idle timeout')) - } -} - -function onSocketReadable () { - const { [kParser]: parser } = this - if (parser) { - parser.readMore() - } -} - -function onSocketError (err) { - const { [kClient]: client, [kParser]: parser } = this - - assert(err.code !== 'ERR_TLS_CERT_ALTNAME_INVALID') - - if (client[kHTTPConnVersion] !== 'h2') { - // On Mac OS, we get an ECONNRESET even if there is a full body to be forwarded - // to the user. - if (err.code === 'ECONNRESET' && parser.statusCode && !parser.shouldKeepAlive) { - // We treat all incoming data so for as a valid response. - parser.onMessageComplete() - return - } - } - - this[kError] = err - - onError(this[kClient], err) -} - -function onError (client, err) { - if ( - client[kRunning] === 0 && - err.code !== 'UND_ERR_INFO' && - err.code !== 'UND_ERR_SOCKET' - ) { - // Error is not caused by running request and not a recoverable - // socket error. - - assert(client[kPendingIdx] === client[kRunningIdx]) - - const requests = client[kQueue].splice(client[kRunningIdx]) - for (let i = 0; i < requests.length; i++) { - const request = requests[i] - errorRequest(client, request, err) - } - assert(client[kSize] === 0) - } -} - -function onSocketEnd () { - const { [kParser]: parser, [kClient]: client } = this - - if (client[kHTTPConnVersion] !== 'h2') { - if (parser.statusCode && !parser.shouldKeepAlive) { - // We treat all incoming data so far as a valid response. - parser.onMessageComplete() - return - } - } - - util.destroy(this, new SocketError('other side closed', util.getSocketInfo(this))) -} - -function onSocketClose () { - const { [kClient]: client, [kParser]: parser } = this - - if (client[kHTTPConnVersion] === 'h1' && parser) { - if (!this[kError] && parser.statusCode && !parser.shouldKeepAlive) { - // We treat all incoming data so far as a valid response. - parser.onMessageComplete() - } - - this[kParser].destroy() - this[kParser] = null - } - - const err = this[kError] || new SocketError('closed', util.getSocketInfo(this)) - - client[kSocket] = null - - if (client.destroyed) { - assert(client[kPending] === 0) - - // Fail entire queue. - const requests = client[kQueue].splice(client[kRunningIdx]) - for (let i = 0; i < requests.length; i++) { - const request = requests[i] - errorRequest(client, request, err) - } - } else if (client[kRunning] > 0 && err.code !== 'UND_ERR_INFO') { - // Fail head of pipeline. - const request = client[kQueue][client[kRunningIdx]] - client[kQueue][client[kRunningIdx]++] = null - - errorRequest(client, request, err) - } - - client[kPendingIdx] = client[kRunningIdx] - - assert(client[kRunning] === 0) - - client.emit('disconnect', client[kUrl], [client], err) - - resume(client) -} - -async function connect (client) { - assert(!client[kConnecting]) - assert(!client[kSocket]) - - let { host, hostname, protocol, port } = client[kUrl] - - // Resolve ipv6 - if (hostname[0] === '[') { - const idx = hostname.indexOf(']') - - assert(idx !== -1) - const ip = hostname.substring(1, idx) - - assert(net.isIP(ip)) - hostname = ip - } - - client[kConnecting] = true - - if (channels.beforeConnect.hasSubscribers) { - channels.beforeConnect.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector] - }) - } - - try { - const socket = await new Promise((resolve, reject) => { - client[kConnector]({ - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, (err, socket) => { - if (err) { - reject(err) - } else { - resolve(socket) - } - }) - }) - - if (client.destroyed) { - util.destroy(socket.on('error', () => {}), new ClientDestroyedError()) - return - } - - client[kConnecting] = false - - assert(socket) - - const isH2 = socket.alpnProtocol === 'h2' - if (isH2) { - if (!h2ExperimentalWarned) { - h2ExperimentalWarned = true - process.emitWarning('H2 support is experimental, expect them to change at any time.', { - code: 'UNDICI-H2' - }) - } - - const session = http2.connect(client[kUrl], { - createConnection: () => socket, - peerMaxConcurrentStreams: client[kHTTP2SessionState].maxConcurrentStreams - }) - - client[kHTTPConnVersion] = 'h2' - session[kClient] = client - session[kSocket] = socket - session.on('error', onHttp2SessionError) - session.on('frameError', onHttp2FrameError) - session.on('end', onHttp2SessionEnd) - session.on('goaway', onHTTP2GoAway) - session.on('close', onSocketClose) - session.unref() - - client[kHTTP2Session] = session - socket[kHTTP2Session] = session - } else { - if (!llhttpInstance) { - llhttpInstance = await llhttpPromise - llhttpPromise = null - } - - socket[kNoRef] = false - socket[kWriting] = false - socket[kReset] = false - socket[kBlocking] = false - socket[kParser] = new Parser(client, socket, llhttpInstance) - } - - socket[kCounter] = 0 - socket[kMaxRequests] = client[kMaxRequests] - socket[kClient] = client - socket[kError] = null - - socket - .on('error', onSocketError) - .on('readable', onSocketReadable) - .on('end', onSocketEnd) - .on('close', onSocketClose) - - client[kSocket] = socket - - if (channels.connected.hasSubscribers) { - channels.connected.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector], - socket - }) - } - client.emit('connect', client[kUrl], [client]) - } catch (err) { - if (client.destroyed) { - return - } - - client[kConnecting] = false - - if (channels.connectError.hasSubscribers) { - channels.connectError.publish({ - connectParams: { - host, - hostname, - protocol, - port, - servername: client[kServerName], - localAddress: client[kLocalAddress] - }, - connector: client[kConnector], - error: err - }) - } - - if (err.code === 'ERR_TLS_CERT_ALTNAME_INVALID') { - assert(client[kRunning] === 0) - while (client[kPending] > 0 && client[kQueue][client[kPendingIdx]].servername === client[kServerName]) { - const request = client[kQueue][client[kPendingIdx]++] - errorRequest(client, request, err) - } - } else { - onError(client, err) - } - - client.emit('connectionError', client[kUrl], [client], err) - } - - resume(client) -} - -function emitDrain (client) { - client[kNeedDrain] = 0 - client.emit('drain', client[kUrl], [client]) -} - -function resume (client, sync) { - if (client[kResuming] === 2) { - return - } - - client[kResuming] = 2 - - _resume(client, sync) - client[kResuming] = 0 - - if (client[kRunningIdx] > 256) { - client[kQueue].splice(0, client[kRunningIdx]) - client[kPendingIdx] -= client[kRunningIdx] - client[kRunningIdx] = 0 - } -} - -function _resume (client, sync) { - while (true) { - if (client.destroyed) { - assert(client[kPending] === 0) - return - } - - if (client[kClosedResolve] && !client[kSize]) { - client[kClosedResolve]() - client[kClosedResolve] = null - return - } - - const socket = client[kSocket] - - if (socket && !socket.destroyed && socket.alpnProtocol !== 'h2') { - if (client[kSize] === 0) { - if (!socket[kNoRef] && socket.unref) { - socket.unref() - socket[kNoRef] = true - } - } else if (socket[kNoRef] && socket.ref) { - socket.ref() - socket[kNoRef] = false - } - - if (client[kSize] === 0) { - if (socket[kParser].timeoutType !== TIMEOUT_IDLE) { - socket[kParser].setTimeout(client[kKeepAliveTimeoutValue], TIMEOUT_IDLE) - } - } else if (client[kRunning] > 0 && socket[kParser].statusCode < 200) { - if (socket[kParser].timeoutType !== TIMEOUT_HEADERS) { - const request = client[kQueue][client[kRunningIdx]] - const headersTimeout = request.headersTimeout != null - ? request.headersTimeout - : client[kHeadersTimeout] - socket[kParser].setTimeout(headersTimeout, TIMEOUT_HEADERS) - } - } - } - - if (client[kBusy]) { - client[kNeedDrain] = 2 - } else if (client[kNeedDrain] === 2) { - if (sync) { - client[kNeedDrain] = 1 - process.nextTick(emitDrain, client) - } else { - emitDrain(client) - } - continue - } - - if (client[kPending] === 0) { - return - } - - if (client[kRunning] >= (client[kPipelining] || 1)) { - return - } - - const request = client[kQueue][client[kPendingIdx]] - - if (client[kUrl].protocol === 'https:' && client[kServerName] !== request.servername) { - if (client[kRunning] > 0) { - return - } - - client[kServerName] = request.servername - - if (socket && socket.servername !== request.servername) { - util.destroy(socket, new InformationalError('servername changed')) - return - } - } - - if (client[kConnecting]) { - return - } - - if (!socket && !client[kHTTP2Session]) { - connect(client) - return - } - - if (socket.destroyed || socket[kWriting] || socket[kReset] || socket[kBlocking]) { - return - } - - if (client[kRunning] > 0 && !request.idempotent) { - // Non-idempotent request cannot be retried. - // Ensure that no other requests are inflight and - // could cause failure. - return - } - - if (client[kRunning] > 0 && (request.upgrade || request.method === 'CONNECT')) { - // Don't dispatch an upgrade until all preceding requests have completed. - // A misbehaving server might upgrade the connection before all pipelined - // request has completed. - return - } - - if (client[kRunning] > 0 && util.bodyLength(request.body) !== 0 && - (util.isStream(request.body) || util.isAsyncIterable(request.body))) { - // Request with stream or iterator body can error while other requests - // are inflight and indirectly error those as well. - // Ensure this doesn't happen by waiting for inflight - // to complete before dispatching. - - // Request with stream or iterator body cannot be retried. - // Ensure that no other requests are inflight and - // could cause failure. - return - } - - if (!request.aborted && write(client, request)) { - client[kPendingIdx]++ - } else { - client[kQueue].splice(client[kPendingIdx], 1) - } - } -} - -// https://www.rfc-editor.org/rfc/rfc7230#section-3.3.2 -function shouldSendContentLength (method) { - return method !== 'GET' && method !== 'HEAD' && method !== 'OPTIONS' && method !== 'TRACE' && method !== 'CONNECT' -} - -function write (client, request) { - if (client[kHTTPConnVersion] === 'h2') { - writeH2(client, client[kHTTP2Session], request) - return - } - - const { body, method, path, host, upgrade, headers, blocking, reset } = request - - // https://tools.ietf.org/html/rfc7231#section-4.3.1 - // https://tools.ietf.org/html/rfc7231#section-4.3.2 - // https://tools.ietf.org/html/rfc7231#section-4.3.5 - - // Sending a payload body on a request that does not - // expect it can cause undefined behavior on some - // servers and corrupt connection state. Do not - // re-use the connection for further requests. - - const expectsPayload = ( - method === 'PUT' || - method === 'POST' || - method === 'PATCH' - ) - - if (body && typeof body.read === 'function') { - // Try to read EOF in order to get length. - body.read(0) - } - - const bodyLength = util.bodyLength(body) - - let contentLength = bodyLength - - if (contentLength === null) { - contentLength = request.contentLength - } - - if (contentLength === 0 && !expectsPayload) { - // https://tools.ietf.org/html/rfc7230#section-3.3.2 - // A user agent SHOULD NOT send a Content-Length header field when - // the request message does not contain a payload body and the method - // semantics do not anticipate such a body. - - contentLength = null - } - - // https://github.com/nodejs/undici/issues/2046 - // A user agent may send a Content-Length header with 0 value, this should be allowed. - if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength !== null && request.contentLength !== contentLength) { - if (client[kStrictContentLength]) { - errorRequest(client, request, new RequestContentLengthMismatchError()) - return false - } - - process.emitWarning(new RequestContentLengthMismatchError()) - } - - const socket = client[kSocket] - - try { - request.onConnect((err) => { - if (request.aborted || request.completed) { - return - } - - errorRequest(client, request, err || new RequestAbortedError()) - - util.destroy(socket, new InformationalError('aborted')) - }) - } catch (err) { - errorRequest(client, request, err) - } - - if (request.aborted) { - return false - } - - if (method === 'HEAD') { - // https://github.com/mcollina/undici/issues/258 - // Close after a HEAD request to interop with misbehaving servers - // that may send a body in the response. - - socket[kReset] = true - } - - if (upgrade || method === 'CONNECT') { - // On CONNECT or upgrade, block pipeline from dispatching further - // requests on this connection. - - socket[kReset] = true - } - - if (reset != null) { - socket[kReset] = reset - } - - if (client[kMaxRequests] && socket[kCounter]++ >= client[kMaxRequests]) { - socket[kReset] = true - } - - if (blocking) { - socket[kBlocking] = true - } - - let header = `${method} ${path} HTTP/1.1\r\n` - - if (typeof host === 'string') { - header += `host: ${host}\r\n` - } else { - header += client[kHostHeader] - } - - if (upgrade) { - header += `connection: upgrade\r\nupgrade: ${upgrade}\r\n` - } else if (client[kPipelining] && !socket[kReset]) { - header += 'connection: keep-alive\r\n' - } else { - header += 'connection: close\r\n' - } - - if (headers) { - header += headers - } - - if (channels.sendHeaders.hasSubscribers) { - channels.sendHeaders.publish({ request, headers: header, socket }) - } - - /* istanbul ignore else: assertion */ - if (!body || bodyLength === 0) { - if (contentLength === 0) { - socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') - } else { - assert(contentLength === null, 'no body must not have content length') - socket.write(`${header}\r\n`, 'latin1') - } - request.onRequestSent() - } else if (util.isBuffer(body)) { - assert(contentLength === body.byteLength, 'buffer body must have content length') - - socket.cork() - socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') - socket.write(body) - socket.uncork() - request.onBodySent(body) - request.onRequestSent() - if (!expectsPayload) { - socket[kReset] = true - } - } else if (util.isBlobLike(body)) { - if (typeof body.stream === 'function') { - writeIterable({ body: body.stream(), client, request, socket, contentLength, header, expectsPayload }) - } else { - writeBlob({ body, client, request, socket, contentLength, header, expectsPayload }) - } - } else if (util.isStream(body)) { - writeStream({ body, client, request, socket, contentLength, header, expectsPayload }) - } else if (util.isIterable(body)) { - writeIterable({ body, client, request, socket, contentLength, header, expectsPayload }) - } else { - assert(false) - } - - return true -} - -function writeH2 (client, session, request) { - const { body, method, path, host, upgrade, expectContinue, signal, headers: reqHeaders } = request - - let headers - if (typeof reqHeaders === 'string') headers = Request[kHTTP2CopyHeaders](reqHeaders.trim()) - else headers = reqHeaders - - if (upgrade) { - errorRequest(client, request, new Error('Upgrade not supported for H2')) - return false - } - - try { - // TODO(HTTP/2): Should we call onConnect immediately or on stream ready event? - request.onConnect((err) => { - if (request.aborted || request.completed) { - return - } - - errorRequest(client, request, err || new RequestAbortedError()) - }) - } catch (err) { - errorRequest(client, request, err) - } - - if (request.aborted) { - return false - } - - /** @type {import('node:http2').ClientHttp2Stream} */ - let stream - const h2State = client[kHTTP2SessionState] - - headers[HTTP2_HEADER_AUTHORITY] = host || client[kHost] - headers[HTTP2_HEADER_METHOD] = method - - if (method === 'CONNECT') { - session.ref() - // we are already connected, streams are pending, first request - // will create a new stream. We trigger a request to create the stream and wait until - // `ready` event is triggered - // We disabled endStream to allow the user to write to the stream - stream = session.request(headers, { endStream: false, signal }) - - if (stream.id && !stream.pending) { - request.onUpgrade(null, null, stream) - ++h2State.openStreams - } else { - stream.once('ready', () => { - request.onUpgrade(null, null, stream) - ++h2State.openStreams - }) - } - - stream.once('close', () => { - h2State.openStreams -= 1 - // TODO(HTTP/2): unref only if current streams count is 0 - if (h2State.openStreams === 0) session.unref() - }) - - return true - } - - // https://tools.ietf.org/html/rfc7540#section-8.3 - // :path and :scheme headers must be omited when sending CONNECT - - headers[HTTP2_HEADER_PATH] = path - headers[HTTP2_HEADER_SCHEME] = 'https' - - // https://tools.ietf.org/html/rfc7231#section-4.3.1 - // https://tools.ietf.org/html/rfc7231#section-4.3.2 - // https://tools.ietf.org/html/rfc7231#section-4.3.5 - - // Sending a payload body on a request that does not - // expect it can cause undefined behavior on some - // servers and corrupt connection state. Do not - // re-use the connection for further requests. - - const expectsPayload = ( - method === 'PUT' || - method === 'POST' || - method === 'PATCH' - ) - - if (body && typeof body.read === 'function') { - // Try to read EOF in order to get length. - body.read(0) - } - - let contentLength = util.bodyLength(body) - - if (contentLength == null) { - contentLength = request.contentLength - } - - if (contentLength === 0 || !expectsPayload) { - // https://tools.ietf.org/html/rfc7230#section-3.3.2 - // A user agent SHOULD NOT send a Content-Length header field when - // the request message does not contain a payload body and the method - // semantics do not anticipate such a body. - - contentLength = null - } - - // https://github.com/nodejs/undici/issues/2046 - // A user agent may send a Content-Length header with 0 value, this should be allowed. - if (shouldSendContentLength(method) && contentLength > 0 && request.contentLength != null && request.contentLength !== contentLength) { - if (client[kStrictContentLength]) { - errorRequest(client, request, new RequestContentLengthMismatchError()) - return false - } - - process.emitWarning(new RequestContentLengthMismatchError()) - } - - if (contentLength != null) { - assert(body, 'no body must not have content length') - headers[HTTP2_HEADER_CONTENT_LENGTH] = `${contentLength}` - } - - session.ref() - - const shouldEndStream = method === 'GET' || method === 'HEAD' - if (expectContinue) { - headers[HTTP2_HEADER_EXPECT] = '100-continue' - stream = session.request(headers, { endStream: shouldEndStream, signal }) - - stream.once('continue', writeBodyH2) - } else { - stream = session.request(headers, { - endStream: shouldEndStream, - signal - }) - writeBodyH2() - } - - // Increment counter as we have new several streams open - ++h2State.openStreams - - stream.once('response', headers => { - const { [HTTP2_HEADER_STATUS]: statusCode, ...realHeaders } = headers - - if (request.onHeaders(Number(statusCode), realHeaders, stream.resume.bind(stream), '') === false) { - stream.pause() - } - }) - - stream.once('end', () => { - request.onComplete([]) - }) - - stream.on('data', (chunk) => { - if (request.onData(chunk) === false) { - stream.pause() - } - }) - - stream.once('close', () => { - h2State.openStreams -= 1 - // TODO(HTTP/2): unref only if current streams count is 0 - if (h2State.openStreams === 0) { - session.unref() - } - }) - - stream.once('error', function (err) { - if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { - h2State.streams -= 1 - util.destroy(stream, err) - } - }) - - stream.once('frameError', (type, code) => { - const err = new InformationalError(`HTTP/2: "frameError" received - type ${type}, code ${code}`) - errorRequest(client, request, err) - - if (client[kHTTP2Session] && !client[kHTTP2Session].destroyed && !this.closed && !this.destroyed) { - h2State.streams -= 1 - util.destroy(stream, err) - } - }) - - // stream.on('aborted', () => { - // // TODO(HTTP/2): Support aborted - // }) - - // stream.on('timeout', () => { - // // TODO(HTTP/2): Support timeout - // }) - - // stream.on('push', headers => { - // // TODO(HTTP/2): Suppor push - // }) - - // stream.on('trailers', headers => { - // // TODO(HTTP/2): Support trailers - // }) - - return true - - function writeBodyH2 () { - /* istanbul ignore else: assertion */ - if (!body) { - request.onRequestSent() - } else if (util.isBuffer(body)) { - assert(contentLength === body.byteLength, 'buffer body must have content length') - stream.cork() - stream.write(body) - stream.uncork() - stream.end() - request.onBodySent(body) - request.onRequestSent() - } else if (util.isBlobLike(body)) { - if (typeof body.stream === 'function') { - writeIterable({ - client, - request, - contentLength, - h2stream: stream, - expectsPayload, - body: body.stream(), - socket: client[kSocket], - header: '' - }) - } else { - writeBlob({ - body, - client, - request, - contentLength, - expectsPayload, - h2stream: stream, - header: '', - socket: client[kSocket] - }) - } - } else if (util.isStream(body)) { - writeStream({ - body, - client, - request, - contentLength, - expectsPayload, - socket: client[kSocket], - h2stream: stream, - header: '' - }) - } else if (util.isIterable(body)) { - writeIterable({ - body, - client, - request, - contentLength, - expectsPayload, - header: '', - h2stream: stream, - socket: client[kSocket] - }) - } else { - assert(false) - } - } -} - -function writeStream ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength !== 0 || client[kRunning] === 0, 'stream body cannot be pipelined') - - if (client[kHTTPConnVersion] === 'h2') { - // For HTTP/2, is enough to pipe the stream - const pipe = pipeline( - body, - h2stream, - (err) => { - if (err) { - util.destroy(body, err) - util.destroy(h2stream, err) - } else { - request.onRequestSent() - } - } - ) - - pipe.on('data', onPipeData) - pipe.once('end', () => { - pipe.removeListener('data', onPipeData) - util.destroy(pipe) - }) - - function onPipeData (chunk) { - request.onBodySent(chunk) - } - - return - } - - let finished = false - - const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) - - const onData = function (chunk) { - if (finished) { - return - } - - try { - if (!writer.write(chunk) && this.pause) { - this.pause() - } - } catch (err) { - util.destroy(this, err) - } - } - const onDrain = function () { - if (finished) { - return - } - - if (body.resume) { - body.resume() - } - } - const onAbort = function () { - if (finished) { - return - } - const err = new RequestAbortedError() - queueMicrotask(() => onFinished(err)) - } - const onFinished = function (err) { - if (finished) { - return - } - - finished = true - - assert(socket.destroyed || (socket[kWriting] && client[kRunning] <= 1)) - - socket - .off('drain', onDrain) - .off('error', onFinished) - - body - .removeListener('data', onData) - .removeListener('end', onFinished) - .removeListener('error', onFinished) - .removeListener('close', onAbort) - - if (!err) { - try { - writer.end() - } catch (er) { - err = er - } - } - - writer.destroy(err) - - if (err && (err.code !== 'UND_ERR_INFO' || err.message !== 'reset')) { - util.destroy(body, err) - } else { - util.destroy(body) - } - } - - body - .on('data', onData) - .on('end', onFinished) - .on('error', onFinished) - .on('close', onAbort) - - if (body.resume) { - body.resume() - } - - socket - .on('drain', onDrain) - .on('error', onFinished) -} - -async function writeBlob ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength === body.size, 'blob body must have content length') - - const isH2 = client[kHTTPConnVersion] === 'h2' - try { - if (contentLength != null && contentLength !== body.size) { - throw new RequestContentLengthMismatchError() - } - - const buffer = Buffer.from(await body.arrayBuffer()) - - if (isH2) { - h2stream.cork() - h2stream.write(buffer) - h2stream.uncork() - } else { - socket.cork() - socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') - socket.write(buffer) - socket.uncork() - } - - request.onBodySent(buffer) - request.onRequestSent() - - if (!expectsPayload) { - socket[kReset] = true - } - - resume(client) - } catch (err) { - util.destroy(isH2 ? h2stream : socket, err) - } -} - -async function writeIterable ({ h2stream, body, client, request, socket, contentLength, header, expectsPayload }) { - assert(contentLength !== 0 || client[kRunning] === 0, 'iterator body cannot be pipelined') - - let callback = null - function onDrain () { - if (callback) { - const cb = callback - callback = null - cb() - } - } - - const waitForDrain = () => new Promise((resolve, reject) => { - assert(callback === null) - - if (socket[kError]) { - reject(socket[kError]) - } else { - callback = resolve - } - }) - - if (client[kHTTPConnVersion] === 'h2') { - h2stream - .on('close', onDrain) - .on('drain', onDrain) - - try { - // It's up to the user to somehow abort the async iterable. - for await (const chunk of body) { - if (socket[kError]) { - throw socket[kError] - } - - const res = h2stream.write(chunk) - request.onBodySent(chunk) - if (!res) { - await waitForDrain() - } - } - } catch (err) { - h2stream.destroy(err) - } finally { - request.onRequestSent() - h2stream.end() - h2stream - .off('close', onDrain) - .off('drain', onDrain) - } - - return - } - - socket - .on('close', onDrain) - .on('drain', onDrain) - - const writer = new AsyncWriter({ socket, request, contentLength, client, expectsPayload, header }) - try { - // It's up to the user to somehow abort the async iterable. - for await (const chunk of body) { - if (socket[kError]) { - throw socket[kError] - } - - if (!writer.write(chunk)) { - await waitForDrain() - } - } - - writer.end() - } catch (err) { - writer.destroy(err) - } finally { - socket - .off('close', onDrain) - .off('drain', onDrain) - } -} - -class AsyncWriter { - constructor ({ socket, request, contentLength, client, expectsPayload, header }) { - this.socket = socket - this.request = request - this.contentLength = contentLength - this.client = client - this.bytesWritten = 0 - this.expectsPayload = expectsPayload - this.header = header - - socket[kWriting] = true - } - - write (chunk) { - const { socket, request, contentLength, client, bytesWritten, expectsPayload, header } = this - - if (socket[kError]) { - throw socket[kError] - } - - if (socket.destroyed) { - return false - } - - const len = Buffer.byteLength(chunk) - if (!len) { - return true - } - - // We should defer writing chunks. - if (contentLength !== null && bytesWritten + len > contentLength) { - if (client[kStrictContentLength]) { - throw new RequestContentLengthMismatchError() - } - - process.emitWarning(new RequestContentLengthMismatchError()) - } - - socket.cork() - - if (bytesWritten === 0) { - if (!expectsPayload) { - socket[kReset] = true - } - - if (contentLength === null) { - socket.write(`${header}transfer-encoding: chunked\r\n`, 'latin1') - } else { - socket.write(`${header}content-length: ${contentLength}\r\n\r\n`, 'latin1') - } - } - - if (contentLength === null) { - socket.write(`\r\n${len.toString(16)}\r\n`, 'latin1') - } - - this.bytesWritten += len - - const ret = socket.write(chunk) - - socket.uncork() - - request.onBodySent(chunk) - - if (!ret) { - if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { - // istanbul ignore else: only for jest - if (socket[kParser].timeout.refresh) { - socket[kParser].timeout.refresh() - } - } - } - - return ret - } - - end () { - const { socket, contentLength, client, bytesWritten, expectsPayload, header, request } = this - request.onRequestSent() - - socket[kWriting] = false - - if (socket[kError]) { - throw socket[kError] - } - - if (socket.destroyed) { - return - } - - if (bytesWritten === 0) { - if (expectsPayload) { - // https://tools.ietf.org/html/rfc7230#section-3.3.2 - // A user agent SHOULD send a Content-Length in a request message when - // no Transfer-Encoding is sent and the request method defines a meaning - // for an enclosed payload body. - - socket.write(`${header}content-length: 0\r\n\r\n`, 'latin1') - } else { - socket.write(`${header}\r\n`, 'latin1') - } - } else if (contentLength === null) { - socket.write('\r\n0\r\n\r\n', 'latin1') - } - - if (contentLength !== null && bytesWritten !== contentLength) { - if (client[kStrictContentLength]) { - throw new RequestContentLengthMismatchError() - } else { - process.emitWarning(new RequestContentLengthMismatchError()) - } - } - - if (socket[kParser].timeout && socket[kParser].timeoutType === TIMEOUT_HEADERS) { - // istanbul ignore else: only for jest - if (socket[kParser].timeout.refresh) { - socket[kParser].timeout.refresh() - } - } - - resume(client) - } - - destroy (err) { - const { socket, client } = this - - socket[kWriting] = false - - if (err) { - assert(client[kRunning] <= 1, 'pipeline should only contain this request') - util.destroy(socket, err) - } - } -} - -function errorRequest (client, request, err) { - try { - request.onError(err) - assert(request.aborted) - } catch (err) { - client.emit('error', err) - } -} - -module.exports = Client - - -/***/ }), - -/***/ 3194: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -/* istanbul ignore file: only for Node 12 */ - -const { kConnected, kSize } = __nccwpck_require__(6443) - -class CompatWeakRef { - constructor (value) { - this.value = value - } - - deref () { - return this.value[kConnected] === 0 && this.value[kSize] === 0 - ? undefined - : this.value - } -} - -class CompatFinalizer { - constructor (finalizer) { - this.finalizer = finalizer - } - - register (dispatcher, key) { - if (dispatcher.on) { - dispatcher.on('disconnect', () => { - if (dispatcher[kConnected] === 0 && dispatcher[kSize] === 0) { - this.finalizer(key) - } - }) - } - } -} - -module.exports = function () { - // FIXME: remove workaround when the Node bug is fixed - // https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 - if (process.env.NODE_V8_COVERAGE) { - return { - WeakRef: CompatWeakRef, - FinalizationRegistry: CompatFinalizer - } - } - return { - WeakRef: global.WeakRef || CompatWeakRef, - FinalizationRegistry: global.FinalizationRegistry || CompatFinalizer - } -} - - -/***/ }), - -/***/ 9237: -/***/ ((module) => { - - - -// https://wicg.github.io/cookie-store/#cookie-maximum-attribute-value-size -const maxAttributeValueSize = 1024 - -// https://wicg.github.io/cookie-store/#cookie-maximum-name-value-pair-size -const maxNameValuePairSize = 4096 - -module.exports = { - maxAttributeValueSize, - maxNameValuePairSize -} - - -/***/ }), - -/***/ 3168: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { parseSetCookie } = __nccwpck_require__(8915) -const { stringify } = __nccwpck_require__(3834) -const { webidl } = __nccwpck_require__(4222) -const { Headers } = __nccwpck_require__(6349) - -/** - * @typedef {Object} Cookie - * @property {string} name - * @property {string} value - * @property {Date|number|undefined} expires - * @property {number|undefined} maxAge - * @property {string|undefined} domain - * @property {string|undefined} path - * @property {boolean|undefined} secure - * @property {boolean|undefined} httpOnly - * @property {'Strict'|'Lax'|'None'} sameSite - * @property {string[]} unparsed - */ - -/** - * @param {Headers} headers - * @returns {Record} - */ -function getCookies (headers) { - webidl.argumentLengthCheck(arguments, 1, { header: 'getCookies' }) - - webidl.brandCheck(headers, Headers, { strict: false }) - - const cookie = headers.get('cookie') - const out = {} - - if (!cookie) { - return out - } - - for (const piece of cookie.split(';')) { - const [name, ...value] = piece.split('=') - - out[name.trim()] = value.join('=') - } - - return out -} - -/** - * @param {Headers} headers - * @param {string} name - * @param {{ path?: string, domain?: string }|undefined} attributes - * @returns {void} - */ -function deleteCookie (headers, name, attributes) { - webidl.argumentLengthCheck(arguments, 2, { header: 'deleteCookie' }) - - webidl.brandCheck(headers, Headers, { strict: false }) - - name = webidl.converters.DOMString(name) - attributes = webidl.converters.DeleteCookieAttributes(attributes) - - // Matches behavior of - // https://github.com/denoland/deno_std/blob/63827b16330b82489a04614027c33b7904e08be5/http/cookie.ts#L278 - setCookie(headers, { - name, - value: '', - expires: new Date(0), - ...attributes - }) -} - -/** - * @param {Headers} headers - * @returns {Cookie[]} - */ -function getSetCookies (headers) { - webidl.argumentLengthCheck(arguments, 1, { header: 'getSetCookies' }) - - webidl.brandCheck(headers, Headers, { strict: false }) - - const cookies = headers.getSetCookie() - - if (!cookies) { - return [] - } - - return cookies.map((pair) => parseSetCookie(pair)) -} - -/** - * @param {Headers} headers - * @param {Cookie} cookie - * @returns {void} - */ -function setCookie (headers, cookie) { - webidl.argumentLengthCheck(arguments, 2, { header: 'setCookie' }) - - webidl.brandCheck(headers, Headers, { strict: false }) - - cookie = webidl.converters.Cookie(cookie) - - const str = stringify(cookie) - - if (str) { - headers.append('Set-Cookie', stringify(cookie)) - } -} - -webidl.converters.DeleteCookieAttributes = webidl.dictionaryConverter([ - { - converter: webidl.nullableConverter(webidl.converters.DOMString), - key: 'path', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters.DOMString), - key: 'domain', - defaultValue: null - } -]) - -webidl.converters.Cookie = webidl.dictionaryConverter([ - { - converter: webidl.converters.DOMString, - key: 'name' - }, - { - converter: webidl.converters.DOMString, - key: 'value' - }, - { - converter: webidl.nullableConverter((value) => { - if (typeof value === 'number') { - return webidl.converters['unsigned long long'](value) - } - - return new Date(value) - }), - key: 'expires', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters['long long']), - key: 'maxAge', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters.DOMString), - key: 'domain', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters.DOMString), - key: 'path', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters.boolean), - key: 'secure', - defaultValue: null - }, - { - converter: webidl.nullableConverter(webidl.converters.boolean), - key: 'httpOnly', - defaultValue: null - }, - { - converter: webidl.converters.USVString, - key: 'sameSite', - allowedValues: ['Strict', 'Lax', 'None'] - }, - { - converter: webidl.sequenceConverter(webidl.converters.DOMString), - key: 'unparsed', - defaultValue: [] - } -]) - -module.exports = { - getCookies, - deleteCookie, - getSetCookies, - setCookie -} - - -/***/ }), - -/***/ 8915: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { maxNameValuePairSize, maxAttributeValueSize } = __nccwpck_require__(9237) -const { isCTLExcludingHtab } = __nccwpck_require__(3834) -const { collectASequenceOfCodePointsFast } = __nccwpck_require__(4322) -const assert = __nccwpck_require__(2613) - -/** - * @description Parses the field-value attributes of a set-cookie header string. - * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 - * @param {string} header - * @returns if the header is invalid, null will be returned - */ -function parseSetCookie (header) { - // 1. If the set-cookie-string contains a %x00-08 / %x0A-1F / %x7F - // character (CTL characters excluding HTAB): Abort these steps and - // ignore the set-cookie-string entirely. - if (isCTLExcludingHtab(header)) { - return null - } - - let nameValuePair = '' - let unparsedAttributes = '' - let name = '' - let value = '' - - // 2. If the set-cookie-string contains a %x3B (";") character: - if (header.includes(';')) { - // 1. The name-value-pair string consists of the characters up to, - // but not including, the first %x3B (";"), and the unparsed- - // attributes consist of the remainder of the set-cookie-string - // (including the %x3B (";") in question). - const position = { position: 0 } - - nameValuePair = collectASequenceOfCodePointsFast(';', header, position) - unparsedAttributes = header.slice(position.position) - } else { - // Otherwise: - - // 1. The name-value-pair string consists of all the characters - // contained in the set-cookie-string, and the unparsed- - // attributes is the empty string. - nameValuePair = header - } - - // 3. If the name-value-pair string lacks a %x3D ("=") character, then - // the name string is empty, and the value string is the value of - // name-value-pair. - if (!nameValuePair.includes('=')) { - value = nameValuePair - } else { - // Otherwise, the name string consists of the characters up to, but - // not including, the first %x3D ("=") character, and the (possibly - // empty) value string consists of the characters after the first - // %x3D ("=") character. - const position = { position: 0 } - name = collectASequenceOfCodePointsFast( - '=', - nameValuePair, - position - ) - value = nameValuePair.slice(position.position + 1) - } - - // 4. Remove any leading or trailing WSP characters from the name - // string and the value string. - name = name.trim() - value = value.trim() - - // 5. If the sum of the lengths of the name string and the value string - // is more than 4096 octets, abort these steps and ignore the set- - // cookie-string entirely. - if (name.length + value.length > maxNameValuePairSize) { - return null - } - - // 6. The cookie-name is the name string, and the cookie-value is the - // value string. - return { - name, value, ...parseUnparsedAttributes(unparsedAttributes) - } -} - -/** - * Parses the remaining attributes of a set-cookie header - * @see https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4 - * @param {string} unparsedAttributes - * @param {[Object.]={}} cookieAttributeList - */ -function parseUnparsedAttributes (unparsedAttributes, cookieAttributeList = {}) { - // 1. If the unparsed-attributes string is empty, skip the rest of - // these steps. - if (unparsedAttributes.length === 0) { - return cookieAttributeList - } - - // 2. Discard the first character of the unparsed-attributes (which - // will be a %x3B (";") character). - assert(unparsedAttributes[0] === ';') - unparsedAttributes = unparsedAttributes.slice(1) - - let cookieAv = '' - - // 3. If the remaining unparsed-attributes contains a %x3B (";") - // character: - if (unparsedAttributes.includes(';')) { - // 1. Consume the characters of the unparsed-attributes up to, but - // not including, the first %x3B (";") character. - cookieAv = collectASequenceOfCodePointsFast( - ';', - unparsedAttributes, - { position: 0 } - ) - unparsedAttributes = unparsedAttributes.slice(cookieAv.length) - } else { - // Otherwise: - - // 1. Consume the remainder of the unparsed-attributes. - cookieAv = unparsedAttributes - unparsedAttributes = '' - } - - // Let the cookie-av string be the characters consumed in this step. - - let attributeName = '' - let attributeValue = '' - - // 4. If the cookie-av string contains a %x3D ("=") character: - if (cookieAv.includes('=')) { - // 1. The (possibly empty) attribute-name string consists of the - // characters up to, but not including, the first %x3D ("=") - // character, and the (possibly empty) attribute-value string - // consists of the characters after the first %x3D ("=") - // character. - const position = { position: 0 } - - attributeName = collectASequenceOfCodePointsFast( - '=', - cookieAv, - position - ) - attributeValue = cookieAv.slice(position.position + 1) - } else { - // Otherwise: - - // 1. The attribute-name string consists of the entire cookie-av - // string, and the attribute-value string is empty. - attributeName = cookieAv - } - - // 5. Remove any leading or trailing WSP characters from the attribute- - // name string and the attribute-value string. - attributeName = attributeName.trim() - attributeValue = attributeValue.trim() - - // 6. If the attribute-value is longer than 1024 octets, ignore the - // cookie-av string and return to Step 1 of this algorithm. - if (attributeValue.length > maxAttributeValueSize) { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) - } - - // 7. Process the attribute-name and attribute-value according to the - // requirements in the following subsections. (Notice that - // attributes with unrecognized attribute-names are ignored.) - const attributeNameLowercase = attributeName.toLowerCase() - - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.1 - // If the attribute-name case-insensitively matches the string - // "Expires", the user agent MUST process the cookie-av as follows. - if (attributeNameLowercase === 'expires') { - // 1. Let the expiry-time be the result of parsing the attribute-value - // as cookie-date (see Section 5.1.1). - const expiryTime = new Date(attributeValue) - - // 2. If the attribute-value failed to parse as a cookie date, ignore - // the cookie-av. - - cookieAttributeList.expires = expiryTime - } else if (attributeNameLowercase === 'max-age') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.2 - // If the attribute-name case-insensitively matches the string "Max- - // Age", the user agent MUST process the cookie-av as follows. - - // 1. If the first character of the attribute-value is not a DIGIT or a - // "-" character, ignore the cookie-av. - const charCode = attributeValue.charCodeAt(0) - - if ((charCode < 48 || charCode > 57) && attributeValue[0] !== '-') { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) - } - - // 2. If the remainder of attribute-value contains a non-DIGIT - // character, ignore the cookie-av. - if (!/^\d+$/.test(attributeValue)) { - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) - } - - // 3. Let delta-seconds be the attribute-value converted to an integer. - const deltaSeconds = Number(attributeValue) - - // 4. Let cookie-age-limit be the maximum age of the cookie (which - // SHOULD be 400 days or less, see Section 4.1.2.2). - - // 5. Set delta-seconds to the smaller of its present value and cookie- - // age-limit. - // deltaSeconds = Math.min(deltaSeconds * 1000, maxExpiresMs) - - // 6. If delta-seconds is less than or equal to zero (0), let expiry- - // time be the earliest representable date and time. Otherwise, let - // the expiry-time be the current date and time plus delta-seconds - // seconds. - // const expiryTime = deltaSeconds <= 0 ? Date.now() : Date.now() + deltaSeconds - - // 7. Append an attribute to the cookie-attribute-list with an - // attribute-name of Max-Age and an attribute-value of expiry-time. - cookieAttributeList.maxAge = deltaSeconds - } else if (attributeNameLowercase === 'domain') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.3 - // If the attribute-name case-insensitively matches the string "Domain", - // the user agent MUST process the cookie-av as follows. - - // 1. Let cookie-domain be the attribute-value. - let cookieDomain = attributeValue - - // 2. If cookie-domain starts with %x2E ("."), let cookie-domain be - // cookie-domain without its leading %x2E ("."). - if (cookieDomain[0] === '.') { - cookieDomain = cookieDomain.slice(1) - } - - // 3. Convert the cookie-domain to lower case. - cookieDomain = cookieDomain.toLowerCase() - - // 4. Append an attribute to the cookie-attribute-list with an - // attribute-name of Domain and an attribute-value of cookie-domain. - cookieAttributeList.domain = cookieDomain - } else if (attributeNameLowercase === 'path') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.4 - // If the attribute-name case-insensitively matches the string "Path", - // the user agent MUST process the cookie-av as follows. - - // 1. If the attribute-value is empty or if the first character of the - // attribute-value is not %x2F ("/"): - let cookiePath = '' - if (attributeValue.length === 0 || attributeValue[0] !== '/') { - // 1. Let cookie-path be the default-path. - cookiePath = '/' - } else { - // Otherwise: - - // 1. Let cookie-path be the attribute-value. - cookiePath = attributeValue - } - - // 2. Append an attribute to the cookie-attribute-list with an - // attribute-name of Path and an attribute-value of cookie-path. - cookieAttributeList.path = cookiePath - } else if (attributeNameLowercase === 'secure') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.5 - // If the attribute-name case-insensitively matches the string "Secure", - // the user agent MUST append an attribute to the cookie-attribute-list - // with an attribute-name of Secure and an empty attribute-value. - - cookieAttributeList.secure = true - } else if (attributeNameLowercase === 'httponly') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.6 - // If the attribute-name case-insensitively matches the string - // "HttpOnly", the user agent MUST append an attribute to the cookie- - // attribute-list with an attribute-name of HttpOnly and an empty - // attribute-value. - - cookieAttributeList.httpOnly = true - } else if (attributeNameLowercase === 'samesite') { - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-rfc6265bis#section-5.4.7 - // If the attribute-name case-insensitively matches the string - // "SameSite", the user agent MUST process the cookie-av as follows: - - // 1. Let enforcement be "Default". - let enforcement = 'Default' - - const attributeValueLowercase = attributeValue.toLowerCase() - // 2. If cookie-av's attribute-value is a case-insensitive match for - // "None", set enforcement to "None". - if (attributeValueLowercase.includes('none')) { - enforcement = 'None' - } - - // 3. If cookie-av's attribute-value is a case-insensitive match for - // "Strict", set enforcement to "Strict". - if (attributeValueLowercase.includes('strict')) { - enforcement = 'Strict' - } - - // 4. If cookie-av's attribute-value is a case-insensitive match for - // "Lax", set enforcement to "Lax". - if (attributeValueLowercase.includes('lax')) { - enforcement = 'Lax' - } - - // 5. Append an attribute to the cookie-attribute-list with an - // attribute-name of "SameSite" and an attribute-value of - // enforcement. - cookieAttributeList.sameSite = enforcement - } else { - cookieAttributeList.unparsed ??= [] - - cookieAttributeList.unparsed.push(`${attributeName}=${attributeValue}`) - } - - // 8. Return to Step 1 of this algorithm. - return parseUnparsedAttributes(unparsedAttributes, cookieAttributeList) -} - -module.exports = { - parseSetCookie, - parseUnparsedAttributes -} - - -/***/ }), - -/***/ 3834: -/***/ ((module) => { - - - -/** - * @param {string} value - * @returns {boolean} - */ -function isCTLExcludingHtab (value) { - if (value.length === 0) { - return false - } - - for (const char of value) { - const code = char.charCodeAt(0) - - if ( - (code >= 0x00 || code <= 0x08) || - (code >= 0x0A || code <= 0x1F) || - code === 0x7F - ) { - return false - } - } -} - -/** - CHAR = - token = 1* - separators = "(" | ")" | "<" | ">" | "@" - | "," | ";" | ":" | "\" | <"> - | "/" | "[" | "]" | "?" | "=" - | "{" | "}" | SP | HT - * @param {string} name - */ -function validateCookieName (name) { - for (const char of name) { - const code = char.charCodeAt(0) - - if ( - (code <= 0x20 || code > 0x7F) || - char === '(' || - char === ')' || - char === '>' || - char === '<' || - char === '@' || - char === ',' || - char === ';' || - char === ':' || - char === '\\' || - char === '"' || - char === '/' || - char === '[' || - char === ']' || - char === '?' || - char === '=' || - char === '{' || - char === '}' - ) { - throw new Error('Invalid cookie name') - } - } -} - -/** - cookie-value = *cookie-octet / ( DQUOTE *cookie-octet DQUOTE ) - cookie-octet = %x21 / %x23-2B / %x2D-3A / %x3C-5B / %x5D-7E - ; US-ASCII characters excluding CTLs, - ; whitespace DQUOTE, comma, semicolon, - ; and backslash - * @param {string} value - */ -function validateCookieValue (value) { - for (const char of value) { - const code = char.charCodeAt(0) - - if ( - code < 0x21 || // exclude CTLs (0-31) - code === 0x22 || - code === 0x2C || - code === 0x3B || - code === 0x5C || - code > 0x7E // non-ascii - ) { - throw new Error('Invalid header value') - } - } -} - -/** - * path-value = - * @param {string} path - */ -function validateCookiePath (path) { - for (const char of path) { - const code = char.charCodeAt(0) - - if (code < 0x21 || char === ';') { - throw new Error('Invalid cookie path') - } - } -} - -/** - * I have no idea why these values aren't allowed to be honest, - * but Deno tests these. - Khafra - * @param {string} domain - */ -function validateCookieDomain (domain) { - if ( - domain.startsWith('-') || - domain.endsWith('.') || - domain.endsWith('-') - ) { - throw new Error('Invalid cookie domain') - } -} - -/** - * @see https://www.rfc-editor.org/rfc/rfc7231#section-7.1.1.1 - * @param {number|Date} date - IMF-fixdate = day-name "," SP date1 SP time-of-day SP GMT - ; fixed length/zone/capitalization subset of the format - ; see Section 3.3 of [RFC5322] - - day-name = %x4D.6F.6E ; "Mon", case-sensitive - / %x54.75.65 ; "Tue", case-sensitive - / %x57.65.64 ; "Wed", case-sensitive - / %x54.68.75 ; "Thu", case-sensitive - / %x46.72.69 ; "Fri", case-sensitive - / %x53.61.74 ; "Sat", case-sensitive - / %x53.75.6E ; "Sun", case-sensitive - date1 = day SP month SP year - ; e.g., 02 Jun 1982 - - day = 2DIGIT - month = %x4A.61.6E ; "Jan", case-sensitive - / %x46.65.62 ; "Feb", case-sensitive - / %x4D.61.72 ; "Mar", case-sensitive - / %x41.70.72 ; "Apr", case-sensitive - / %x4D.61.79 ; "May", case-sensitive - / %x4A.75.6E ; "Jun", case-sensitive - / %x4A.75.6C ; "Jul", case-sensitive - / %x41.75.67 ; "Aug", case-sensitive - / %x53.65.70 ; "Sep", case-sensitive - / %x4F.63.74 ; "Oct", case-sensitive - / %x4E.6F.76 ; "Nov", case-sensitive - / %x44.65.63 ; "Dec", case-sensitive - year = 4DIGIT - - GMT = %x47.4D.54 ; "GMT", case-sensitive - - time-of-day = hour ":" minute ":" second - ; 00:00:00 - 23:59:60 (leap second) - - hour = 2DIGIT - minute = 2DIGIT - second = 2DIGIT - */ -function toIMFDate (date) { - if (typeof date === 'number') { - date = new Date(date) - } - - const days = [ - 'Sun', 'Mon', 'Tue', 'Wed', - 'Thu', 'Fri', 'Sat' - ] - - const months = [ - 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec' - ] - - const dayName = days[date.getUTCDay()] - const day = date.getUTCDate().toString().padStart(2, '0') - const month = months[date.getUTCMonth()] - const year = date.getUTCFullYear() - const hour = date.getUTCHours().toString().padStart(2, '0') - const minute = date.getUTCMinutes().toString().padStart(2, '0') - const second = date.getUTCSeconds().toString().padStart(2, '0') - - return `${dayName}, ${day} ${month} ${year} ${hour}:${minute}:${second} GMT` -} - -/** - max-age-av = "Max-Age=" non-zero-digit *DIGIT - ; In practice, both expires-av and max-age-av - ; are limited to dates representable by the - ; user agent. - * @param {number} maxAge - */ -function validateCookieMaxAge (maxAge) { - if (maxAge < 0) { - throw new Error('Invalid cookie max-age') - } -} - -/** - * @see https://www.rfc-editor.org/rfc/rfc6265#section-4.1.1 - * @param {import('./index').Cookie} cookie - */ -function stringify (cookie) { - if (cookie.name.length === 0) { - return null - } - - validateCookieName(cookie.name) - validateCookieValue(cookie.value) - - const out = [`${cookie.name}=${cookie.value}`] - - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.1 - // https://datatracker.ietf.org/doc/html/draft-ietf-httpbis-cookie-prefixes-00#section-3.2 - if (cookie.name.startsWith('__Secure-')) { - cookie.secure = true - } - - if (cookie.name.startsWith('__Host-')) { - cookie.secure = true - cookie.domain = null - cookie.path = '/' - } - - if (cookie.secure) { - out.push('Secure') - } - - if (cookie.httpOnly) { - out.push('HttpOnly') - } - - if (typeof cookie.maxAge === 'number') { - validateCookieMaxAge(cookie.maxAge) - out.push(`Max-Age=${cookie.maxAge}`) - } - - if (cookie.domain) { - validateCookieDomain(cookie.domain) - out.push(`Domain=${cookie.domain}`) - } - - if (cookie.path) { - validateCookiePath(cookie.path) - out.push(`Path=${cookie.path}`) - } - - if (cookie.expires && cookie.expires.toString() !== 'Invalid Date') { - out.push(`Expires=${toIMFDate(cookie.expires)}`) - } - - if (cookie.sameSite) { - out.push(`SameSite=${cookie.sameSite}`) - } - - for (const part of cookie.unparsed) { - if (!part.includes('=')) { - throw new Error('Invalid unparsed') - } - - const [key, ...value] = part.split('=') - - out.push(`${key.trim()}=${value.join('=')}`) - } - - return out.join('; ') -} - -module.exports = { - isCTLExcludingHtab, - validateCookieName, - validateCookiePath, - validateCookieValue, - toIMFDate, - stringify -} - - -/***/ }), - -/***/ 9136: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const net = __nccwpck_require__(9278) -const assert = __nccwpck_require__(2613) -const util = __nccwpck_require__(3440) -const { InvalidArgumentError, ConnectTimeoutError } = __nccwpck_require__(8707) - -let tls // include tls conditionally since it is not always available - -// TODO: session re-use does not wait for the first -// connection to resolve the session and might therefore -// resolve the same servername multiple times even when -// re-use is enabled. - -let SessionCache -// FIXME: remove workaround when the Node bug is fixed -// https://github.com/nodejs/node/issues/49344#issuecomment-1741776308 -if (global.FinalizationRegistry && !process.env.NODE_V8_COVERAGE) { - SessionCache = class WeakSessionCache { - constructor (maxCachedSessions) { - this._maxCachedSessions = maxCachedSessions - this._sessionCache = new Map() - this._sessionRegistry = new global.FinalizationRegistry((key) => { - if (this._sessionCache.size < this._maxCachedSessions) { - return - } - - const ref = this._sessionCache.get(key) - if (ref !== undefined && ref.deref() === undefined) { - this._sessionCache.delete(key) - } - }) - } - - get (sessionKey) { - const ref = this._sessionCache.get(sessionKey) - return ref ? ref.deref() : null - } - - set (sessionKey, session) { - if (this._maxCachedSessions === 0) { - return - } - - this._sessionCache.set(sessionKey, new WeakRef(session)) - this._sessionRegistry.register(session, sessionKey) - } - } -} else { - SessionCache = class SimpleSessionCache { - constructor (maxCachedSessions) { - this._maxCachedSessions = maxCachedSessions - this._sessionCache = new Map() - } - - get (sessionKey) { - return this._sessionCache.get(sessionKey) - } - - set (sessionKey, session) { - if (this._maxCachedSessions === 0) { - return - } - - if (this._sessionCache.size >= this._maxCachedSessions) { - // remove the oldest session - const { value: oldestKey } = this._sessionCache.keys().next() - this._sessionCache.delete(oldestKey) - } - - this._sessionCache.set(sessionKey, session) - } - } -} - -function buildConnector ({ allowH2, maxCachedSessions, socketPath, timeout, ...opts }) { - if (maxCachedSessions != null && (!Number.isInteger(maxCachedSessions) || maxCachedSessions < 0)) { - throw new InvalidArgumentError('maxCachedSessions must be a positive integer or zero') - } - - const options = { path: socketPath, ...opts } - const sessionCache = new SessionCache(maxCachedSessions == null ? 100 : maxCachedSessions) - timeout = timeout == null ? 10e3 : timeout - allowH2 = allowH2 != null ? allowH2 : false - return function connect ({ hostname, host, protocol, port, servername, localAddress, httpSocket }, callback) { - let socket - if (protocol === 'https:') { - if (!tls) { - tls = __nccwpck_require__(4756) - } - servername = servername || options.servername || util.getServerName(host) || null - - const sessionKey = servername || hostname - const session = sessionCache.get(sessionKey) || null - - assert(sessionKey) - - socket = tls.connect({ - highWaterMark: 16384, // TLS in node can't have bigger HWM anyway... - ...options, - servername, - session, - localAddress, - // TODO(HTTP/2): Add support for h2c - ALPNProtocols: allowH2 ? ['http/1.1', 'h2'] : ['http/1.1'], - socket: httpSocket, // upgrade socket connection - port: port || 443, - host: hostname - }) - - socket - .on('session', function (session) { - // TODO (fix): Can a session become invalid once established? Don't think so? - sessionCache.set(sessionKey, session) - }) - } else { - assert(!httpSocket, 'httpSocket can only be sent on TLS update') - socket = net.connect({ - highWaterMark: 64 * 1024, // Same as nodejs fs streams. - ...options, - localAddress, - port: port || 80, - host: hostname - }) - } - - // Set TCP keep alive options on the socket here instead of in connect() for the case of assigning the socket - if (options.keepAlive == null || options.keepAlive) { - const keepAliveInitialDelay = options.keepAliveInitialDelay === undefined ? 60e3 : options.keepAliveInitialDelay - socket.setKeepAlive(true, keepAliveInitialDelay) - } - - const cancelTimeout = setupTimeout(() => onConnectTimeout(socket), timeout) - - socket - .setNoDelay(true) - .once(protocol === 'https:' ? 'secureConnect' : 'connect', function () { - cancelTimeout() - - if (callback) { - const cb = callback - callback = null - cb(null, this) - } - }) - .on('error', function (err) { - cancelTimeout() - - if (callback) { - const cb = callback - callback = null - cb(err) - } - }) - - return socket - } -} - -function setupTimeout (onConnectTimeout, timeout) { - if (!timeout) { - return () => {} - } - - let s1 = null - let s2 = null - const timeoutId = setTimeout(() => { - // setImmediate is added to make sure that we priotorise socket error events over timeouts - s1 = setImmediate(() => { - if (process.platform === 'win32') { - // Windows needs an extra setImmediate probably due to implementation differences in the socket logic - s2 = setImmediate(() => onConnectTimeout()) - } else { - onConnectTimeout() - } - }) - }, timeout) - return () => { - clearTimeout(timeoutId) - clearImmediate(s1) - clearImmediate(s2) - } -} - -function onConnectTimeout (socket) { - util.destroy(socket, new ConnectTimeoutError()) -} - -module.exports = buildConnector - - -/***/ }), - -/***/ 735: -/***/ ((module) => { - - - -/** @type {Record} */ -const headerNameLowerCasedRecord = {} - -// https://developer.mozilla.org/docs/Web/HTTP/Headers -const wellknownHeaderNames = [ - 'Accept', - 'Accept-Encoding', - 'Accept-Language', - 'Accept-Ranges', - 'Access-Control-Allow-Credentials', - 'Access-Control-Allow-Headers', - 'Access-Control-Allow-Methods', - 'Access-Control-Allow-Origin', - 'Access-Control-Expose-Headers', - 'Access-Control-Max-Age', - 'Access-Control-Request-Headers', - 'Access-Control-Request-Method', - 'Age', - 'Allow', - 'Alt-Svc', - 'Alt-Used', - 'Authorization', - 'Cache-Control', - 'Clear-Site-Data', - 'Connection', - 'Content-Disposition', - 'Content-Encoding', - 'Content-Language', - 'Content-Length', - 'Content-Location', - 'Content-Range', - 'Content-Security-Policy', - 'Content-Security-Policy-Report-Only', - 'Content-Type', - 'Cookie', - 'Cross-Origin-Embedder-Policy', - 'Cross-Origin-Opener-Policy', - 'Cross-Origin-Resource-Policy', - 'Date', - 'Device-Memory', - 'Downlink', - 'ECT', - 'ETag', - 'Expect', - 'Expect-CT', - 'Expires', - 'Forwarded', - 'From', - 'Host', - 'If-Match', - 'If-Modified-Since', - 'If-None-Match', - 'If-Range', - 'If-Unmodified-Since', - 'Keep-Alive', - 'Last-Modified', - 'Link', - 'Location', - 'Max-Forwards', - 'Origin', - 'Permissions-Policy', - 'Pragma', - 'Proxy-Authenticate', - 'Proxy-Authorization', - 'RTT', - 'Range', - 'Referer', - 'Referrer-Policy', - 'Refresh', - 'Retry-After', - 'Sec-WebSocket-Accept', - 'Sec-WebSocket-Extensions', - 'Sec-WebSocket-Key', - 'Sec-WebSocket-Protocol', - 'Sec-WebSocket-Version', - 'Server', - 'Server-Timing', - 'Service-Worker-Allowed', - 'Service-Worker-Navigation-Preload', - 'Set-Cookie', - 'SourceMap', - 'Strict-Transport-Security', - 'Supports-Loading-Mode', - 'TE', - 'Timing-Allow-Origin', - 'Trailer', - 'Transfer-Encoding', - 'Upgrade', - 'Upgrade-Insecure-Requests', - 'User-Agent', - 'Vary', - 'Via', - 'WWW-Authenticate', - 'X-Content-Type-Options', - 'X-DNS-Prefetch-Control', - 'X-Frame-Options', - 'X-Permitted-Cross-Domain-Policies', - 'X-Powered-By', - 'X-Requested-With', - 'X-XSS-Protection' -] - -for (let i = 0; i < wellknownHeaderNames.length; ++i) { - const key = wellknownHeaderNames[i] - const lowerCasedKey = key.toLowerCase() - headerNameLowerCasedRecord[key] = headerNameLowerCasedRecord[lowerCasedKey] = - lowerCasedKey -} - -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(headerNameLowerCasedRecord, null) - -module.exports = { - wellknownHeaderNames, - headerNameLowerCasedRecord -} - - -/***/ }), - -/***/ 8707: -/***/ ((module) => { - - - -class UndiciError extends Error { - constructor (message) { - super(message) - this.name = 'UndiciError' - this.code = 'UND_ERR' - } -} - -class ConnectTimeoutError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, ConnectTimeoutError) - this.name = 'ConnectTimeoutError' - this.message = message || 'Connect Timeout Error' - this.code = 'UND_ERR_CONNECT_TIMEOUT' - } -} - -class HeadersTimeoutError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, HeadersTimeoutError) - this.name = 'HeadersTimeoutError' - this.message = message || 'Headers Timeout Error' - this.code = 'UND_ERR_HEADERS_TIMEOUT' - } -} - -class HeadersOverflowError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, HeadersOverflowError) - this.name = 'HeadersOverflowError' - this.message = message || 'Headers Overflow Error' - this.code = 'UND_ERR_HEADERS_OVERFLOW' - } -} - -class BodyTimeoutError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, BodyTimeoutError) - this.name = 'BodyTimeoutError' - this.message = message || 'Body Timeout Error' - this.code = 'UND_ERR_BODY_TIMEOUT' - } -} - -class ResponseStatusCodeError extends UndiciError { - constructor (message, statusCode, headers, body) { - super(message) - Error.captureStackTrace(this, ResponseStatusCodeError) - this.name = 'ResponseStatusCodeError' - this.message = message || 'Response Status Code Error' - this.code = 'UND_ERR_RESPONSE_STATUS_CODE' - this.body = body - this.status = statusCode - this.statusCode = statusCode - this.headers = headers - } -} - -class InvalidArgumentError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, InvalidArgumentError) - this.name = 'InvalidArgumentError' - this.message = message || 'Invalid Argument Error' - this.code = 'UND_ERR_INVALID_ARG' - } -} - -class InvalidReturnValueError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, InvalidReturnValueError) - this.name = 'InvalidReturnValueError' - this.message = message || 'Invalid Return Value Error' - this.code = 'UND_ERR_INVALID_RETURN_VALUE' - } -} - -class RequestAbortedError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, RequestAbortedError) - this.name = 'AbortError' - this.message = message || 'Request aborted' - this.code = 'UND_ERR_ABORTED' - } -} - -class InformationalError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, InformationalError) - this.name = 'InformationalError' - this.message = message || 'Request information' - this.code = 'UND_ERR_INFO' - } -} - -class RequestContentLengthMismatchError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, RequestContentLengthMismatchError) - this.name = 'RequestContentLengthMismatchError' - this.message = message || 'Request body length does not match content-length header' - this.code = 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH' - } -} - -class ResponseContentLengthMismatchError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, ResponseContentLengthMismatchError) - this.name = 'ResponseContentLengthMismatchError' - this.message = message || 'Response body length does not match content-length header' - this.code = 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH' - } -} - -class ClientDestroyedError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, ClientDestroyedError) - this.name = 'ClientDestroyedError' - this.message = message || 'The client is destroyed' - this.code = 'UND_ERR_DESTROYED' - } -} - -class ClientClosedError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, ClientClosedError) - this.name = 'ClientClosedError' - this.message = message || 'The client is closed' - this.code = 'UND_ERR_CLOSED' - } -} - -class SocketError extends UndiciError { - constructor (message, socket) { - super(message) - Error.captureStackTrace(this, SocketError) - this.name = 'SocketError' - this.message = message || 'Socket error' - this.code = 'UND_ERR_SOCKET' - this.socket = socket - } -} - -class NotSupportedError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, NotSupportedError) - this.name = 'NotSupportedError' - this.message = message || 'Not supported error' - this.code = 'UND_ERR_NOT_SUPPORTED' - } -} - -class BalancedPoolMissingUpstreamError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, NotSupportedError) - this.name = 'MissingUpstreamError' - this.message = message || 'No upstream has been added to the BalancedPool' - this.code = 'UND_ERR_BPL_MISSING_UPSTREAM' - } -} - -class HTTPParserError extends Error { - constructor (message, code, data) { - super(message) - Error.captureStackTrace(this, HTTPParserError) - this.name = 'HTTPParserError' - this.code = code ? `HPE_${code}` : undefined - this.data = data ? data.toString() : undefined - } -} - -class ResponseExceededMaxSizeError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, ResponseExceededMaxSizeError) - this.name = 'ResponseExceededMaxSizeError' - this.message = message || 'Response content exceeded max size' - this.code = 'UND_ERR_RES_EXCEEDED_MAX_SIZE' - } -} - -class RequestRetryError extends UndiciError { - constructor (message, code, { headers, data }) { - super(message) - Error.captureStackTrace(this, RequestRetryError) - this.name = 'RequestRetryError' - this.message = message || 'Request retry error' - this.code = 'UND_ERR_REQ_RETRY' - this.statusCode = code - this.data = data - this.headers = headers - } -} - -module.exports = { - HTTPParserError, - UndiciError, - HeadersTimeoutError, - HeadersOverflowError, - BodyTimeoutError, - RequestContentLengthMismatchError, - ConnectTimeoutError, - ResponseStatusCodeError, - InvalidArgumentError, - InvalidReturnValueError, - RequestAbortedError, - ClientDestroyedError, - ClientClosedError, - InformationalError, - SocketError, - NotSupportedError, - ResponseContentLengthMismatchError, - BalancedPoolMissingUpstreamError, - ResponseExceededMaxSizeError, - RequestRetryError -} - - -/***/ }), - -/***/ 4655: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - InvalidArgumentError, - NotSupportedError -} = __nccwpck_require__(8707) -const assert = __nccwpck_require__(2613) -const { kHTTP2BuildRequest, kHTTP2CopyHeaders, kHTTP1BuildRequest } = __nccwpck_require__(6443) -const util = __nccwpck_require__(3440) - -// tokenRegExp and headerCharRegex have been lifted from -// https://github.com/nodejs/node/blob/main/lib/_http_common.js - -/** - * Verifies that the given val is a valid HTTP token - * per the rules defined in RFC 7230 - * See https://tools.ietf.org/html/rfc7230#section-3.2.6 - */ -const tokenRegExp = /^[\^_`a-zA-Z\-0-9!#$%&'*+.|~]+$/ - -/** - * Matches if val contains an invalid field-vchar - * field-value = *( field-content / obs-fold ) - * field-content = field-vchar [ 1*( SP / HTAB ) field-vchar ] - * field-vchar = VCHAR / obs-text - */ -const headerCharRegex = /[^\t\x20-\x7e\x80-\xff]/ - -// Verifies that a given path is valid does not contain control chars \x00 to \x20 -const invalidPathRegex = /[^\u0021-\u00ff]/ - -const kHandler = Symbol('handler') - -const channels = {} - -let extractBody - -try { - const diagnosticsChannel = __nccwpck_require__(1637) - channels.create = diagnosticsChannel.channel('undici:request:create') - channels.bodySent = diagnosticsChannel.channel('undici:request:bodySent') - channels.headers = diagnosticsChannel.channel('undici:request:headers') - channels.trailers = diagnosticsChannel.channel('undici:request:trailers') - channels.error = diagnosticsChannel.channel('undici:request:error') -} catch { - channels.create = { hasSubscribers: false } - channels.bodySent = { hasSubscribers: false } - channels.headers = { hasSubscribers: false } - channels.trailers = { hasSubscribers: false } - channels.error = { hasSubscribers: false } -} - -class Request { - constructor (origin, { - path, - method, - body, - headers, - query, - idempotent, - blocking, - upgrade, - headersTimeout, - bodyTimeout, - reset, - throwOnError, - expectContinue - }, handler) { - if (typeof path !== 'string') { - throw new InvalidArgumentError('path must be a string') - } else if ( - path[0] !== '/' && - !(path.startsWith('http://') || path.startsWith('https://')) && - method !== 'CONNECT' - ) { - throw new InvalidArgumentError('path must be an absolute URL or start with a slash') - } else if (invalidPathRegex.exec(path) !== null) { - throw new InvalidArgumentError('invalid request path') - } - - if (typeof method !== 'string') { - throw new InvalidArgumentError('method must be a string') - } else if (tokenRegExp.exec(method) === null) { - throw new InvalidArgumentError('invalid request method') - } - - if (upgrade && typeof upgrade !== 'string') { - throw new InvalidArgumentError('upgrade must be a string') - } - - if (headersTimeout != null && (!Number.isFinite(headersTimeout) || headersTimeout < 0)) { - throw new InvalidArgumentError('invalid headersTimeout') - } - - if (bodyTimeout != null && (!Number.isFinite(bodyTimeout) || bodyTimeout < 0)) { - throw new InvalidArgumentError('invalid bodyTimeout') - } - - if (reset != null && typeof reset !== 'boolean') { - throw new InvalidArgumentError('invalid reset') - } - - if (expectContinue != null && typeof expectContinue !== 'boolean') { - throw new InvalidArgumentError('invalid expectContinue') - } - - this.headersTimeout = headersTimeout - - this.bodyTimeout = bodyTimeout - - this.throwOnError = throwOnError === true - - this.method = method - - this.abort = null - - if (body == null) { - this.body = null - } else if (util.isStream(body)) { - this.body = body - - const rState = this.body._readableState - if (!rState || !rState.autoDestroy) { - this.endHandler = function autoDestroy () { - util.destroy(this) - } - this.body.on('end', this.endHandler) - } - - this.errorHandler = err => { - if (this.abort) { - this.abort(err) - } else { - this.error = err - } - } - this.body.on('error', this.errorHandler) - } else if (util.isBuffer(body)) { - this.body = body.byteLength ? body : null - } else if (ArrayBuffer.isView(body)) { - this.body = body.buffer.byteLength ? Buffer.from(body.buffer, body.byteOffset, body.byteLength) : null - } else if (body instanceof ArrayBuffer) { - this.body = body.byteLength ? Buffer.from(body) : null - } else if (typeof body === 'string') { - this.body = body.length ? Buffer.from(body) : null - } else if (util.isFormDataLike(body) || util.isIterable(body) || util.isBlobLike(body)) { - this.body = body - } else { - throw new InvalidArgumentError('body must be a string, a Buffer, a Readable stream, an iterable, or an async iterable') - } - - this.completed = false - - this.aborted = false - - this.upgrade = upgrade || null - - this.path = query ? util.buildURL(path, query) : path - - this.origin = origin - - this.idempotent = idempotent == null - ? method === 'HEAD' || method === 'GET' - : idempotent - - this.blocking = blocking == null ? false : blocking - - this.reset = reset == null ? null : reset - - this.host = null - - this.contentLength = null - - this.contentType = null - - this.headers = '' - - // Only for H2 - this.expectContinue = expectContinue != null ? expectContinue : false - - if (Array.isArray(headers)) { - if (headers.length % 2 !== 0) { - throw new InvalidArgumentError('headers array must be even') - } - for (let i = 0; i < headers.length; i += 2) { - processHeader(this, headers[i], headers[i + 1]) - } - } else if (headers && typeof headers === 'object') { - const keys = Object.keys(headers) - for (let i = 0; i < keys.length; i++) { - const key = keys[i] - processHeader(this, key, headers[key]) - } - } else if (headers != null) { - throw new InvalidArgumentError('headers must be an object or an array') - } - - if (util.isFormDataLike(this.body)) { - if (util.nodeMajor < 16 || (util.nodeMajor === 16 && util.nodeMinor < 8)) { - throw new InvalidArgumentError('Form-Data bodies are only supported in node v16.8 and newer.') - } - - if (!extractBody) { - extractBody = (__nccwpck_require__(8923).extractBody) - } - - const [bodyStream, contentType] = extractBody(body) - if (this.contentType == null) { - this.contentType = contentType - this.headers += `content-type: ${contentType}\r\n` - } - this.body = bodyStream.stream - this.contentLength = bodyStream.length - } else if (util.isBlobLike(body) && this.contentType == null && body.type) { - this.contentType = body.type - this.headers += `content-type: ${body.type}\r\n` - } - - util.validateHandler(handler, method, upgrade) - - this.servername = util.getServerName(this.host) - - this[kHandler] = handler - - if (channels.create.hasSubscribers) { - channels.create.publish({ request: this }) - } - } - - onBodySent (chunk) { - if (this[kHandler].onBodySent) { - try { - return this[kHandler].onBodySent(chunk) - } catch (err) { - this.abort(err) - } - } - } - - onRequestSent () { - if (channels.bodySent.hasSubscribers) { - channels.bodySent.publish({ request: this }) - } - - if (this[kHandler].onRequestSent) { - try { - return this[kHandler].onRequestSent() - } catch (err) { - this.abort(err) - } - } - } - - onConnect (abort) { - assert(!this.aborted) - assert(!this.completed) - - if (this.error) { - abort(this.error) - } else { - this.abort = abort - return this[kHandler].onConnect(abort) - } - } - - onHeaders (statusCode, headers, resume, statusText) { - assert(!this.aborted) - assert(!this.completed) - - if (channels.headers.hasSubscribers) { - channels.headers.publish({ request: this, response: { statusCode, headers, statusText } }) - } - - try { - return this[kHandler].onHeaders(statusCode, headers, resume, statusText) - } catch (err) { - this.abort(err) - } - } - - onData (chunk) { - assert(!this.aborted) - assert(!this.completed) - - try { - return this[kHandler].onData(chunk) - } catch (err) { - this.abort(err) - return false - } - } - - onUpgrade (statusCode, headers, socket) { - assert(!this.aborted) - assert(!this.completed) - - return this[kHandler].onUpgrade(statusCode, headers, socket) - } - - onComplete (trailers) { - this.onFinally() - - assert(!this.aborted) - - this.completed = true - if (channels.trailers.hasSubscribers) { - channels.trailers.publish({ request: this, trailers }) - } - - try { - return this[kHandler].onComplete(trailers) - } catch (err) { - // TODO (fix): This might be a bad idea? - this.onError(err) - } - } - - onError (error) { - this.onFinally() - - if (channels.error.hasSubscribers) { - channels.error.publish({ request: this, error }) - } - - if (this.aborted) { - return - } - this.aborted = true - - return this[kHandler].onError(error) - } - - onFinally () { - if (this.errorHandler) { - this.body.off('error', this.errorHandler) - this.errorHandler = null - } - - if (this.endHandler) { - this.body.off('end', this.endHandler) - this.endHandler = null - } - } - - // TODO: adjust to support H2 - addHeader (key, value) { - processHeader(this, key, value) - return this - } - - static [kHTTP1BuildRequest] (origin, opts, handler) { - // TODO: Migrate header parsing here, to make Requests - // HTTP agnostic - return new Request(origin, opts, handler) - } - - static [kHTTP2BuildRequest] (origin, opts, handler) { - const headers = opts.headers - opts = { ...opts, headers: null } - - const request = new Request(origin, opts, handler) - - request.headers = {} - - if (Array.isArray(headers)) { - if (headers.length % 2 !== 0) { - throw new InvalidArgumentError('headers array must be even') - } - for (let i = 0; i < headers.length; i += 2) { - processHeader(request, headers[i], headers[i + 1], true) - } - } else if (headers && typeof headers === 'object') { - const keys = Object.keys(headers) - for (let i = 0; i < keys.length; i++) { - const key = keys[i] - processHeader(request, key, headers[key], true) - } - } else if (headers != null) { - throw new InvalidArgumentError('headers must be an object or an array') - } - - return request - } - - static [kHTTP2CopyHeaders] (raw) { - const rawHeaders = raw.split('\r\n') - const headers = {} - - for (const header of rawHeaders) { - const [key, value] = header.split(': ') - - if (value == null || value.length === 0) continue - - if (headers[key]) headers[key] += `,${value}` - else headers[key] = value - } - - return headers - } -} - -function processHeaderValue (key, val, skipAppend) { - if (val && typeof val === 'object') { - throw new InvalidArgumentError(`invalid ${key} header`) - } - - val = val != null ? `${val}` : '' - - if (headerCharRegex.exec(val) !== null) { - throw new InvalidArgumentError(`invalid ${key} header`) - } - - return skipAppend ? val : `${key}: ${val}\r\n` -} - -function processHeader (request, key, val, skipAppend = false) { - if (val && (typeof val === 'object' && !Array.isArray(val))) { - throw new InvalidArgumentError(`invalid ${key} header`) - } else if (val === undefined) { - return - } - - if ( - request.host === null && - key.length === 4 && - key.toLowerCase() === 'host' - ) { - if (headerCharRegex.exec(val) !== null) { - throw new InvalidArgumentError(`invalid ${key} header`) - } - // Consumed by Client - request.host = val - } else if ( - request.contentLength === null && - key.length === 14 && - key.toLowerCase() === 'content-length' - ) { - request.contentLength = parseInt(val, 10) - if (!Number.isFinite(request.contentLength)) { - throw new InvalidArgumentError('invalid content-length header') - } - } else if ( - request.contentType === null && - key.length === 12 && - key.toLowerCase() === 'content-type' - ) { - request.contentType = val - if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) - else request.headers += processHeaderValue(key, val) - } else if ( - key.length === 17 && - key.toLowerCase() === 'transfer-encoding' - ) { - throw new InvalidArgumentError('invalid transfer-encoding header') - } else if ( - key.length === 10 && - key.toLowerCase() === 'connection' - ) { - const value = typeof val === 'string' ? val.toLowerCase() : null - if (value !== 'close' && value !== 'keep-alive') { - throw new InvalidArgumentError('invalid connection header') - } else if (value === 'close') { - request.reset = true - } - } else if ( - key.length === 10 && - key.toLowerCase() === 'keep-alive' - ) { - throw new InvalidArgumentError('invalid keep-alive header') - } else if ( - key.length === 7 && - key.toLowerCase() === 'upgrade' - ) { - throw new InvalidArgumentError('invalid upgrade header') - } else if ( - key.length === 6 && - key.toLowerCase() === 'expect' - ) { - throw new NotSupportedError('expect header not supported') - } else if (tokenRegExp.exec(key) === null) { - throw new InvalidArgumentError('invalid header key') - } else { - if (Array.isArray(val)) { - for (let i = 0; i < val.length; i++) { - if (skipAppend) { - if (request.headers[key]) request.headers[key] += `,${processHeaderValue(key, val[i], skipAppend)}` - else request.headers[key] = processHeaderValue(key, val[i], skipAppend) - } else { - request.headers += processHeaderValue(key, val[i]) - } - } - } else { - if (skipAppend) request.headers[key] = processHeaderValue(key, val, skipAppend) - else request.headers += processHeaderValue(key, val) - } - } -} - -module.exports = Request - - -/***/ }), - -/***/ 6443: -/***/ ((module) => { - -module.exports = { - kClose: Symbol('close'), - kDestroy: Symbol('destroy'), - kDispatch: Symbol('dispatch'), - kUrl: Symbol('url'), - kWriting: Symbol('writing'), - kResuming: Symbol('resuming'), - kQueue: Symbol('queue'), - kConnect: Symbol('connect'), - kConnecting: Symbol('connecting'), - kHeadersList: Symbol('headers list'), - kKeepAliveDefaultTimeout: Symbol('default keep alive timeout'), - kKeepAliveMaxTimeout: Symbol('max keep alive timeout'), - kKeepAliveTimeoutThreshold: Symbol('keep alive timeout threshold'), - kKeepAliveTimeoutValue: Symbol('keep alive timeout'), - kKeepAlive: Symbol('keep alive'), - kHeadersTimeout: Symbol('headers timeout'), - kBodyTimeout: Symbol('body timeout'), - kServerName: Symbol('server name'), - kLocalAddress: Symbol('local address'), - kHost: Symbol('host'), - kNoRef: Symbol('no ref'), - kBodyUsed: Symbol('used'), - kRunning: Symbol('running'), - kBlocking: Symbol('blocking'), - kPending: Symbol('pending'), - kSize: Symbol('size'), - kBusy: Symbol('busy'), - kQueued: Symbol('queued'), - kFree: Symbol('free'), - kConnected: Symbol('connected'), - kClosed: Symbol('closed'), - kNeedDrain: Symbol('need drain'), - kReset: Symbol('reset'), - kDestroyed: Symbol.for('nodejs.stream.destroyed'), - kMaxHeadersSize: Symbol('max headers size'), - kRunningIdx: Symbol('running index'), - kPendingIdx: Symbol('pending index'), - kError: Symbol('error'), - kClients: Symbol('clients'), - kClient: Symbol('client'), - kParser: Symbol('parser'), - kOnDestroyed: Symbol('destroy callbacks'), - kPipelining: Symbol('pipelining'), - kSocket: Symbol('socket'), - kHostHeader: Symbol('host header'), - kConnector: Symbol('connector'), - kStrictContentLength: Symbol('strict content length'), - kMaxRedirections: Symbol('maxRedirections'), - kMaxRequests: Symbol('maxRequestsPerClient'), - kProxy: Symbol('proxy agent options'), - kCounter: Symbol('socket request counter'), - kInterceptors: Symbol('dispatch interceptors'), - kMaxResponseSize: Symbol('max response size'), - kHTTP2Session: Symbol('http2Session'), - kHTTP2SessionState: Symbol('http2Session state'), - kHTTP2BuildRequest: Symbol('http2 build request'), - kHTTP1BuildRequest: Symbol('http1 build request'), - kHTTP2CopyHeaders: Symbol('http2 copy headers'), - kHTTPConnVersion: Symbol('http connection version'), - kRetryHandlerDefaultRetry: Symbol('retry agent default retry'), - kConstruct: Symbol('constructable') -} - - -/***/ }), - -/***/ 3440: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const assert = __nccwpck_require__(2613) -const { kDestroyed, kBodyUsed } = __nccwpck_require__(6443) -const { IncomingMessage } = __nccwpck_require__(8611) -const stream = __nccwpck_require__(2203) -const net = __nccwpck_require__(9278) -const { InvalidArgumentError } = __nccwpck_require__(8707) -const { Blob } = __nccwpck_require__(181) -const nodeUtil = __nccwpck_require__(9023) -const { stringify } = __nccwpck_require__(3480) -const { headerNameLowerCasedRecord } = __nccwpck_require__(735) - -const [nodeMajor, nodeMinor] = process.versions.node.split('.').map(v => Number(v)) - -function nop () {} - -function isStream (obj) { - return obj && typeof obj === 'object' && typeof obj.pipe === 'function' && typeof obj.on === 'function' -} - -// based on https://github.com/node-fetch/fetch-blob/blob/8ab587d34080de94140b54f07168451e7d0b655e/index.js#L229-L241 (MIT License) -function isBlobLike (object) { - return (Blob && object instanceof Blob) || ( - object && - typeof object === 'object' && - (typeof object.stream === 'function' || - typeof object.arrayBuffer === 'function') && - /^(Blob|File)$/.test(object[Symbol.toStringTag]) - ) -} - -function buildURL (url, queryParams) { - if (url.includes('?') || url.includes('#')) { - throw new Error('Query params cannot be passed when url already contains "?" or "#".') - } - - const stringified = stringify(queryParams) - - if (stringified) { - url += '?' + stringified - } - - return url -} - -function parseURL (url) { - if (typeof url === 'string') { - url = new URL(url) - - if (!/^https?:/.test(url.origin || url.protocol)) { - throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') - } - - return url - } - - if (!url || typeof url !== 'object') { - throw new InvalidArgumentError('Invalid URL: The URL argument must be a non-null object.') - } - - if (!/^https?:/.test(url.origin || url.protocol)) { - throw new InvalidArgumentError('Invalid URL protocol: the URL must start with `http:` or `https:`.') - } - - if (!(url instanceof URL)) { - if (url.port != null && url.port !== '' && !Number.isFinite(parseInt(url.port))) { - throw new InvalidArgumentError('Invalid URL: port must be a valid integer or a string representation of an integer.') - } - - if (url.path != null && typeof url.path !== 'string') { - throw new InvalidArgumentError('Invalid URL path: the path must be a string or null/undefined.') - } - - if (url.pathname != null && typeof url.pathname !== 'string') { - throw new InvalidArgumentError('Invalid URL pathname: the pathname must be a string or null/undefined.') - } - - if (url.hostname != null && typeof url.hostname !== 'string') { - throw new InvalidArgumentError('Invalid URL hostname: the hostname must be a string or null/undefined.') - } - - if (url.origin != null && typeof url.origin !== 'string') { - throw new InvalidArgumentError('Invalid URL origin: the origin must be a string or null/undefined.') - } - - const port = url.port != null - ? url.port - : (url.protocol === 'https:' ? 443 : 80) - let origin = url.origin != null - ? url.origin - : `${url.protocol}//${url.hostname}:${port}` - let path = url.path != null - ? url.path - : `${url.pathname || ''}${url.search || ''}` - - if (origin.endsWith('/')) { - origin = origin.substring(0, origin.length - 1) - } - - if (path && !path.startsWith('/')) { - path = `/${path}` - } - // new URL(path, origin) is unsafe when `path` contains an absolute URL - // From https://developer.mozilla.org/en-US/docs/Web/API/URL/URL: - // If first parameter is a relative URL, second param is required, and will be used as the base URL. - // If first parameter is an absolute URL, a given second param will be ignored. - url = new URL(origin + path) - } - - return url -} - -function parseOrigin (url) { - url = parseURL(url) - - if (url.pathname !== '/' || url.search || url.hash) { - throw new InvalidArgumentError('invalid url') - } - - return url -} - -function getHostname (host) { - if (host[0] === '[') { - const idx = host.indexOf(']') - - assert(idx !== -1) - return host.substring(1, idx) - } - - const idx = host.indexOf(':') - if (idx === -1) return host - - return host.substring(0, idx) -} - -// IP addresses are not valid server names per RFC6066 -// > Currently, the only server names supported are DNS hostnames -function getServerName (host) { - if (!host) { - return null - } - - assert.strictEqual(typeof host, 'string') - - const servername = getHostname(host) - if (net.isIP(servername)) { - return '' - } - - return servername -} - -function deepClone (obj) { - return JSON.parse(JSON.stringify(obj)) -} - -function isAsyncIterable (obj) { - return !!(obj != null && typeof obj[Symbol.asyncIterator] === 'function') -} - -function isIterable (obj) { - return !!(obj != null && (typeof obj[Symbol.iterator] === 'function' || typeof obj[Symbol.asyncIterator] === 'function')) -} - -function bodyLength (body) { - if (body == null) { - return 0 - } else if (isStream(body)) { - const state = body._readableState - return state && state.objectMode === false && state.ended === true && Number.isFinite(state.length) - ? state.length - : null - } else if (isBlobLike(body)) { - return body.size != null ? body.size : null - } else if (isBuffer(body)) { - return body.byteLength - } - - return null -} - -function isDestroyed (stream) { - return !stream || !!(stream.destroyed || stream[kDestroyed]) -} - -function isReadableAborted (stream) { - const state = stream && stream._readableState - return isDestroyed(stream) && state && !state.endEmitted -} - -function destroy (stream, err) { - if (stream == null || !isStream(stream) || isDestroyed(stream)) { - return - } - - if (typeof stream.destroy === 'function') { - if (Object.getPrototypeOf(stream).constructor === IncomingMessage) { - // See: https://github.com/nodejs/node/pull/38505/files - stream.socket = null - } - - stream.destroy(err) - } else if (err) { - process.nextTick((stream, err) => { - stream.emit('error', err) - }, stream, err) - } - - if (stream.destroyed !== true) { - stream[kDestroyed] = true - } -} - -const KEEPALIVE_TIMEOUT_EXPR = /timeout=(\d+)/ -function parseKeepAliveTimeout (val) { - const m = val.toString().match(KEEPALIVE_TIMEOUT_EXPR) - return m ? parseInt(m[1], 10) * 1000 : null -} - -/** - * Retrieves a header name and returns its lowercase value. - * @param {string | Buffer} value Header name - * @returns {string} - */ -function headerNameToString (value) { - return headerNameLowerCasedRecord[value] || value.toLowerCase() -} - -function parseHeaders (headers, obj = {}) { - // For H2 support - if (!Array.isArray(headers)) return headers - - for (let i = 0; i < headers.length; i += 2) { - const key = headers[i].toString().toLowerCase() - let val = obj[key] - - if (!val) { - if (Array.isArray(headers[i + 1])) { - obj[key] = headers[i + 1].map(x => x.toString('utf8')) - } else { - obj[key] = headers[i + 1].toString('utf8') - } - } else { - if (!Array.isArray(val)) { - val = [val] - obj[key] = val - } - val.push(headers[i + 1].toString('utf8')) - } - } - - // See https://github.com/nodejs/node/pull/46528 - if ('content-length' in obj && 'content-disposition' in obj) { - obj['content-disposition'] = Buffer.from(obj['content-disposition']).toString('latin1') - } - - return obj -} - -function parseRawHeaders (headers) { - const ret = [] - let hasContentLength = false - let contentDispositionIdx = -1 - - for (let n = 0; n < headers.length; n += 2) { - const key = headers[n + 0].toString() - const val = headers[n + 1].toString('utf8') - - if (key.length === 14 && (key === 'content-length' || key.toLowerCase() === 'content-length')) { - ret.push(key, val) - hasContentLength = true - } else if (key.length === 19 && (key === 'content-disposition' || key.toLowerCase() === 'content-disposition')) { - contentDispositionIdx = ret.push(key, val) - 1 - } else { - ret.push(key, val) - } - } - - // See https://github.com/nodejs/node/pull/46528 - if (hasContentLength && contentDispositionIdx !== -1) { - ret[contentDispositionIdx] = Buffer.from(ret[contentDispositionIdx]).toString('latin1') - } - - return ret -} - -function isBuffer (buffer) { - // See, https://github.com/mcollina/undici/pull/319 - return buffer instanceof Uint8Array || Buffer.isBuffer(buffer) -} - -function validateHandler (handler, method, upgrade) { - if (!handler || typeof handler !== 'object') { - throw new InvalidArgumentError('handler must be an object') - } - - if (typeof handler.onConnect !== 'function') { - throw new InvalidArgumentError('invalid onConnect method') - } - - if (typeof handler.onError !== 'function') { - throw new InvalidArgumentError('invalid onError method') - } - - if (typeof handler.onBodySent !== 'function' && handler.onBodySent !== undefined) { - throw new InvalidArgumentError('invalid onBodySent method') - } - - if (upgrade || method === 'CONNECT') { - if (typeof handler.onUpgrade !== 'function') { - throw new InvalidArgumentError('invalid onUpgrade method') - } - } else { - if (typeof handler.onHeaders !== 'function') { - throw new InvalidArgumentError('invalid onHeaders method') - } - - if (typeof handler.onData !== 'function') { - throw new InvalidArgumentError('invalid onData method') - } - - if (typeof handler.onComplete !== 'function') { - throw new InvalidArgumentError('invalid onComplete method') - } - } -} - -// A body is disturbed if it has been read from and it cannot -// be re-used without losing state or data. -function isDisturbed (body) { - return !!(body && ( - stream.isDisturbed - ? stream.isDisturbed(body) || body[kBodyUsed] // TODO (fix): Why is body[kBodyUsed] needed? - : body[kBodyUsed] || - body.readableDidRead || - (body._readableState && body._readableState.dataEmitted) || - isReadableAborted(body) - )) -} - -function isErrored (body) { - return !!(body && ( - stream.isErrored - ? stream.isErrored(body) - : /state: 'errored'/.test(nodeUtil.inspect(body) - ))) -} - -function isReadable (body) { - return !!(body && ( - stream.isReadable - ? stream.isReadable(body) - : /state: 'readable'/.test(nodeUtil.inspect(body) - ))) -} - -function getSocketInfo (socket) { - return { - localAddress: socket.localAddress, - localPort: socket.localPort, - remoteAddress: socket.remoteAddress, - remotePort: socket.remotePort, - remoteFamily: socket.remoteFamily, - timeout: socket.timeout, - bytesWritten: socket.bytesWritten, - bytesRead: socket.bytesRead - } -} - -async function * convertIterableToBuffer (iterable) { - for await (const chunk of iterable) { - yield Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk) - } -} - -let ReadableStream -function ReadableStreamFrom (iterable) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) - } - - if (ReadableStream.from) { - return ReadableStream.from(convertIterableToBuffer(iterable)) - } - - let iterator - return new ReadableStream( - { - async start () { - iterator = iterable[Symbol.asyncIterator]() - }, - async pull (controller) { - const { done, value } = await iterator.next() - if (done) { - queueMicrotask(() => { - controller.close() - }) - } else { - const buf = Buffer.isBuffer(value) ? value : Buffer.from(value) - controller.enqueue(new Uint8Array(buf)) - } - return controller.desiredSize > 0 - }, - async cancel (reason) { - await iterator.return() - } - }, - 0 - ) -} - -// The chunk should be a FormData instance and contains -// all the required methods. -function isFormDataLike (object) { - return ( - object && - typeof object === 'object' && - typeof object.append === 'function' && - typeof object.delete === 'function' && - typeof object.get === 'function' && - typeof object.getAll === 'function' && - typeof object.has === 'function' && - typeof object.set === 'function' && - object[Symbol.toStringTag] === 'FormData' - ) -} - -function throwIfAborted (signal) { - if (!signal) { return } - if (typeof signal.throwIfAborted === 'function') { - signal.throwIfAborted() - } else { - if (signal.aborted) { - // DOMException not available < v17.0.0 - const err = new Error('The operation was aborted') - err.name = 'AbortError' - throw err - } - } -} - -function addAbortListener (signal, listener) { - if ('addEventListener' in signal) { - signal.addEventListener('abort', listener, { once: true }) - return () => signal.removeEventListener('abort', listener) - } - signal.addListener('abort', listener) - return () => signal.removeListener('abort', listener) -} - -const hasToWellFormed = !!String.prototype.toWellFormed - -/** - * @param {string} val - */ -function toUSVString (val) { - if (hasToWellFormed) { - return `${val}`.toWellFormed() - } else if (nodeUtil.toUSVString) { - return nodeUtil.toUSVString(val) - } - - return `${val}` -} - -// Parsed accordingly to RFC 9110 -// https://www.rfc-editor.org/rfc/rfc9110#field.content-range -function parseRangeHeader (range) { - if (range == null || range === '') return { start: 0, end: null, size: null } - - const m = range ? range.match(/^bytes (\d+)-(\d+)\/(\d+)?$/) : null - return m - ? { - start: parseInt(m[1]), - end: m[2] ? parseInt(m[2]) : null, - size: m[3] ? parseInt(m[3]) : null - } - : null -} - -const kEnumerableProperty = Object.create(null) -kEnumerableProperty.enumerable = true - -module.exports = { - kEnumerableProperty, - nop, - isDisturbed, - isErrored, - isReadable, - toUSVString, - isReadableAborted, - isBlobLike, - parseOrigin, - parseURL, - getServerName, - isStream, - isIterable, - isAsyncIterable, - isDestroyed, - headerNameToString, - parseRawHeaders, - parseHeaders, - parseKeepAliveTimeout, - destroy, - bodyLength, - deepClone, - ReadableStreamFrom, - isBuffer, - validateHandler, - getSocketInfo, - isFormDataLike, - buildURL, - throwIfAborted, - addAbortListener, - parseRangeHeader, - nodeMajor, - nodeMinor, - nodeHasAutoSelectFamily: nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 13), - safeHTTPMethods: ['GET', 'HEAD', 'OPTIONS', 'TRACE'] -} - - -/***/ }), - -/***/ 1: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Dispatcher = __nccwpck_require__(992) -const { - ClientDestroyedError, - ClientClosedError, - InvalidArgumentError -} = __nccwpck_require__(8707) -const { kDestroy, kClose, kDispatch, kInterceptors } = __nccwpck_require__(6443) - -const kDestroyed = Symbol('destroyed') -const kClosed = Symbol('closed') -const kOnDestroyed = Symbol('onDestroyed') -const kOnClosed = Symbol('onClosed') -const kInterceptedDispatch = Symbol('Intercepted Dispatch') - -class DispatcherBase extends Dispatcher { - constructor () { - super() - - this[kDestroyed] = false - this[kOnDestroyed] = null - this[kClosed] = false - this[kOnClosed] = [] - } - - get destroyed () { - return this[kDestroyed] - } - - get closed () { - return this[kClosed] - } - - get interceptors () { - return this[kInterceptors] - } - - set interceptors (newInterceptors) { - if (newInterceptors) { - for (let i = newInterceptors.length - 1; i >= 0; i--) { - const interceptor = this[kInterceptors][i] - if (typeof interceptor !== 'function') { - throw new InvalidArgumentError('interceptor must be an function') - } - } - } - - this[kInterceptors] = newInterceptors - } - - close (callback) { - if (callback === undefined) { - return new Promise((resolve, reject) => { - this.close((err, data) => { - return err ? reject(err) : resolve(data) - }) - }) - } - - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - if (this[kDestroyed]) { - queueMicrotask(() => callback(new ClientDestroyedError(), null)) - return - } - - if (this[kClosed]) { - if (this[kOnClosed]) { - this[kOnClosed].push(callback) - } else { - queueMicrotask(() => callback(null, null)) - } - return - } - - this[kClosed] = true - this[kOnClosed].push(callback) - - const onClosed = () => { - const callbacks = this[kOnClosed] - this[kOnClosed] = null - for (let i = 0; i < callbacks.length; i++) { - callbacks[i](null, null) - } - } - - // Should not error. - this[kClose]() - .then(() => this.destroy()) - .then(() => { - queueMicrotask(onClosed) - }) - } - - destroy (err, callback) { - if (typeof err === 'function') { - callback = err - err = null - } - - if (callback === undefined) { - return new Promise((resolve, reject) => { - this.destroy(err, (err, data) => { - return err ? /* istanbul ignore next: should never error */ reject(err) : resolve(data) - }) - }) - } - - if (typeof callback !== 'function') { - throw new InvalidArgumentError('invalid callback') - } - - if (this[kDestroyed]) { - if (this[kOnDestroyed]) { - this[kOnDestroyed].push(callback) - } else { - queueMicrotask(() => callback(null, null)) - } - return - } - - if (!err) { - err = new ClientDestroyedError() - } - - this[kDestroyed] = true - this[kOnDestroyed] = this[kOnDestroyed] || [] - this[kOnDestroyed].push(callback) - - const onDestroyed = () => { - const callbacks = this[kOnDestroyed] - this[kOnDestroyed] = null - for (let i = 0; i < callbacks.length; i++) { - callbacks[i](null, null) - } - } - - // Should not error. - this[kDestroy](err).then(() => { - queueMicrotask(onDestroyed) - }) - } - - [kInterceptedDispatch] (opts, handler) { - if (!this[kInterceptors] || this[kInterceptors].length === 0) { - this[kInterceptedDispatch] = this[kDispatch] - return this[kDispatch](opts, handler) - } - - let dispatch = this[kDispatch].bind(this) - for (let i = this[kInterceptors].length - 1; i >= 0; i--) { - dispatch = this[kInterceptors][i](dispatch) - } - this[kInterceptedDispatch] = dispatch - return dispatch(opts, handler) - } - - dispatch (opts, handler) { - if (!handler || typeof handler !== 'object') { - throw new InvalidArgumentError('handler must be an object') - } - - try { - if (!opts || typeof opts !== 'object') { - throw new InvalidArgumentError('opts must be an object.') - } - - if (this[kDestroyed] || this[kOnDestroyed]) { - throw new ClientDestroyedError() - } - - if (this[kClosed]) { - throw new ClientClosedError() - } - - return this[kInterceptedDispatch](opts, handler) - } catch (err) { - if (typeof handler.onError !== 'function') { - throw new InvalidArgumentError('invalid onError method') - } - - handler.onError(err) - - return false - } - } -} - -module.exports = DispatcherBase - - -/***/ }), - -/***/ 992: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const EventEmitter = __nccwpck_require__(4434) - -class Dispatcher extends EventEmitter { - dispatch () { - throw new Error('not implemented') - } - - close () { - throw new Error('not implemented') - } - - destroy () { - throw new Error('not implemented') - } -} - -module.exports = Dispatcher - - -/***/ }), - -/***/ 8923: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Busboy = __nccwpck_require__(9581) -const util = __nccwpck_require__(3440) -const { - ReadableStreamFrom, - isBlobLike, - isReadableStreamLike, - readableStreamClose, - createDeferredPromise, - fullyReadBody -} = __nccwpck_require__(5523) -const { FormData } = __nccwpck_require__(3073) -const { kState } = __nccwpck_require__(9710) -const { webidl } = __nccwpck_require__(4222) -const { DOMException, structuredClone } = __nccwpck_require__(7326) -const { Blob, File: NativeFile } = __nccwpck_require__(181) -const { kBodyUsed } = __nccwpck_require__(6443) -const assert = __nccwpck_require__(2613) -const { isErrored } = __nccwpck_require__(3440) -const { isUint8Array, isArrayBuffer } = __nccwpck_require__(8253) -const { File: UndiciFile } = __nccwpck_require__(3041) -const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) - -let random -try { - const crypto = __nccwpck_require__(7598) - random = (max) => crypto.randomInt(0, max) -} catch { - random = (max) => Math.floor(Math.random(max)) -} - -let ReadableStream = globalThis.ReadableStream - -/** @type {globalThis['File']} */ -const File = NativeFile ?? UndiciFile -const textEncoder = new TextEncoder() -const textDecoder = new TextDecoder() - -// https://fetch.spec.whatwg.org/#concept-bodyinit-extract -function extractBody (object, keepalive = false) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) - } - - // 1. Let stream be null. - let stream = null - - // 2. If object is a ReadableStream object, then set stream to object. - if (object instanceof ReadableStream) { - stream = object - } else if (isBlobLike(object)) { - // 3. Otherwise, if object is a Blob object, set stream to the - // result of running object’s get stream. - stream = object.stream() - } else { - // 4. Otherwise, set stream to a new ReadableStream object, and set - // up stream. - stream = new ReadableStream({ - async pull (controller) { - controller.enqueue( - typeof source === 'string' ? textEncoder.encode(source) : source - ) - queueMicrotask(() => readableStreamClose(controller)) - }, - start () {}, - type: undefined - }) - } - - // 5. Assert: stream is a ReadableStream object. - assert(isReadableStreamLike(stream)) - - // 6. Let action be null. - let action = null - - // 7. Let source be null. - let source = null - - // 8. Let length be null. - let length = null - - // 9. Let type be null. - let type = null - - // 10. Switch on object: - if (typeof object === 'string') { - // Set source to the UTF-8 encoding of object. - // Note: setting source to a Uint8Array here breaks some mocking assumptions. - source = object - - // Set type to `text/plain;charset=UTF-8`. - type = 'text/plain;charset=UTF-8' - } else if (object instanceof URLSearchParams) { - // URLSearchParams - - // spec says to run application/x-www-form-urlencoded on body.list - // this is implemented in Node.js as apart of an URLSearchParams instance toString method - // See: https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L490 - // and https://github.com/nodejs/node/blob/e46c680bf2b211bbd52cf959ca17ee98c7f657f5/lib/internal/url.js#L1100 - - // Set source to the result of running the application/x-www-form-urlencoded serializer with object’s list. - source = object.toString() - - // Set type to `application/x-www-form-urlencoded;charset=UTF-8`. - type = 'application/x-www-form-urlencoded;charset=UTF-8' - } else if (isArrayBuffer(object)) { - // BufferSource/ArrayBuffer - - // Set source to a copy of the bytes held by object. - source = new Uint8Array(object.slice()) - } else if (ArrayBuffer.isView(object)) { - // BufferSource/ArrayBufferView - - // Set source to a copy of the bytes held by object. - source = new Uint8Array(object.buffer.slice(object.byteOffset, object.byteOffset + object.byteLength)) - } else if (util.isFormDataLike(object)) { - const boundary = `----formdata-undici-0${`${random(1e11)}`.padStart(11, '0')}` - const prefix = `--${boundary}\r\nContent-Disposition: form-data` - - /*! formdata-polyfill. MIT License. Jimmy Wärting */ - const escape = (str) => - str.replace(/\n/g, '%0A').replace(/\r/g, '%0D').replace(/"/g, '%22') - const normalizeLinefeeds = (value) => value.replace(/\r?\n|\r/g, '\r\n') - - // Set action to this step: run the multipart/form-data - // encoding algorithm, with object’s entry list and UTF-8. - // - This ensures that the body is immutable and can't be changed afterwords - // - That the content-length is calculated in advance. - // - And that all parts are pre-encoded and ready to be sent. - - const blobParts = [] - const rn = new Uint8Array([13, 10]) // '\r\n' - length = 0 - let hasUnknownSizeValue = false - - for (const [name, value] of object) { - if (typeof value === 'string') { - const chunk = textEncoder.encode(prefix + - `; name="${escape(normalizeLinefeeds(name))}"` + - `\r\n\r\n${normalizeLinefeeds(value)}\r\n`) - blobParts.push(chunk) - length += chunk.byteLength - } else { - const chunk = textEncoder.encode(`${prefix}; name="${escape(normalizeLinefeeds(name))}"` + - (value.name ? `; filename="${escape(value.name)}"` : '') + '\r\n' + - `Content-Type: ${ - value.type || 'application/octet-stream' - }\r\n\r\n`) - blobParts.push(chunk, value, rn) - if (typeof value.size === 'number') { - length += chunk.byteLength + value.size + rn.byteLength - } else { - hasUnknownSizeValue = true - } - } - } - - const chunk = textEncoder.encode(`--${boundary}--`) - blobParts.push(chunk) - length += chunk.byteLength - if (hasUnknownSizeValue) { - length = null - } - - // Set source to object. - source = object - - action = async function * () { - for (const part of blobParts) { - if (part.stream) { - yield * part.stream() - } else { - yield part - } - } - } - - // Set type to `multipart/form-data; boundary=`, - // followed by the multipart/form-data boundary string generated - // by the multipart/form-data encoding algorithm. - type = 'multipart/form-data; boundary=' + boundary - } else if (isBlobLike(object)) { - // Blob - - // Set source to object. - source = object - - // Set length to object’s size. - length = object.size - - // If object’s type attribute is not the empty byte sequence, set - // type to its value. - if (object.type) { - type = object.type - } - } else if (typeof object[Symbol.asyncIterator] === 'function') { - // If keepalive is true, then throw a TypeError. - if (keepalive) { - throw new TypeError('keepalive') - } - - // If object is disturbed or locked, then throw a TypeError. - if (util.isDisturbed(object) || object.locked) { - throw new TypeError( - 'Response body object should not be disturbed or locked' - ) - } - - stream = - object instanceof ReadableStream ? object : ReadableStreamFrom(object) - } - - // 11. If source is a byte sequence, then set action to a - // step that returns source and length to source’s length. - if (typeof source === 'string' || util.isBuffer(source)) { - length = Buffer.byteLength(source) - } - - // 12. If action is non-null, then run these steps in in parallel: - if (action != null) { - // Run action. - let iterator - stream = new ReadableStream({ - async start () { - iterator = action(object)[Symbol.asyncIterator]() - }, - async pull (controller) { - const { value, done } = await iterator.next() - if (done) { - // When running action is done, close stream. - queueMicrotask(() => { - controller.close() - }) - } else { - // Whenever one or more bytes are available and stream is not errored, - // enqueue a Uint8Array wrapping an ArrayBuffer containing the available - // bytes into stream. - if (!isErrored(stream)) { - controller.enqueue(new Uint8Array(value)) - } - } - return controller.desiredSize > 0 - }, - async cancel (reason) { - await iterator.return() - }, - type: undefined - }) - } - - // 13. Let body be a body whose stream is stream, source is source, - // and length is length. - const body = { stream, source, length } - - // 14. Return (body, type). - return [body, type] -} - -// https://fetch.spec.whatwg.org/#bodyinit-safely-extract -function safelyExtractBody (object, keepalive = false) { - if (!ReadableStream) { - // istanbul ignore next - ReadableStream = (__nccwpck_require__(3774).ReadableStream) - } - - // To safely extract a body and a `Content-Type` value from - // a byte sequence or BodyInit object object, run these steps: - - // 1. If object is a ReadableStream object, then: - if (object instanceof ReadableStream) { - // Assert: object is neither disturbed nor locked. - // istanbul ignore next - assert(!util.isDisturbed(object), 'The body has already been consumed.') - // istanbul ignore next - assert(!object.locked, 'The stream is locked.') - } - - // 2. Return the results of extracting object. - return extractBody(object, keepalive) -} - -function cloneBody (body) { - // To clone a body body, run these steps: - - // https://fetch.spec.whatwg.org/#concept-body-clone - - // 1. Let « out1, out2 » be the result of teeing body’s stream. - const [out1, out2] = body.stream.tee() - const out2Clone = structuredClone(out2, { transfer: [out2] }) - // This, for whatever reasons, unrefs out2Clone which allows - // the process to exit by itself. - const [, finalClone] = out2Clone.tee() - - // 2. Set body’s stream to out1. - body.stream = out1 - - // 3. Return a body whose stream is out2 and other members are copied from body. - return { - stream: finalClone, - length: body.length, - source: body.source - } -} - -async function * consumeBody (body) { - if (body) { - if (isUint8Array(body)) { - yield body - } else { - const stream = body.stream - - if (util.isDisturbed(stream)) { - throw new TypeError('The body has already been consumed.') - } - - if (stream.locked) { - throw new TypeError('The stream is locked.') - } - - // Compat. - stream[kBodyUsed] = true - - yield * stream - } - } -} - -function throwIfAborted (state) { - if (state.aborted) { - throw new DOMException('The operation was aborted.', 'AbortError') - } -} - -function bodyMixinMethods (instance) { - const methods = { - blob () { - // The blob() method steps are to return the result of - // running consume body with this and the following step - // given a byte sequence bytes: return a Blob whose - // contents are bytes and whose type attribute is this’s - // MIME type. - return specConsumeBody(this, (bytes) => { - let mimeType = bodyMimeType(this) - - if (mimeType === 'failure') { - mimeType = '' - } else if (mimeType) { - mimeType = serializeAMimeType(mimeType) - } - - // Return a Blob whose contents are bytes and type attribute - // is mimeType. - return new Blob([bytes], { type: mimeType }) - }, instance) - }, - - arrayBuffer () { - // The arrayBuffer() method steps are to return the result - // of running consume body with this and the following step - // given a byte sequence bytes: return a new ArrayBuffer - // whose contents are bytes. - return specConsumeBody(this, (bytes) => { - return new Uint8Array(bytes).buffer - }, instance) - }, - - text () { - // The text() method steps are to return the result of running - // consume body with this and UTF-8 decode. - return specConsumeBody(this, utf8DecodeBytes, instance) - }, - - json () { - // The json() method steps are to return the result of running - // consume body with this and parse JSON from bytes. - return specConsumeBody(this, parseJSONFromBytes, instance) - }, - - async formData () { - webidl.brandCheck(this, instance) - - throwIfAborted(this[kState]) - - const contentType = this.headers.get('Content-Type') - - // If mimeType’s essence is "multipart/form-data", then: - if (/multipart\/form-data/.test(contentType)) { - const headers = {} - for (const [key, value] of this.headers) headers[key.toLowerCase()] = value - - const responseFormData = new FormData() - - let busboy - - try { - busboy = new Busboy({ - headers, - preservePath: true - }) - } catch (err) { - throw new DOMException(`${err}`, 'AbortError') - } - - busboy.on('field', (name, value) => { - responseFormData.append(name, value) - }) - busboy.on('file', (name, value, filename, encoding, mimeType) => { - const chunks = [] - - if (encoding === 'base64' || encoding.toLowerCase() === 'base64') { - let base64chunk = '' - - value.on('data', (chunk) => { - base64chunk += chunk.toString().replace(/[\r\n]/gm, '') - - const end = base64chunk.length - base64chunk.length % 4 - chunks.push(Buffer.from(base64chunk.slice(0, end), 'base64')) - - base64chunk = base64chunk.slice(end) - }) - value.on('end', () => { - chunks.push(Buffer.from(base64chunk, 'base64')) - responseFormData.append(name, new File(chunks, filename, { type: mimeType })) - }) - } else { - value.on('data', (chunk) => { - chunks.push(chunk) - }) - value.on('end', () => { - responseFormData.append(name, new File(chunks, filename, { type: mimeType })) - }) - } - }) - - const busboyResolve = new Promise((resolve, reject) => { - busboy.on('finish', resolve) - busboy.on('error', (err) => reject(new TypeError(err))) - }) - - if (this.body !== null) for await (const chunk of consumeBody(this[kState].body)) busboy.write(chunk) - busboy.end() - await busboyResolve - - return responseFormData - } else if (/application\/x-www-form-urlencoded/.test(contentType)) { - // Otherwise, if mimeType’s essence is "application/x-www-form-urlencoded", then: - - // 1. Let entries be the result of parsing bytes. - let entries - try { - let text = '' - // application/x-www-form-urlencoded parser will keep the BOM. - // https://url.spec.whatwg.org/#concept-urlencoded-parser - // Note that streaming decoder is stateful and cannot be reused - const streamingDecoder = new TextDecoder('utf-8', { ignoreBOM: true }) - - for await (const chunk of consumeBody(this[kState].body)) { - if (!isUint8Array(chunk)) { - throw new TypeError('Expected Uint8Array chunk') - } - text += streamingDecoder.decode(chunk, { stream: true }) - } - text += streamingDecoder.decode() - entries = new URLSearchParams(text) - } catch (err) { - // istanbul ignore next: Unclear when new URLSearchParams can fail on a string. - // 2. If entries is failure, then throw a TypeError. - throw Object.assign(new TypeError(), { cause: err }) - } - - // 3. Return a new FormData object whose entries are entries. - const formData = new FormData() - for (const [name, value] of entries) { - formData.append(name, value) - } - return formData - } else { - // Wait a tick before checking if the request has been aborted. - // Otherwise, a TypeError can be thrown when an AbortError should. - await Promise.resolve() - - throwIfAborted(this[kState]) - - // Otherwise, throw a TypeError. - throw webidl.errors.exception({ - header: `${instance.name}.formData`, - message: 'Could not parse content as FormData.' - }) - } - } - } - - return methods -} - -function mixinBody (prototype) { - Object.assign(prototype.prototype, bodyMixinMethods(prototype)) -} - -/** - * @see https://fetch.spec.whatwg.org/#concept-body-consume-body - * @param {Response|Request} object - * @param {(value: unknown) => unknown} convertBytesToJSValue - * @param {Response|Request} instance - */ -async function specConsumeBody (object, convertBytesToJSValue, instance) { - webidl.brandCheck(object, instance) - - throwIfAborted(object[kState]) - - // 1. If object is unusable, then return a promise rejected - // with a TypeError. - if (bodyUnusable(object[kState].body)) { - throw new TypeError('Body is unusable') - } - - // 2. Let promise be a new promise. - const promise = createDeferredPromise() - - // 3. Let errorSteps given error be to reject promise with error. - const errorSteps = (error) => promise.reject(error) - - // 4. Let successSteps given a byte sequence data be to resolve - // promise with the result of running convertBytesToJSValue - // with data. If that threw an exception, then run errorSteps - // with that exception. - const successSteps = (data) => { - try { - promise.resolve(convertBytesToJSValue(data)) - } catch (e) { - errorSteps(e) - } - } - - // 5. If object’s body is null, then run successSteps with an - // empty byte sequence. - if (object[kState].body == null) { - successSteps(new Uint8Array()) - return promise.promise - } - - // 6. Otherwise, fully read object’s body given successSteps, - // errorSteps, and object’s relevant global object. - await fullyReadBody(object[kState].body, successSteps, errorSteps) - - // 7. Return promise. - return promise.promise -} - -// https://fetch.spec.whatwg.org/#body-unusable -function bodyUnusable (body) { - // An object including the Body interface mixin is - // said to be unusable if its body is non-null and - // its body’s stream is disturbed or locked. - return body != null && (body.stream.locked || util.isDisturbed(body.stream)) -} - -/** - * @see https://encoding.spec.whatwg.org/#utf-8-decode - * @param {Buffer} buffer - */ -function utf8DecodeBytes (buffer) { - if (buffer.length === 0) { - return '' - } - - // 1. Let buffer be the result of peeking three bytes from - // ioQueue, converted to a byte sequence. - - // 2. If buffer is 0xEF 0xBB 0xBF, then read three - // bytes from ioQueue. (Do nothing with those bytes.) - if (buffer[0] === 0xEF && buffer[1] === 0xBB && buffer[2] === 0xBF) { - buffer = buffer.subarray(3) - } - - // 3. Process a queue with an instance of UTF-8’s - // decoder, ioQueue, output, and "replacement". - const output = textDecoder.decode(buffer) - - // 4. Return output. - return output -} - -/** - * @see https://infra.spec.whatwg.org/#parse-json-bytes-to-a-javascript-value - * @param {Uint8Array} bytes - */ -function parseJSONFromBytes (bytes) { - return JSON.parse(utf8DecodeBytes(bytes)) -} - -/** - * @see https://fetch.spec.whatwg.org/#concept-body-mime-type - * @param {import('./response').Response|import('./request').Request} object - */ -function bodyMimeType (object) { - const { headersList } = object[kState] - const contentType = headersList.get('content-type') - - if (contentType === null) { - return 'failure' - } - - return parseMIMEType(contentType) -} - -module.exports = { - extractBody, - safelyExtractBody, - cloneBody, - mixinBody -} - - -/***/ }), - -/***/ 7326: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { MessageChannel, receiveMessageOnPort } = __nccwpck_require__(8167) - -const corsSafeListedMethods = ['GET', 'HEAD', 'POST'] -const corsSafeListedMethodsSet = new Set(corsSafeListedMethods) - -const nullBodyStatus = [101, 204, 205, 304] - -const redirectStatus = [301, 302, 303, 307, 308] -const redirectStatusSet = new Set(redirectStatus) - -// https://fetch.spec.whatwg.org/#block-bad-port -const badPorts = [ - '1', '7', '9', '11', '13', '15', '17', '19', '20', '21', '22', '23', '25', '37', '42', '43', '53', '69', '77', '79', - '87', '95', '101', '102', '103', '104', '109', '110', '111', '113', '115', '117', '119', '123', '135', '137', - '139', '143', '161', '179', '389', '427', '465', '512', '513', '514', '515', '526', '530', '531', '532', - '540', '548', '554', '556', '563', '587', '601', '636', '989', '990', '993', '995', '1719', '1720', '1723', - '2049', '3659', '4045', '5060', '5061', '6000', '6566', '6665', '6666', '6667', '6668', '6669', '6697', - '10080' -] - -const badPortsSet = new Set(badPorts) - -// https://w3c.github.io/webappsec-referrer-policy/#referrer-policies -const referrerPolicy = [ - '', - 'no-referrer', - 'no-referrer-when-downgrade', - 'same-origin', - 'origin', - 'strict-origin', - 'origin-when-cross-origin', - 'strict-origin-when-cross-origin', - 'unsafe-url' -] -const referrerPolicySet = new Set(referrerPolicy) - -const requestRedirect = ['follow', 'manual', 'error'] - -const safeMethods = ['GET', 'HEAD', 'OPTIONS', 'TRACE'] -const safeMethodsSet = new Set(safeMethods) - -const requestMode = ['navigate', 'same-origin', 'no-cors', 'cors'] - -const requestCredentials = ['omit', 'same-origin', 'include'] - -const requestCache = [ - 'default', - 'no-store', - 'reload', - 'no-cache', - 'force-cache', - 'only-if-cached' -] - -// https://fetch.spec.whatwg.org/#request-body-header-name -const requestBodyHeader = [ - 'content-encoding', - 'content-language', - 'content-location', - 'content-type', - // See https://github.com/nodejs/undici/issues/2021 - // 'Content-Length' is a forbidden header name, which is typically - // removed in the Headers implementation. However, undici doesn't - // filter out headers, so we add it here. - 'content-length' -] - -// https://fetch.spec.whatwg.org/#enumdef-requestduplex -const requestDuplex = [ - 'half' -] - -// http://fetch.spec.whatwg.org/#forbidden-method -const forbiddenMethods = ['CONNECT', 'TRACE', 'TRACK'] -const forbiddenMethodsSet = new Set(forbiddenMethods) - -const subresource = [ - 'audio', - 'audioworklet', - 'font', - 'image', - 'manifest', - 'paintworklet', - 'script', - 'style', - 'track', - 'video', - 'xslt', - '' -] -const subresourceSet = new Set(subresource) - -/** @type {globalThis['DOMException']} */ -const DOMException = globalThis.DOMException ?? (() => { - // DOMException was only made a global in Node v17.0.0, - // but fetch supports >= v16.8. - try { - atob('~') - } catch (err) { - return Object.getPrototypeOf(err).constructor - } -})() - -let channel - -/** @type {globalThis['structuredClone']} */ -const structuredClone = - globalThis.structuredClone ?? - // https://github.com/nodejs/node/blob/b27ae24dcc4251bad726d9d84baf678d1f707fed/lib/internal/structured_clone.js - // structuredClone was added in v17.0.0, but fetch supports v16.8 - function structuredClone (value, options = undefined) { - if (arguments.length === 0) { - throw new TypeError('missing argument') - } - - if (!channel) { - channel = new MessageChannel() - } - channel.port1.unref() - channel.port2.unref() - channel.port1.postMessage(value, options?.transfer) - return receiveMessageOnPort(channel.port2).message - } - -module.exports = { - DOMException, - structuredClone, - subresource, - forbiddenMethods, - requestBodyHeader, - referrerPolicy, - requestRedirect, - requestMode, - requestCredentials, - requestCache, - redirectStatus, - corsSafeListedMethods, - nullBodyStatus, - safeMethods, - badPorts, - requestDuplex, - subresourceSet, - badPortsSet, - redirectStatusSet, - corsSafeListedMethodsSet, - safeMethodsSet, - forbiddenMethodsSet, - referrerPolicySet -} - - -/***/ }), - -/***/ 4322: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const assert = __nccwpck_require__(2613) -const { atob } = __nccwpck_require__(181) -const { isomorphicDecode } = __nccwpck_require__(5523) - -const encoder = new TextEncoder() - -/** - * @see https://mimesniff.spec.whatwg.org/#http-token-code-point - */ -const HTTP_TOKEN_CODEPOINTS = /^[!#$%&'*+-.^_|~A-Za-z0-9]+$/ -const HTTP_WHITESPACE_REGEX = /(\u000A|\u000D|\u0009|\u0020)/ // eslint-disable-line -/** - * @see https://mimesniff.spec.whatwg.org/#http-quoted-string-token-code-point - */ -const HTTP_QUOTED_STRING_TOKENS = /[\u0009|\u0020-\u007E|\u0080-\u00FF]/ // eslint-disable-line - -// https://fetch.spec.whatwg.org/#data-url-processor -/** @param {URL} dataURL */ -function dataURLProcessor (dataURL) { - // 1. Assert: dataURL’s scheme is "data". - assert(dataURL.protocol === 'data:') - - // 2. Let input be the result of running the URL - // serializer on dataURL with exclude fragment - // set to true. - let input = URLSerializer(dataURL, true) - - // 3. Remove the leading "data:" string from input. - input = input.slice(5) - - // 4. Let position point at the start of input. - const position = { position: 0 } - - // 5. Let mimeType be the result of collecting a - // sequence of code points that are not equal - // to U+002C (,), given position. - let mimeType = collectASequenceOfCodePointsFast( - ',', - input, - position - ) - - // 6. Strip leading and trailing ASCII whitespace - // from mimeType. - // Undici implementation note: we need to store the - // length because if the mimetype has spaces removed, - // the wrong amount will be sliced from the input in - // step #9 - const mimeTypeLength = mimeType.length - mimeType = removeASCIIWhitespace(mimeType, true, true) - - // 7. If position is past the end of input, then - // return failure - if (position.position >= input.length) { - return 'failure' - } - - // 8. Advance position by 1. - position.position++ - - // 9. Let encodedBody be the remainder of input. - const encodedBody = input.slice(mimeTypeLength + 1) - - // 10. Let body be the percent-decoding of encodedBody. - let body = stringPercentDecode(encodedBody) - - // 11. If mimeType ends with U+003B (;), followed by - // zero or more U+0020 SPACE, followed by an ASCII - // case-insensitive match for "base64", then: - if (/;(\u0020){0,}base64$/i.test(mimeType)) { - // 1. Let stringBody be the isomorphic decode of body. - const stringBody = isomorphicDecode(body) - - // 2. Set body to the forgiving-base64 decode of - // stringBody. - body = forgivingBase64(stringBody) - - // 3. If body is failure, then return failure. - if (body === 'failure') { - return 'failure' - } - - // 4. Remove the last 6 code points from mimeType. - mimeType = mimeType.slice(0, -6) - - // 5. Remove trailing U+0020 SPACE code points from mimeType, - // if any. - mimeType = mimeType.replace(/(\u0020)+$/, '') - - // 6. Remove the last U+003B (;) code point from mimeType. - mimeType = mimeType.slice(0, -1) - } - - // 12. If mimeType starts with U+003B (;), then prepend - // "text/plain" to mimeType. - if (mimeType.startsWith(';')) { - mimeType = 'text/plain' + mimeType - } - - // 13. Let mimeTypeRecord be the result of parsing - // mimeType. - let mimeTypeRecord = parseMIMEType(mimeType) - - // 14. If mimeTypeRecord is failure, then set - // mimeTypeRecord to text/plain;charset=US-ASCII. - if (mimeTypeRecord === 'failure') { - mimeTypeRecord = parseMIMEType('text/plain;charset=US-ASCII') - } - - // 15. Return a new data: URL struct whose MIME - // type is mimeTypeRecord and body is body. - // https://fetch.spec.whatwg.org/#data-url-struct - return { mimeType: mimeTypeRecord, body } -} - -// https://url.spec.whatwg.org/#concept-url-serializer -/** - * @param {URL} url - * @param {boolean} excludeFragment - */ -function URLSerializer (url, excludeFragment = false) { - if (!excludeFragment) { - return url.href - } - - const href = url.href - const hashLength = url.hash.length - - return hashLength === 0 ? href : href.substring(0, href.length - hashLength) -} - -// https://infra.spec.whatwg.org/#collect-a-sequence-of-code-points -/** - * @param {(char: string) => boolean} condition - * @param {string} input - * @param {{ position: number }} position - */ -function collectASequenceOfCodePoints (condition, input, position) { - // 1. Let result be the empty string. - let result = '' - - // 2. While position doesn’t point past the end of input and the - // code point at position within input meets the condition condition: - while (position.position < input.length && condition(input[position.position])) { - // 1. Append that code point to the end of result. - result += input[position.position] - - // 2. Advance position by 1. - position.position++ - } - - // 3. Return result. - return result -} - -/** - * A faster collectASequenceOfCodePoints that only works when comparing a single character. - * @param {string} char - * @param {string} input - * @param {{ position: number }} position - */ -function collectASequenceOfCodePointsFast (char, input, position) { - const idx = input.indexOf(char, position.position) - const start = position.position - - if (idx === -1) { - position.position = input.length - return input.slice(start) - } - - position.position = idx - return input.slice(start, position.position) -} - -// https://url.spec.whatwg.org/#string-percent-decode -/** @param {string} input */ -function stringPercentDecode (input) { - // 1. Let bytes be the UTF-8 encoding of input. - const bytes = encoder.encode(input) - - // 2. Return the percent-decoding of bytes. - return percentDecode(bytes) -} - -// https://url.spec.whatwg.org/#percent-decode -/** @param {Uint8Array} input */ -function percentDecode (input) { - // 1. Let output be an empty byte sequence. - /** @type {number[]} */ - const output = [] - - // 2. For each byte byte in input: - for (let i = 0; i < input.length; i++) { - const byte = input[i] - - // 1. If byte is not 0x25 (%), then append byte to output. - if (byte !== 0x25) { - output.push(byte) - - // 2. Otherwise, if byte is 0x25 (%) and the next two bytes - // after byte in input are not in the ranges - // 0x30 (0) to 0x39 (9), 0x41 (A) to 0x46 (F), - // and 0x61 (a) to 0x66 (f), all inclusive, append byte - // to output. - } else if ( - byte === 0x25 && - !/^[0-9A-Fa-f]{2}$/i.test(String.fromCharCode(input[i + 1], input[i + 2])) - ) { - output.push(0x25) - - // 3. Otherwise: - } else { - // 1. Let bytePoint be the two bytes after byte in input, - // decoded, and then interpreted as hexadecimal number. - const nextTwoBytes = String.fromCharCode(input[i + 1], input[i + 2]) - const bytePoint = Number.parseInt(nextTwoBytes, 16) - - // 2. Append a byte whose value is bytePoint to output. - output.push(bytePoint) - - // 3. Skip the next two bytes in input. - i += 2 - } - } - - // 3. Return output. - return Uint8Array.from(output) -} - -// https://mimesniff.spec.whatwg.org/#parse-a-mime-type -/** @param {string} input */ -function parseMIMEType (input) { - // 1. Remove any leading and trailing HTTP whitespace - // from input. - input = removeHTTPWhitespace(input, true, true) - - // 2. Let position be a position variable for input, - // initially pointing at the start of input. - const position = { position: 0 } - - // 3. Let type be the result of collecting a sequence - // of code points that are not U+002F (/) from - // input, given position. - const type = collectASequenceOfCodePointsFast( - '/', - input, - position - ) - - // 4. If type is the empty string or does not solely - // contain HTTP token code points, then return failure. - // https://mimesniff.spec.whatwg.org/#http-token-code-point - if (type.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(type)) { - return 'failure' - } - - // 5. If position is past the end of input, then return - // failure - if (position.position > input.length) { - return 'failure' - } - - // 6. Advance position by 1. (This skips past U+002F (/).) - position.position++ - - // 7. Let subtype be the result of collecting a sequence of - // code points that are not U+003B (;) from input, given - // position. - let subtype = collectASequenceOfCodePointsFast( - ';', - input, - position - ) - - // 8. Remove any trailing HTTP whitespace from subtype. - subtype = removeHTTPWhitespace(subtype, false, true) - - // 9. If subtype is the empty string or does not solely - // contain HTTP token code points, then return failure. - if (subtype.length === 0 || !HTTP_TOKEN_CODEPOINTS.test(subtype)) { - return 'failure' - } - - const typeLowercase = type.toLowerCase() - const subtypeLowercase = subtype.toLowerCase() - - // 10. Let mimeType be a new MIME type record whose type - // is type, in ASCII lowercase, and subtype is subtype, - // in ASCII lowercase. - // https://mimesniff.spec.whatwg.org/#mime-type - const mimeType = { - type: typeLowercase, - subtype: subtypeLowercase, - /** @type {Map} */ - parameters: new Map(), - // https://mimesniff.spec.whatwg.org/#mime-type-essence - essence: `${typeLowercase}/${subtypeLowercase}` - } - - // 11. While position is not past the end of input: - while (position.position < input.length) { - // 1. Advance position by 1. (This skips past U+003B (;).) - position.position++ - - // 2. Collect a sequence of code points that are HTTP - // whitespace from input given position. - collectASequenceOfCodePoints( - // https://fetch.spec.whatwg.org/#http-whitespace - char => HTTP_WHITESPACE_REGEX.test(char), - input, - position - ) - - // 3. Let parameterName be the result of collecting a - // sequence of code points that are not U+003B (;) - // or U+003D (=) from input, given position. - let parameterName = collectASequenceOfCodePoints( - (char) => char !== ';' && char !== '=', - input, - position - ) - - // 4. Set parameterName to parameterName, in ASCII - // lowercase. - parameterName = parameterName.toLowerCase() - - // 5. If position is not past the end of input, then: - if (position.position < input.length) { - // 1. If the code point at position within input is - // U+003B (;), then continue. - if (input[position.position] === ';') { - continue - } - - // 2. Advance position by 1. (This skips past U+003D (=).) - position.position++ - } - - // 6. If position is past the end of input, then break. - if (position.position > input.length) { - break - } - - // 7. Let parameterValue be null. - let parameterValue = null - - // 8. If the code point at position within input is - // U+0022 ("), then: - if (input[position.position] === '"') { - // 1. Set parameterValue to the result of collecting - // an HTTP quoted string from input, given position - // and the extract-value flag. - parameterValue = collectAnHTTPQuotedString(input, position, true) - - // 2. Collect a sequence of code points that are not - // U+003B (;) from input, given position. - collectASequenceOfCodePointsFast( - ';', - input, - position - ) - - // 9. Otherwise: - } else { - // 1. Set parameterValue to the result of collecting - // a sequence of code points that are not U+003B (;) - // from input, given position. - parameterValue = collectASequenceOfCodePointsFast( - ';', - input, - position - ) - - // 2. Remove any trailing HTTP whitespace from parameterValue. - parameterValue = removeHTTPWhitespace(parameterValue, false, true) - - // 3. If parameterValue is the empty string, then continue. - if (parameterValue.length === 0) { - continue - } - } - - // 10. If all of the following are true - // - parameterName is not the empty string - // - parameterName solely contains HTTP token code points - // - parameterValue solely contains HTTP quoted-string token code points - // - mimeType’s parameters[parameterName] does not exist - // then set mimeType’s parameters[parameterName] to parameterValue. - if ( - parameterName.length !== 0 && - HTTP_TOKEN_CODEPOINTS.test(parameterName) && - (parameterValue.length === 0 || HTTP_QUOTED_STRING_TOKENS.test(parameterValue)) && - !mimeType.parameters.has(parameterName) - ) { - mimeType.parameters.set(parameterName, parameterValue) - } - } - - // 12. Return mimeType. - return mimeType -} - -// https://infra.spec.whatwg.org/#forgiving-base64-decode -/** @param {string} data */ -function forgivingBase64 (data) { - // 1. Remove all ASCII whitespace from data. - data = data.replace(/[\u0009\u000A\u000C\u000D\u0020]/g, '') // eslint-disable-line - - // 2. If data’s code point length divides by 4 leaving - // no remainder, then: - if (data.length % 4 === 0) { - // 1. If data ends with one or two U+003D (=) code points, - // then remove them from data. - data = data.replace(/=?=$/, '') - } - - // 3. If data’s code point length divides by 4 leaving - // a remainder of 1, then return failure. - if (data.length % 4 === 1) { - return 'failure' - } - - // 4. If data contains a code point that is not one of - // U+002B (+) - // U+002F (/) - // ASCII alphanumeric - // then return failure. - if (/[^+/0-9A-Za-z]/.test(data)) { - return 'failure' - } - - const binary = atob(data) - const bytes = new Uint8Array(binary.length) - - for (let byte = 0; byte < binary.length; byte++) { - bytes[byte] = binary.charCodeAt(byte) - } - - return bytes -} - -// https://fetch.spec.whatwg.org/#collect-an-http-quoted-string -// tests: https://fetch.spec.whatwg.org/#example-http-quoted-string -/** - * @param {string} input - * @param {{ position: number }} position - * @param {boolean?} extractValue - */ -function collectAnHTTPQuotedString (input, position, extractValue) { - // 1. Let positionStart be position. - const positionStart = position.position - - // 2. Let value be the empty string. - let value = '' - - // 3. Assert: the code point at position within input - // is U+0022 ("). - assert(input[position.position] === '"') - - // 4. Advance position by 1. - position.position++ - - // 5. While true: - while (true) { - // 1. Append the result of collecting a sequence of code points - // that are not U+0022 (") or U+005C (\) from input, given - // position, to value. - value += collectASequenceOfCodePoints( - (char) => char !== '"' && char !== '\\', - input, - position - ) - - // 2. If position is past the end of input, then break. - if (position.position >= input.length) { - break - } - - // 3. Let quoteOrBackslash be the code point at position within - // input. - const quoteOrBackslash = input[position.position] - - // 4. Advance position by 1. - position.position++ - - // 5. If quoteOrBackslash is U+005C (\), then: - if (quoteOrBackslash === '\\') { - // 1. If position is past the end of input, then append - // U+005C (\) to value and break. - if (position.position >= input.length) { - value += '\\' - break - } - - // 2. Append the code point at position within input to value. - value += input[position.position] - - // 3. Advance position by 1. - position.position++ - - // 6. Otherwise: - } else { - // 1. Assert: quoteOrBackslash is U+0022 ("). - assert(quoteOrBackslash === '"') - - // 2. Break. - break - } - } - - // 6. If the extract-value flag is set, then return value. - if (extractValue) { - return value - } - - // 7. Return the code points from positionStart to position, - // inclusive, within input. - return input.slice(positionStart, position.position) -} - -/** - * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type - */ -function serializeAMimeType (mimeType) { - assert(mimeType !== 'failure') - const { parameters, essence } = mimeType - - // 1. Let serialization be the concatenation of mimeType’s - // type, U+002F (/), and mimeType’s subtype. - let serialization = essence - - // 2. For each name → value of mimeType’s parameters: - for (let [name, value] of parameters.entries()) { - // 1. Append U+003B (;) to serialization. - serialization += ';' - - // 2. Append name to serialization. - serialization += name - - // 3. Append U+003D (=) to serialization. - serialization += '=' - - // 4. If value does not solely contain HTTP token code - // points or value is the empty string, then: - if (!HTTP_TOKEN_CODEPOINTS.test(value)) { - // 1. Precede each occurence of U+0022 (") or - // U+005C (\) in value with U+005C (\). - value = value.replace(/(\\|")/g, '\\$1') - - // 2. Prepend U+0022 (") to value. - value = '"' + value - - // 3. Append U+0022 (") to value. - value += '"' - } - - // 5. Append value to serialization. - serialization += value - } - - // 3. Return serialization. - return serialization -} - -/** - * @see https://fetch.spec.whatwg.org/#http-whitespace - * @param {string} char - */ -function isHTTPWhiteSpace (char) { - return char === '\r' || char === '\n' || char === '\t' || char === ' ' -} - -/** - * @see https://fetch.spec.whatwg.org/#http-whitespace - * @param {string} str - */ -function removeHTTPWhitespace (str, leading = true, trailing = true) { - let lead = 0 - let trail = str.length - 1 - - if (leading) { - for (; lead < str.length && isHTTPWhiteSpace(str[lead]); lead++); - } - - if (trailing) { - for (; trail > 0 && isHTTPWhiteSpace(str[trail]); trail--); - } - - return str.slice(lead, trail + 1) -} - -/** - * @see https://infra.spec.whatwg.org/#ascii-whitespace - * @param {string} char - */ -function isASCIIWhitespace (char) { - return char === '\r' || char === '\n' || char === '\t' || char === '\f' || char === ' ' -} - -/** - * @see https://infra.spec.whatwg.org/#strip-leading-and-trailing-ascii-whitespace - */ -function removeASCIIWhitespace (str, leading = true, trailing = true) { - let lead = 0 - let trail = str.length - 1 - - if (leading) { - for (; lead < str.length && isASCIIWhitespace(str[lead]); lead++); - } - - if (trailing) { - for (; trail > 0 && isASCIIWhitespace(str[trail]); trail--); - } - - return str.slice(lead, trail + 1) -} - -module.exports = { - dataURLProcessor, - URLSerializer, - collectASequenceOfCodePoints, - collectASequenceOfCodePointsFast, - stringPercentDecode, - parseMIMEType, - collectAnHTTPQuotedString, - serializeAMimeType -} - - -/***/ }), - -/***/ 3041: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { Blob, File: NativeFile } = __nccwpck_require__(181) -const { types } = __nccwpck_require__(9023) -const { kState } = __nccwpck_require__(9710) -const { isBlobLike } = __nccwpck_require__(5523) -const { webidl } = __nccwpck_require__(4222) -const { parseMIMEType, serializeAMimeType } = __nccwpck_require__(4322) -const { kEnumerableProperty } = __nccwpck_require__(3440) -const encoder = new TextEncoder() - -class File extends Blob { - constructor (fileBits, fileName, options = {}) { - // The File constructor is invoked with two or three parameters, depending - // on whether the optional dictionary parameter is used. When the File() - // constructor is invoked, user agents must run the following steps: - webidl.argumentLengthCheck(arguments, 2, { header: 'File constructor' }) - - fileBits = webidl.converters['sequence'](fileBits) - fileName = webidl.converters.USVString(fileName) - options = webidl.converters.FilePropertyBag(options) - - // 1. Let bytes be the result of processing blob parts given fileBits and - // options. - // Note: Blob handles this for us - - // 2. Let n be the fileName argument to the constructor. - const n = fileName - - // 3. Process FilePropertyBag dictionary argument by running the following - // substeps: - - // 1. If the type member is provided and is not the empty string, let t - // be set to the type dictionary member. If t contains any characters - // outside the range U+0020 to U+007E, then set t to the empty string - // and return from these substeps. - // 2. Convert every character in t to ASCII lowercase. - let t = options.type - let d - - // eslint-disable-next-line no-labels - substep: { - if (t) { - t = parseMIMEType(t) - - if (t === 'failure') { - t = '' - // eslint-disable-next-line no-labels - break substep - } - - t = serializeAMimeType(t).toLowerCase() - } - - // 3. If the lastModified member is provided, let d be set to the - // lastModified dictionary member. If it is not provided, set d to the - // current date and time represented as the number of milliseconds since - // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). - d = options.lastModified - } - - // 4. Return a new File object F such that: - // F refers to the bytes byte sequence. - // F.size is set to the number of total bytes in bytes. - // F.name is set to n. - // F.type is set to t. - // F.lastModified is set to d. - - super(processBlobParts(fileBits, options), { type: t }) - this[kState] = { - name: n, - lastModified: d, - type: t - } - } - - get name () { - webidl.brandCheck(this, File) - - return this[kState].name - } - - get lastModified () { - webidl.brandCheck(this, File) - - return this[kState].lastModified - } - - get type () { - webidl.brandCheck(this, File) - - return this[kState].type - } -} - -class FileLike { - constructor (blobLike, fileName, options = {}) { - // TODO: argument idl type check - - // The File constructor is invoked with two or three parameters, depending - // on whether the optional dictionary parameter is used. When the File() - // constructor is invoked, user agents must run the following steps: - - // 1. Let bytes be the result of processing blob parts given fileBits and - // options. - - // 2. Let n be the fileName argument to the constructor. - const n = fileName - - // 3. Process FilePropertyBag dictionary argument by running the following - // substeps: - - // 1. If the type member is provided and is not the empty string, let t - // be set to the type dictionary member. If t contains any characters - // outside the range U+0020 to U+007E, then set t to the empty string - // and return from these substeps. - // TODO - const t = options.type - - // 2. Convert every character in t to ASCII lowercase. - // TODO - - // 3. If the lastModified member is provided, let d be set to the - // lastModified dictionary member. If it is not provided, set d to the - // current date and time represented as the number of milliseconds since - // the Unix Epoch (which is the equivalent of Date.now() [ECMA-262]). - const d = options.lastModified ?? Date.now() - - // 4. Return a new File object F such that: - // F refers to the bytes byte sequence. - // F.size is set to the number of total bytes in bytes. - // F.name is set to n. - // F.type is set to t. - // F.lastModified is set to d. - - this[kState] = { - blobLike, - name: n, - type: t, - lastModified: d - } - } - - stream (...args) { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.stream(...args) - } - - arrayBuffer (...args) { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.arrayBuffer(...args) - } - - slice (...args) { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.slice(...args) - } - - text (...args) { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.text(...args) - } - - get size () { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.size - } - - get type () { - webidl.brandCheck(this, FileLike) - - return this[kState].blobLike.type - } - - get name () { - webidl.brandCheck(this, FileLike) - - return this[kState].name - } - - get lastModified () { - webidl.brandCheck(this, FileLike) - - return this[kState].lastModified - } - - get [Symbol.toStringTag] () { - return 'File' - } -} - -Object.defineProperties(File.prototype, { - [Symbol.toStringTag]: { - value: 'File', - configurable: true - }, - name: kEnumerableProperty, - lastModified: kEnumerableProperty -}) - -webidl.converters.Blob = webidl.interfaceConverter(Blob) - -webidl.converters.BlobPart = function (V, opts) { - if (webidl.util.Type(V) === 'Object') { - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) - } - - if ( - ArrayBuffer.isView(V) || - types.isAnyArrayBuffer(V) - ) { - return webidl.converters.BufferSource(V, opts) - } - } - - return webidl.converters.USVString(V, opts) -} - -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.BlobPart -) - -// https://www.w3.org/TR/FileAPI/#dfn-FilePropertyBag -webidl.converters.FilePropertyBag = webidl.dictionaryConverter([ - { - key: 'lastModified', - converter: webidl.converters['long long'], - get defaultValue () { - return Date.now() - } - }, - { - key: 'type', - converter: webidl.converters.DOMString, - defaultValue: '' - }, - { - key: 'endings', - converter: (value) => { - value = webidl.converters.DOMString(value) - value = value.toLowerCase() - - if (value !== 'native') { - value = 'transparent' - } - - return value - }, - defaultValue: 'transparent' - } -]) - -/** - * @see https://www.w3.org/TR/FileAPI/#process-blob-parts - * @param {(NodeJS.TypedArray|Blob|string)[]} parts - * @param {{ type: string, endings: string }} options - */ -function processBlobParts (parts, options) { - // 1. Let bytes be an empty sequence of bytes. - /** @type {NodeJS.TypedArray[]} */ - const bytes = [] - - // 2. For each element in parts: - for (const element of parts) { - // 1. If element is a USVString, run the following substeps: - if (typeof element === 'string') { - // 1. Let s be element. - let s = element - - // 2. If the endings member of options is "native", set s - // to the result of converting line endings to native - // of element. - if (options.endings === 'native') { - s = convertLineEndingsNative(s) - } - - // 3. Append the result of UTF-8 encoding s to bytes. - bytes.push(encoder.encode(s)) - } else if ( - types.isAnyArrayBuffer(element) || - types.isTypedArray(element) - ) { - // 2. If element is a BufferSource, get a copy of the - // bytes held by the buffer source, and append those - // bytes to bytes. - if (!element.buffer) { // ArrayBuffer - bytes.push(new Uint8Array(element)) - } else { - bytes.push( - new Uint8Array(element.buffer, element.byteOffset, element.byteLength) - ) - } - } else if (isBlobLike(element)) { - // 3. If element is a Blob, append the bytes it represents - // to bytes. - bytes.push(element) - } - } - - // 3. Return bytes. - return bytes -} - -/** - * @see https://www.w3.org/TR/FileAPI/#convert-line-endings-to-native - * @param {string} s - */ -function convertLineEndingsNative (s) { - // 1. Let native line ending be be the code point U+000A LF. - let nativeLineEnding = '\n' - - // 2. If the underlying platform’s conventions are to - // represent newlines as a carriage return and line feed - // sequence, set native line ending to the code point - // U+000D CR followed by the code point U+000A LF. - if (process.platform === 'win32') { - nativeLineEnding = '\r\n' - } - - return s.replace(/\r?\n/g, nativeLineEnding) -} - -// If this function is moved to ./util.js, some tools (such as -// rollup) will warn about circular dependencies. See: -// https://github.com/nodejs/undici/issues/1629 -function isFileLike (object) { - return ( - (NativeFile && object instanceof NativeFile) || - object instanceof File || ( - object && - (typeof object.stream === 'function' || - typeof object.arrayBuffer === 'function') && - object[Symbol.toStringTag] === 'File' - ) - ) -} - -module.exports = { File, FileLike, isFileLike } - - -/***/ }), - -/***/ 3073: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { isBlobLike, toUSVString, makeIterator } = __nccwpck_require__(5523) -const { kState } = __nccwpck_require__(9710) -const { File: UndiciFile, FileLike, isFileLike } = __nccwpck_require__(3041) -const { webidl } = __nccwpck_require__(4222) -const { Blob, File: NativeFile } = __nccwpck_require__(181) - -/** @type {globalThis['File']} */ -const File = NativeFile ?? UndiciFile - -// https://xhr.spec.whatwg.org/#formdata -class FormData { - constructor (form) { - if (form !== undefined) { - throw webidl.errors.conversionFailed({ - prefix: 'FormData constructor', - argument: 'Argument 1', - types: ['undefined'] - }) - } - - this[kState] = [] - } - - append (name, value, filename = undefined) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.append' }) - - if (arguments.length === 3 && !isBlobLike(value)) { - throw new TypeError( - "Failed to execute 'append' on 'FormData': parameter 2 is not of type 'Blob'" - ) - } - - // 1. Let value be value if given; otherwise blobValue. - - name = webidl.converters.USVString(name) - value = isBlobLike(value) - ? webidl.converters.Blob(value, { strict: false }) - : webidl.converters.USVString(value) - filename = arguments.length === 3 - ? webidl.converters.USVString(filename) - : undefined - - // 2. Let entry be the result of creating an entry with - // name, value, and filename if given. - const entry = makeEntry(name, value, filename) - - // 3. Append entry to this’s entry list. - this[kState].push(entry) - } - - delete (name) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.delete' }) - - name = webidl.converters.USVString(name) - - // The delete(name) method steps are to remove all entries whose name - // is name from this’s entry list. - this[kState] = this[kState].filter(entry => entry.name !== name) - } - - get (name) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.get' }) - - name = webidl.converters.USVString(name) - - // 1. If there is no entry whose name is name in this’s entry list, - // then return null. - const idx = this[kState].findIndex((entry) => entry.name === name) - if (idx === -1) { - return null - } - - // 2. Return the value of the first entry whose name is name from - // this’s entry list. - return this[kState][idx].value - } - - getAll (name) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.getAll' }) - - name = webidl.converters.USVString(name) - - // 1. If there is no entry whose name is name in this’s entry list, - // then return the empty list. - // 2. Return the values of all entries whose name is name, in order, - // from this’s entry list. - return this[kState] - .filter((entry) => entry.name === name) - .map((entry) => entry.value) - } - - has (name) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.has' }) - - name = webidl.converters.USVString(name) - - // The has(name) method steps are to return true if there is an entry - // whose name is name in this’s entry list; otherwise false. - return this[kState].findIndex((entry) => entry.name === name) !== -1 - } - - set (name, value, filename = undefined) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 2, { header: 'FormData.set' }) - - if (arguments.length === 3 && !isBlobLike(value)) { - throw new TypeError( - "Failed to execute 'set' on 'FormData': parameter 2 is not of type 'Blob'" - ) - } - - // The set(name, value) and set(name, blobValue, filename) method steps - // are: - - // 1. Let value be value if given; otherwise blobValue. - - name = webidl.converters.USVString(name) - value = isBlobLike(value) - ? webidl.converters.Blob(value, { strict: false }) - : webidl.converters.USVString(value) - filename = arguments.length === 3 - ? toUSVString(filename) - : undefined - - // 2. Let entry be the result of creating an entry with name, value, and - // filename if given. - const entry = makeEntry(name, value, filename) - - // 3. If there are entries in this’s entry list whose name is name, then - // replace the first such entry with entry and remove the others. - const idx = this[kState].findIndex((entry) => entry.name === name) - if (idx !== -1) { - this[kState] = [ - ...this[kState].slice(0, idx), - entry, - ...this[kState].slice(idx + 1).filter((entry) => entry.name !== name) - ] - } else { - // 4. Otherwise, append entry to this’s entry list. - this[kState].push(entry) - } - } - - entries () { - webidl.brandCheck(this, FormData) - - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'key+value' - ) - } - - keys () { - webidl.brandCheck(this, FormData) - - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'key' - ) - } - - values () { - webidl.brandCheck(this, FormData) - - return makeIterator( - () => this[kState].map(pair => [pair.name, pair.value]), - 'FormData', - 'value' - ) - } - - /** - * @param {(value: string, key: string, self: FormData) => void} callbackFn - * @param {unknown} thisArg - */ - forEach (callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, FormData) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FormData.forEach' }) - - if (typeof callbackFn !== 'function') { - throw new TypeError( - "Failed to execute 'forEach' on 'FormData': parameter 1 is not of type 'Function'." - ) - } - - for (const [key, value] of this) { - callbackFn.apply(thisArg, [value, key, this]) - } - } -} - -FormData.prototype[Symbol.iterator] = FormData.prototype.entries - -Object.defineProperties(FormData.prototype, { - [Symbol.toStringTag]: { - value: 'FormData', - configurable: true - } -}) - -/** - * @see https://html.spec.whatwg.org/multipage/form-control-infrastructure.html#create-an-entry - * @param {string} name - * @param {string|Blob} value - * @param {?string} filename - * @returns - */ -function makeEntry (name, value, filename) { - // 1. Set name to the result of converting name into a scalar value string. - // "To convert a string into a scalar value string, replace any surrogates - // with U+FFFD." - // see: https://nodejs.org/dist/latest-v18.x/docs/api/buffer.html#buftostringencoding-start-end - name = Buffer.from(name).toString('utf8') - - // 2. If value is a string, then set value to the result of converting - // value into a scalar value string. - if (typeof value === 'string') { - value = Buffer.from(value).toString('utf8') - } else { - // 3. Otherwise: - - // 1. If value is not a File object, then set value to a new File object, - // representing the same bytes, whose name attribute value is "blob" - if (!isFileLike(value)) { - value = value instanceof Blob - ? new File([value], 'blob', { type: value.type }) - : new FileLike(value, 'blob', { type: value.type }) - } - - // 2. If filename is given, then set value to a new File object, - // representing the same bytes, whose name attribute is filename. - if (filename !== undefined) { - /** @type {FilePropertyBag} */ - const options = { - type: value.type, - lastModified: value.lastModified - } - - value = (NativeFile && value instanceof NativeFile) || value instanceof UndiciFile - ? new File([value], filename, options) - : new FileLike(value, filename, options) - } - } - - // 4. Return an entry whose name is name and whose value is value. - return { name, value } -} - -module.exports = { FormData } - - -/***/ }), - -/***/ 5628: -/***/ ((module) => { - - - -// In case of breaking changes, increase the version -// number to avoid conflicts. -const globalOrigin = Symbol.for('undici.globalOrigin.1') - -function getGlobalOrigin () { - return globalThis[globalOrigin] -} - -function setGlobalOrigin (newOrigin) { - if (newOrigin === undefined) { - Object.defineProperty(globalThis, globalOrigin, { - value: undefined, - writable: true, - enumerable: false, - configurable: false - }) - - return - } - - const parsedURL = new URL(newOrigin) - - if (parsedURL.protocol !== 'http:' && parsedURL.protocol !== 'https:') { - throw new TypeError(`Only http & https urls are allowed, received ${parsedURL.protocol}`) - } - - Object.defineProperty(globalThis, globalOrigin, { - value: parsedURL, - writable: true, - enumerable: false, - configurable: false - }) -} - -module.exports = { - getGlobalOrigin, - setGlobalOrigin -} - - -/***/ }), - -/***/ 6349: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// https://github.com/Ethan-Arrowood/undici-fetch - - - -const { kHeadersList, kConstruct } = __nccwpck_require__(6443) -const { kGuard } = __nccwpck_require__(9710) -const { kEnumerableProperty } = __nccwpck_require__(3440) -const { - makeIterator, - isValidHeaderName, - isValidHeaderValue -} = __nccwpck_require__(5523) -const util = __nccwpck_require__(9023) -const { webidl } = __nccwpck_require__(4222) -const assert = __nccwpck_require__(2613) - -const kHeadersMap = Symbol('headers map') -const kHeadersSortedMap = Symbol('headers map sorted') - -/** - * @param {number} code - */ -function isHTTPWhiteSpaceCharCode (code) { - return code === 0x00a || code === 0x00d || code === 0x009 || code === 0x020 -} - -/** - * @see https://fetch.spec.whatwg.org/#concept-header-value-normalize - * @param {string} potentialValue - */ -function headerValueNormalize (potentialValue) { - // To normalize a byte sequence potentialValue, remove - // any leading and trailing HTTP whitespace bytes from - // potentialValue. - let i = 0; let j = potentialValue.length - - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(j - 1))) --j - while (j > i && isHTTPWhiteSpaceCharCode(potentialValue.charCodeAt(i))) ++i - - return i === 0 && j === potentialValue.length ? potentialValue : potentialValue.substring(i, j) -} - -function fill (headers, object) { - // To fill a Headers object headers with a given object object, run these steps: - - // 1. If object is a sequence, then for each header in object: - // Note: webidl conversion to array has already been done. - if (Array.isArray(object)) { - for (let i = 0; i < object.length; ++i) { - const header = object[i] - // 1. If header does not contain exactly two items, then throw a TypeError. - if (header.length !== 2) { - throw webidl.errors.exception({ - header: 'Headers constructor', - message: `expected name/value pair to be length 2, found ${header.length}.` - }) - } - - // 2. Append (header’s first item, header’s second item) to headers. - appendHeader(headers, header[0], header[1]) - } - } else if (typeof object === 'object' && object !== null) { - // Note: null should throw - - // 2. Otherwise, object is a record, then for each key → value in object, - // append (key, value) to headers - const keys = Object.keys(object) - for (let i = 0; i < keys.length; ++i) { - appendHeader(headers, keys[i], object[keys[i]]) - } - } else { - throw webidl.errors.conversionFailed({ - prefix: 'Headers constructor', - argument: 'Argument 1', - types: ['sequence>', 'record'] - }) - } -} - -/** - * @see https://fetch.spec.whatwg.org/#concept-headers-append - */ -function appendHeader (headers, name, value) { - // 1. Normalize value. - value = headerValueNormalize(value) - - // 2. If name is not a header name or value is not a - // header value, then throw a TypeError. - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.append', - value: name, - type: 'header name' - }) - } else if (!isValidHeaderValue(value)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.append', - value, - type: 'header value' - }) - } - - // 3. If headers’s guard is "immutable", then throw a TypeError. - // 4. Otherwise, if headers’s guard is "request" and name is a - // forbidden header name, return. - // Note: undici does not implement forbidden header names - if (headers[kGuard] === 'immutable') { - throw new TypeError('immutable') - } else if (headers[kGuard] === 'request-no-cors') { - // 5. Otherwise, if headers’s guard is "request-no-cors": - // TODO - } - - // 6. Otherwise, if headers’s guard is "response" and name is a - // forbidden response-header name, return. - - // 7. Append (name, value) to headers’s header list. - return headers[kHeadersList].append(name, value) - - // 8. If headers’s guard is "request-no-cors", then remove - // privileged no-CORS request headers from headers -} - -class HeadersList { - /** @type {[string, string][]|null} */ - cookies = null - - constructor (init) { - if (init instanceof HeadersList) { - this[kHeadersMap] = new Map(init[kHeadersMap]) - this[kHeadersSortedMap] = init[kHeadersSortedMap] - this.cookies = init.cookies === null ? null : [...init.cookies] - } else { - this[kHeadersMap] = new Map(init) - this[kHeadersSortedMap] = null - } - } - - // https://fetch.spec.whatwg.org/#header-list-contains - contains (name) { - // A header list list contains a header name name if list - // contains a header whose name is a byte-case-insensitive - // match for name. - name = name.toLowerCase() - - return this[kHeadersMap].has(name) - } - - clear () { - this[kHeadersMap].clear() - this[kHeadersSortedMap] = null - this.cookies = null - } - - // https://fetch.spec.whatwg.org/#concept-header-list-append - append (name, value) { - this[kHeadersSortedMap] = null - - // 1. If list contains name, then set name to the first such - // header’s name. - const lowercaseName = name.toLowerCase() - const exists = this[kHeadersMap].get(lowercaseName) - - // 2. Append (name, value) to list. - if (exists) { - const delimiter = lowercaseName === 'cookie' ? '; ' : ', ' - this[kHeadersMap].set(lowercaseName, { - name: exists.name, - value: `${exists.value}${delimiter}${value}` - }) - } else { - this[kHeadersMap].set(lowercaseName, { name, value }) - } - - if (lowercaseName === 'set-cookie') { - this.cookies ??= [] - this.cookies.push(value) - } - } - - // https://fetch.spec.whatwg.org/#concept-header-list-set - set (name, value) { - this[kHeadersSortedMap] = null - const lowercaseName = name.toLowerCase() - - if (lowercaseName === 'set-cookie') { - this.cookies = [value] - } - - // 1. If list contains name, then set the value of - // the first such header to value and remove the - // others. - // 2. Otherwise, append header (name, value) to list. - this[kHeadersMap].set(lowercaseName, { name, value }) - } - - // https://fetch.spec.whatwg.org/#concept-header-list-delete - delete (name) { - this[kHeadersSortedMap] = null - - name = name.toLowerCase() - - if (name === 'set-cookie') { - this.cookies = null - } - - this[kHeadersMap].delete(name) - } - - // https://fetch.spec.whatwg.org/#concept-header-list-get - get (name) { - const value = this[kHeadersMap].get(name.toLowerCase()) - - // 1. If list does not contain name, then return null. - // 2. Return the values of all headers in list whose name - // is a byte-case-insensitive match for name, - // separated from each other by 0x2C 0x20, in order. - return value === undefined ? null : value.value - } - - * [Symbol.iterator] () { - // use the lowercased name - for (const [name, { value }] of this[kHeadersMap]) { - yield [name, value] - } - } - - get entries () { - const headers = {} - - if (this[kHeadersMap].size) { - for (const { name, value } of this[kHeadersMap].values()) { - headers[name] = value - } - } - - return headers - } -} - -// https://fetch.spec.whatwg.org/#headers-class -class Headers { - constructor (init = undefined) { - if (init === kConstruct) { - return - } - this[kHeadersList] = new HeadersList() - - // The new Headers(init) constructor steps are: - - // 1. Set this’s guard to "none". - this[kGuard] = 'none' - - // 2. If init is given, then fill this with init. - if (init !== undefined) { - init = webidl.converters.HeadersInit(init) - fill(this, init) - } - } - - // https://fetch.spec.whatwg.org/#dom-headers-append - append (name, value) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.append' }) - - name = webidl.converters.ByteString(name) - value = webidl.converters.ByteString(value) - - return appendHeader(this, name, value) - } - - // https://fetch.spec.whatwg.org/#dom-headers-delete - delete (name) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.delete' }) - - name = webidl.converters.ByteString(name) - - // 1. If name is not a header name, then throw a TypeError. - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.delete', - value: name, - type: 'header name' - }) - } - - // 2. If this’s guard is "immutable", then throw a TypeError. - // 3. Otherwise, if this’s guard is "request" and name is a - // forbidden header name, return. - // 4. Otherwise, if this’s guard is "request-no-cors", name - // is not a no-CORS-safelisted request-header name, and - // name is not a privileged no-CORS request-header name, - // return. - // 5. Otherwise, if this’s guard is "response" and name is - // a forbidden response-header name, return. - // Note: undici does not implement forbidden header names - if (this[kGuard] === 'immutable') { - throw new TypeError('immutable') - } else if (this[kGuard] === 'request-no-cors') { - // TODO - } - - // 6. If this’s header list does not contain name, then - // return. - if (!this[kHeadersList].contains(name)) { - return - } - - // 7. Delete name from this’s header list. - // 8. If this’s guard is "request-no-cors", then remove - // privileged no-CORS request headers from this. - this[kHeadersList].delete(name) - } - - // https://fetch.spec.whatwg.org/#dom-headers-get - get (name) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.get' }) - - name = webidl.converters.ByteString(name) - - // 1. If name is not a header name, then throw a TypeError. - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.get', - value: name, - type: 'header name' - }) - } - - // 2. Return the result of getting name from this’s header - // list. - return this[kHeadersList].get(name) - } - - // https://fetch.spec.whatwg.org/#dom-headers-has - has (name) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.has' }) - - name = webidl.converters.ByteString(name) - - // 1. If name is not a header name, then throw a TypeError. - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.has', - value: name, - type: 'header name' - }) - } - - // 2. Return true if this’s header list contains name; - // otherwise false. - return this[kHeadersList].contains(name) - } - - // https://fetch.spec.whatwg.org/#dom-headers-set - set (name, value) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 2, { header: 'Headers.set' }) - - name = webidl.converters.ByteString(name) - value = webidl.converters.ByteString(value) - - // 1. Normalize value. - value = headerValueNormalize(value) - - // 2. If name is not a header name or value is not a - // header value, then throw a TypeError. - if (!isValidHeaderName(name)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.set', - value: name, - type: 'header name' - }) - } else if (!isValidHeaderValue(value)) { - throw webidl.errors.invalidArgument({ - prefix: 'Headers.set', - value, - type: 'header value' - }) - } - - // 3. If this’s guard is "immutable", then throw a TypeError. - // 4. Otherwise, if this’s guard is "request" and name is a - // forbidden header name, return. - // 5. Otherwise, if this’s guard is "request-no-cors" and - // name/value is not a no-CORS-safelisted request-header, - // return. - // 6. Otherwise, if this’s guard is "response" and name is a - // forbidden response-header name, return. - // Note: undici does not implement forbidden header names - if (this[kGuard] === 'immutable') { - throw new TypeError('immutable') - } else if (this[kGuard] === 'request-no-cors') { - // TODO - } - - // 7. Set (name, value) in this’s header list. - // 8. If this’s guard is "request-no-cors", then remove - // privileged no-CORS request headers from this - this[kHeadersList].set(name, value) - } - - // https://fetch.spec.whatwg.org/#dom-headers-getsetcookie - getSetCookie () { - webidl.brandCheck(this, Headers) - - // 1. If this’s header list does not contain `Set-Cookie`, then return « ». - // 2. Return the values of all headers in this’s header list whose name is - // a byte-case-insensitive match for `Set-Cookie`, in order. - - const list = this[kHeadersList].cookies - - if (list) { - return [...list] - } - - return [] - } - - // https://fetch.spec.whatwg.org/#concept-header-list-sort-and-combine - get [kHeadersSortedMap] () { - if (this[kHeadersList][kHeadersSortedMap]) { - return this[kHeadersList][kHeadersSortedMap] - } - - // 1. Let headers be an empty list of headers with the key being the name - // and value the value. - const headers = [] - - // 2. Let names be the result of convert header names to a sorted-lowercase - // set with all the names of the headers in list. - const names = [...this[kHeadersList]].sort((a, b) => a[0] < b[0] ? -1 : 1) - const cookies = this[kHeadersList].cookies - - // 3. For each name of names: - for (let i = 0; i < names.length; ++i) { - const [name, value] = names[i] - // 1. If name is `set-cookie`, then: - if (name === 'set-cookie') { - // 1. Let values be a list of all values of headers in list whose name - // is a byte-case-insensitive match for name, in order. - - // 2. For each value of values: - // 1. Append (name, value) to headers. - for (let j = 0; j < cookies.length; ++j) { - headers.push([name, cookies[j]]) - } - } else { - // 2. Otherwise: - - // 1. Let value be the result of getting name from list. - - // 2. Assert: value is non-null. - assert(value !== null) - - // 3. Append (name, value) to headers. - headers.push([name, value]) - } - } - - this[kHeadersList][kHeadersSortedMap] = headers - - // 4. Return headers. - return headers - } - - keys () { - webidl.brandCheck(this, Headers) - - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'key') - } - - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'key' - ) - } - - values () { - webidl.brandCheck(this, Headers) - - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'value') - } - - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'value' - ) - } - - entries () { - webidl.brandCheck(this, Headers) - - if (this[kGuard] === 'immutable') { - const value = this[kHeadersSortedMap] - return makeIterator(() => value, 'Headers', - 'key+value') - } - - return makeIterator( - () => [...this[kHeadersSortedMap].values()], - 'Headers', - 'key+value' - ) - } - - /** - * @param {(value: string, key: string, self: Headers) => void} callbackFn - * @param {unknown} thisArg - */ - forEach (callbackFn, thisArg = globalThis) { - webidl.brandCheck(this, Headers) - - webidl.argumentLengthCheck(arguments, 1, { header: 'Headers.forEach' }) - - if (typeof callbackFn !== 'function') { - throw new TypeError( - "Failed to execute 'forEach' on 'Headers': parameter 1 is not of type 'Function'." - ) - } - - for (const [key, value] of this) { - callbackFn.apply(thisArg, [value, key, this]) - } - } - - [Symbol.for('nodejs.util.inspect.custom')] () { - webidl.brandCheck(this, Headers) - - return this[kHeadersList] - } -} - -Headers.prototype[Symbol.iterator] = Headers.prototype.entries - -Object.defineProperties(Headers.prototype, { - append: kEnumerableProperty, - delete: kEnumerableProperty, - get: kEnumerableProperty, - has: kEnumerableProperty, - set: kEnumerableProperty, - getSetCookie: kEnumerableProperty, - keys: kEnumerableProperty, - values: kEnumerableProperty, - entries: kEnumerableProperty, - forEach: kEnumerableProperty, - [Symbol.iterator]: { enumerable: false }, - [Symbol.toStringTag]: { - value: 'Headers', - configurable: true - }, - [util.inspect.custom]: { - enumerable: false - } -}) - -webidl.converters.HeadersInit = function (V) { - if (webidl.util.Type(V) === 'Object') { - if (V[Symbol.iterator]) { - return webidl.converters['sequence>'](V) - } - - return webidl.converters['record'](V) - } - - throw webidl.errors.conversionFailed({ - prefix: 'Headers constructor', - argument: 'Argument 1', - types: ['sequence>', 'record'] - }) -} - -module.exports = { - fill, - Headers, - HeadersList -} - - -/***/ }), - -/***/ 2315: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -// https://github.com/Ethan-Arrowood/undici-fetch - - - -const { - Response, - makeNetworkError, - makeAppropriateNetworkError, - filterResponse, - makeResponse -} = __nccwpck_require__(8676) -const { Headers } = __nccwpck_require__(6349) -const { Request, makeRequest } = __nccwpck_require__(5194) -const zlib = __nccwpck_require__(3106) -const { - bytesMatch, - makePolicyContainer, - clonePolicyContainer, - requestBadPort, - TAOCheck, - appendRequestOriginHeader, - responseLocationURL, - requestCurrentURL, - setRequestReferrerPolicyOnRedirect, - tryUpgradeRequestToAPotentiallyTrustworthyURL, - createOpaqueTimingInfo, - appendFetchMetadata, - corsCheck, - crossOriginResourcePolicyCheck, - determineRequestsReferrer, - coarsenedSharedCurrentTime, - createDeferredPromise, - isBlobLike, - sameOrigin, - isCancelled, - isAborted, - isErrorLike, - fullyReadBody, - readableStreamClose, - isomorphicEncode, - urlIsLocal, - urlIsHttpHttpsScheme, - urlHasHttpsScheme -} = __nccwpck_require__(5523) -const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) -const assert = __nccwpck_require__(2613) -const { safelyExtractBody } = __nccwpck_require__(8923) -const { - redirectStatusSet, - nullBodyStatus, - safeMethodsSet, - requestBodyHeader, - subresourceSet, - DOMException -} = __nccwpck_require__(7326) -const { kHeadersList } = __nccwpck_require__(6443) -const EE = __nccwpck_require__(4434) -const { Readable, pipeline } = __nccwpck_require__(2203) -const { addAbortListener, isErrored, isReadable, nodeMajor, nodeMinor } = __nccwpck_require__(3440) -const { dataURLProcessor, serializeAMimeType } = __nccwpck_require__(4322) -const { TransformStream } = __nccwpck_require__(3774) -const { getGlobalDispatcher } = __nccwpck_require__(2581) -const { webidl } = __nccwpck_require__(4222) -const { STATUS_CODES } = __nccwpck_require__(8611) -const GET_OR_HEAD = ['GET', 'HEAD'] - -/** @type {import('buffer').resolveObjectURL} */ -let resolveObjectURL -let ReadableStream = globalThis.ReadableStream - -class Fetch extends EE { - constructor (dispatcher) { - super() - - this.dispatcher = dispatcher - this.connection = null - this.dump = false - this.state = 'ongoing' - // 2 terminated listeners get added per request, - // but only 1 gets removed. If there are 20 redirects, - // 21 listeners will be added. - // See https://github.com/nodejs/undici/issues/1711 - // TODO (fix): Find and fix root cause for leaked listener. - this.setMaxListeners(21) - } - - terminate (reason) { - if (this.state !== 'ongoing') { - return - } - - this.state = 'terminated' - this.connection?.destroy(reason) - this.emit('terminated', reason) - } - - // https://fetch.spec.whatwg.org/#fetch-controller-abort - abort (error) { - if (this.state !== 'ongoing') { - return - } - - // 1. Set controller’s state to "aborted". - this.state = 'aborted' - - // 2. Let fallbackError be an "AbortError" DOMException. - // 3. Set error to fallbackError if it is not given. - if (!error) { - error = new DOMException('The operation was aborted.', 'AbortError') - } - - // 4. Let serializedError be StructuredSerialize(error). - // If that threw an exception, catch it, and let - // serializedError be StructuredSerialize(fallbackError). - - // 5. Set controller’s serialized abort reason to serializedError. - this.serializedAbortReason = error - - this.connection?.destroy(error) - this.emit('terminated', error) - } -} - -// https://fetch.spec.whatwg.org/#fetch-method -function fetch (input, init = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'globalThis.fetch' }) - - // 1. Let p be a new promise. - const p = createDeferredPromise() - - // 2. Let requestObject be the result of invoking the initial value of - // Request as constructor with input and init as arguments. If this throws - // an exception, reject p with it and return p. - let requestObject - - try { - requestObject = new Request(input, init) - } catch (e) { - p.reject(e) - return p.promise - } - - // 3. Let request be requestObject’s request. - const request = requestObject[kState] - - // 4. If requestObject’s signal’s aborted flag is set, then: - if (requestObject.signal.aborted) { - // 1. Abort the fetch() call with p, request, null, and - // requestObject’s signal’s abort reason. - abortFetch(p, request, null, requestObject.signal.reason) - - // 2. Return p. - return p.promise - } - - // 5. Let globalObject be request’s client’s global object. - const globalObject = request.client.globalObject - - // 6. If globalObject is a ServiceWorkerGlobalScope object, then set - // request’s service-workers mode to "none". - if (globalObject?.constructor?.name === 'ServiceWorkerGlobalScope') { - request.serviceWorkers = 'none' - } - - // 7. Let responseObject be null. - let responseObject = null - - // 8. Let relevantRealm be this’s relevant Realm. - const relevantRealm = null - - // 9. Let locallyAborted be false. - let locallyAborted = false - - // 10. Let controller be null. - let controller = null - - // 11. Add the following abort steps to requestObject’s signal: - addAbortListener( - requestObject.signal, - () => { - // 1. Set locallyAborted to true. - locallyAborted = true - - // 2. Assert: controller is non-null. - assert(controller != null) - - // 3. Abort controller with requestObject’s signal’s abort reason. - controller.abort(requestObject.signal.reason) - - // 4. Abort the fetch() call with p, request, responseObject, - // and requestObject’s signal’s abort reason. - abortFetch(p, request, responseObject, requestObject.signal.reason) - } - ) - - // 12. Let handleFetchDone given response response be to finalize and - // report timing with response, globalObject, and "fetch". - const handleFetchDone = (response) => - finalizeAndReportTiming(response, 'fetch') - - // 13. Set controller to the result of calling fetch given request, - // with processResponseEndOfBody set to handleFetchDone, and processResponse - // given response being these substeps: - - const processResponse = (response) => { - // 1. If locallyAborted is true, terminate these substeps. - if (locallyAborted) { - return Promise.resolve() - } - - // 2. If response’s aborted flag is set, then: - if (response.aborted) { - // 1. Let deserializedError be the result of deserialize a serialized - // abort reason given controller’s serialized abort reason and - // relevantRealm. - - // 2. Abort the fetch() call with p, request, responseObject, and - // deserializedError. - - abortFetch(p, request, responseObject, controller.serializedAbortReason) - return Promise.resolve() - } - - // 3. If response is a network error, then reject p with a TypeError - // and terminate these substeps. - if (response.type === 'error') { - p.reject( - Object.assign(new TypeError('fetch failed'), { cause: response.error }) - ) - return Promise.resolve() - } - - // 4. Set responseObject to the result of creating a Response object, - // given response, "immutable", and relevantRealm. - responseObject = new Response() - responseObject[kState] = response - responseObject[kRealm] = relevantRealm - responseObject[kHeaders][kHeadersList] = response.headersList - responseObject[kHeaders][kGuard] = 'immutable' - responseObject[kHeaders][kRealm] = relevantRealm - - // 5. Resolve p with responseObject. - p.resolve(responseObject) - } - - controller = fetching({ - request, - processResponseEndOfBody: handleFetchDone, - processResponse, - dispatcher: init.dispatcher ?? getGlobalDispatcher() // undici - }) - - // 14. Return p. - return p.promise -} - -// https://fetch.spec.whatwg.org/#finalize-and-report-timing -function finalizeAndReportTiming (response, initiatorType = 'other') { - // 1. If response is an aborted network error, then return. - if (response.type === 'error' && response.aborted) { - return - } - - // 2. If response’s URL list is null or empty, then return. - if (!response.urlList?.length) { - return - } - - // 3. Let originalURL be response’s URL list[0]. - const originalURL = response.urlList[0] - - // 4. Let timingInfo be response’s timing info. - let timingInfo = response.timingInfo - - // 5. Let cacheState be response’s cache state. - let cacheState = response.cacheState - - // 6. If originalURL’s scheme is not an HTTP(S) scheme, then return. - if (!urlIsHttpHttpsScheme(originalURL)) { - return - } - - // 7. If timingInfo is null, then return. - if (timingInfo === null) { - return - } - - // 8. If response’s timing allow passed flag is not set, then: - if (!response.timingAllowPassed) { - // 1. Set timingInfo to a the result of creating an opaque timing info for timingInfo. - timingInfo = createOpaqueTimingInfo({ - startTime: timingInfo.startTime - }) - - // 2. Set cacheState to the empty string. - cacheState = '' - } - - // 9. Set timingInfo’s end time to the coarsened shared current time - // given global’s relevant settings object’s cross-origin isolated - // capability. - // TODO: given global’s relevant settings object’s cross-origin isolated - // capability? - timingInfo.endTime = coarsenedSharedCurrentTime() - - // 10. Set response’s timing info to timingInfo. - response.timingInfo = timingInfo - - // 11. Mark resource timing for timingInfo, originalURL, initiatorType, - // global, and cacheState. - markResourceTiming( - timingInfo, - originalURL, - initiatorType, - globalThis, - cacheState - ) -} - -// https://w3c.github.io/resource-timing/#dfn-mark-resource-timing -function markResourceTiming (timingInfo, originalURL, initiatorType, globalThis, cacheState) { - if (nodeMajor > 18 || (nodeMajor === 18 && nodeMinor >= 2)) { - performance.markResourceTiming(timingInfo, originalURL.href, initiatorType, globalThis, cacheState) - } -} - -// https://fetch.spec.whatwg.org/#abort-fetch -function abortFetch (p, request, responseObject, error) { - // Note: AbortSignal.reason was added in node v17.2.0 - // which would give us an undefined error to reject with. - // Remove this once node v16 is no longer supported. - if (!error) { - error = new DOMException('The operation was aborted.', 'AbortError') - } - - // 1. Reject promise with error. - p.reject(error) - - // 2. If request’s body is not null and is readable, then cancel request’s - // body with error. - if (request.body != null && isReadable(request.body?.stream)) { - request.body.stream.cancel(error).catch((err) => { - if (err.code === 'ERR_INVALID_STATE') { - // Node bug? - return - } - throw err - }) - } - - // 3. If responseObject is null, then return. - if (responseObject == null) { - return - } - - // 4. Let response be responseObject’s response. - const response = responseObject[kState] - - // 5. If response’s body is not null and is readable, then error response’s - // body with error. - if (response.body != null && isReadable(response.body?.stream)) { - response.body.stream.cancel(error).catch((err) => { - if (err.code === 'ERR_INVALID_STATE') { - // Node bug? - return - } - throw err - }) - } -} - -// https://fetch.spec.whatwg.org/#fetching -function fetching ({ - request, - processRequestBodyChunkLength, - processRequestEndOfBody, - processResponse, - processResponseEndOfBody, - processResponseConsumeBody, - useParallelQueue = false, - dispatcher // undici -}) { - // 1. Let taskDestination be null. - let taskDestination = null - - // 2. Let crossOriginIsolatedCapability be false. - let crossOriginIsolatedCapability = false - - // 3. If request’s client is non-null, then: - if (request.client != null) { - // 1. Set taskDestination to request’s client’s global object. - taskDestination = request.client.globalObject - - // 2. Set crossOriginIsolatedCapability to request’s client’s cross-origin - // isolated capability. - crossOriginIsolatedCapability = - request.client.crossOriginIsolatedCapability - } - - // 4. If useParallelQueue is true, then set taskDestination to the result of - // starting a new parallel queue. - // TODO - - // 5. Let timingInfo be a new fetch timing info whose start time and - // post-redirect start time are the coarsened shared current time given - // crossOriginIsolatedCapability. - const currenTime = coarsenedSharedCurrentTime(crossOriginIsolatedCapability) - const timingInfo = createOpaqueTimingInfo({ - startTime: currenTime - }) - - // 6. Let fetchParams be a new fetch params whose - // request is request, - // timing info is timingInfo, - // process request body chunk length is processRequestBodyChunkLength, - // process request end-of-body is processRequestEndOfBody, - // process response is processResponse, - // process response consume body is processResponseConsumeBody, - // process response end-of-body is processResponseEndOfBody, - // task destination is taskDestination, - // and cross-origin isolated capability is crossOriginIsolatedCapability. - const fetchParams = { - controller: new Fetch(dispatcher), - request, - timingInfo, - processRequestBodyChunkLength, - processRequestEndOfBody, - processResponse, - processResponseConsumeBody, - processResponseEndOfBody, - taskDestination, - crossOriginIsolatedCapability - } - - // 7. If request’s body is a byte sequence, then set request’s body to - // request’s body as a body. - // NOTE: Since fetching is only called from fetch, body should already be - // extracted. - assert(!request.body || request.body.stream) - - // 8. If request’s window is "client", then set request’s window to request’s - // client, if request’s client’s global object is a Window object; otherwise - // "no-window". - if (request.window === 'client') { - // TODO: What if request.client is null? - request.window = - request.client?.globalObject?.constructor?.name === 'Window' - ? request.client - : 'no-window' - } - - // 9. If request’s origin is "client", then set request’s origin to request’s - // client’s origin. - if (request.origin === 'client') { - // TODO: What if request.client is null? - request.origin = request.client?.origin - } - - // 10. If all of the following conditions are true: - // TODO - - // 11. If request’s policy container is "client", then: - if (request.policyContainer === 'client') { - // 1. If request’s client is non-null, then set request’s policy - // container to a clone of request’s client’s policy container. [HTML] - if (request.client != null) { - request.policyContainer = clonePolicyContainer( - request.client.policyContainer - ) - } else { - // 2. Otherwise, set request’s policy container to a new policy - // container. - request.policyContainer = makePolicyContainer() - } - } - - // 12. If request’s header list does not contain `Accept`, then: - if (!request.headersList.contains('accept')) { - // 1. Let value be `*/*`. - const value = '*/*' - - // 2. A user agent should set value to the first matching statement, if - // any, switching on request’s destination: - // "document" - // "frame" - // "iframe" - // `text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8` - // "image" - // `image/png,image/svg+xml,image/*;q=0.8,*/*;q=0.5` - // "style" - // `text/css,*/*;q=0.1` - // TODO - - // 3. Append `Accept`/value to request’s header list. - request.headersList.append('accept', value) - } - - // 13. If request’s header list does not contain `Accept-Language`, then - // user agents should append `Accept-Language`/an appropriate value to - // request’s header list. - if (!request.headersList.contains('accept-language')) { - request.headersList.append('accept-language', '*') - } - - // 14. If request’s priority is null, then use request’s initiator and - // destination appropriately in setting request’s priority to a - // user-agent-defined object. - if (request.priority === null) { - // TODO - } - - // 15. If request is a subresource request, then: - if (subresourceSet.has(request.destination)) { - // TODO - } - - // 16. Run main fetch given fetchParams. - mainFetch(fetchParams) - .catch(err => { - fetchParams.controller.terminate(err) - }) - - // 17. Return fetchParam's controller - return fetchParams.controller -} - -// https://fetch.spec.whatwg.org/#concept-main-fetch -async function mainFetch (fetchParams, recursive = false) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - - // 2. Let response be null. - let response = null - - // 3. If request’s local-URLs-only flag is set and request’s current URL is - // not local, then set response to a network error. - if (request.localURLsOnly && !urlIsLocal(requestCurrentURL(request))) { - response = makeNetworkError('local URLs only') - } - - // 4. Run report Content Security Policy violations for request. - // TODO - - // 5. Upgrade request to a potentially trustworthy URL, if appropriate. - tryUpgradeRequestToAPotentiallyTrustworthyURL(request) - - // 6. If should request be blocked due to a bad port, should fetching request - // be blocked as mixed content, or should request be blocked by Content - // Security Policy returns blocked, then set response to a network error. - if (requestBadPort(request) === 'blocked') { - response = makeNetworkError('bad port') - } - // TODO: should fetching request be blocked as mixed content? - // TODO: should request be blocked by Content Security Policy? - - // 7. If request’s referrer policy is the empty string, then set request’s - // referrer policy to request’s policy container’s referrer policy. - if (request.referrerPolicy === '') { - request.referrerPolicy = request.policyContainer.referrerPolicy - } - - // 8. If request’s referrer is not "no-referrer", then set request’s - // referrer to the result of invoking determine request’s referrer. - if (request.referrer !== 'no-referrer') { - request.referrer = determineRequestsReferrer(request) - } - - // 9. Set request’s current URL’s scheme to "https" if all of the following - // conditions are true: - // - request’s current URL’s scheme is "http" - // - request’s current URL’s host is a domain - // - Matching request’s current URL’s host per Known HSTS Host Domain Name - // Matching results in either a superdomain match with an asserted - // includeSubDomains directive or a congruent match (with or without an - // asserted includeSubDomains directive). [HSTS] - // TODO - - // 10. If recursive is false, then run the remaining steps in parallel. - // TODO - - // 11. If response is null, then set response to the result of running - // the steps corresponding to the first matching statement: - if (response === null) { - response = await (async () => { - const currentURL = requestCurrentURL(request) - - if ( - // - request’s current URL’s origin is same origin with request’s origin, - // and request’s response tainting is "basic" - (sameOrigin(currentURL, request.url) && request.responseTainting === 'basic') || - // request’s current URL’s scheme is "data" - (currentURL.protocol === 'data:') || - // - request’s mode is "navigate" or "websocket" - (request.mode === 'navigate' || request.mode === 'websocket') - ) { - // 1. Set request’s response tainting to "basic". - request.responseTainting = 'basic' - - // 2. Return the result of running scheme fetch given fetchParams. - return await schemeFetch(fetchParams) - } - - // request’s mode is "same-origin" - if (request.mode === 'same-origin') { - // 1. Return a network error. - return makeNetworkError('request mode cannot be "same-origin"') - } - - // request’s mode is "no-cors" - if (request.mode === 'no-cors') { - // 1. If request’s redirect mode is not "follow", then return a network - // error. - if (request.redirect !== 'follow') { - return makeNetworkError( - 'redirect mode cannot be "follow" for "no-cors" request' - ) - } - - // 2. Set request’s response tainting to "opaque". - request.responseTainting = 'opaque' - - // 3. Return the result of running scheme fetch given fetchParams. - return await schemeFetch(fetchParams) - } - - // request’s current URL’s scheme is not an HTTP(S) scheme - if (!urlIsHttpHttpsScheme(requestCurrentURL(request))) { - // Return a network error. - return makeNetworkError('URL scheme must be a HTTP(S) scheme') - } - - // - request’s use-CORS-preflight flag is set - // - request’s unsafe-request flag is set and either request’s method is - // not a CORS-safelisted method or CORS-unsafe request-header names with - // request’s header list is not empty - // 1. Set request’s response tainting to "cors". - // 2. Let corsWithPreflightResponse be the result of running HTTP fetch - // given fetchParams and true. - // 3. If corsWithPreflightResponse is a network error, then clear cache - // entries using request. - // 4. Return corsWithPreflightResponse. - // TODO - - // Otherwise - // 1. Set request’s response tainting to "cors". - request.responseTainting = 'cors' - - // 2. Return the result of running HTTP fetch given fetchParams. - return await httpFetch(fetchParams) - })() - } - - // 12. If recursive is true, then return response. - if (recursive) { - return response - } - - // 13. If response is not a network error and response is not a filtered - // response, then: - if (response.status !== 0 && !response.internalResponse) { - // If request’s response tainting is "cors", then: - if (request.responseTainting === 'cors') { - // 1. Let headerNames be the result of extracting header list values - // given `Access-Control-Expose-Headers` and response’s header list. - // TODO - // 2. If request’s credentials mode is not "include" and headerNames - // contains `*`, then set response’s CORS-exposed header-name list to - // all unique header names in response’s header list. - // TODO - // 3. Otherwise, if headerNames is not null or failure, then set - // response’s CORS-exposed header-name list to headerNames. - // TODO - } - - // Set response to the following filtered response with response as its - // internal response, depending on request’s response tainting: - if (request.responseTainting === 'basic') { - response = filterResponse(response, 'basic') - } else if (request.responseTainting === 'cors') { - response = filterResponse(response, 'cors') - } else if (request.responseTainting === 'opaque') { - response = filterResponse(response, 'opaque') - } else { - assert(false) - } - } - - // 14. Let internalResponse be response, if response is a network error, - // and response’s internal response otherwise. - let internalResponse = - response.status === 0 ? response : response.internalResponse - - // 15. If internalResponse’s URL list is empty, then set it to a clone of - // request’s URL list. - if (internalResponse.urlList.length === 0) { - internalResponse.urlList.push(...request.urlList) - } - - // 16. If request’s timing allow failed flag is unset, then set - // internalResponse’s timing allow passed flag. - if (!request.timingAllowFailed) { - response.timingAllowPassed = true - } - - // 17. If response is not a network error and any of the following returns - // blocked - // - should internalResponse to request be blocked as mixed content - // - should internalResponse to request be blocked by Content Security Policy - // - should internalResponse to request be blocked due to its MIME type - // - should internalResponse to request be blocked due to nosniff - // TODO - - // 18. If response’s type is "opaque", internalResponse’s status is 206, - // internalResponse’s range-requested flag is set, and request’s header - // list does not contain `Range`, then set response and internalResponse - // to a network error. - if ( - response.type === 'opaque' && - internalResponse.status === 206 && - internalResponse.rangeRequested && - !request.headers.contains('range') - ) { - response = internalResponse = makeNetworkError() - } - - // 19. If response is not a network error and either request’s method is - // `HEAD` or `CONNECT`, or internalResponse’s status is a null body status, - // set internalResponse’s body to null and disregard any enqueuing toward - // it (if any). - if ( - response.status !== 0 && - (request.method === 'HEAD' || - request.method === 'CONNECT' || - nullBodyStatus.includes(internalResponse.status)) - ) { - internalResponse.body = null - fetchParams.controller.dump = true - } - - // 20. If request’s integrity metadata is not the empty string, then: - if (request.integrity) { - // 1. Let processBodyError be this step: run fetch finale given fetchParams - // and a network error. - const processBodyError = (reason) => - fetchFinale(fetchParams, makeNetworkError(reason)) - - // 2. If request’s response tainting is "opaque", or response’s body is null, - // then run processBodyError and abort these steps. - if (request.responseTainting === 'opaque' || response.body == null) { - processBodyError(response.error) - return - } - - // 3. Let processBody given bytes be these steps: - const processBody = (bytes) => { - // 1. If bytes do not match request’s integrity metadata, - // then run processBodyError and abort these steps. [SRI] - if (!bytesMatch(bytes, request.integrity)) { - processBodyError('integrity mismatch') - return - } - - // 2. Set response’s body to bytes as a body. - response.body = safelyExtractBody(bytes)[0] - - // 3. Run fetch finale given fetchParams and response. - fetchFinale(fetchParams, response) - } - - // 4. Fully read response’s body given processBody and processBodyError. - await fullyReadBody(response.body, processBody, processBodyError) - } else { - // 21. Otherwise, run fetch finale given fetchParams and response. - fetchFinale(fetchParams, response) - } -} - -// https://fetch.spec.whatwg.org/#concept-scheme-fetch -// given a fetch params fetchParams -function schemeFetch (fetchParams) { - // Note: since the connection is destroyed on redirect, which sets fetchParams to a - // cancelled state, we do not want this condition to trigger *unless* there have been - // no redirects. See https://github.com/nodejs/undici/issues/1776 - // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. - if (isCancelled(fetchParams) && fetchParams.request.redirectCount === 0) { - return Promise.resolve(makeAppropriateNetworkError(fetchParams)) - } - - // 2. Let request be fetchParams’s request. - const { request } = fetchParams - - const { protocol: scheme } = requestCurrentURL(request) - - // 3. Switch on request’s current URL’s scheme and run the associated steps: - switch (scheme) { - case 'about:': { - // If request’s current URL’s path is the string "blank", then return a new response - // whose status message is `OK`, header list is « (`Content-Type`, `text/html;charset=utf-8`) », - // and body is the empty byte sequence as a body. - - // Otherwise, return a network error. - return Promise.resolve(makeNetworkError('about scheme is not supported')) - } - case 'blob:': { - if (!resolveObjectURL) { - resolveObjectURL = (__nccwpck_require__(181).resolveObjectURL) - } - - // 1. Let blobURLEntry be request’s current URL’s blob URL entry. - const blobURLEntry = requestCurrentURL(request) - - // https://github.com/web-platform-tests/wpt/blob/7b0ebaccc62b566a1965396e5be7bb2bc06f841f/FileAPI/url/resources/fetch-tests.js#L52-L56 - // Buffer.resolveObjectURL does not ignore URL queries. - if (blobURLEntry.search.length !== 0) { - return Promise.resolve(makeNetworkError('NetworkError when attempting to fetch resource.')) - } - - const blobURLEntryObject = resolveObjectURL(blobURLEntry.toString()) - - // 2. If request’s method is not `GET`, blobURLEntry is null, or blobURLEntry’s - // object is not a Blob object, then return a network error. - if (request.method !== 'GET' || !isBlobLike(blobURLEntryObject)) { - return Promise.resolve(makeNetworkError('invalid method')) - } - - // 3. Let bodyWithType be the result of safely extracting blobURLEntry’s object. - const bodyWithType = safelyExtractBody(blobURLEntryObject) - - // 4. Let body be bodyWithType’s body. - const body = bodyWithType[0] - - // 5. Let length be body’s length, serialized and isomorphic encoded. - const length = isomorphicEncode(`${body.length}`) - - // 6. Let type be bodyWithType’s type if it is non-null; otherwise the empty byte sequence. - const type = bodyWithType[1] ?? '' - - // 7. Return a new response whose status message is `OK`, header list is - // « (`Content-Length`, length), (`Content-Type`, type) », and body is body. - const response = makeResponse({ - statusText: 'OK', - headersList: [ - ['content-length', { name: 'Content-Length', value: length }], - ['content-type', { name: 'Content-Type', value: type }] - ] - }) - - response.body = body - - return Promise.resolve(response) - } - case 'data:': { - // 1. Let dataURLStruct be the result of running the - // data: URL processor on request’s current URL. - const currentURL = requestCurrentURL(request) - const dataURLStruct = dataURLProcessor(currentURL) - - // 2. If dataURLStruct is failure, then return a - // network error. - if (dataURLStruct === 'failure') { - return Promise.resolve(makeNetworkError('failed to fetch the data URL')) - } - - // 3. Let mimeType be dataURLStruct’s MIME type, serialized. - const mimeType = serializeAMimeType(dataURLStruct.mimeType) - - // 4. Return a response whose status message is `OK`, - // header list is « (`Content-Type`, mimeType) », - // and body is dataURLStruct’s body as a body. - return Promise.resolve(makeResponse({ - statusText: 'OK', - headersList: [ - ['content-type', { name: 'Content-Type', value: mimeType }] - ], - body: safelyExtractBody(dataURLStruct.body)[0] - })) - } - case 'file:': { - // For now, unfortunate as it is, file URLs are left as an exercise for the reader. - // When in doubt, return a network error. - return Promise.resolve(makeNetworkError('not implemented... yet...')) - } - case 'http:': - case 'https:': { - // Return the result of running HTTP fetch given fetchParams. - - return httpFetch(fetchParams) - .catch((err) => makeNetworkError(err)) - } - default: { - return Promise.resolve(makeNetworkError('unknown scheme')) - } - } -} - -// https://fetch.spec.whatwg.org/#finalize-response -function finalizeResponse (fetchParams, response) { - // 1. Set fetchParams’s request’s done flag. - fetchParams.request.done = true - - // 2, If fetchParams’s process response done is not null, then queue a fetch - // task to run fetchParams’s process response done given response, with - // fetchParams’s task destination. - if (fetchParams.processResponseDone != null) { - queueMicrotask(() => fetchParams.processResponseDone(response)) - } -} - -// https://fetch.spec.whatwg.org/#fetch-finale -function fetchFinale (fetchParams, response) { - // 1. If response is a network error, then: - if (response.type === 'error') { - // 1. Set response’s URL list to « fetchParams’s request’s URL list[0] ». - response.urlList = [fetchParams.request.urlList[0]] - - // 2. Set response’s timing info to the result of creating an opaque timing - // info for fetchParams’s timing info. - response.timingInfo = createOpaqueTimingInfo({ - startTime: fetchParams.timingInfo.startTime - }) - } - - // 2. Let processResponseEndOfBody be the following steps: - const processResponseEndOfBody = () => { - // 1. Set fetchParams’s request’s done flag. - fetchParams.request.done = true - - // If fetchParams’s process response end-of-body is not null, - // then queue a fetch task to run fetchParams’s process response - // end-of-body given response with fetchParams’s task destination. - if (fetchParams.processResponseEndOfBody != null) { - queueMicrotask(() => fetchParams.processResponseEndOfBody(response)) - } - } - - // 3. If fetchParams’s process response is non-null, then queue a fetch task - // to run fetchParams’s process response given response, with fetchParams’s - // task destination. - if (fetchParams.processResponse != null) { - queueMicrotask(() => fetchParams.processResponse(response)) - } - - // 4. If response’s body is null, then run processResponseEndOfBody. - if (response.body == null) { - processResponseEndOfBody() - } else { - // 5. Otherwise: - - // 1. Let transformStream be a new a TransformStream. - - // 2. Let identityTransformAlgorithm be an algorithm which, given chunk, - // enqueues chunk in transformStream. - const identityTransformAlgorithm = (chunk, controller) => { - controller.enqueue(chunk) - } - - // 3. Set up transformStream with transformAlgorithm set to identityTransformAlgorithm - // and flushAlgorithm set to processResponseEndOfBody. - const transformStream = new TransformStream({ - start () {}, - transform: identityTransformAlgorithm, - flush: processResponseEndOfBody - }, { - size () { - return 1 - } - }, { - size () { - return 1 - } - }) - - // 4. Set response’s body to the result of piping response’s body through transformStream. - response.body = { stream: response.body.stream.pipeThrough(transformStream) } - } - - // 6. If fetchParams’s process response consume body is non-null, then: - if (fetchParams.processResponseConsumeBody != null) { - // 1. Let processBody given nullOrBytes be this step: run fetchParams’s - // process response consume body given response and nullOrBytes. - const processBody = (nullOrBytes) => fetchParams.processResponseConsumeBody(response, nullOrBytes) - - // 2. Let processBodyError be this step: run fetchParams’s process - // response consume body given response and failure. - const processBodyError = (failure) => fetchParams.processResponseConsumeBody(response, failure) - - // 3. If response’s body is null, then queue a fetch task to run processBody - // given null, with fetchParams’s task destination. - if (response.body == null) { - queueMicrotask(() => processBody(null)) - } else { - // 4. Otherwise, fully read response’s body given processBody, processBodyError, - // and fetchParams’s task destination. - return fullyReadBody(response.body, processBody, processBodyError) - } - return Promise.resolve() - } -} - -// https://fetch.spec.whatwg.org/#http-fetch -async function httpFetch (fetchParams) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - - // 2. Let response be null. - let response = null - - // 3. Let actualResponse be null. - let actualResponse = null - - // 4. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo - - // 5. If request’s service-workers mode is "all", then: - if (request.serviceWorkers === 'all') { - // TODO - } - - // 6. If response is null, then: - if (response === null) { - // 1. If makeCORSPreflight is true and one of these conditions is true: - // TODO - - // 2. If request’s redirect mode is "follow", then set request’s - // service-workers mode to "none". - if (request.redirect === 'follow') { - request.serviceWorkers = 'none' - } - - // 3. Set response and actualResponse to the result of running - // HTTP-network-or-cache fetch given fetchParams. - actualResponse = response = await httpNetworkOrCacheFetch(fetchParams) - - // 4. If request’s response tainting is "cors" and a CORS check - // for request and response returns failure, then return a network error. - if ( - request.responseTainting === 'cors' && - corsCheck(request, response) === 'failure' - ) { - return makeNetworkError('cors failure') - } - - // 5. If the TAO check for request and response returns failure, then set - // request’s timing allow failed flag. - if (TAOCheck(request, response) === 'failure') { - request.timingAllowFailed = true - } - } - - // 7. If either request’s response tainting or response’s type - // is "opaque", and the cross-origin resource policy check with - // request’s origin, request’s client, request’s destination, - // and actualResponse returns blocked, then return a network error. - if ( - (request.responseTainting === 'opaque' || response.type === 'opaque') && - crossOriginResourcePolicyCheck( - request.origin, - request.client, - request.destination, - actualResponse - ) === 'blocked' - ) { - return makeNetworkError('blocked') - } - - // 8. If actualResponse’s status is a redirect status, then: - if (redirectStatusSet.has(actualResponse.status)) { - // 1. If actualResponse’s status is not 303, request’s body is not null, - // and the connection uses HTTP/2, then user agents may, and are even - // encouraged to, transmit an RST_STREAM frame. - // See, https://github.com/whatwg/fetch/issues/1288 - if (request.redirect !== 'manual') { - fetchParams.controller.connection.destroy() - } - - // 2. Switch on request’s redirect mode: - if (request.redirect === 'error') { - // Set response to a network error. - response = makeNetworkError('unexpected redirect') - } else if (request.redirect === 'manual') { - // Set response to an opaque-redirect filtered response whose internal - // response is actualResponse. - // NOTE(spec): On the web this would return an `opaqueredirect` response, - // but that doesn't make sense server side. - // See https://github.com/nodejs/undici/issues/1193. - response = actualResponse - } else if (request.redirect === 'follow') { - // Set response to the result of running HTTP-redirect fetch given - // fetchParams and response. - response = await httpRedirectFetch(fetchParams, response) - } else { - assert(false) - } - } - - // 9. Set response’s timing info to timingInfo. - response.timingInfo = timingInfo - - // 10. Return response. - return response -} - -// https://fetch.spec.whatwg.org/#http-redirect-fetch -function httpRedirectFetch (fetchParams, response) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - - // 2. Let actualResponse be response, if response is not a filtered response, - // and response’s internal response otherwise. - const actualResponse = response.internalResponse - ? response.internalResponse - : response - - // 3. Let locationURL be actualResponse’s location URL given request’s current - // URL’s fragment. - let locationURL - - try { - locationURL = responseLocationURL( - actualResponse, - requestCurrentURL(request).hash - ) - - // 4. If locationURL is null, then return response. - if (locationURL == null) { - return response - } - } catch (err) { - // 5. If locationURL is failure, then return a network error. - return Promise.resolve(makeNetworkError(err)) - } - - // 6. If locationURL’s scheme is not an HTTP(S) scheme, then return a network - // error. - if (!urlIsHttpHttpsScheme(locationURL)) { - return Promise.resolve(makeNetworkError('URL scheme must be a HTTP(S) scheme')) - } - - // 7. If request’s redirect count is 20, then return a network error. - if (request.redirectCount === 20) { - return Promise.resolve(makeNetworkError('redirect count exceeded')) - } - - // 8. Increase request’s redirect count by 1. - request.redirectCount += 1 - - // 9. If request’s mode is "cors", locationURL includes credentials, and - // request’s origin is not same origin with locationURL’s origin, then return - // a network error. - if ( - request.mode === 'cors' && - (locationURL.username || locationURL.password) && - !sameOrigin(request, locationURL) - ) { - return Promise.resolve(makeNetworkError('cross origin not allowed for request mode "cors"')) - } - - // 10. If request’s response tainting is "cors" and locationURL includes - // credentials, then return a network error. - if ( - request.responseTainting === 'cors' && - (locationURL.username || locationURL.password) - ) { - return Promise.resolve(makeNetworkError( - 'URL cannot contain credentials for request mode "cors"' - )) - } - - // 11. If actualResponse’s status is not 303, request’s body is non-null, - // and request’s body’s source is null, then return a network error. - if ( - actualResponse.status !== 303 && - request.body != null && - request.body.source == null - ) { - return Promise.resolve(makeNetworkError()) - } - - // 12. If one of the following is true - // - actualResponse’s status is 301 or 302 and request’s method is `POST` - // - actualResponse’s status is 303 and request’s method is not `GET` or `HEAD` - if ( - ([301, 302].includes(actualResponse.status) && request.method === 'POST') || - (actualResponse.status === 303 && - !GET_OR_HEAD.includes(request.method)) - ) { - // then: - // 1. Set request’s method to `GET` and request’s body to null. - request.method = 'GET' - request.body = null - - // 2. For each headerName of request-body-header name, delete headerName from - // request’s header list. - for (const headerName of requestBodyHeader) { - request.headersList.delete(headerName) - } - } - - // 13. If request’s current URL’s origin is not same origin with locationURL’s - // origin, then for each headerName of CORS non-wildcard request-header name, - // delete headerName from request’s header list. - if (!sameOrigin(requestCurrentURL(request), locationURL)) { - // https://fetch.spec.whatwg.org/#cors-non-wildcard-request-header-name - request.headersList.delete('authorization') - - // https://fetch.spec.whatwg.org/#authentication-entries - request.headersList.delete('proxy-authorization', true) - - // "Cookie" and "Host" are forbidden request-headers, which undici doesn't implement. - request.headersList.delete('cookie') - request.headersList.delete('host') - } - - // 14. If request’s body is non-null, then set request’s body to the first return - // value of safely extracting request’s body’s source. - if (request.body != null) { - assert(request.body.source != null) - request.body = safelyExtractBody(request.body.source)[0] - } - - // 15. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo - - // 16. Set timingInfo’s redirect end time and post-redirect start time to the - // coarsened shared current time given fetchParams’s cross-origin isolated - // capability. - timingInfo.redirectEndTime = timingInfo.postRedirectStartTime = - coarsenedSharedCurrentTime(fetchParams.crossOriginIsolatedCapability) - - // 17. If timingInfo’s redirect start time is 0, then set timingInfo’s - // redirect start time to timingInfo’s start time. - if (timingInfo.redirectStartTime === 0) { - timingInfo.redirectStartTime = timingInfo.startTime - } - - // 18. Append locationURL to request’s URL list. - request.urlList.push(locationURL) - - // 19. Invoke set request’s referrer policy on redirect on request and - // actualResponse. - setRequestReferrerPolicyOnRedirect(request, actualResponse) - - // 20. Return the result of running main fetch given fetchParams and true. - return mainFetch(fetchParams, true) -} - -// https://fetch.spec.whatwg.org/#http-network-or-cache-fetch -async function httpNetworkOrCacheFetch ( - fetchParams, - isAuthenticationFetch = false, - isNewConnectionFetch = false -) { - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - - // 2. Let httpFetchParams be null. - let httpFetchParams = null - - // 3. Let httpRequest be null. - let httpRequest = null - - // 4. Let response be null. - let response = null - - // 5. Let storedResponse be null. - // TODO: cache - - // 6. Let httpCache be null. - const httpCache = null - - // 7. Let the revalidatingFlag be unset. - const revalidatingFlag = false - - // 8. Run these steps, but abort when the ongoing fetch is terminated: - - // 1. If request’s window is "no-window" and request’s redirect mode is - // "error", then set httpFetchParams to fetchParams and httpRequest to - // request. - if (request.window === 'no-window' && request.redirect === 'error') { - httpFetchParams = fetchParams - httpRequest = request - } else { - // Otherwise: - - // 1. Set httpRequest to a clone of request. - httpRequest = makeRequest(request) - - // 2. Set httpFetchParams to a copy of fetchParams. - httpFetchParams = { ...fetchParams } - - // 3. Set httpFetchParams’s request to httpRequest. - httpFetchParams.request = httpRequest - } - - // 3. Let includeCredentials be true if one of - const includeCredentials = - request.credentials === 'include' || - (request.credentials === 'same-origin' && - request.responseTainting === 'basic') - - // 4. Let contentLength be httpRequest’s body’s length, if httpRequest’s - // body is non-null; otherwise null. - const contentLength = httpRequest.body ? httpRequest.body.length : null - - // 5. Let contentLengthHeaderValue be null. - let contentLengthHeaderValue = null - - // 6. If httpRequest’s body is null and httpRequest’s method is `POST` or - // `PUT`, then set contentLengthHeaderValue to `0`. - if ( - httpRequest.body == null && - ['POST', 'PUT'].includes(httpRequest.method) - ) { - contentLengthHeaderValue = '0' - } - - // 7. If contentLength is non-null, then set contentLengthHeaderValue to - // contentLength, serialized and isomorphic encoded. - if (contentLength != null) { - contentLengthHeaderValue = isomorphicEncode(`${contentLength}`) - } - - // 8. If contentLengthHeaderValue is non-null, then append - // `Content-Length`/contentLengthHeaderValue to httpRequest’s header - // list. - if (contentLengthHeaderValue != null) { - httpRequest.headersList.append('content-length', contentLengthHeaderValue) - } - - // 9. If contentLengthHeaderValue is non-null, then append (`Content-Length`, - // contentLengthHeaderValue) to httpRequest’s header list. - - // 10. If contentLength is non-null and httpRequest’s keepalive is true, - // then: - if (contentLength != null && httpRequest.keepalive) { - // NOTE: keepalive is a noop outside of browser context. - } - - // 11. If httpRequest’s referrer is a URL, then append - // `Referer`/httpRequest’s referrer, serialized and isomorphic encoded, - // to httpRequest’s header list. - if (httpRequest.referrer instanceof URL) { - httpRequest.headersList.append('referer', isomorphicEncode(httpRequest.referrer.href)) - } - - // 12. Append a request `Origin` header for httpRequest. - appendRequestOriginHeader(httpRequest) - - // 13. Append the Fetch metadata headers for httpRequest. [FETCH-METADATA] - appendFetchMetadata(httpRequest) - - // 14. If httpRequest’s header list does not contain `User-Agent`, then - // user agents should append `User-Agent`/default `User-Agent` value to - // httpRequest’s header list. - if (!httpRequest.headersList.contains('user-agent')) { - httpRequest.headersList.append('user-agent', typeof esbuildDetection === 'undefined' ? 'undici' : 'node') - } - - // 15. If httpRequest’s cache mode is "default" and httpRequest’s header - // list contains `If-Modified-Since`, `If-None-Match`, - // `If-Unmodified-Since`, `If-Match`, or `If-Range`, then set - // httpRequest’s cache mode to "no-store". - if ( - httpRequest.cache === 'default' && - (httpRequest.headersList.contains('if-modified-since') || - httpRequest.headersList.contains('if-none-match') || - httpRequest.headersList.contains('if-unmodified-since') || - httpRequest.headersList.contains('if-match') || - httpRequest.headersList.contains('if-range')) - ) { - httpRequest.cache = 'no-store' - } - - // 16. If httpRequest’s cache mode is "no-cache", httpRequest’s prevent - // no-cache cache-control header modification flag is unset, and - // httpRequest’s header list does not contain `Cache-Control`, then append - // `Cache-Control`/`max-age=0` to httpRequest’s header list. - if ( - httpRequest.cache === 'no-cache' && - !httpRequest.preventNoCacheCacheControlHeaderModification && - !httpRequest.headersList.contains('cache-control') - ) { - httpRequest.headersList.append('cache-control', 'max-age=0') - } - - // 17. If httpRequest’s cache mode is "no-store" or "reload", then: - if (httpRequest.cache === 'no-store' || httpRequest.cache === 'reload') { - // 1. If httpRequest’s header list does not contain `Pragma`, then append - // `Pragma`/`no-cache` to httpRequest’s header list. - if (!httpRequest.headersList.contains('pragma')) { - httpRequest.headersList.append('pragma', 'no-cache') - } - - // 2. If httpRequest’s header list does not contain `Cache-Control`, - // then append `Cache-Control`/`no-cache` to httpRequest’s header list. - if (!httpRequest.headersList.contains('cache-control')) { - httpRequest.headersList.append('cache-control', 'no-cache') - } - } - - // 18. If httpRequest’s header list contains `Range`, then append - // `Accept-Encoding`/`identity` to httpRequest’s header list. - if (httpRequest.headersList.contains('range')) { - httpRequest.headersList.append('accept-encoding', 'identity') - } - - // 19. Modify httpRequest’s header list per HTTP. Do not append a given - // header if httpRequest’s header list contains that header’s name. - // TODO: https://github.com/whatwg/fetch/issues/1285#issuecomment-896560129 - if (!httpRequest.headersList.contains('accept-encoding')) { - if (urlHasHttpsScheme(requestCurrentURL(httpRequest))) { - httpRequest.headersList.append('accept-encoding', 'br, gzip, deflate') - } else { - httpRequest.headersList.append('accept-encoding', 'gzip, deflate') - } - } - - httpRequest.headersList.delete('host') - - // 20. If includeCredentials is true, then: - if (includeCredentials) { - // 1. If the user agent is not configured to block cookies for httpRequest - // (see section 7 of [COOKIES]), then: - // TODO: credentials - // 2. If httpRequest’s header list does not contain `Authorization`, then: - // TODO: credentials - } - - // 21. If there’s a proxy-authentication entry, use it as appropriate. - // TODO: proxy-authentication - - // 22. Set httpCache to the result of determining the HTTP cache - // partition, given httpRequest. - // TODO: cache - - // 23. If httpCache is null, then set httpRequest’s cache mode to - // "no-store". - if (httpCache == null) { - httpRequest.cache = 'no-store' - } - - // 24. If httpRequest’s cache mode is neither "no-store" nor "reload", - // then: - if (httpRequest.mode !== 'no-store' && httpRequest.mode !== 'reload') { - // TODO: cache - } - - // 9. If aborted, then return the appropriate network error for fetchParams. - // TODO - - // 10. If response is null, then: - if (response == null) { - // 1. If httpRequest’s cache mode is "only-if-cached", then return a - // network error. - if (httpRequest.mode === 'only-if-cached') { - return makeNetworkError('only if cached') - } - - // 2. Let forwardResponse be the result of running HTTP-network fetch - // given httpFetchParams, includeCredentials, and isNewConnectionFetch. - const forwardResponse = await httpNetworkFetch( - httpFetchParams, - includeCredentials, - isNewConnectionFetch - ) - - // 3. If httpRequest’s method is unsafe and forwardResponse’s status is - // in the range 200 to 399, inclusive, invalidate appropriate stored - // responses in httpCache, as per the "Invalidation" chapter of HTTP - // Caching, and set storedResponse to null. [HTTP-CACHING] - if ( - !safeMethodsSet.has(httpRequest.method) && - forwardResponse.status >= 200 && - forwardResponse.status <= 399 - ) { - // TODO: cache - } - - // 4. If the revalidatingFlag is set and forwardResponse’s status is 304, - // then: - if (revalidatingFlag && forwardResponse.status === 304) { - // TODO: cache - } - - // 5. If response is null, then: - if (response == null) { - // 1. Set response to forwardResponse. - response = forwardResponse - - // 2. Store httpRequest and forwardResponse in httpCache, as per the - // "Storing Responses in Caches" chapter of HTTP Caching. [HTTP-CACHING] - // TODO: cache - } - } - - // 11. Set response’s URL list to a clone of httpRequest’s URL list. - response.urlList = [...httpRequest.urlList] - - // 12. If httpRequest’s header list contains `Range`, then set response’s - // range-requested flag. - if (httpRequest.headersList.contains('range')) { - response.rangeRequested = true - } - - // 13. Set response’s request-includes-credentials to includeCredentials. - response.requestIncludesCredentials = includeCredentials - - // 14. If response’s status is 401, httpRequest’s response tainting is not - // "cors", includeCredentials is true, and request’s window is an environment - // settings object, then: - // TODO - - // 15. If response’s status is 407, then: - if (response.status === 407) { - // 1. If request’s window is "no-window", then return a network error. - if (request.window === 'no-window') { - return makeNetworkError() - } - - // 2. ??? - - // 3. If fetchParams is canceled, then return the appropriate network error for fetchParams. - if (isCancelled(fetchParams)) { - return makeAppropriateNetworkError(fetchParams) - } - - // 4. Prompt the end user as appropriate in request’s window and store - // the result as a proxy-authentication entry. [HTTP-AUTH] - // TODO: Invoke some kind of callback? - - // 5. Set response to the result of running HTTP-network-or-cache fetch given - // fetchParams. - // TODO - return makeNetworkError('proxy authentication required') - } - - // 16. If all of the following are true - if ( - // response’s status is 421 - response.status === 421 && - // isNewConnectionFetch is false - !isNewConnectionFetch && - // request’s body is null, or request’s body is non-null and request’s body’s source is non-null - (request.body == null || request.body.source != null) - ) { - // then: - - // 1. If fetchParams is canceled, then return the appropriate network error for fetchParams. - if (isCancelled(fetchParams)) { - return makeAppropriateNetworkError(fetchParams) - } - - // 2. Set response to the result of running HTTP-network-or-cache - // fetch given fetchParams, isAuthenticationFetch, and true. - - // TODO (spec): The spec doesn't specify this but we need to cancel - // the active response before we can start a new one. - // https://github.com/whatwg/fetch/issues/1293 - fetchParams.controller.connection.destroy() - - response = await httpNetworkOrCacheFetch( - fetchParams, - isAuthenticationFetch, - true - ) - } - - // 17. If isAuthenticationFetch is true, then create an authentication entry - if (isAuthenticationFetch) { - // TODO - } - - // 18. Return response. - return response -} - -// https://fetch.spec.whatwg.org/#http-network-fetch -async function httpNetworkFetch ( - fetchParams, - includeCredentials = false, - forceNewConnection = false -) { - assert(!fetchParams.controller.connection || fetchParams.controller.connection.destroyed) - - fetchParams.controller.connection = { - abort: null, - destroyed: false, - destroy (err) { - if (!this.destroyed) { - this.destroyed = true - this.abort?.(err ?? new DOMException('The operation was aborted.', 'AbortError')) - } - } - } - - // 1. Let request be fetchParams’s request. - const request = fetchParams.request - - // 2. Let response be null. - let response = null - - // 3. Let timingInfo be fetchParams’s timing info. - const timingInfo = fetchParams.timingInfo - - // 4. Let httpCache be the result of determining the HTTP cache partition, - // given request. - // TODO: cache - const httpCache = null - - // 5. If httpCache is null, then set request’s cache mode to "no-store". - if (httpCache == null) { - request.cache = 'no-store' - } - - // 6. Let networkPartitionKey be the result of determining the network - // partition key given request. - // TODO - - // 7. Let newConnection be "yes" if forceNewConnection is true; otherwise - // "no". - const newConnection = forceNewConnection ? 'yes' : 'no' // eslint-disable-line no-unused-vars - - // 8. Switch on request’s mode: - if (request.mode === 'websocket') { - // Let connection be the result of obtaining a WebSocket connection, - // given request’s current URL. - // TODO - } else { - // Let connection be the result of obtaining a connection, given - // networkPartitionKey, request’s current URL’s origin, - // includeCredentials, and forceNewConnection. - // TODO - } - - // 9. Run these steps, but abort when the ongoing fetch is terminated: - - // 1. If connection is failure, then return a network error. - - // 2. Set timingInfo’s final connection timing info to the result of - // calling clamp and coarsen connection timing info with connection’s - // timing info, timingInfo’s post-redirect start time, and fetchParams’s - // cross-origin isolated capability. - - // 3. If connection is not an HTTP/2 connection, request’s body is non-null, - // and request’s body’s source is null, then append (`Transfer-Encoding`, - // `chunked`) to request’s header list. - - // 4. Set timingInfo’s final network-request start time to the coarsened - // shared current time given fetchParams’s cross-origin isolated - // capability. - - // 5. Set response to the result of making an HTTP request over connection - // using request with the following caveats: - - // - Follow the relevant requirements from HTTP. [HTTP] [HTTP-SEMANTICS] - // [HTTP-COND] [HTTP-CACHING] [HTTP-AUTH] - - // - If request’s body is non-null, and request’s body’s source is null, - // then the user agent may have a buffer of up to 64 kibibytes and store - // a part of request’s body in that buffer. If the user agent reads from - // request’s body beyond that buffer’s size and the user agent needs to - // resend request, then instead return a network error. - - // - Set timingInfo’s final network-response start time to the coarsened - // shared current time given fetchParams’s cross-origin isolated capability, - // immediately after the user agent’s HTTP parser receives the first byte - // of the response (e.g., frame header bytes for HTTP/2 or response status - // line for HTTP/1.x). - - // - Wait until all the headers are transmitted. - - // - Any responses whose status is in the range 100 to 199, inclusive, - // and is not 101, are to be ignored, except for the purposes of setting - // timingInfo’s final network-response start time above. - - // - If request’s header list contains `Transfer-Encoding`/`chunked` and - // response is transferred via HTTP/1.0 or older, then return a network - // error. - - // - If the HTTP request results in a TLS client certificate dialog, then: - - // 1. If request’s window is an environment settings object, make the - // dialog available in request’s window. - - // 2. Otherwise, return a network error. - - // To transmit request’s body body, run these steps: - let requestBody = null - // 1. If body is null and fetchParams’s process request end-of-body is - // non-null, then queue a fetch task given fetchParams’s process request - // end-of-body and fetchParams’s task destination. - if (request.body == null && fetchParams.processRequestEndOfBody) { - queueMicrotask(() => fetchParams.processRequestEndOfBody()) - } else if (request.body != null) { - // 2. Otherwise, if body is non-null: - - // 1. Let processBodyChunk given bytes be these steps: - const processBodyChunk = async function * (bytes) { - // 1. If the ongoing fetch is terminated, then abort these steps. - if (isCancelled(fetchParams)) { - return - } - - // 2. Run this step in parallel: transmit bytes. - yield bytes - - // 3. If fetchParams’s process request body is non-null, then run - // fetchParams’s process request body given bytes’s length. - fetchParams.processRequestBodyChunkLength?.(bytes.byteLength) - } - - // 2. Let processEndOfBody be these steps: - const processEndOfBody = () => { - // 1. If fetchParams is canceled, then abort these steps. - if (isCancelled(fetchParams)) { - return - } - - // 2. If fetchParams’s process request end-of-body is non-null, - // then run fetchParams’s process request end-of-body. - if (fetchParams.processRequestEndOfBody) { - fetchParams.processRequestEndOfBody() - } - } - - // 3. Let processBodyError given e be these steps: - const processBodyError = (e) => { - // 1. If fetchParams is canceled, then abort these steps. - if (isCancelled(fetchParams)) { - return - } - - // 2. If e is an "AbortError" DOMException, then abort fetchParams’s controller. - if (e.name === 'AbortError') { - fetchParams.controller.abort() - } else { - fetchParams.controller.terminate(e) - } - } - - // 4. Incrementally read request’s body given processBodyChunk, processEndOfBody, - // processBodyError, and fetchParams’s task destination. - requestBody = (async function * () { - try { - for await (const bytes of request.body.stream) { - yield * processBodyChunk(bytes) - } - processEndOfBody() - } catch (err) { - processBodyError(err) - } - })() - } - - try { - // socket is only provided for websockets - const { body, status, statusText, headersList, socket } = await dispatch({ body: requestBody }) - - if (socket) { - response = makeResponse({ status, statusText, headersList, socket }) - } else { - const iterator = body[Symbol.asyncIterator]() - fetchParams.controller.next = () => iterator.next() - - response = makeResponse({ status, statusText, headersList }) - } - } catch (err) { - // 10. If aborted, then: - if (err.name === 'AbortError') { - // 1. If connection uses HTTP/2, then transmit an RST_STREAM frame. - fetchParams.controller.connection.destroy() - - // 2. Return the appropriate network error for fetchParams. - return makeAppropriateNetworkError(fetchParams, err) - } - - return makeNetworkError(err) - } - - // 11. Let pullAlgorithm be an action that resumes the ongoing fetch - // if it is suspended. - const pullAlgorithm = () => { - fetchParams.controller.resume() - } - - // 12. Let cancelAlgorithm be an algorithm that aborts fetchParams’s - // controller with reason, given reason. - const cancelAlgorithm = (reason) => { - fetchParams.controller.abort(reason) - } - - // 13. Let highWaterMark be a non-negative, non-NaN number, chosen by - // the user agent. - // TODO - - // 14. Let sizeAlgorithm be an algorithm that accepts a chunk object - // and returns a non-negative, non-NaN, non-infinite number, chosen by the user agent. - // TODO - - // 15. Let stream be a new ReadableStream. - // 16. Set up stream with pullAlgorithm set to pullAlgorithm, - // cancelAlgorithm set to cancelAlgorithm, highWaterMark set to - // highWaterMark, and sizeAlgorithm set to sizeAlgorithm. - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) - } - - const stream = new ReadableStream( - { - async start (controller) { - fetchParams.controller.controller = controller - }, - async pull (controller) { - await pullAlgorithm(controller) - }, - async cancel (reason) { - await cancelAlgorithm(reason) - } - }, - { - highWaterMark: 0, - size () { - return 1 - } - } - ) - - // 17. Run these steps, but abort when the ongoing fetch is terminated: - - // 1. Set response’s body to a new body whose stream is stream. - response.body = { stream } - - // 2. If response is not a network error and request’s cache mode is - // not "no-store", then update response in httpCache for request. - // TODO - - // 3. If includeCredentials is true and the user agent is not configured - // to block cookies for request (see section 7 of [COOKIES]), then run the - // "set-cookie-string" parsing algorithm (see section 5.2 of [COOKIES]) on - // the value of each header whose name is a byte-case-insensitive match for - // `Set-Cookie` in response’s header list, if any, and request’s current URL. - // TODO - - // 18. If aborted, then: - // TODO - - // 19. Run these steps in parallel: - - // 1. Run these steps, but abort when fetchParams is canceled: - fetchParams.controller.on('terminated', onAborted) - fetchParams.controller.resume = async () => { - // 1. While true - while (true) { - // 1-3. See onData... - - // 4. Set bytes to the result of handling content codings given - // codings and bytes. - let bytes - let isFailure - try { - const { done, value } = await fetchParams.controller.next() - - if (isAborted(fetchParams)) { - break - } - - bytes = done ? undefined : value - } catch (err) { - if (fetchParams.controller.ended && !timingInfo.encodedBodySize) { - // zlib doesn't like empty streams. - bytes = undefined - } else { - bytes = err - - // err may be propagated from the result of calling readablestream.cancel, - // which might not be an error. https://github.com/nodejs/undici/issues/2009 - isFailure = true - } - } - - if (bytes === undefined) { - // 2. Otherwise, if the bytes transmission for response’s message - // body is done normally and stream is readable, then close - // stream, finalize response for fetchParams and response, and - // abort these in-parallel steps. - readableStreamClose(fetchParams.controller.controller) - - finalizeResponse(fetchParams, response) - - return - } - - // 5. Increase timingInfo’s decoded body size by bytes’s length. - timingInfo.decodedBodySize += bytes?.byteLength ?? 0 - - // 6. If bytes is failure, then terminate fetchParams’s controller. - if (isFailure) { - fetchParams.controller.terminate(bytes) - return - } - - // 7. Enqueue a Uint8Array wrapping an ArrayBuffer containing bytes - // into stream. - fetchParams.controller.controller.enqueue(new Uint8Array(bytes)) - - // 8. If stream is errored, then terminate the ongoing fetch. - if (isErrored(stream)) { - fetchParams.controller.terminate() - return - } - - // 9. If stream doesn’t need more data ask the user agent to suspend - // the ongoing fetch. - if (!fetchParams.controller.controller.desiredSize) { - return - } - } - } - - // 2. If aborted, then: - function onAborted (reason) { - // 2. If fetchParams is aborted, then: - if (isAborted(fetchParams)) { - // 1. Set response’s aborted flag. - response.aborted = true - - // 2. If stream is readable, then error stream with the result of - // deserialize a serialized abort reason given fetchParams’s - // controller’s serialized abort reason and an - // implementation-defined realm. - if (isReadable(stream)) { - fetchParams.controller.controller.error( - fetchParams.controller.serializedAbortReason - ) - } - } else { - // 3. Otherwise, if stream is readable, error stream with a TypeError. - if (isReadable(stream)) { - fetchParams.controller.controller.error(new TypeError('terminated', { - cause: isErrorLike(reason) ? reason : undefined - })) - } - } - - // 4. If connection uses HTTP/2, then transmit an RST_STREAM frame. - // 5. Otherwise, the user agent should close connection unless it would be bad for performance to do so. - fetchParams.controller.connection.destroy() - } - - // 20. Return response. - return response - - async function dispatch ({ body }) { - const url = requestCurrentURL(request) - /** @type {import('../..').Agent} */ - const agent = fetchParams.controller.dispatcher - - return new Promise((resolve, reject) => agent.dispatch( - { - path: url.pathname + url.search, - origin: url.origin, - method: request.method, - body: fetchParams.controller.dispatcher.isMockActive ? request.body && (request.body.source || request.body.stream) : body, - headers: request.headersList.entries, - maxRedirections: 0, - upgrade: request.mode === 'websocket' ? 'websocket' : undefined - }, - { - body: null, - abort: null, - - onConnect (abort) { - // TODO (fix): Do we need connection here? - const { connection } = fetchParams.controller - - if (connection.destroyed) { - abort(new DOMException('The operation was aborted.', 'AbortError')) - } else { - fetchParams.controller.on('terminated', abort) - this.abort = connection.abort = abort - } - }, - - onHeaders (status, headersList, resume, statusText) { - if (status < 200) { - return - } - - let codings = [] - let location = '' - - const headers = new Headers() - - // For H2, the headers are a plain JS object - // We distinguish between them and iterate accordingly - if (Array.isArray(headersList)) { - for (let n = 0; n < headersList.length; n += 2) { - const key = headersList[n + 0].toString('latin1') - const val = headersList[n + 1].toString('latin1') - if (key.toLowerCase() === 'content-encoding') { - // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 - // "All content-coding values are case-insensitive..." - codings = val.toLowerCase().split(',').map((x) => x.trim()) - } else if (key.toLowerCase() === 'location') { - location = val - } - - headers[kHeadersList].append(key, val) - } - } else { - const keys = Object.keys(headersList) - for (const key of keys) { - const val = headersList[key] - if (key.toLowerCase() === 'content-encoding') { - // https://www.rfc-editor.org/rfc/rfc7231#section-3.1.2.1 - // "All content-coding values are case-insensitive..." - codings = val.toLowerCase().split(',').map((x) => x.trim()).reverse() - } else if (key.toLowerCase() === 'location') { - location = val - } - - headers[kHeadersList].append(key, val) - } - } - - this.body = new Readable({ read: resume }) - - const decoders = [] - - const willFollow = request.redirect === 'follow' && - location && - redirectStatusSet.has(status) - - // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding - if (request.method !== 'HEAD' && request.method !== 'CONNECT' && !nullBodyStatus.includes(status) && !willFollow) { - for (const coding of codings) { - // https://www.rfc-editor.org/rfc/rfc9112.html#section-7.2 - if (coding === 'x-gzip' || coding === 'gzip') { - decoders.push(zlib.createGunzip({ - // Be less strict when decoding compressed responses, since sometimes - // servers send slightly invalid responses that are still accepted - // by common browsers. - // Always using Z_SYNC_FLUSH is what cURL does. - flush: zlib.constants.Z_SYNC_FLUSH, - finishFlush: zlib.constants.Z_SYNC_FLUSH - })) - } else if (coding === 'deflate') { - decoders.push(zlib.createInflate()) - } else if (coding === 'br') { - decoders.push(zlib.createBrotliDecompress()) - } else { - decoders.length = 0 - break - } - } - } - - resolve({ - status, - statusText, - headersList: headers[kHeadersList], - body: decoders.length - ? pipeline(this.body, ...decoders, () => { }) - : this.body.on('error', () => {}) - }) - - return true - }, - - onData (chunk) { - if (fetchParams.controller.dump) { - return - } - - // 1. If one or more bytes have been transmitted from response’s - // message body, then: - - // 1. Let bytes be the transmitted bytes. - const bytes = chunk - - // 2. Let codings be the result of extracting header list values - // given `Content-Encoding` and response’s header list. - // See pullAlgorithm. - - // 3. Increase timingInfo’s encoded body size by bytes’s length. - timingInfo.encodedBodySize += bytes.byteLength - - // 4. See pullAlgorithm... - - return this.body.push(bytes) - }, - - onComplete () { - if (this.abort) { - fetchParams.controller.off('terminated', this.abort) - } - - fetchParams.controller.ended = true - - this.body.push(null) - }, - - onError (error) { - if (this.abort) { - fetchParams.controller.off('terminated', this.abort) - } - - this.body?.destroy(error) - - fetchParams.controller.terminate(error) - - reject(error) - }, - - onUpgrade (status, headersList, socket) { - if (status !== 101) { - return - } - - const headers = new Headers() - - for (let n = 0; n < headersList.length; n += 2) { - const key = headersList[n + 0].toString('latin1') - const val = headersList[n + 1].toString('latin1') - - headers[kHeadersList].append(key, val) - } - - resolve({ - status, - statusText: STATUS_CODES[status], - headersList: headers[kHeadersList], - socket - }) - - return true - } - } - )) - } -} - -module.exports = { - fetch, - Fetch, - fetching, - finalizeAndReportTiming -} - - -/***/ }), - -/***/ 5194: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* globals AbortController */ - - - -const { extractBody, mixinBody, cloneBody } = __nccwpck_require__(8923) -const { Headers, fill: fillHeaders, HeadersList } = __nccwpck_require__(6349) -const { FinalizationRegistry } = __nccwpck_require__(3194)() -const util = __nccwpck_require__(3440) -const { - isValidHTTPToken, - sameOrigin, - normalizeMethod, - makePolicyContainer, - normalizeMethodRecord -} = __nccwpck_require__(5523) -const { - forbiddenMethodsSet, - corsSafeListedMethodsSet, - referrerPolicy, - requestRedirect, - requestMode, - requestCredentials, - requestCache, - requestDuplex -} = __nccwpck_require__(7326) -const { kEnumerableProperty } = util -const { kHeaders, kSignal, kState, kGuard, kRealm } = __nccwpck_require__(9710) -const { webidl } = __nccwpck_require__(4222) -const { getGlobalOrigin } = __nccwpck_require__(5628) -const { URLSerializer } = __nccwpck_require__(4322) -const { kHeadersList, kConstruct } = __nccwpck_require__(6443) -const assert = __nccwpck_require__(2613) -const { getMaxListeners, setMaxListeners, getEventListeners, defaultMaxListeners } = __nccwpck_require__(4434) - -let TransformStream = globalThis.TransformStream - -const kAbortController = Symbol('abortController') - -const requestFinalizer = new FinalizationRegistry(({ signal, abort }) => { - signal.removeEventListener('abort', abort) -}) - -// https://fetch.spec.whatwg.org/#request-class -class Request { - // https://fetch.spec.whatwg.org/#dom-request - constructor (input, init = {}) { - if (input === kConstruct) { - return - } - - webidl.argumentLengthCheck(arguments, 1, { header: 'Request constructor' }) - - input = webidl.converters.RequestInfo(input) - init = webidl.converters.RequestInit(init) - - // https://html.spec.whatwg.org/multipage/webappapis.html#environment-settings-object - this[kRealm] = { - settingsObject: { - baseUrl: getGlobalOrigin(), - get origin () { - return this.baseUrl?.origin - }, - policyContainer: makePolicyContainer() - } - } - - // 1. Let request be null. - let request = null - - // 2. Let fallbackMode be null. - let fallbackMode = null - - // 3. Let baseURL be this’s relevant settings object’s API base URL. - const baseUrl = this[kRealm].settingsObject.baseUrl - - // 4. Let signal be null. - let signal = null - - // 5. If input is a string, then: - if (typeof input === 'string') { - // 1. Let parsedURL be the result of parsing input with baseURL. - // 2. If parsedURL is failure, then throw a TypeError. - let parsedURL - try { - parsedURL = new URL(input, baseUrl) - } catch (err) { - throw new TypeError('Failed to parse URL from ' + input, { cause: err }) - } - - // 3. If parsedURL includes credentials, then throw a TypeError. - if (parsedURL.username || parsedURL.password) { - throw new TypeError( - 'Request cannot be constructed from a URL that includes credentials: ' + - input - ) - } - - // 4. Set request to a new request whose URL is parsedURL. - request = makeRequest({ urlList: [parsedURL] }) - - // 5. Set fallbackMode to "cors". - fallbackMode = 'cors' - } else { - // 6. Otherwise: - - // 7. Assert: input is a Request object. - assert(input instanceof Request) - - // 8. Set request to input’s request. - request = input[kState] - - // 9. Set signal to input’s signal. - signal = input[kSignal] - } - - // 7. Let origin be this’s relevant settings object’s origin. - const origin = this[kRealm].settingsObject.origin - - // 8. Let window be "client". - let window = 'client' - - // 9. If request’s window is an environment settings object and its origin - // is same origin with origin, then set window to request’s window. - if ( - request.window?.constructor?.name === 'EnvironmentSettingsObject' && - sameOrigin(request.window, origin) - ) { - window = request.window - } - - // 10. If init["window"] exists and is non-null, then throw a TypeError. - if (init.window != null) { - throw new TypeError(`'window' option '${window}' must be null`) - } - - // 11. If init["window"] exists, then set window to "no-window". - if ('window' in init) { - window = 'no-window' - } - - // 12. Set request to a new request with the following properties: - request = makeRequest({ - // URL request’s URL. - // undici implementation note: this is set as the first item in request's urlList in makeRequest - // method request’s method. - method: request.method, - // header list A copy of request’s header list. - // undici implementation note: headersList is cloned in makeRequest - headersList: request.headersList, - // unsafe-request flag Set. - unsafeRequest: request.unsafeRequest, - // client This’s relevant settings object. - client: this[kRealm].settingsObject, - // window window. - window, - // priority request’s priority. - priority: request.priority, - // origin request’s origin. The propagation of the origin is only significant for navigation requests - // being handled by a service worker. In this scenario a request can have an origin that is different - // from the current client. - origin: request.origin, - // referrer request’s referrer. - referrer: request.referrer, - // referrer policy request’s referrer policy. - referrerPolicy: request.referrerPolicy, - // mode request’s mode. - mode: request.mode, - // credentials mode request’s credentials mode. - credentials: request.credentials, - // cache mode request’s cache mode. - cache: request.cache, - // redirect mode request’s redirect mode. - redirect: request.redirect, - // integrity metadata request’s integrity metadata. - integrity: request.integrity, - // keepalive request’s keepalive. - keepalive: request.keepalive, - // reload-navigation flag request’s reload-navigation flag. - reloadNavigation: request.reloadNavigation, - // history-navigation flag request’s history-navigation flag. - historyNavigation: request.historyNavigation, - // URL list A clone of request’s URL list. - urlList: [...request.urlList] - }) - - const initHasKey = Object.keys(init).length !== 0 - - // 13. If init is not empty, then: - if (initHasKey) { - // 1. If request’s mode is "navigate", then set it to "same-origin". - if (request.mode === 'navigate') { - request.mode = 'same-origin' - } - - // 2. Unset request’s reload-navigation flag. - request.reloadNavigation = false - - // 3. Unset request’s history-navigation flag. - request.historyNavigation = false - - // 4. Set request’s origin to "client". - request.origin = 'client' - - // 5. Set request’s referrer to "client" - request.referrer = 'client' - - // 6. Set request’s referrer policy to the empty string. - request.referrerPolicy = '' - - // 7. Set request’s URL to request’s current URL. - request.url = request.urlList[request.urlList.length - 1] - - // 8. Set request’s URL list to « request’s URL ». - request.urlList = [request.url] - } - - // 14. If init["referrer"] exists, then: - if (init.referrer !== undefined) { - // 1. Let referrer be init["referrer"]. - const referrer = init.referrer - - // 2. If referrer is the empty string, then set request’s referrer to "no-referrer". - if (referrer === '') { - request.referrer = 'no-referrer' - } else { - // 1. Let parsedReferrer be the result of parsing referrer with - // baseURL. - // 2. If parsedReferrer is failure, then throw a TypeError. - let parsedReferrer - try { - parsedReferrer = new URL(referrer, baseUrl) - } catch (err) { - throw new TypeError(`Referrer "${referrer}" is not a valid URL.`, { cause: err }) - } - - // 3. If one of the following is true - // - parsedReferrer’s scheme is "about" and path is the string "client" - // - parsedReferrer’s origin is not same origin with origin - // then set request’s referrer to "client". - if ( - (parsedReferrer.protocol === 'about:' && parsedReferrer.hostname === 'client') || - (origin && !sameOrigin(parsedReferrer, this[kRealm].settingsObject.baseUrl)) - ) { - request.referrer = 'client' - } else { - // 4. Otherwise, set request’s referrer to parsedReferrer. - request.referrer = parsedReferrer - } - } - } - - // 15. If init["referrerPolicy"] exists, then set request’s referrer policy - // to it. - if (init.referrerPolicy !== undefined) { - request.referrerPolicy = init.referrerPolicy - } - - // 16. Let mode be init["mode"] if it exists, and fallbackMode otherwise. - let mode - if (init.mode !== undefined) { - mode = init.mode - } else { - mode = fallbackMode - } - - // 17. If mode is "navigate", then throw a TypeError. - if (mode === 'navigate') { - throw webidl.errors.exception({ - header: 'Request constructor', - message: 'invalid request mode navigate.' - }) - } - - // 18. If mode is non-null, set request’s mode to mode. - if (mode != null) { - request.mode = mode - } - - // 19. If init["credentials"] exists, then set request’s credentials mode - // to it. - if (init.credentials !== undefined) { - request.credentials = init.credentials - } - - // 18. If init["cache"] exists, then set request’s cache mode to it. - if (init.cache !== undefined) { - request.cache = init.cache - } - - // 21. If request’s cache mode is "only-if-cached" and request’s mode is - // not "same-origin", then throw a TypeError. - if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') { - throw new TypeError( - "'only-if-cached' can be set only with 'same-origin' mode" - ) - } - - // 22. If init["redirect"] exists, then set request’s redirect mode to it. - if (init.redirect !== undefined) { - request.redirect = init.redirect - } - - // 23. If init["integrity"] exists, then set request’s integrity metadata to it. - if (init.integrity != null) { - request.integrity = String(init.integrity) - } - - // 24. If init["keepalive"] exists, then set request’s keepalive to it. - if (init.keepalive !== undefined) { - request.keepalive = Boolean(init.keepalive) - } - - // 25. If init["method"] exists, then: - if (init.method !== undefined) { - // 1. Let method be init["method"]. - let method = init.method - - // 2. If method is not a method or method is a forbidden method, then - // throw a TypeError. - if (!isValidHTTPToken(method)) { - throw new TypeError(`'${method}' is not a valid HTTP method.`) - } - - if (forbiddenMethodsSet.has(method.toUpperCase())) { - throw new TypeError(`'${method}' HTTP method is unsupported.`) - } - - // 3. Normalize method. - method = normalizeMethodRecord[method] ?? normalizeMethod(method) - - // 4. Set request’s method to method. - request.method = method - } - - // 26. If init["signal"] exists, then set signal to it. - if (init.signal !== undefined) { - signal = init.signal - } - - // 27. Set this’s request to request. - this[kState] = request - - // 28. Set this’s signal to a new AbortSignal object with this’s relevant - // Realm. - // TODO: could this be simplified with AbortSignal.any - // (https://dom.spec.whatwg.org/#dom-abortsignal-any) - const ac = new AbortController() - this[kSignal] = ac.signal - this[kSignal][kRealm] = this[kRealm] - - // 29. If signal is not null, then make this’s signal follow signal. - if (signal != null) { - if ( - !signal || - typeof signal.aborted !== 'boolean' || - typeof signal.addEventListener !== 'function' - ) { - throw new TypeError( - "Failed to construct 'Request': member signal is not of type AbortSignal." - ) - } - - if (signal.aborted) { - ac.abort(signal.reason) - } else { - // Keep a strong ref to ac while request object - // is alive. This is needed to prevent AbortController - // from being prematurely garbage collected. - // See, https://github.com/nodejs/undici/issues/1926. - this[kAbortController] = ac - - const acRef = new WeakRef(ac) - const abort = function () { - const ac = acRef.deref() - if (ac !== undefined) { - ac.abort(this.reason) - } - } - - // Third-party AbortControllers may not work with these. - // See, https://github.com/nodejs/undici/pull/1910#issuecomment-1464495619. - try { - // If the max amount of listeners is equal to the default, increase it - // This is only available in node >= v19.9.0 - if (typeof getMaxListeners === 'function' && getMaxListeners(signal) === defaultMaxListeners) { - setMaxListeners(100, signal) - } else if (getEventListeners(signal, 'abort').length >= defaultMaxListeners) { - setMaxListeners(100, signal) - } - } catch {} - - util.addAbortListener(signal, abort) - requestFinalizer.register(ac, { signal, abort }) - } - } - - // 30. Set this’s headers to a new Headers object with this’s relevant - // Realm, whose header list is request’s header list and guard is - // "request". - this[kHeaders] = new Headers(kConstruct) - this[kHeaders][kHeadersList] = request.headersList - this[kHeaders][kGuard] = 'request' - this[kHeaders][kRealm] = this[kRealm] - - // 31. If this’s request’s mode is "no-cors", then: - if (mode === 'no-cors') { - // 1. If this’s request’s method is not a CORS-safelisted method, - // then throw a TypeError. - if (!corsSafeListedMethodsSet.has(request.method)) { - throw new TypeError( - `'${request.method} is unsupported in no-cors mode.` - ) - } - - // 2. Set this’s headers’s guard to "request-no-cors". - this[kHeaders][kGuard] = 'request-no-cors' - } - - // 32. If init is not empty, then: - if (initHasKey) { - /** @type {HeadersList} */ - const headersList = this[kHeaders][kHeadersList] - // 1. Let headers be a copy of this’s headers and its associated header - // list. - // 2. If init["headers"] exists, then set headers to init["headers"]. - const headers = init.headers !== undefined ? init.headers : new HeadersList(headersList) - - // 3. Empty this’s headers’s header list. - headersList.clear() - - // 4. If headers is a Headers object, then for each header in its header - // list, append header’s name/header’s value to this’s headers. - if (headers instanceof HeadersList) { - for (const [key, val] of headers) { - headersList.append(key, val) - } - // Note: Copy the `set-cookie` meta-data. - headersList.cookies = headers.cookies - } else { - // 5. Otherwise, fill this’s headers with headers. - fillHeaders(this[kHeaders], headers) - } - } - - // 33. Let inputBody be input’s request’s body if input is a Request - // object; otherwise null. - const inputBody = input instanceof Request ? input[kState].body : null - - // 34. If either init["body"] exists and is non-null or inputBody is - // non-null, and request’s method is `GET` or `HEAD`, then throw a - // TypeError. - if ( - (init.body != null || inputBody != null) && - (request.method === 'GET' || request.method === 'HEAD') - ) { - throw new TypeError('Request with GET/HEAD method cannot have body.') - } - - // 35. Let initBody be null. - let initBody = null - - // 36. If init["body"] exists and is non-null, then: - if (init.body != null) { - // 1. Let Content-Type be null. - // 2. Set initBody and Content-Type to the result of extracting - // init["body"], with keepalive set to request’s keepalive. - const [extractedBody, contentType] = extractBody( - init.body, - request.keepalive - ) - initBody = extractedBody - - // 3, If Content-Type is non-null and this’s headers’s header list does - // not contain `Content-Type`, then append `Content-Type`/Content-Type to - // this’s headers. - if (contentType && !this[kHeaders][kHeadersList].contains('content-type')) { - this[kHeaders].append('content-type', contentType) - } - } - - // 37. Let inputOrInitBody be initBody if it is non-null; otherwise - // inputBody. - const inputOrInitBody = initBody ?? inputBody - - // 38. If inputOrInitBody is non-null and inputOrInitBody’s source is - // null, then: - if (inputOrInitBody != null && inputOrInitBody.source == null) { - // 1. If initBody is non-null and init["duplex"] does not exist, - // then throw a TypeError. - if (initBody != null && init.duplex == null) { - throw new TypeError('RequestInit: duplex option is required when sending a body.') - } - - // 2. If this’s request’s mode is neither "same-origin" nor "cors", - // then throw a TypeError. - if (request.mode !== 'same-origin' && request.mode !== 'cors') { - throw new TypeError( - 'If request is made from ReadableStream, mode should be "same-origin" or "cors"' - ) - } - - // 3. Set this’s request’s use-CORS-preflight flag. - request.useCORSPreflightFlag = true - } - - // 39. Let finalBody be inputOrInitBody. - let finalBody = inputOrInitBody - - // 40. If initBody is null and inputBody is non-null, then: - if (initBody == null && inputBody != null) { - // 1. If input is unusable, then throw a TypeError. - if (util.isDisturbed(inputBody.stream) || inputBody.stream.locked) { - throw new TypeError( - 'Cannot construct a Request with a Request object that has already been used.' - ) - } - - // 2. Set finalBody to the result of creating a proxy for inputBody. - if (!TransformStream) { - TransformStream = (__nccwpck_require__(3774).TransformStream) - } - - // https://streams.spec.whatwg.org/#readablestream-create-a-proxy - const identityTransform = new TransformStream() - inputBody.stream.pipeThrough(identityTransform) - finalBody = { - source: inputBody.source, - length: inputBody.length, - stream: identityTransform.readable - } - } - - // 41. Set this’s request’s body to finalBody. - this[kState].body = finalBody - } - - // Returns request’s HTTP method, which is "GET" by default. - get method () { - webidl.brandCheck(this, Request) - - // The method getter steps are to return this’s request’s method. - return this[kState].method - } - - // Returns the URL of request as a string. - get url () { - webidl.brandCheck(this, Request) - - // The url getter steps are to return this’s request’s URL, serialized. - return URLSerializer(this[kState].url) - } - - // Returns a Headers object consisting of the headers associated with request. - // Note that headers added in the network layer by the user agent will not - // be accounted for in this object, e.g., the "Host" header. - get headers () { - webidl.brandCheck(this, Request) - - // The headers getter steps are to return this’s headers. - return this[kHeaders] - } - - // Returns the kind of resource requested by request, e.g., "document" - // or "script". - get destination () { - webidl.brandCheck(this, Request) - - // The destination getter are to return this’s request’s destination. - return this[kState].destination - } - - // Returns the referrer of request. Its value can be a same-origin URL if - // explicitly set in init, the empty string to indicate no referrer, and - // "about:client" when defaulting to the global’s default. This is used - // during fetching to determine the value of the `Referer` header of the - // request being made. - get referrer () { - webidl.brandCheck(this, Request) - - // 1. If this’s request’s referrer is "no-referrer", then return the - // empty string. - if (this[kState].referrer === 'no-referrer') { - return '' - } - - // 2. If this’s request’s referrer is "client", then return - // "about:client". - if (this[kState].referrer === 'client') { - return 'about:client' - } - - // Return this’s request’s referrer, serialized. - return this[kState].referrer.toString() - } - - // Returns the referrer policy associated with request. - // This is used during fetching to compute the value of the request’s - // referrer. - get referrerPolicy () { - webidl.brandCheck(this, Request) - - // The referrerPolicy getter steps are to return this’s request’s referrer policy. - return this[kState].referrerPolicy - } - - // Returns the mode associated with request, which is a string indicating - // whether the request will use CORS, or will be restricted to same-origin - // URLs. - get mode () { - webidl.brandCheck(this, Request) - - // The mode getter steps are to return this’s request’s mode. - return this[kState].mode - } - - // Returns the credentials mode associated with request, - // which is a string indicating whether credentials will be sent with the - // request always, never, or only when sent to a same-origin URL. - get credentials () { - // The credentials getter steps are to return this’s request’s credentials mode. - return this[kState].credentials - } - - // Returns the cache mode associated with request, - // which is a string indicating how the request will - // interact with the browser’s cache when fetching. - get cache () { - webidl.brandCheck(this, Request) - - // The cache getter steps are to return this’s request’s cache mode. - return this[kState].cache - } - - // Returns the redirect mode associated with request, - // which is a string indicating how redirects for the - // request will be handled during fetching. A request - // will follow redirects by default. - get redirect () { - webidl.brandCheck(this, Request) - - // The redirect getter steps are to return this’s request’s redirect mode. - return this[kState].redirect - } - - // Returns request’s subresource integrity metadata, which is a - // cryptographic hash of the resource being fetched. Its value - // consists of multiple hashes separated by whitespace. [SRI] - get integrity () { - webidl.brandCheck(this, Request) - - // The integrity getter steps are to return this’s request’s integrity - // metadata. - return this[kState].integrity - } - - // Returns a boolean indicating whether or not request can outlive the - // global in which it was created. - get keepalive () { - webidl.brandCheck(this, Request) - - // The keepalive getter steps are to return this’s request’s keepalive. - return this[kState].keepalive - } - - // Returns a boolean indicating whether or not request is for a reload - // navigation. - get isReloadNavigation () { - webidl.brandCheck(this, Request) - - // The isReloadNavigation getter steps are to return true if this’s - // request’s reload-navigation flag is set; otherwise false. - return this[kState].reloadNavigation - } - - // Returns a boolean indicating whether or not request is for a history - // navigation (a.k.a. back-foward navigation). - get isHistoryNavigation () { - webidl.brandCheck(this, Request) - - // The isHistoryNavigation getter steps are to return true if this’s request’s - // history-navigation flag is set; otherwise false. - return this[kState].historyNavigation - } - - // Returns the signal associated with request, which is an AbortSignal - // object indicating whether or not request has been aborted, and its - // abort event handler. - get signal () { - webidl.brandCheck(this, Request) - - // The signal getter steps are to return this’s signal. - return this[kSignal] - } - - get body () { - webidl.brandCheck(this, Request) - - return this[kState].body ? this[kState].body.stream : null - } - - get bodyUsed () { - webidl.brandCheck(this, Request) - - return !!this[kState].body && util.isDisturbed(this[kState].body.stream) - } - - get duplex () { - webidl.brandCheck(this, Request) - - return 'half' - } - - // Returns a clone of request. - clone () { - webidl.brandCheck(this, Request) - - // 1. If this is unusable, then throw a TypeError. - if (this.bodyUsed || this.body?.locked) { - throw new TypeError('unusable') - } - - // 2. Let clonedRequest be the result of cloning this’s request. - const clonedRequest = cloneRequest(this[kState]) - - // 3. Let clonedRequestObject be the result of creating a Request object, - // given clonedRequest, this’s headers’s guard, and this’s relevant Realm. - const clonedRequestObject = new Request(kConstruct) - clonedRequestObject[kState] = clonedRequest - clonedRequestObject[kRealm] = this[kRealm] - clonedRequestObject[kHeaders] = new Headers(kConstruct) - clonedRequestObject[kHeaders][kHeadersList] = clonedRequest.headersList - clonedRequestObject[kHeaders][kGuard] = this[kHeaders][kGuard] - clonedRequestObject[kHeaders][kRealm] = this[kHeaders][kRealm] - - // 4. Make clonedRequestObject’s signal follow this’s signal. - const ac = new AbortController() - if (this.signal.aborted) { - ac.abort(this.signal.reason) - } else { - util.addAbortListener( - this.signal, - () => { - ac.abort(this.signal.reason) - } - ) - } - clonedRequestObject[kSignal] = ac.signal - - // 4. Return clonedRequestObject. - return clonedRequestObject - } -} - -mixinBody(Request) - -function makeRequest (init) { - // https://fetch.spec.whatwg.org/#requests - const request = { - method: 'GET', - localURLsOnly: false, - unsafeRequest: false, - body: null, - client: null, - reservedClient: null, - replacesClientId: '', - window: 'client', - keepalive: false, - serviceWorkers: 'all', - initiator: '', - destination: '', - priority: null, - origin: 'client', - policyContainer: 'client', - referrer: 'client', - referrerPolicy: '', - mode: 'no-cors', - useCORSPreflightFlag: false, - credentials: 'same-origin', - useCredentials: false, - cache: 'default', - redirect: 'follow', - integrity: '', - cryptoGraphicsNonceMetadata: '', - parserMetadata: '', - reloadNavigation: false, - historyNavigation: false, - userActivation: false, - taintedOrigin: false, - redirectCount: 0, - responseTainting: 'basic', - preventNoCacheCacheControlHeaderModification: false, - done: false, - timingAllowFailed: false, - ...init, - headersList: init.headersList - ? new HeadersList(init.headersList) - : new HeadersList() - } - request.url = request.urlList[0] - return request -} - -// https://fetch.spec.whatwg.org/#concept-request-clone -function cloneRequest (request) { - // To clone a request request, run these steps: - - // 1. Let newRequest be a copy of request, except for its body. - const newRequest = makeRequest({ ...request, body: null }) - - // 2. If request’s body is non-null, set newRequest’s body to the - // result of cloning request’s body. - if (request.body != null) { - newRequest.body = cloneBody(request.body) - } - - // 3. Return newRequest. - return newRequest -} - -Object.defineProperties(Request.prototype, { - method: kEnumerableProperty, - url: kEnumerableProperty, - headers: kEnumerableProperty, - redirect: kEnumerableProperty, - clone: kEnumerableProperty, - signal: kEnumerableProperty, - duplex: kEnumerableProperty, - destination: kEnumerableProperty, - body: kEnumerableProperty, - bodyUsed: kEnumerableProperty, - isHistoryNavigation: kEnumerableProperty, - isReloadNavigation: kEnumerableProperty, - keepalive: kEnumerableProperty, - integrity: kEnumerableProperty, - cache: kEnumerableProperty, - credentials: kEnumerableProperty, - attribute: kEnumerableProperty, - referrerPolicy: kEnumerableProperty, - referrer: kEnumerableProperty, - mode: kEnumerableProperty, - [Symbol.toStringTag]: { - value: 'Request', - configurable: true - } -}) - -webidl.converters.Request = webidl.interfaceConverter( - Request -) - -// https://fetch.spec.whatwg.org/#requestinfo -webidl.converters.RequestInfo = function (V) { - if (typeof V === 'string') { - return webidl.converters.USVString(V) - } - - if (V instanceof Request) { - return webidl.converters.Request(V) - } - - return webidl.converters.USVString(V) -} - -webidl.converters.AbortSignal = webidl.interfaceConverter( - AbortSignal -) - -// https://fetch.spec.whatwg.org/#requestinit -webidl.converters.RequestInit = webidl.dictionaryConverter([ - { - key: 'method', - converter: webidl.converters.ByteString - }, - { - key: 'headers', - converter: webidl.converters.HeadersInit - }, - { - key: 'body', - converter: webidl.nullableConverter( - webidl.converters.BodyInit - ) - }, - { - key: 'referrer', - converter: webidl.converters.USVString - }, - { - key: 'referrerPolicy', - converter: webidl.converters.DOMString, - // https://w3c.github.io/webappsec-referrer-policy/#referrer-policy - allowedValues: referrerPolicy - }, - { - key: 'mode', - converter: webidl.converters.DOMString, - // https://fetch.spec.whatwg.org/#concept-request-mode - allowedValues: requestMode - }, - { - key: 'credentials', - converter: webidl.converters.DOMString, - // https://fetch.spec.whatwg.org/#requestcredentials - allowedValues: requestCredentials - }, - { - key: 'cache', - converter: webidl.converters.DOMString, - // https://fetch.spec.whatwg.org/#requestcache - allowedValues: requestCache - }, - { - key: 'redirect', - converter: webidl.converters.DOMString, - // https://fetch.spec.whatwg.org/#requestredirect - allowedValues: requestRedirect - }, - { - key: 'integrity', - converter: webidl.converters.DOMString - }, - { - key: 'keepalive', - converter: webidl.converters.boolean - }, - { - key: 'signal', - converter: webidl.nullableConverter( - (signal) => webidl.converters.AbortSignal( - signal, - { strict: false } - ) - ) - }, - { - key: 'window', - converter: webidl.converters.any - }, - { - key: 'duplex', - converter: webidl.converters.DOMString, - allowedValues: requestDuplex - } -]) - -module.exports = { Request, makeRequest } - - -/***/ }), - -/***/ 8676: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { Headers, HeadersList, fill } = __nccwpck_require__(6349) -const { extractBody, cloneBody, mixinBody } = __nccwpck_require__(8923) -const util = __nccwpck_require__(3440) -const { kEnumerableProperty } = util -const { - isValidReasonPhrase, - isCancelled, - isAborted, - isBlobLike, - serializeJavascriptValueToJSONString, - isErrorLike, - isomorphicEncode -} = __nccwpck_require__(5523) -const { - redirectStatusSet, - nullBodyStatus, - DOMException -} = __nccwpck_require__(7326) -const { kState, kHeaders, kGuard, kRealm } = __nccwpck_require__(9710) -const { webidl } = __nccwpck_require__(4222) -const { FormData } = __nccwpck_require__(3073) -const { getGlobalOrigin } = __nccwpck_require__(5628) -const { URLSerializer } = __nccwpck_require__(4322) -const { kHeadersList, kConstruct } = __nccwpck_require__(6443) -const assert = __nccwpck_require__(2613) -const { types } = __nccwpck_require__(9023) - -const ReadableStream = globalThis.ReadableStream || (__nccwpck_require__(3774).ReadableStream) -const textEncoder = new TextEncoder('utf-8') - -// https://fetch.spec.whatwg.org/#response-class -class Response { - // Creates network error Response. - static error () { - // TODO - const relevantRealm = { settingsObject: {} } - - // The static error() method steps are to return the result of creating a - // Response object, given a new network error, "immutable", and this’s - // relevant Realm. - const responseObject = new Response() - responseObject[kState] = makeNetworkError() - responseObject[kRealm] = relevantRealm - responseObject[kHeaders][kHeadersList] = responseObject[kState].headersList - responseObject[kHeaders][kGuard] = 'immutable' - responseObject[kHeaders][kRealm] = relevantRealm - return responseObject - } - - // https://fetch.spec.whatwg.org/#dom-response-json - static json (data, init = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'Response.json' }) - - if (init !== null) { - init = webidl.converters.ResponseInit(init) - } - - // 1. Let bytes the result of running serialize a JavaScript value to JSON bytes on data. - const bytes = textEncoder.encode( - serializeJavascriptValueToJSONString(data) - ) - - // 2. Let body be the result of extracting bytes. - const body = extractBody(bytes) - - // 3. Let responseObject be the result of creating a Response object, given a new response, - // "response", and this’s relevant Realm. - const relevantRealm = { settingsObject: {} } - const responseObject = new Response() - responseObject[kRealm] = relevantRealm - responseObject[kHeaders][kGuard] = 'response' - responseObject[kHeaders][kRealm] = relevantRealm - - // 4. Perform initialize a response given responseObject, init, and (body, "application/json"). - initializeResponse(responseObject, init, { body: body[0], type: 'application/json' }) - - // 5. Return responseObject. - return responseObject - } - - // Creates a redirect Response that redirects to url with status status. - static redirect (url, status = 302) { - const relevantRealm = { settingsObject: {} } - - webidl.argumentLengthCheck(arguments, 1, { header: 'Response.redirect' }) - - url = webidl.converters.USVString(url) - status = webidl.converters['unsigned short'](status) - - // 1. Let parsedURL be the result of parsing url with current settings - // object’s API base URL. - // 2. If parsedURL is failure, then throw a TypeError. - // TODO: base-URL? - let parsedURL - try { - parsedURL = new URL(url, getGlobalOrigin()) - } catch (err) { - throw Object.assign(new TypeError('Failed to parse URL from ' + url), { - cause: err - }) - } - - // 3. If status is not a redirect status, then throw a RangeError. - if (!redirectStatusSet.has(status)) { - throw new RangeError('Invalid status code ' + status) - } - - // 4. Let responseObject be the result of creating a Response object, - // given a new response, "immutable", and this’s relevant Realm. - const responseObject = new Response() - responseObject[kRealm] = relevantRealm - responseObject[kHeaders][kGuard] = 'immutable' - responseObject[kHeaders][kRealm] = relevantRealm - - // 5. Set responseObject’s response’s status to status. - responseObject[kState].status = status - - // 6. Let value be parsedURL, serialized and isomorphic encoded. - const value = isomorphicEncode(URLSerializer(parsedURL)) - - // 7. Append `Location`/value to responseObject’s response’s header list. - responseObject[kState].headersList.append('location', value) - - // 8. Return responseObject. - return responseObject - } - - // https://fetch.spec.whatwg.org/#dom-response - constructor (body = null, init = {}) { - if (body !== null) { - body = webidl.converters.BodyInit(body) - } - - init = webidl.converters.ResponseInit(init) - - // TODO - this[kRealm] = { settingsObject: {} } - - // 1. Set this’s response to a new response. - this[kState] = makeResponse({}) - - // 2. Set this’s headers to a new Headers object with this’s relevant - // Realm, whose header list is this’s response’s header list and guard - // is "response". - this[kHeaders] = new Headers(kConstruct) - this[kHeaders][kGuard] = 'response' - this[kHeaders][kHeadersList] = this[kState].headersList - this[kHeaders][kRealm] = this[kRealm] - - // 3. Let bodyWithType be null. - let bodyWithType = null - - // 4. If body is non-null, then set bodyWithType to the result of extracting body. - if (body != null) { - const [extractedBody, type] = extractBody(body) - bodyWithType = { body: extractedBody, type } - } - - // 5. Perform initialize a response given this, init, and bodyWithType. - initializeResponse(this, init, bodyWithType) - } - - // Returns response’s type, e.g., "cors". - get type () { - webidl.brandCheck(this, Response) - - // The type getter steps are to return this’s response’s type. - return this[kState].type - } - - // Returns response’s URL, if it has one; otherwise the empty string. - get url () { - webidl.brandCheck(this, Response) - - const urlList = this[kState].urlList - - // The url getter steps are to return the empty string if this’s - // response’s URL is null; otherwise this’s response’s URL, - // serialized with exclude fragment set to true. - const url = urlList[urlList.length - 1] ?? null - - if (url === null) { - return '' - } - - return URLSerializer(url, true) - } - - // Returns whether response was obtained through a redirect. - get redirected () { - webidl.brandCheck(this, Response) - - // The redirected getter steps are to return true if this’s response’s URL - // list has more than one item; otherwise false. - return this[kState].urlList.length > 1 - } - - // Returns response’s status. - get status () { - webidl.brandCheck(this, Response) - - // The status getter steps are to return this’s response’s status. - return this[kState].status - } - - // Returns whether response’s status is an ok status. - get ok () { - webidl.brandCheck(this, Response) - - // The ok getter steps are to return true if this’s response’s status is an - // ok status; otherwise false. - return this[kState].status >= 200 && this[kState].status <= 299 - } - - // Returns response’s status message. - get statusText () { - webidl.brandCheck(this, Response) - - // The statusText getter steps are to return this’s response’s status - // message. - return this[kState].statusText - } - - // Returns response’s headers as Headers. - get headers () { - webidl.brandCheck(this, Response) - - // The headers getter steps are to return this’s headers. - return this[kHeaders] - } - - get body () { - webidl.brandCheck(this, Response) - - return this[kState].body ? this[kState].body.stream : null - } - - get bodyUsed () { - webidl.brandCheck(this, Response) - - return !!this[kState].body && util.isDisturbed(this[kState].body.stream) - } - - // Returns a clone of response. - clone () { - webidl.brandCheck(this, Response) - - // 1. If this is unusable, then throw a TypeError. - if (this.bodyUsed || (this.body && this.body.locked)) { - throw webidl.errors.exception({ - header: 'Response.clone', - message: 'Body has already been consumed.' - }) - } - - // 2. Let clonedResponse be the result of cloning this’s response. - const clonedResponse = cloneResponse(this[kState]) - - // 3. Return the result of creating a Response object, given - // clonedResponse, this’s headers’s guard, and this’s relevant Realm. - const clonedResponseObject = new Response() - clonedResponseObject[kState] = clonedResponse - clonedResponseObject[kRealm] = this[kRealm] - clonedResponseObject[kHeaders][kHeadersList] = clonedResponse.headersList - clonedResponseObject[kHeaders][kGuard] = this[kHeaders][kGuard] - clonedResponseObject[kHeaders][kRealm] = this[kHeaders][kRealm] - - return clonedResponseObject - } -} - -mixinBody(Response) - -Object.defineProperties(Response.prototype, { - type: kEnumerableProperty, - url: kEnumerableProperty, - status: kEnumerableProperty, - ok: kEnumerableProperty, - redirected: kEnumerableProperty, - statusText: kEnumerableProperty, - headers: kEnumerableProperty, - clone: kEnumerableProperty, - body: kEnumerableProperty, - bodyUsed: kEnumerableProperty, - [Symbol.toStringTag]: { - value: 'Response', - configurable: true - } -}) - -Object.defineProperties(Response, { - json: kEnumerableProperty, - redirect: kEnumerableProperty, - error: kEnumerableProperty -}) - -// https://fetch.spec.whatwg.org/#concept-response-clone -function cloneResponse (response) { - // To clone a response response, run these steps: - - // 1. If response is a filtered response, then return a new identical - // filtered response whose internal response is a clone of response’s - // internal response. - if (response.internalResponse) { - return filterResponse( - cloneResponse(response.internalResponse), - response.type - ) - } - - // 2. Let newResponse be a copy of response, except for its body. - const newResponse = makeResponse({ ...response, body: null }) - - // 3. If response’s body is non-null, then set newResponse’s body to the - // result of cloning response’s body. - if (response.body != null) { - newResponse.body = cloneBody(response.body) - } - - // 4. Return newResponse. - return newResponse -} - -function makeResponse (init) { - return { - aborted: false, - rangeRequested: false, - timingAllowPassed: false, - requestIncludesCredentials: false, - type: 'default', - status: 200, - timingInfo: null, - cacheState: '', - statusText: '', - ...init, - headersList: init.headersList - ? new HeadersList(init.headersList) - : new HeadersList(), - urlList: init.urlList ? [...init.urlList] : [] - } -} - -function makeNetworkError (reason) { - const isError = isErrorLike(reason) - return makeResponse({ - type: 'error', - status: 0, - error: isError - ? reason - : new Error(reason ? String(reason) : reason), - aborted: reason && reason.name === 'AbortError' - }) -} - -function makeFilteredResponse (response, state) { - state = { - internalResponse: response, - ...state - } - - return new Proxy(response, { - get (target, p) { - return p in state ? state[p] : target[p] - }, - set (target, p, value) { - assert(!(p in state)) - target[p] = value - return true - } - }) -} - -// https://fetch.spec.whatwg.org/#concept-filtered-response -function filterResponse (response, type) { - // Set response to the following filtered response with response as its - // internal response, depending on request’s response tainting: - if (type === 'basic') { - // A basic filtered response is a filtered response whose type is "basic" - // and header list excludes any headers in internal response’s header list - // whose name is a forbidden response-header name. - - // Note: undici does not implement forbidden response-header names - return makeFilteredResponse(response, { - type: 'basic', - headersList: response.headersList - }) - } else if (type === 'cors') { - // A CORS filtered response is a filtered response whose type is "cors" - // and header list excludes any headers in internal response’s header - // list whose name is not a CORS-safelisted response-header name, given - // internal response’s CORS-exposed header-name list. - - // Note: undici does not implement CORS-safelisted response-header names - return makeFilteredResponse(response, { - type: 'cors', - headersList: response.headersList - }) - } else if (type === 'opaque') { - // An opaque filtered response is a filtered response whose type is - // "opaque", URL list is the empty list, status is 0, status message - // is the empty byte sequence, header list is empty, and body is null. - - return makeFilteredResponse(response, { - type: 'opaque', - urlList: Object.freeze([]), - status: 0, - statusText: '', - body: null - }) - } else if (type === 'opaqueredirect') { - // An opaque-redirect filtered response is a filtered response whose type - // is "opaqueredirect", status is 0, status message is the empty byte - // sequence, header list is empty, and body is null. - - return makeFilteredResponse(response, { - type: 'opaqueredirect', - status: 0, - statusText: '', - headersList: [], - body: null - }) - } else { - assert(false) - } -} - -// https://fetch.spec.whatwg.org/#appropriate-network-error -function makeAppropriateNetworkError (fetchParams, err = null) { - // 1. Assert: fetchParams is canceled. - assert(isCancelled(fetchParams)) - - // 2. Return an aborted network error if fetchParams is aborted; - // otherwise return a network error. - return isAborted(fetchParams) - ? makeNetworkError(Object.assign(new DOMException('The operation was aborted.', 'AbortError'), { cause: err })) - : makeNetworkError(Object.assign(new DOMException('Request was cancelled.'), { cause: err })) -} - -// https://whatpr.org/fetch/1392.html#initialize-a-response -function initializeResponse (response, init, body) { - // 1. If init["status"] is not in the range 200 to 599, inclusive, then - // throw a RangeError. - if (init.status !== null && (init.status < 200 || init.status > 599)) { - throw new RangeError('init["status"] must be in the range of 200 to 599, inclusive.') - } - - // 2. If init["statusText"] does not match the reason-phrase token production, - // then throw a TypeError. - if ('statusText' in init && init.statusText != null) { - // See, https://datatracker.ietf.org/doc/html/rfc7230#section-3.1.2: - // reason-phrase = *( HTAB / SP / VCHAR / obs-text ) - if (!isValidReasonPhrase(String(init.statusText))) { - throw new TypeError('Invalid statusText') - } - } - - // 3. Set response’s response’s status to init["status"]. - if ('status' in init && init.status != null) { - response[kState].status = init.status - } - - // 4. Set response’s response’s status message to init["statusText"]. - if ('statusText' in init && init.statusText != null) { - response[kState].statusText = init.statusText - } - - // 5. If init["headers"] exists, then fill response’s headers with init["headers"]. - if ('headers' in init && init.headers != null) { - fill(response[kHeaders], init.headers) - } - - // 6. If body was given, then: - if (body) { - // 1. If response's status is a null body status, then throw a TypeError. - if (nullBodyStatus.includes(response.status)) { - throw webidl.errors.exception({ - header: 'Response constructor', - message: 'Invalid response status code ' + response.status - }) - } - - // 2. Set response's body to body's body. - response[kState].body = body.body - - // 3. If body's type is non-null and response's header list does not contain - // `Content-Type`, then append (`Content-Type`, body's type) to response's header list. - if (body.type != null && !response[kState].headersList.contains('Content-Type')) { - response[kState].headersList.append('content-type', body.type) - } - } -} - -webidl.converters.ReadableStream = webidl.interfaceConverter( - ReadableStream -) - -webidl.converters.FormData = webidl.interfaceConverter( - FormData -) - -webidl.converters.URLSearchParams = webidl.interfaceConverter( - URLSearchParams -) - -// https://fetch.spec.whatwg.org/#typedefdef-xmlhttprequestbodyinit -webidl.converters.XMLHttpRequestBodyInit = function (V) { - if (typeof V === 'string') { - return webidl.converters.USVString(V) - } - - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) - } - - if (types.isArrayBuffer(V) || types.isTypedArray(V) || types.isDataView(V)) { - return webidl.converters.BufferSource(V) - } - - if (util.isFormDataLike(V)) { - return webidl.converters.FormData(V, { strict: false }) - } - - if (V instanceof URLSearchParams) { - return webidl.converters.URLSearchParams(V) - } - - return webidl.converters.DOMString(V) -} - -// https://fetch.spec.whatwg.org/#bodyinit -webidl.converters.BodyInit = function (V) { - if (V instanceof ReadableStream) { - return webidl.converters.ReadableStream(V) - } - - // Note: the spec doesn't include async iterables, - // this is an undici extension. - if (V?.[Symbol.asyncIterator]) { - return V - } - - return webidl.converters.XMLHttpRequestBodyInit(V) -} - -webidl.converters.ResponseInit = webidl.dictionaryConverter([ - { - key: 'status', - converter: webidl.converters['unsigned short'], - defaultValue: 200 - }, - { - key: 'statusText', - converter: webidl.converters.ByteString, - defaultValue: '' - }, - { - key: 'headers', - converter: webidl.converters.HeadersInit - } -]) - -module.exports = { - makeNetworkError, - makeResponse, - makeAppropriateNetworkError, - filterResponse, - Response, - cloneResponse -} - - -/***/ }), - -/***/ 9710: -/***/ ((module) => { - - - -module.exports = { - kUrl: Symbol('url'), - kHeaders: Symbol('headers'), - kSignal: Symbol('signal'), - kState: Symbol('state'), - kGuard: Symbol('guard'), - kRealm: Symbol('realm') -} - - -/***/ }), - -/***/ 5523: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { redirectStatusSet, referrerPolicySet: referrerPolicyTokens, badPortsSet } = __nccwpck_require__(7326) -const { getGlobalOrigin } = __nccwpck_require__(5628) -const { performance } = __nccwpck_require__(2987) -const { isBlobLike, toUSVString, ReadableStreamFrom } = __nccwpck_require__(3440) -const assert = __nccwpck_require__(2613) -const { isUint8Array } = __nccwpck_require__(8253) - -let supportedHashes = [] - -// https://nodejs.org/api/crypto.html#determining-if-crypto-support-is-unavailable -/** @type {import('crypto')|undefined} */ -let crypto - -try { - crypto = __nccwpck_require__(6982) - const possibleRelevantHashes = ['sha256', 'sha384', 'sha512'] - supportedHashes = crypto.getHashes().filter((hash) => possibleRelevantHashes.includes(hash)) -/* c8 ignore next 3 */ -} catch { -} - -function responseURL (response) { - // https://fetch.spec.whatwg.org/#responses - // A response has an associated URL. It is a pointer to the last URL - // in response’s URL list and null if response’s URL list is empty. - const urlList = response.urlList - const length = urlList.length - return length === 0 ? null : urlList[length - 1].toString() -} - -// https://fetch.spec.whatwg.org/#concept-response-location-url -function responseLocationURL (response, requestFragment) { - // 1. If response’s status is not a redirect status, then return null. - if (!redirectStatusSet.has(response.status)) { - return null - } - - // 2. Let location be the result of extracting header list values given - // `Location` and response’s header list. - let location = response.headersList.get('location') - - // 3. If location is a header value, then set location to the result of - // parsing location with response’s URL. - if (location !== null && isValidHeaderValue(location)) { - location = new URL(location, responseURL(response)) - } - - // 4. If location is a URL whose fragment is null, then set location’s - // fragment to requestFragment. - if (location && !location.hash) { - location.hash = requestFragment - } - - // 5. Return location. - return location -} - -/** @returns {URL} */ -function requestCurrentURL (request) { - return request.urlList[request.urlList.length - 1] -} - -function requestBadPort (request) { - // 1. Let url be request’s current URL. - const url = requestCurrentURL(request) - - // 2. If url’s scheme is an HTTP(S) scheme and url’s port is a bad port, - // then return blocked. - if (urlIsHttpHttpsScheme(url) && badPortsSet.has(url.port)) { - return 'blocked' - } - - // 3. Return allowed. - return 'allowed' -} - -function isErrorLike (object) { - return object instanceof Error || ( - object?.constructor?.name === 'Error' || - object?.constructor?.name === 'DOMException' - ) -} - -// Check whether |statusText| is a ByteString and -// matches the Reason-Phrase token production. -// RFC 2616: https://tools.ietf.org/html/rfc2616 -// RFC 7230: https://tools.ietf.org/html/rfc7230 -// "reason-phrase = *( HTAB / SP / VCHAR / obs-text )" -// https://github.com/chromium/chromium/blob/94.0.4604.1/third_party/blink/renderer/core/fetch/response.cc#L116 -function isValidReasonPhrase (statusText) { - for (let i = 0; i < statusText.length; ++i) { - const c = statusText.charCodeAt(i) - if ( - !( - ( - c === 0x09 || // HTAB - (c >= 0x20 && c <= 0x7e) || // SP / VCHAR - (c >= 0x80 && c <= 0xff) - ) // obs-text - ) - ) { - return false - } - } - return true -} - -/** - * @see https://tools.ietf.org/html/rfc7230#section-3.2.6 - * @param {number} c - */ -function isTokenCharCode (c) { - switch (c) { - case 0x22: - case 0x28: - case 0x29: - case 0x2c: - case 0x2f: - case 0x3a: - case 0x3b: - case 0x3c: - case 0x3d: - case 0x3e: - case 0x3f: - case 0x40: - case 0x5b: - case 0x5c: - case 0x5d: - case 0x7b: - case 0x7d: - // DQUOTE and "(),/:;<=>?@[\]{}" - return false - default: - // VCHAR %x21-7E - return c >= 0x21 && c <= 0x7e - } -} - -/** - * @param {string} characters - */ -function isValidHTTPToken (characters) { - if (characters.length === 0) { - return false - } - for (let i = 0; i < characters.length; ++i) { - if (!isTokenCharCode(characters.charCodeAt(i))) { - return false - } - } - return true -} - -/** - * @see https://fetch.spec.whatwg.org/#header-name - * @param {string} potentialValue - */ -function isValidHeaderName (potentialValue) { - return isValidHTTPToken(potentialValue) -} - -/** - * @see https://fetch.spec.whatwg.org/#header-value - * @param {string} potentialValue - */ -function isValidHeaderValue (potentialValue) { - // - Has no leading or trailing HTTP tab or space bytes. - // - Contains no 0x00 (NUL) or HTTP newline bytes. - if ( - potentialValue.startsWith('\t') || - potentialValue.startsWith(' ') || - potentialValue.endsWith('\t') || - potentialValue.endsWith(' ') - ) { - return false - } - - if ( - potentialValue.includes('\0') || - potentialValue.includes('\r') || - potentialValue.includes('\n') - ) { - return false - } - - return true -} - -// https://w3c.github.io/webappsec-referrer-policy/#set-requests-referrer-policy-on-redirect -function setRequestReferrerPolicyOnRedirect (request, actualResponse) { - // Given a request request and a response actualResponse, this algorithm - // updates request’s referrer policy according to the Referrer-Policy - // header (if any) in actualResponse. - - // 1. Let policy be the result of executing § 8.1 Parse a referrer policy - // from a Referrer-Policy header on actualResponse. - - // 8.1 Parse a referrer policy from a Referrer-Policy header - // 1. Let policy-tokens be the result of extracting header list values given `Referrer-Policy` and response’s header list. - const { headersList } = actualResponse - // 2. Let policy be the empty string. - // 3. For each token in policy-tokens, if token is a referrer policy and token is not the empty string, then set policy to token. - // 4. Return policy. - const policyHeader = (headersList.get('referrer-policy') ?? '').split(',') - - // Note: As the referrer-policy can contain multiple policies - // separated by comma, we need to loop through all of them - // and pick the first valid one. - // Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Referrer-Policy#specify_a_fallback_policy - let policy = '' - if (policyHeader.length > 0) { - // The right-most policy takes precedence. - // The left-most policy is the fallback. - for (let i = policyHeader.length; i !== 0; i--) { - const token = policyHeader[i - 1].trim() - if (referrerPolicyTokens.has(token)) { - policy = token - break - } - } - } - - // 2. If policy is not the empty string, then set request’s referrer policy to policy. - if (policy !== '') { - request.referrerPolicy = policy - } -} - -// https://fetch.spec.whatwg.org/#cross-origin-resource-policy-check -function crossOriginResourcePolicyCheck () { - // TODO - return 'allowed' -} - -// https://fetch.spec.whatwg.org/#concept-cors-check -function corsCheck () { - // TODO - return 'success' -} - -// https://fetch.spec.whatwg.org/#concept-tao-check -function TAOCheck () { - // TODO - return 'success' -} - -function appendFetchMetadata (httpRequest) { - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-dest-header - // TODO - - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-mode-header - - // 1. Assert: r’s url is a potentially trustworthy URL. - // TODO - - // 2. Let header be a Structured Header whose value is a token. - let header = null - - // 3. Set header’s value to r’s mode. - header = httpRequest.mode - - // 4. Set a structured field value `Sec-Fetch-Mode`/header in r’s header list. - httpRequest.headersList.set('sec-fetch-mode', header) - - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-site-header - // TODO - - // https://w3c.github.io/webappsec-fetch-metadata/#sec-fetch-user-header - // TODO -} - -// https://fetch.spec.whatwg.org/#append-a-request-origin-header -function appendRequestOriginHeader (request) { - // 1. Let serializedOrigin be the result of byte-serializing a request origin with request. - let serializedOrigin = request.origin - - // 2. If request’s response tainting is "cors" or request’s mode is "websocket", then append (`Origin`, serializedOrigin) to request’s header list. - if (request.responseTainting === 'cors' || request.mode === 'websocket') { - if (serializedOrigin) { - request.headersList.append('origin', serializedOrigin) - } - - // 3. Otherwise, if request’s method is neither `GET` nor `HEAD`, then: - } else if (request.method !== 'GET' && request.method !== 'HEAD') { - // 1. Switch on request’s referrer policy: - switch (request.referrerPolicy) { - case 'no-referrer': - // Set serializedOrigin to `null`. - serializedOrigin = null - break - case 'no-referrer-when-downgrade': - case 'strict-origin': - case 'strict-origin-when-cross-origin': - // If request’s origin is a tuple origin, its scheme is "https", and request’s current URL’s scheme is not "https", then set serializedOrigin to `null`. - if (request.origin && urlHasHttpsScheme(request.origin) && !urlHasHttpsScheme(requestCurrentURL(request))) { - serializedOrigin = null - } - break - case 'same-origin': - // If request’s origin is not same origin with request’s current URL’s origin, then set serializedOrigin to `null`. - if (!sameOrigin(request, requestCurrentURL(request))) { - serializedOrigin = null - } - break - default: - // Do nothing. - } - - if (serializedOrigin) { - // 2. Append (`Origin`, serializedOrigin) to request’s header list. - request.headersList.append('origin', serializedOrigin) - } - } -} - -function coarsenedSharedCurrentTime (crossOriginIsolatedCapability) { - // TODO - return performance.now() -} - -// https://fetch.spec.whatwg.org/#create-an-opaque-timing-info -function createOpaqueTimingInfo (timingInfo) { - return { - startTime: timingInfo.startTime ?? 0, - redirectStartTime: 0, - redirectEndTime: 0, - postRedirectStartTime: timingInfo.startTime ?? 0, - finalServiceWorkerStartTime: 0, - finalNetworkResponseStartTime: 0, - finalNetworkRequestStartTime: 0, - endTime: 0, - encodedBodySize: 0, - decodedBodySize: 0, - finalConnectionTimingInfo: null - } -} - -// https://html.spec.whatwg.org/multipage/origin.html#policy-container -function makePolicyContainer () { - // Note: the fetch spec doesn't make use of embedder policy or CSP list - return { - referrerPolicy: 'strict-origin-when-cross-origin' - } -} - -// https://html.spec.whatwg.org/multipage/origin.html#clone-a-policy-container -function clonePolicyContainer (policyContainer) { - return { - referrerPolicy: policyContainer.referrerPolicy - } -} - -// https://w3c.github.io/webappsec-referrer-policy/#determine-requests-referrer -function determineRequestsReferrer (request) { - // 1. Let policy be request's referrer policy. - const policy = request.referrerPolicy - - // Note: policy cannot (shouldn't) be null or an empty string. - assert(policy) - - // 2. Let environment be request’s client. - - let referrerSource = null - - // 3. Switch on request’s referrer: - if (request.referrer === 'client') { - // Note: node isn't a browser and doesn't implement document/iframes, - // so we bypass this step and replace it with our own. - - const globalOrigin = getGlobalOrigin() - - if (!globalOrigin || globalOrigin.origin === 'null') { - return 'no-referrer' - } - - // note: we need to clone it as it's mutated - referrerSource = new URL(globalOrigin) - } else if (request.referrer instanceof URL) { - // Let referrerSource be request’s referrer. - referrerSource = request.referrer - } - - // 4. Let request’s referrerURL be the result of stripping referrerSource for - // use as a referrer. - let referrerURL = stripURLForReferrer(referrerSource) - - // 5. Let referrerOrigin be the result of stripping referrerSource for use as - // a referrer, with the origin-only flag set to true. - const referrerOrigin = stripURLForReferrer(referrerSource, true) - - // 6. If the result of serializing referrerURL is a string whose length is - // greater than 4096, set referrerURL to referrerOrigin. - if (referrerURL.toString().length > 4096) { - referrerURL = referrerOrigin - } - - const areSameOrigin = sameOrigin(request, referrerURL) - const isNonPotentiallyTrustWorthy = isURLPotentiallyTrustworthy(referrerURL) && - !isURLPotentiallyTrustworthy(request.url) - - // 8. Execute the switch statements corresponding to the value of policy: - switch (policy) { - case 'origin': return referrerOrigin != null ? referrerOrigin : stripURLForReferrer(referrerSource, true) - case 'unsafe-url': return referrerURL - case 'same-origin': - return areSameOrigin ? referrerOrigin : 'no-referrer' - case 'origin-when-cross-origin': - return areSameOrigin ? referrerURL : referrerOrigin - case 'strict-origin-when-cross-origin': { - const currentURL = requestCurrentURL(request) - - // 1. If the origin of referrerURL and the origin of request’s current - // URL are the same, then return referrerURL. - if (sameOrigin(referrerURL, currentURL)) { - return referrerURL - } - - // 2. If referrerURL is a potentially trustworthy URL and request’s - // current URL is not a potentially trustworthy URL, then return no - // referrer. - if (isURLPotentiallyTrustworthy(referrerURL) && !isURLPotentiallyTrustworthy(currentURL)) { - return 'no-referrer' - } - - // 3. Return referrerOrigin. - return referrerOrigin - } - case 'strict-origin': // eslint-disable-line - /** - * 1. If referrerURL is a potentially trustworthy URL and - * request’s current URL is not a potentially trustworthy URL, - * then return no referrer. - * 2. Return referrerOrigin - */ - case 'no-referrer-when-downgrade': // eslint-disable-line - /** - * 1. If referrerURL is a potentially trustworthy URL and - * request’s current URL is not a potentially trustworthy URL, - * then return no referrer. - * 2. Return referrerOrigin - */ - - default: // eslint-disable-line - return isNonPotentiallyTrustWorthy ? 'no-referrer' : referrerOrigin - } -} - -/** - * @see https://w3c.github.io/webappsec-referrer-policy/#strip-url - * @param {URL} url - * @param {boolean|undefined} originOnly - */ -function stripURLForReferrer (url, originOnly) { - // 1. Assert: url is a URL. - assert(url instanceof URL) - - // 2. If url’s scheme is a local scheme, then return no referrer. - if (url.protocol === 'file:' || url.protocol === 'about:' || url.protocol === 'blank:') { - return 'no-referrer' - } - - // 3. Set url’s username to the empty string. - url.username = '' - - // 4. Set url’s password to the empty string. - url.password = '' - - // 5. Set url’s fragment to null. - url.hash = '' - - // 6. If the origin-only flag is true, then: - if (originOnly) { - // 1. Set url’s path to « the empty string ». - url.pathname = '' - - // 2. Set url’s query to null. - url.search = '' - } - - // 7. Return url. - return url -} - -function isURLPotentiallyTrustworthy (url) { - if (!(url instanceof URL)) { - return false - } - - // If child of about, return true - if (url.href === 'about:blank' || url.href === 'about:srcdoc') { - return true - } - - // If scheme is data, return true - if (url.protocol === 'data:') return true - - // If file, return true - if (url.protocol === 'file:') return true - - return isOriginPotentiallyTrustworthy(url.origin) - - function isOriginPotentiallyTrustworthy (origin) { - // If origin is explicitly null, return false - if (origin == null || origin === 'null') return false - - const originAsURL = new URL(origin) - - // If secure, return true - if (originAsURL.protocol === 'https:' || originAsURL.protocol === 'wss:') { - return true - } - - // If localhost or variants, return true - if (/^127(?:\.[0-9]+){0,2}\.[0-9]+$|^\[(?:0*:)*?:?0*1\]$/.test(originAsURL.hostname) || - (originAsURL.hostname === 'localhost' || originAsURL.hostname.includes('localhost.')) || - (originAsURL.hostname.endsWith('.localhost'))) { - return true - } - - // If any other, return false - return false - } -} - -/** - * @see https://w3c.github.io/webappsec-subresource-integrity/#does-response-match-metadatalist - * @param {Uint8Array} bytes - * @param {string} metadataList - */ -function bytesMatch (bytes, metadataList) { - // If node is not built with OpenSSL support, we cannot check - // a request's integrity, so allow it by default (the spec will - // allow requests if an invalid hash is given, as precedence). - /* istanbul ignore if: only if node is built with --without-ssl */ - if (crypto === undefined) { - return true - } - - // 1. Let parsedMetadata be the result of parsing metadataList. - const parsedMetadata = parseMetadata(metadataList) - - // 2. If parsedMetadata is no metadata, return true. - if (parsedMetadata === 'no metadata') { - return true - } - - // 3. If response is not eligible for integrity validation, return false. - // TODO - - // 4. If parsedMetadata is the empty set, return true. - if (parsedMetadata.length === 0) { - return true - } - - // 5. Let metadata be the result of getting the strongest - // metadata from parsedMetadata. - const strongest = getStrongestMetadata(parsedMetadata) - const metadata = filterMetadataListByAlgorithm(parsedMetadata, strongest) - - // 6. For each item in metadata: - for (const item of metadata) { - // 1. Let algorithm be the alg component of item. - const algorithm = item.algo - - // 2. Let expectedValue be the val component of item. - const expectedValue = item.hash - - // See https://github.com/web-platform-tests/wpt/commit/e4c5cc7a5e48093220528dfdd1c4012dc3837a0e - // "be liberal with padding". This is annoying, and it's not even in the spec. - - // 3. Let actualValue be the result of applying algorithm to bytes. - let actualValue = crypto.createHash(algorithm).update(bytes).digest('base64') - - if (actualValue[actualValue.length - 1] === '=') { - if (actualValue[actualValue.length - 2] === '=') { - actualValue = actualValue.slice(0, -2) - } else { - actualValue = actualValue.slice(0, -1) - } - } - - // 4. If actualValue is a case-sensitive match for expectedValue, - // return true. - if (compareBase64Mixed(actualValue, expectedValue)) { - return true - } - } - - // 7. Return false. - return false -} - -// https://w3c.github.io/webappsec-subresource-integrity/#grammardef-hash-with-options -// https://www.w3.org/TR/CSP2/#source-list-syntax -// https://www.rfc-editor.org/rfc/rfc5234#appendix-B.1 -const parseHashWithOptions = /(?sha256|sha384|sha512)-((?[A-Za-z0-9+/]+|[A-Za-z0-9_-]+)={0,2}(?:\s|$)( +[!-~]*)?)?/i - -/** - * @see https://w3c.github.io/webappsec-subresource-integrity/#parse-metadata - * @param {string} metadata - */ -function parseMetadata (metadata) { - // 1. Let result be the empty set. - /** @type {{ algo: string, hash: string }[]} */ - const result = [] - - // 2. Let empty be equal to true. - let empty = true - - // 3. For each token returned by splitting metadata on spaces: - for (const token of metadata.split(' ')) { - // 1. Set empty to false. - empty = false - - // 2. Parse token as a hash-with-options. - const parsedToken = parseHashWithOptions.exec(token) - - // 3. If token does not parse, continue to the next token. - if ( - parsedToken === null || - parsedToken.groups === undefined || - parsedToken.groups.algo === undefined - ) { - // Note: Chromium blocks the request at this point, but Firefox - // gives a warning that an invalid integrity was given. The - // correct behavior is to ignore these, and subsequently not - // check the integrity of the resource. - continue - } - - // 4. Let algorithm be the hash-algo component of token. - const algorithm = parsedToken.groups.algo.toLowerCase() - - // 5. If algorithm is a hash function recognized by the user - // agent, add the parsed token to result. - if (supportedHashes.includes(algorithm)) { - result.push(parsedToken.groups) - } - } - - // 4. Return no metadata if empty is true, otherwise return result. - if (empty === true) { - return 'no metadata' - } - - return result -} - -/** - * @param {{ algo: 'sha256' | 'sha384' | 'sha512' }[]} metadataList - */ -function getStrongestMetadata (metadataList) { - // Let algorithm be the algo component of the first item in metadataList. - // Can be sha256 - let algorithm = metadataList[0].algo - // If the algorithm is sha512, then it is the strongest - // and we can return immediately - if (algorithm[3] === '5') { - return algorithm - } - - for (let i = 1; i < metadataList.length; ++i) { - const metadata = metadataList[i] - // If the algorithm is sha512, then it is the strongest - // and we can break the loop immediately - if (metadata.algo[3] === '5') { - algorithm = 'sha512' - break - // If the algorithm is sha384, then a potential sha256 or sha384 is ignored - } else if (algorithm[3] === '3') { - continue - // algorithm is sha256, check if algorithm is sha384 and if so, set it as - // the strongest - } else if (metadata.algo[3] === '3') { - algorithm = 'sha384' - } - } - return algorithm -} - -function filterMetadataListByAlgorithm (metadataList, algorithm) { - if (metadataList.length === 1) { - return metadataList - } - - let pos = 0 - for (let i = 0; i < metadataList.length; ++i) { - if (metadataList[i].algo === algorithm) { - metadataList[pos++] = metadataList[i] - } - } - - metadataList.length = pos - - return metadataList -} - -/** - * Compares two base64 strings, allowing for base64url - * in the second string. - * -* @param {string} actualValue always base64 - * @param {string} expectedValue base64 or base64url - * @returns {boolean} - */ -function compareBase64Mixed (actualValue, expectedValue) { - if (actualValue.length !== expectedValue.length) { - return false - } - for (let i = 0; i < actualValue.length; ++i) { - if (actualValue[i] !== expectedValue[i]) { - if ( - (actualValue[i] === '+' && expectedValue[i] === '-') || - (actualValue[i] === '/' && expectedValue[i] === '_') - ) { - continue - } - return false - } - } - - return true -} - -// https://w3c.github.io/webappsec-upgrade-insecure-requests/#upgrade-request -function tryUpgradeRequestToAPotentiallyTrustworthyURL (request) { - // TODO -} - -/** - * @link {https://html.spec.whatwg.org/multipage/origin.html#same-origin} - * @param {URL} A - * @param {URL} B - */ -function sameOrigin (A, B) { - // 1. If A and B are the same opaque origin, then return true. - if (A.origin === B.origin && A.origin === 'null') { - return true - } - - // 2. If A and B are both tuple origins and their schemes, - // hosts, and port are identical, then return true. - if (A.protocol === B.protocol && A.hostname === B.hostname && A.port === B.port) { - return true - } - - // 3. Return false. - return false -} - -function createDeferredPromise () { - let res - let rej - const promise = new Promise((resolve, reject) => { - res = resolve - rej = reject - }) - - return { promise, resolve: res, reject: rej } -} - -function isAborted (fetchParams) { - return fetchParams.controller.state === 'aborted' -} - -function isCancelled (fetchParams) { - return fetchParams.controller.state === 'aborted' || - fetchParams.controller.state === 'terminated' -} - -const normalizeMethodRecord = { - delete: 'DELETE', - DELETE: 'DELETE', - get: 'GET', - GET: 'GET', - head: 'HEAD', - HEAD: 'HEAD', - options: 'OPTIONS', - OPTIONS: 'OPTIONS', - post: 'POST', - POST: 'POST', - put: 'PUT', - PUT: 'PUT' -} - -// Note: object prototypes should not be able to be referenced. e.g. `Object#hasOwnProperty`. -Object.setPrototypeOf(normalizeMethodRecord, null) - -/** - * @see https://fetch.spec.whatwg.org/#concept-method-normalize - * @param {string} method - */ -function normalizeMethod (method) { - return normalizeMethodRecord[method.toLowerCase()] ?? method -} - -// https://infra.spec.whatwg.org/#serialize-a-javascript-value-to-a-json-string -function serializeJavascriptValueToJSONString (value) { - // 1. Let result be ? Call(%JSON.stringify%, undefined, « value »). - const result = JSON.stringify(value) - - // 2. If result is undefined, then throw a TypeError. - if (result === undefined) { - throw new TypeError('Value is not JSON serializable') - } - - // 3. Assert: result is a string. - assert(typeof result === 'string') - - // 4. Return result. - return result -} - -// https://tc39.es/ecma262/#sec-%25iteratorprototype%25-object -const esIteratorPrototype = Object.getPrototypeOf(Object.getPrototypeOf([][Symbol.iterator]())) - -/** - * @see https://webidl.spec.whatwg.org/#dfn-iterator-prototype-object - * @param {() => unknown[]} iterator - * @param {string} name name of the instance - * @param {'key'|'value'|'key+value'} kind - */ -function makeIterator (iterator, name, kind) { - const object = { - index: 0, - kind, - target: iterator - } - - const i = { - next () { - // 1. Let interface be the interface for which the iterator prototype object exists. - - // 2. Let thisValue be the this value. - - // 3. Let object be ? ToObject(thisValue). - - // 4. If object is a platform object, then perform a security - // check, passing: - - // 5. If object is not a default iterator object for interface, - // then throw a TypeError. - if (Object.getPrototypeOf(this) !== i) { - throw new TypeError( - `'next' called on an object that does not implement interface ${name} Iterator.` - ) - } - - // 6. Let index be object’s index. - // 7. Let kind be object’s kind. - // 8. Let values be object’s target's value pairs to iterate over. - const { index, kind, target } = object - const values = target() - - // 9. Let len be the length of values. - const len = values.length - - // 10. If index is greater than or equal to len, then return - // CreateIterResultObject(undefined, true). - if (index >= len) { - return { value: undefined, done: true } - } - - // 11. Let pair be the entry in values at index index. - const pair = values[index] - - // 12. Set object’s index to index + 1. - object.index = index + 1 - - // 13. Return the iterator result for pair and kind. - return iteratorResult(pair, kind) - }, - // The class string of an iterator prototype object for a given interface is the - // result of concatenating the identifier of the interface and the string " Iterator". - [Symbol.toStringTag]: `${name} Iterator` - } - - // The [[Prototype]] internal slot of an iterator prototype object must be %IteratorPrototype%. - Object.setPrototypeOf(i, esIteratorPrototype) - // esIteratorPrototype needs to be the prototype of i - // which is the prototype of an empty object. Yes, it's confusing. - return Object.setPrototypeOf({}, i) -} - -// https://webidl.spec.whatwg.org/#iterator-result -function iteratorResult (pair, kind) { - let result - - // 1. Let result be a value determined by the value of kind: - switch (kind) { - case 'key': { - // 1. Let idlKey be pair’s key. - // 2. Let key be the result of converting idlKey to an - // ECMAScript value. - // 3. result is key. - result = pair[0] - break - } - case 'value': { - // 1. Let idlValue be pair’s value. - // 2. Let value be the result of converting idlValue to - // an ECMAScript value. - // 3. result is value. - result = pair[1] - break - } - case 'key+value': { - // 1. Let idlKey be pair’s key. - // 2. Let idlValue be pair’s value. - // 3. Let key be the result of converting idlKey to an - // ECMAScript value. - // 4. Let value be the result of converting idlValue to - // an ECMAScript value. - // 5. Let array be ! ArrayCreate(2). - // 6. Call ! CreateDataProperty(array, "0", key). - // 7. Call ! CreateDataProperty(array, "1", value). - // 8. result is array. - result = pair - break - } - } - - // 2. Return CreateIterResultObject(result, false). - return { value: result, done: false } -} - -/** - * @see https://fetch.spec.whatwg.org/#body-fully-read - */ -async function fullyReadBody (body, processBody, processBodyError) { - // 1. If taskDestination is null, then set taskDestination to - // the result of starting a new parallel queue. - - // 2. Let successSteps given a byte sequence bytes be to queue a - // fetch task to run processBody given bytes, with taskDestination. - const successSteps = processBody - - // 3. Let errorSteps be to queue a fetch task to run processBodyError, - // with taskDestination. - const errorSteps = processBodyError - - // 4. Let reader be the result of getting a reader for body’s stream. - // If that threw an exception, then run errorSteps with that - // exception and return. - let reader - - try { - reader = body.stream.getReader() - } catch (e) { - errorSteps(e) - return - } - - // 5. Read all bytes from reader, given successSteps and errorSteps. - try { - const result = await readAllBytes(reader) - successSteps(result) - } catch (e) { - errorSteps(e) - } -} - -/** @type {ReadableStream} */ -let ReadableStream = globalThis.ReadableStream - -function isReadableStreamLike (stream) { - if (!ReadableStream) { - ReadableStream = (__nccwpck_require__(3774).ReadableStream) - } - - return stream instanceof ReadableStream || ( - stream[Symbol.toStringTag] === 'ReadableStream' && - typeof stream.tee === 'function' - ) -} - -const MAXIMUM_ARGUMENT_LENGTH = 65535 - -/** - * @see https://infra.spec.whatwg.org/#isomorphic-decode - * @param {number[]|Uint8Array} input - */ -function isomorphicDecode (input) { - // 1. To isomorphic decode a byte sequence input, return a string whose code point - // length is equal to input’s length and whose code points have the same values - // as the values of input’s bytes, in the same order. - - if (input.length < MAXIMUM_ARGUMENT_LENGTH) { - return String.fromCharCode(...input) - } - - return input.reduce((previous, current) => previous + String.fromCharCode(current), '') -} - -/** - * @param {ReadableStreamController} controller - */ -function readableStreamClose (controller) { - try { - controller.close() - } catch (err) { - // TODO: add comment explaining why this error occurs. - if (!err.message.includes('Controller is already closed')) { - throw err - } - } -} - -/** - * @see https://infra.spec.whatwg.org/#isomorphic-encode - * @param {string} input - */ -function isomorphicEncode (input) { - // 1. Assert: input contains no code points greater than U+00FF. - for (let i = 0; i < input.length; i++) { - assert(input.charCodeAt(i) <= 0xFF) - } - - // 2. Return a byte sequence whose length is equal to input’s code - // point length and whose bytes have the same values as the - // values of input’s code points, in the same order - return input -} - -/** - * @see https://streams.spec.whatwg.org/#readablestreamdefaultreader-read-all-bytes - * @see https://streams.spec.whatwg.org/#read-loop - * @param {ReadableStreamDefaultReader} reader - */ -async function readAllBytes (reader) { - const bytes = [] - let byteLength = 0 - - while (true) { - const { done, value: chunk } = await reader.read() - - if (done) { - // 1. Call successSteps with bytes. - return Buffer.concat(bytes, byteLength) - } - - // 1. If chunk is not a Uint8Array object, call failureSteps - // with a TypeError and abort these steps. - if (!isUint8Array(chunk)) { - throw new TypeError('Received non-Uint8Array chunk') - } - - // 2. Append the bytes represented by chunk to bytes. - bytes.push(chunk) - byteLength += chunk.length - - // 3. Read-loop given reader, bytes, successSteps, and failureSteps. - } -} - -/** - * @see https://fetch.spec.whatwg.org/#is-local - * @param {URL} url - */ -function urlIsLocal (url) { - assert('protocol' in url) // ensure it's a url object - - const protocol = url.protocol - - return protocol === 'about:' || protocol === 'blob:' || protocol === 'data:' -} - -/** - * @param {string|URL} url - */ -function urlHasHttpsScheme (url) { - if (typeof url === 'string') { - return url.startsWith('https:') - } - - return url.protocol === 'https:' -} - -/** - * @see https://fetch.spec.whatwg.org/#http-scheme - * @param {URL} url - */ -function urlIsHttpHttpsScheme (url) { - assert('protocol' in url) // ensure it's a url object - - const protocol = url.protocol - - return protocol === 'http:' || protocol === 'https:' -} - -/** - * Fetch supports node >= 16.8.0, but Object.hasOwn was added in v16.9.0. - */ -const hasOwn = Object.hasOwn || ((dict, key) => Object.prototype.hasOwnProperty.call(dict, key)) - -module.exports = { - isAborted, - isCancelled, - createDeferredPromise, - ReadableStreamFrom, - toUSVString, - tryUpgradeRequestToAPotentiallyTrustworthyURL, - coarsenedSharedCurrentTime, - determineRequestsReferrer, - makePolicyContainer, - clonePolicyContainer, - appendFetchMetadata, - appendRequestOriginHeader, - TAOCheck, - corsCheck, - crossOriginResourcePolicyCheck, - createOpaqueTimingInfo, - setRequestReferrerPolicyOnRedirect, - isValidHTTPToken, - requestBadPort, - requestCurrentURL, - responseURL, - responseLocationURL, - isBlobLike, - isURLPotentiallyTrustworthy, - isValidReasonPhrase, - sameOrigin, - normalizeMethod, - serializeJavascriptValueToJSONString, - makeIterator, - isValidHeaderName, - isValidHeaderValue, - hasOwn, - isErrorLike, - fullyReadBody, - bytesMatch, - isReadableStreamLike, - readableStreamClose, - isomorphicEncode, - isomorphicDecode, - urlIsLocal, - urlHasHttpsScheme, - urlIsHttpHttpsScheme, - readAllBytes, - normalizeMethodRecord, - parseMetadata -} - - -/***/ }), - -/***/ 4222: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { types } = __nccwpck_require__(9023) -const { hasOwn, toUSVString } = __nccwpck_require__(5523) - -/** @type {import('../../types/webidl').Webidl} */ -const webidl = {} -webidl.converters = {} -webidl.util = {} -webidl.errors = {} - -webidl.errors.exception = function (message) { - return new TypeError(`${message.header}: ${message.message}`) -} - -webidl.errors.conversionFailed = function (context) { - const plural = context.types.length === 1 ? '' : ' one of' - const message = - `${context.argument} could not be converted to` + - `${plural}: ${context.types.join(', ')}.` - - return webidl.errors.exception({ - header: context.prefix, - message - }) -} - -webidl.errors.invalidArgument = function (context) { - return webidl.errors.exception({ - header: context.prefix, - message: `"${context.value}" is an invalid ${context.type}.` - }) -} - -// https://webidl.spec.whatwg.org/#implements -webidl.brandCheck = function (V, I, opts = undefined) { - if (opts?.strict !== false && !(V instanceof I)) { - throw new TypeError('Illegal invocation') - } else { - return V?.[Symbol.toStringTag] === I.prototype[Symbol.toStringTag] - } -} - -webidl.argumentLengthCheck = function ({ length }, min, ctx) { - if (length < min) { - throw webidl.errors.exception({ - message: `${min} argument${min !== 1 ? 's' : ''} required, ` + - `but${length ? ' only' : ''} ${length} found.`, - ...ctx - }) - } -} - -webidl.illegalConstructor = function () { - throw webidl.errors.exception({ - header: 'TypeError', - message: 'Illegal constructor' - }) -} - -// https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values -webidl.util.Type = function (V) { - switch (typeof V) { - case 'undefined': return 'Undefined' - case 'boolean': return 'Boolean' - case 'string': return 'String' - case 'symbol': return 'Symbol' - case 'number': return 'Number' - case 'bigint': return 'BigInt' - case 'function': - case 'object': { - if (V === null) { - return 'Null' - } - - return 'Object' - } - } -} - -// https://webidl.spec.whatwg.org/#abstract-opdef-converttoint -webidl.util.ConvertToInt = function (V, bitLength, signedness, opts = {}) { - let upperBound - let lowerBound - - // 1. If bitLength is 64, then: - if (bitLength === 64) { - // 1. Let upperBound be 2^53 − 1. - upperBound = Math.pow(2, 53) - 1 - - // 2. If signedness is "unsigned", then let lowerBound be 0. - if (signedness === 'unsigned') { - lowerBound = 0 - } else { - // 3. Otherwise let lowerBound be −2^53 + 1. - lowerBound = Math.pow(-2, 53) + 1 - } - } else if (signedness === 'unsigned') { - // 2. Otherwise, if signedness is "unsigned", then: - - // 1. Let lowerBound be 0. - lowerBound = 0 - - // 2. Let upperBound be 2^bitLength − 1. - upperBound = Math.pow(2, bitLength) - 1 - } else { - // 3. Otherwise: - - // 1. Let lowerBound be -2^bitLength − 1. - lowerBound = Math.pow(-2, bitLength) - 1 - - // 2. Let upperBound be 2^bitLength − 1 − 1. - upperBound = Math.pow(2, bitLength - 1) - 1 - } - - // 4. Let x be ? ToNumber(V). - let x = Number(V) - - // 5. If x is −0, then set x to +0. - if (x === 0) { - x = 0 - } - - // 6. If the conversion is to an IDL type associated - // with the [EnforceRange] extended attribute, then: - if (opts.enforceRange === true) { - // 1. If x is NaN, +∞, or −∞, then throw a TypeError. - if ( - Number.isNaN(x) || - x === Number.POSITIVE_INFINITY || - x === Number.NEGATIVE_INFINITY - ) { - throw webidl.errors.exception({ - header: 'Integer conversion', - message: `Could not convert ${V} to an integer.` - }) - } - - // 2. Set x to IntegerPart(x). - x = webidl.util.IntegerPart(x) - - // 3. If x < lowerBound or x > upperBound, then - // throw a TypeError. - if (x < lowerBound || x > upperBound) { - throw webidl.errors.exception({ - header: 'Integer conversion', - message: `Value must be between ${lowerBound}-${upperBound}, got ${x}.` - }) - } - - // 4. Return x. - return x - } - - // 7. If x is not NaN and the conversion is to an IDL - // type associated with the [Clamp] extended - // attribute, then: - if (!Number.isNaN(x) && opts.clamp === true) { - // 1. Set x to min(max(x, lowerBound), upperBound). - x = Math.min(Math.max(x, lowerBound), upperBound) - - // 2. Round x to the nearest integer, choosing the - // even integer if it lies halfway between two, - // and choosing +0 rather than −0. - if (Math.floor(x) % 2 === 0) { - x = Math.floor(x) - } else { - x = Math.ceil(x) - } - - // 3. Return x. - return x - } - - // 8. If x is NaN, +0, +∞, or −∞, then return +0. - if ( - Number.isNaN(x) || - (x === 0 && Object.is(0, x)) || - x === Number.POSITIVE_INFINITY || - x === Number.NEGATIVE_INFINITY - ) { - return 0 - } - - // 9. Set x to IntegerPart(x). - x = webidl.util.IntegerPart(x) - - // 10. Set x to x modulo 2^bitLength. - x = x % Math.pow(2, bitLength) - - // 11. If signedness is "signed" and x ≥ 2^bitLength − 1, - // then return x − 2^bitLength. - if (signedness === 'signed' && x >= Math.pow(2, bitLength) - 1) { - return x - Math.pow(2, bitLength) - } - - // 12. Otherwise, return x. - return x -} - -// https://webidl.spec.whatwg.org/#abstract-opdef-integerpart -webidl.util.IntegerPart = function (n) { - // 1. Let r be floor(abs(n)). - const r = Math.floor(Math.abs(n)) - - // 2. If n < 0, then return -1 × r. - if (n < 0) { - return -1 * r - } - - // 3. Otherwise, return r. - return r -} - -// https://webidl.spec.whatwg.org/#es-sequence -webidl.sequenceConverter = function (converter) { - return (V) => { - // 1. If Type(V) is not Object, throw a TypeError. - if (webidl.util.Type(V) !== 'Object') { - throw webidl.errors.exception({ - header: 'Sequence', - message: `Value of type ${webidl.util.Type(V)} is not an Object.` - }) - } - - // 2. Let method be ? GetMethod(V, @@iterator). - /** @type {Generator} */ - const method = V?.[Symbol.iterator]?.() - const seq = [] - - // 3. If method is undefined, throw a TypeError. - if ( - method === undefined || - typeof method.next !== 'function' - ) { - throw webidl.errors.exception({ - header: 'Sequence', - message: 'Object is not an iterator.' - }) - } - - // https://webidl.spec.whatwg.org/#create-sequence-from-iterable - while (true) { - const { done, value } = method.next() - - if (done) { - break - } - - seq.push(converter(value)) - } - - return seq - } -} - -// https://webidl.spec.whatwg.org/#es-to-record -webidl.recordConverter = function (keyConverter, valueConverter) { - return (O) => { - // 1. If Type(O) is not Object, throw a TypeError. - if (webidl.util.Type(O) !== 'Object') { - throw webidl.errors.exception({ - header: 'Record', - message: `Value of type ${webidl.util.Type(O)} is not an Object.` - }) - } - - // 2. Let result be a new empty instance of record. - const result = {} - - if (!types.isProxy(O)) { - // Object.keys only returns enumerable properties - const keys = Object.keys(O) - - for (const key of keys) { - // 1. Let typedKey be key converted to an IDL value of type K. - const typedKey = keyConverter(key) - - // 2. Let value be ? Get(O, key). - // 3. Let typedValue be value converted to an IDL value of type V. - const typedValue = valueConverter(O[key]) - - // 4. Set result[typedKey] to typedValue. - result[typedKey] = typedValue - } - - // 5. Return result. - return result - } - - // 3. Let keys be ? O.[[OwnPropertyKeys]](). - const keys = Reflect.ownKeys(O) - - // 4. For each key of keys. - for (const key of keys) { - // 1. Let desc be ? O.[[GetOwnProperty]](key). - const desc = Reflect.getOwnPropertyDescriptor(O, key) - - // 2. If desc is not undefined and desc.[[Enumerable]] is true: - if (desc?.enumerable) { - // 1. Let typedKey be key converted to an IDL value of type K. - const typedKey = keyConverter(key) - - // 2. Let value be ? Get(O, key). - // 3. Let typedValue be value converted to an IDL value of type V. - const typedValue = valueConverter(O[key]) - - // 4. Set result[typedKey] to typedValue. - result[typedKey] = typedValue - } - } - - // 5. Return result. - return result - } -} - -webidl.interfaceConverter = function (i) { - return (V, opts = {}) => { - if (opts.strict !== false && !(V instanceof i)) { - throw webidl.errors.exception({ - header: i.name, - message: `Expected ${V} to be an instance of ${i.name}.` - }) - } - - return V - } -} - -webidl.dictionaryConverter = function (converters) { - return (dictionary) => { - const type = webidl.util.Type(dictionary) - const dict = {} - - if (type === 'Null' || type === 'Undefined') { - return dict - } else if (type !== 'Object') { - throw webidl.errors.exception({ - header: 'Dictionary', - message: `Expected ${dictionary} to be one of: Null, Undefined, Object.` - }) - } - - for (const options of converters) { - const { key, defaultValue, required, converter } = options - - if (required === true) { - if (!hasOwn(dictionary, key)) { - throw webidl.errors.exception({ - header: 'Dictionary', - message: `Missing required key "${key}".` - }) - } - } - - let value = dictionary[key] - const hasDefault = hasOwn(options, 'defaultValue') - - // Only use defaultValue if value is undefined and - // a defaultValue options was provided. - if (hasDefault && value !== null) { - value = value ?? defaultValue - } - - // A key can be optional and have no default value. - // When this happens, do not perform a conversion, - // and do not assign the key a value. - if (required || hasDefault || value !== undefined) { - value = converter(value) - - if ( - options.allowedValues && - !options.allowedValues.includes(value) - ) { - throw webidl.errors.exception({ - header: 'Dictionary', - message: `${value} is not an accepted type. Expected one of ${options.allowedValues.join(', ')}.` - }) - } - - dict[key] = value - } - } - - return dict - } -} - -webidl.nullableConverter = function (converter) { - return (V) => { - if (V === null) { - return V - } - - return converter(V) - } -} - -// https://webidl.spec.whatwg.org/#es-DOMString -webidl.converters.DOMString = function (V, opts = {}) { - // 1. If V is null and the conversion is to an IDL type - // associated with the [LegacyNullToEmptyString] - // extended attribute, then return the DOMString value - // that represents the empty string. - if (V === null && opts.legacyNullToEmptyString) { - return '' - } - - // 2. Let x be ? ToString(V). - if (typeof V === 'symbol') { - throw new TypeError('Could not convert argument of type symbol to string.') - } - - // 3. Return the IDL DOMString value that represents the - // same sequence of code units as the one the - // ECMAScript String value x represents. - return String(V) -} - -// https://webidl.spec.whatwg.org/#es-ByteString -webidl.converters.ByteString = function (V) { - // 1. Let x be ? ToString(V). - // Note: DOMString converter perform ? ToString(V) - const x = webidl.converters.DOMString(V) - - // 2. If the value of any element of x is greater than - // 255, then throw a TypeError. - for (let index = 0; index < x.length; index++) { - if (x.charCodeAt(index) > 255) { - throw new TypeError( - 'Cannot convert argument to a ByteString because the character at ' + - `index ${index} has a value of ${x.charCodeAt(index)} which is greater than 255.` - ) - } - } - - // 3. Return an IDL ByteString value whose length is the - // length of x, and where the value of each element is - // the value of the corresponding element of x. - return x -} - -// https://webidl.spec.whatwg.org/#es-USVString -webidl.converters.USVString = toUSVString - -// https://webidl.spec.whatwg.org/#es-boolean -webidl.converters.boolean = function (V) { - // 1. Let x be the result of computing ToBoolean(V). - const x = Boolean(V) - - // 2. Return the IDL boolean value that is the one that represents - // the same truth value as the ECMAScript Boolean value x. - return x -} - -// https://webidl.spec.whatwg.org/#es-any -webidl.converters.any = function (V) { - return V -} - -// https://webidl.spec.whatwg.org/#es-long-long -webidl.converters['long long'] = function (V) { - // 1. Let x be ? ConvertToInt(V, 64, "signed"). - const x = webidl.util.ConvertToInt(V, 64, 'signed') - - // 2. Return the IDL long long value that represents - // the same numeric value as x. - return x -} - -// https://webidl.spec.whatwg.org/#es-unsigned-long-long -webidl.converters['unsigned long long'] = function (V) { - // 1. Let x be ? ConvertToInt(V, 64, "unsigned"). - const x = webidl.util.ConvertToInt(V, 64, 'unsigned') - - // 2. Return the IDL unsigned long long value that - // represents the same numeric value as x. - return x -} - -// https://webidl.spec.whatwg.org/#es-unsigned-long -webidl.converters['unsigned long'] = function (V) { - // 1. Let x be ? ConvertToInt(V, 32, "unsigned"). - const x = webidl.util.ConvertToInt(V, 32, 'unsigned') - - // 2. Return the IDL unsigned long value that - // represents the same numeric value as x. - return x -} - -// https://webidl.spec.whatwg.org/#es-unsigned-short -webidl.converters['unsigned short'] = function (V, opts) { - // 1. Let x be ? ConvertToInt(V, 16, "unsigned"). - const x = webidl.util.ConvertToInt(V, 16, 'unsigned', opts) - - // 2. Return the IDL unsigned short value that represents - // the same numeric value as x. - return x -} - -// https://webidl.spec.whatwg.org/#idl-ArrayBuffer -webidl.converters.ArrayBuffer = function (V, opts = {}) { - // 1. If Type(V) is not Object, or V does not have an - // [[ArrayBufferData]] internal slot, then throw a - // TypeError. - // see: https://tc39.es/ecma262/#sec-properties-of-the-arraybuffer-instances - // see: https://tc39.es/ecma262/#sec-properties-of-the-sharedarraybuffer-instances - if ( - webidl.util.Type(V) !== 'Object' || - !types.isAnyArrayBuffer(V) - ) { - throw webidl.errors.conversionFailed({ - prefix: `${V}`, - argument: `${V}`, - types: ['ArrayBuffer'] - }) - } - - // 2. If the conversion is not to an IDL type associated - // with the [AllowShared] extended attribute, and - // IsSharedArrayBuffer(V) is true, then throw a - // TypeError. - if (opts.allowShared === false && types.isSharedArrayBuffer(V)) { - throw webidl.errors.exception({ - header: 'ArrayBuffer', - message: 'SharedArrayBuffer is not allowed.' - }) - } - - // 3. If the conversion is not to an IDL type associated - // with the [AllowResizable] extended attribute, and - // IsResizableArrayBuffer(V) is true, then throw a - // TypeError. - // Note: resizable ArrayBuffers are currently a proposal. - - // 4. Return the IDL ArrayBuffer value that is a - // reference to the same object as V. - return V -} - -webidl.converters.TypedArray = function (V, T, opts = {}) { - // 1. Let T be the IDL type V is being converted to. - - // 2. If Type(V) is not Object, or V does not have a - // [[TypedArrayName]] internal slot with a value - // equal to T’s name, then throw a TypeError. - if ( - webidl.util.Type(V) !== 'Object' || - !types.isTypedArray(V) || - V.constructor.name !== T.name - ) { - throw webidl.errors.conversionFailed({ - prefix: `${T.name}`, - argument: `${V}`, - types: [T.name] - }) - } - - // 3. If the conversion is not to an IDL type associated - // with the [AllowShared] extended attribute, and - // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is - // true, then throw a TypeError. - if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { - throw webidl.errors.exception({ - header: 'ArrayBuffer', - message: 'SharedArrayBuffer is not allowed.' - }) - } - - // 4. If the conversion is not to an IDL type associated - // with the [AllowResizable] extended attribute, and - // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is - // true, then throw a TypeError. - // Note: resizable array buffers are currently a proposal - - // 5. Return the IDL value of type T that is a reference - // to the same object as V. - return V -} - -webidl.converters.DataView = function (V, opts = {}) { - // 1. If Type(V) is not Object, or V does not have a - // [[DataView]] internal slot, then throw a TypeError. - if (webidl.util.Type(V) !== 'Object' || !types.isDataView(V)) { - throw webidl.errors.exception({ - header: 'DataView', - message: 'Object is not a DataView.' - }) - } - - // 2. If the conversion is not to an IDL type associated - // with the [AllowShared] extended attribute, and - // IsSharedArrayBuffer(V.[[ViewedArrayBuffer]]) is true, - // then throw a TypeError. - if (opts.allowShared === false && types.isSharedArrayBuffer(V.buffer)) { - throw webidl.errors.exception({ - header: 'ArrayBuffer', - message: 'SharedArrayBuffer is not allowed.' - }) - } - - // 3. If the conversion is not to an IDL type associated - // with the [AllowResizable] extended attribute, and - // IsResizableArrayBuffer(V.[[ViewedArrayBuffer]]) is - // true, then throw a TypeError. - // Note: resizable ArrayBuffers are currently a proposal - - // 4. Return the IDL DataView value that is a reference - // to the same object as V. - return V -} - -// https://webidl.spec.whatwg.org/#BufferSource -webidl.converters.BufferSource = function (V, opts = {}) { - if (types.isAnyArrayBuffer(V)) { - return webidl.converters.ArrayBuffer(V, opts) - } - - if (types.isTypedArray(V)) { - return webidl.converters.TypedArray(V, V.constructor) - } - - if (types.isDataView(V)) { - return webidl.converters.DataView(V, opts) - } - - throw new TypeError(`Could not convert ${V} to a BufferSource.`) -} - -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.ByteString -) - -webidl.converters['sequence>'] = webidl.sequenceConverter( - webidl.converters['sequence'] -) - -webidl.converters['record'] = webidl.recordConverter( - webidl.converters.ByteString, - webidl.converters.ByteString -) - -module.exports = { - webidl -} - - -/***/ }), - -/***/ 396: -/***/ ((module) => { - - - -/** - * @see https://encoding.spec.whatwg.org/#concept-encoding-get - * @param {string|undefined} label - */ -function getEncoding (label) { - if (!label) { - return 'failure' - } - - // 1. Remove any leading and trailing ASCII whitespace from label. - // 2. If label is an ASCII case-insensitive match for any of the - // labels listed in the table below, then return the - // corresponding encoding; otherwise return failure. - switch (label.trim().toLowerCase()) { - case 'unicode-1-1-utf-8': - case 'unicode11utf8': - case 'unicode20utf8': - case 'utf-8': - case 'utf8': - case 'x-unicode20utf8': - return 'UTF-8' - case '866': - case 'cp866': - case 'csibm866': - case 'ibm866': - return 'IBM866' - case 'csisolatin2': - case 'iso-8859-2': - case 'iso-ir-101': - case 'iso8859-2': - case 'iso88592': - case 'iso_8859-2': - case 'iso_8859-2:1987': - case 'l2': - case 'latin2': - return 'ISO-8859-2' - case 'csisolatin3': - case 'iso-8859-3': - case 'iso-ir-109': - case 'iso8859-3': - case 'iso88593': - case 'iso_8859-3': - case 'iso_8859-3:1988': - case 'l3': - case 'latin3': - return 'ISO-8859-3' - case 'csisolatin4': - case 'iso-8859-4': - case 'iso-ir-110': - case 'iso8859-4': - case 'iso88594': - case 'iso_8859-4': - case 'iso_8859-4:1988': - case 'l4': - case 'latin4': - return 'ISO-8859-4' - case 'csisolatincyrillic': - case 'cyrillic': - case 'iso-8859-5': - case 'iso-ir-144': - case 'iso8859-5': - case 'iso88595': - case 'iso_8859-5': - case 'iso_8859-5:1988': - return 'ISO-8859-5' - case 'arabic': - case 'asmo-708': - case 'csiso88596e': - case 'csiso88596i': - case 'csisolatinarabic': - case 'ecma-114': - case 'iso-8859-6': - case 'iso-8859-6-e': - case 'iso-8859-6-i': - case 'iso-ir-127': - case 'iso8859-6': - case 'iso88596': - case 'iso_8859-6': - case 'iso_8859-6:1987': - return 'ISO-8859-6' - case 'csisolatingreek': - case 'ecma-118': - case 'elot_928': - case 'greek': - case 'greek8': - case 'iso-8859-7': - case 'iso-ir-126': - case 'iso8859-7': - case 'iso88597': - case 'iso_8859-7': - case 'iso_8859-7:1987': - case 'sun_eu_greek': - return 'ISO-8859-7' - case 'csiso88598e': - case 'csisolatinhebrew': - case 'hebrew': - case 'iso-8859-8': - case 'iso-8859-8-e': - case 'iso-ir-138': - case 'iso8859-8': - case 'iso88598': - case 'iso_8859-8': - case 'iso_8859-8:1988': - case 'visual': - return 'ISO-8859-8' - case 'csiso88598i': - case 'iso-8859-8-i': - case 'logical': - return 'ISO-8859-8-I' - case 'csisolatin6': - case 'iso-8859-10': - case 'iso-ir-157': - case 'iso8859-10': - case 'iso885910': - case 'l6': - case 'latin6': - return 'ISO-8859-10' - case 'iso-8859-13': - case 'iso8859-13': - case 'iso885913': - return 'ISO-8859-13' - case 'iso-8859-14': - case 'iso8859-14': - case 'iso885914': - return 'ISO-8859-14' - case 'csisolatin9': - case 'iso-8859-15': - case 'iso8859-15': - case 'iso885915': - case 'iso_8859-15': - case 'l9': - return 'ISO-8859-15' - case 'iso-8859-16': - return 'ISO-8859-16' - case 'cskoi8r': - case 'koi': - case 'koi8': - case 'koi8-r': - case 'koi8_r': - return 'KOI8-R' - case 'koi8-ru': - case 'koi8-u': - return 'KOI8-U' - case 'csmacintosh': - case 'mac': - case 'macintosh': - case 'x-mac-roman': - return 'macintosh' - case 'iso-8859-11': - case 'iso8859-11': - case 'iso885911': - case 'tis-620': - case 'windows-874': - return 'windows-874' - case 'cp1250': - case 'windows-1250': - case 'x-cp1250': - return 'windows-1250' - case 'cp1251': - case 'windows-1251': - case 'x-cp1251': - return 'windows-1251' - case 'ansi_x3.4-1968': - case 'ascii': - case 'cp1252': - case 'cp819': - case 'csisolatin1': - case 'ibm819': - case 'iso-8859-1': - case 'iso-ir-100': - case 'iso8859-1': - case 'iso88591': - case 'iso_8859-1': - case 'iso_8859-1:1987': - case 'l1': - case 'latin1': - case 'us-ascii': - case 'windows-1252': - case 'x-cp1252': - return 'windows-1252' - case 'cp1253': - case 'windows-1253': - case 'x-cp1253': - return 'windows-1253' - case 'cp1254': - case 'csisolatin5': - case 'iso-8859-9': - case 'iso-ir-148': - case 'iso8859-9': - case 'iso88599': - case 'iso_8859-9': - case 'iso_8859-9:1989': - case 'l5': - case 'latin5': - case 'windows-1254': - case 'x-cp1254': - return 'windows-1254' - case 'cp1255': - case 'windows-1255': - case 'x-cp1255': - return 'windows-1255' - case 'cp1256': - case 'windows-1256': - case 'x-cp1256': - return 'windows-1256' - case 'cp1257': - case 'windows-1257': - case 'x-cp1257': - return 'windows-1257' - case 'cp1258': - case 'windows-1258': - case 'x-cp1258': - return 'windows-1258' - case 'x-mac-cyrillic': - case 'x-mac-ukrainian': - return 'x-mac-cyrillic' - case 'chinese': - case 'csgb2312': - case 'csiso58gb231280': - case 'gb2312': - case 'gb_2312': - case 'gb_2312-80': - case 'gbk': - case 'iso-ir-58': - case 'x-gbk': - return 'GBK' - case 'gb18030': - return 'gb18030' - case 'big5': - case 'big5-hkscs': - case 'cn-big5': - case 'csbig5': - case 'x-x-big5': - return 'Big5' - case 'cseucpkdfmtjapanese': - case 'euc-jp': - case 'x-euc-jp': - return 'EUC-JP' - case 'csiso2022jp': - case 'iso-2022-jp': - return 'ISO-2022-JP' - case 'csshiftjis': - case 'ms932': - case 'ms_kanji': - case 'shift-jis': - case 'shift_jis': - case 'sjis': - case 'windows-31j': - case 'x-sjis': - return 'Shift_JIS' - case 'cseuckr': - case 'csksc56011987': - case 'euc-kr': - case 'iso-ir-149': - case 'korean': - case 'ks_c_5601-1987': - case 'ks_c_5601-1989': - case 'ksc5601': - case 'ksc_5601': - case 'windows-949': - return 'EUC-KR' - case 'csiso2022kr': - case 'hz-gb-2312': - case 'iso-2022-cn': - case 'iso-2022-cn-ext': - case 'iso-2022-kr': - case 'replacement': - return 'replacement' - case 'unicodefffe': - case 'utf-16be': - return 'UTF-16BE' - case 'csunicode': - case 'iso-10646-ucs-2': - case 'ucs-2': - case 'unicode': - case 'unicodefeff': - case 'utf-16': - case 'utf-16le': - return 'UTF-16LE' - case 'x-user-defined': - return 'x-user-defined' - default: return 'failure' - } -} - -module.exports = { - getEncoding -} - - -/***/ }), - -/***/ 2160: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - staticPropertyDescriptors, - readOperation, - fireAProgressEvent -} = __nccwpck_require__(165) -const { - kState, - kError, - kResult, - kEvents, - kAborted -} = __nccwpck_require__(6812) -const { webidl } = __nccwpck_require__(4222) -const { kEnumerableProperty } = __nccwpck_require__(3440) - -class FileReader extends EventTarget { - constructor () { - super() - - this[kState] = 'empty' - this[kResult] = null - this[kError] = null - this[kEvents] = { - loadend: null, - error: null, - abort: null, - load: null, - progress: null, - loadstart: null - } - } - - /** - * @see https://w3c.github.io/FileAPI/#dfn-readAsArrayBuffer - * @param {import('buffer').Blob} blob - */ - readAsArrayBuffer (blob) { - webidl.brandCheck(this, FileReader) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsArrayBuffer' }) - - blob = webidl.converters.Blob(blob, { strict: false }) - - // The readAsArrayBuffer(blob) method, when invoked, - // must initiate a read operation for blob with ArrayBuffer. - readOperation(this, blob, 'ArrayBuffer') - } - - /** - * @see https://w3c.github.io/FileAPI/#readAsBinaryString - * @param {import('buffer').Blob} blob - */ - readAsBinaryString (blob) { - webidl.brandCheck(this, FileReader) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsBinaryString' }) - - blob = webidl.converters.Blob(blob, { strict: false }) - - // The readAsBinaryString(blob) method, when invoked, - // must initiate a read operation for blob with BinaryString. - readOperation(this, blob, 'BinaryString') - } - - /** - * @see https://w3c.github.io/FileAPI/#readAsDataText - * @param {import('buffer').Blob} blob - * @param {string?} encoding - */ - readAsText (blob, encoding = undefined) { - webidl.brandCheck(this, FileReader) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsText' }) - - blob = webidl.converters.Blob(blob, { strict: false }) - - if (encoding !== undefined) { - encoding = webidl.converters.DOMString(encoding) - } - - // The readAsText(blob, encoding) method, when invoked, - // must initiate a read operation for blob with Text and encoding. - readOperation(this, blob, 'Text', encoding) - } - - /** - * @see https://w3c.github.io/FileAPI/#dfn-readAsDataURL - * @param {import('buffer').Blob} blob - */ - readAsDataURL (blob) { - webidl.brandCheck(this, FileReader) - - webidl.argumentLengthCheck(arguments, 1, { header: 'FileReader.readAsDataURL' }) - - blob = webidl.converters.Blob(blob, { strict: false }) - - // The readAsDataURL(blob) method, when invoked, must - // initiate a read operation for blob with DataURL. - readOperation(this, blob, 'DataURL') - } - - /** - * @see https://w3c.github.io/FileAPI/#dfn-abort - */ - abort () { - // 1. If this's state is "empty" or if this's state is - // "done" set this's result to null and terminate - // this algorithm. - if (this[kState] === 'empty' || this[kState] === 'done') { - this[kResult] = null - return - } - - // 2. If this's state is "loading" set this's state to - // "done" and set this's result to null. - if (this[kState] === 'loading') { - this[kState] = 'done' - this[kResult] = null - } - - // 3. If there are any tasks from this on the file reading - // task source in an affiliated task queue, then remove - // those tasks from that task queue. - this[kAborted] = true - - // 4. Terminate the algorithm for the read method being processed. - // TODO - - // 5. Fire a progress event called abort at this. - fireAProgressEvent('abort', this) - - // 6. If this's state is not "loading", fire a progress - // event called loadend at this. - if (this[kState] !== 'loading') { - fireAProgressEvent('loadend', this) - } - } - - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-readystate - */ - get readyState () { - webidl.brandCheck(this, FileReader) - - switch (this[kState]) { - case 'empty': return this.EMPTY - case 'loading': return this.LOADING - case 'done': return this.DONE - } - } - - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-result - */ - get result () { - webidl.brandCheck(this, FileReader) - - // The result attribute’s getter, when invoked, must return - // this's result. - return this[kResult] - } - - /** - * @see https://w3c.github.io/FileAPI/#dom-filereader-error - */ - get error () { - webidl.brandCheck(this, FileReader) - - // The error attribute’s getter, when invoked, must return - // this's error. - return this[kError] - } - - get onloadend () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].loadend - } - - set onloadend (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].loadend) { - this.removeEventListener('loadend', this[kEvents].loadend) - } - - if (typeof fn === 'function') { - this[kEvents].loadend = fn - this.addEventListener('loadend', fn) - } else { - this[kEvents].loadend = null - } - } - - get onerror () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].error - } - - set onerror (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].error) { - this.removeEventListener('error', this[kEvents].error) - } - - if (typeof fn === 'function') { - this[kEvents].error = fn - this.addEventListener('error', fn) - } else { - this[kEvents].error = null - } - } - - get onloadstart () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].loadstart - } - - set onloadstart (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].loadstart) { - this.removeEventListener('loadstart', this[kEvents].loadstart) - } - - if (typeof fn === 'function') { - this[kEvents].loadstart = fn - this.addEventListener('loadstart', fn) - } else { - this[kEvents].loadstart = null - } - } - - get onprogress () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].progress - } - - set onprogress (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].progress) { - this.removeEventListener('progress', this[kEvents].progress) - } - - if (typeof fn === 'function') { - this[kEvents].progress = fn - this.addEventListener('progress', fn) - } else { - this[kEvents].progress = null - } - } - - get onload () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].load - } - - set onload (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].load) { - this.removeEventListener('load', this[kEvents].load) - } - - if (typeof fn === 'function') { - this[kEvents].load = fn - this.addEventListener('load', fn) - } else { - this[kEvents].load = null - } - } - - get onabort () { - webidl.brandCheck(this, FileReader) - - return this[kEvents].abort - } - - set onabort (fn) { - webidl.brandCheck(this, FileReader) - - if (this[kEvents].abort) { - this.removeEventListener('abort', this[kEvents].abort) - } - - if (typeof fn === 'function') { - this[kEvents].abort = fn - this.addEventListener('abort', fn) - } else { - this[kEvents].abort = null - } - } -} - -// https://w3c.github.io/FileAPI/#dom-filereader-empty -FileReader.EMPTY = FileReader.prototype.EMPTY = 0 -// https://w3c.github.io/FileAPI/#dom-filereader-loading -FileReader.LOADING = FileReader.prototype.LOADING = 1 -// https://w3c.github.io/FileAPI/#dom-filereader-done -FileReader.DONE = FileReader.prototype.DONE = 2 - -Object.defineProperties(FileReader.prototype, { - EMPTY: staticPropertyDescriptors, - LOADING: staticPropertyDescriptors, - DONE: staticPropertyDescriptors, - readAsArrayBuffer: kEnumerableProperty, - readAsBinaryString: kEnumerableProperty, - readAsText: kEnumerableProperty, - readAsDataURL: kEnumerableProperty, - abort: kEnumerableProperty, - readyState: kEnumerableProperty, - result: kEnumerableProperty, - error: kEnumerableProperty, - onloadstart: kEnumerableProperty, - onprogress: kEnumerableProperty, - onload: kEnumerableProperty, - onabort: kEnumerableProperty, - onerror: kEnumerableProperty, - onloadend: kEnumerableProperty, - [Symbol.toStringTag]: { - value: 'FileReader', - writable: false, - enumerable: false, - configurable: true - } -}) - -Object.defineProperties(FileReader, { - EMPTY: staticPropertyDescriptors, - LOADING: staticPropertyDescriptors, - DONE: staticPropertyDescriptors -}) - -module.exports = { - FileReader -} - - -/***/ }), - -/***/ 5976: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { webidl } = __nccwpck_require__(4222) - -const kState = Symbol('ProgressEvent state') - -/** - * @see https://xhr.spec.whatwg.org/#progressevent - */ -class ProgressEvent extends Event { - constructor (type, eventInitDict = {}) { - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.ProgressEventInit(eventInitDict ?? {}) - - super(type, eventInitDict) - - this[kState] = { - lengthComputable: eventInitDict.lengthComputable, - loaded: eventInitDict.loaded, - total: eventInitDict.total - } - } - - get lengthComputable () { - webidl.brandCheck(this, ProgressEvent) - - return this[kState].lengthComputable - } - - get loaded () { - webidl.brandCheck(this, ProgressEvent) - - return this[kState].loaded - } - - get total () { - webidl.brandCheck(this, ProgressEvent) - - return this[kState].total - } -} - -webidl.converters.ProgressEventInit = webidl.dictionaryConverter([ - { - key: 'lengthComputable', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'loaded', - converter: webidl.converters['unsigned long long'], - defaultValue: 0 - }, - { - key: 'total', - converter: webidl.converters['unsigned long long'], - defaultValue: 0 - }, - { - key: 'bubbles', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'cancelable', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'composed', - converter: webidl.converters.boolean, - defaultValue: false - } -]) - -module.exports = { - ProgressEvent -} - - -/***/ }), - -/***/ 6812: -/***/ ((module) => { - - - -module.exports = { - kState: Symbol('FileReader state'), - kResult: Symbol('FileReader result'), - kError: Symbol('FileReader error'), - kLastProgressEventFired: Symbol('FileReader last progress event fired timestamp'), - kEvents: Symbol('FileReader events'), - kAborted: Symbol('FileReader aborted') -} - - -/***/ }), - -/***/ 165: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - kState, - kError, - kResult, - kAborted, - kLastProgressEventFired -} = __nccwpck_require__(6812) -const { ProgressEvent } = __nccwpck_require__(5976) -const { getEncoding } = __nccwpck_require__(396) -const { DOMException } = __nccwpck_require__(7326) -const { serializeAMimeType, parseMIMEType } = __nccwpck_require__(4322) -const { types } = __nccwpck_require__(9023) -const { StringDecoder } = __nccwpck_require__(3193) -const { btoa } = __nccwpck_require__(181) - -/** @type {PropertyDescriptor} */ -const staticPropertyDescriptors = { - enumerable: true, - writable: false, - configurable: false -} - -/** - * @see https://w3c.github.io/FileAPI/#readOperation - * @param {import('./filereader').FileReader} fr - * @param {import('buffer').Blob} blob - * @param {string} type - * @param {string?} encodingName - */ -function readOperation (fr, blob, type, encodingName) { - // 1. If fr’s state is "loading", throw an InvalidStateError - // DOMException. - if (fr[kState] === 'loading') { - throw new DOMException('Invalid state', 'InvalidStateError') - } - - // 2. Set fr’s state to "loading". - fr[kState] = 'loading' - - // 3. Set fr’s result to null. - fr[kResult] = null - - // 4. Set fr’s error to null. - fr[kError] = null - - // 5. Let stream be the result of calling get stream on blob. - /** @type {import('stream/web').ReadableStream} */ - const stream = blob.stream() - - // 6. Let reader be the result of getting a reader from stream. - const reader = stream.getReader() - - // 7. Let bytes be an empty byte sequence. - /** @type {Uint8Array[]} */ - const bytes = [] - - // 8. Let chunkPromise be the result of reading a chunk from - // stream with reader. - let chunkPromise = reader.read() - - // 9. Let isFirstChunk be true. - let isFirstChunk = true - - // 10. In parallel, while true: - // Note: "In parallel" just means non-blocking - // Note 2: readOperation itself cannot be async as double - // reading the body would then reject the promise, instead - // of throwing an error. - ;(async () => { - while (!fr[kAborted]) { - // 1. Wait for chunkPromise to be fulfilled or rejected. - try { - const { done, value } = await chunkPromise - - // 2. If chunkPromise is fulfilled, and isFirstChunk is - // true, queue a task to fire a progress event called - // loadstart at fr. - if (isFirstChunk && !fr[kAborted]) { - queueMicrotask(() => { - fireAProgressEvent('loadstart', fr) - }) - } - - // 3. Set isFirstChunk to false. - isFirstChunk = false - - // 4. If chunkPromise is fulfilled with an object whose - // done property is false and whose value property is - // a Uint8Array object, run these steps: - if (!done && types.isUint8Array(value)) { - // 1. Let bs be the byte sequence represented by the - // Uint8Array object. - - // 2. Append bs to bytes. - bytes.push(value) - - // 3. If roughly 50ms have passed since these steps - // were last invoked, queue a task to fire a - // progress event called progress at fr. - if ( - ( - fr[kLastProgressEventFired] === undefined || - Date.now() - fr[kLastProgressEventFired] >= 50 - ) && - !fr[kAborted] - ) { - fr[kLastProgressEventFired] = Date.now() - queueMicrotask(() => { - fireAProgressEvent('progress', fr) - }) - } - - // 4. Set chunkPromise to the result of reading a - // chunk from stream with reader. - chunkPromise = reader.read() - } else if (done) { - // 5. Otherwise, if chunkPromise is fulfilled with an - // object whose done property is true, queue a task - // to run the following steps and abort this algorithm: - queueMicrotask(() => { - // 1. Set fr’s state to "done". - fr[kState] = 'done' - - // 2. Let result be the result of package data given - // bytes, type, blob’s type, and encodingName. - try { - const result = packageData(bytes, type, blob.type, encodingName) - - // 4. Else: - - if (fr[kAborted]) { - return - } - - // 1. Set fr’s result to result. - fr[kResult] = result - - // 2. Fire a progress event called load at the fr. - fireAProgressEvent('load', fr) - } catch (error) { - // 3. If package data threw an exception error: - - // 1. Set fr’s error to error. - fr[kError] = error - - // 2. Fire a progress event called error at fr. - fireAProgressEvent('error', fr) - } - - // 5. If fr’s state is not "loading", fire a progress - // event called loadend at the fr. - if (fr[kState] !== 'loading') { - fireAProgressEvent('loadend', fr) - } - }) - - break - } - } catch (error) { - if (fr[kAborted]) { - return - } - - // 6. Otherwise, if chunkPromise is rejected with an - // error error, queue a task to run the following - // steps and abort this algorithm: - queueMicrotask(() => { - // 1. Set fr’s state to "done". - fr[kState] = 'done' - - // 2. Set fr’s error to error. - fr[kError] = error - - // 3. Fire a progress event called error at fr. - fireAProgressEvent('error', fr) - - // 4. If fr’s state is not "loading", fire a progress - // event called loadend at fr. - if (fr[kState] !== 'loading') { - fireAProgressEvent('loadend', fr) - } - }) - - break - } - } - })() -} - -/** - * @see https://w3c.github.io/FileAPI/#fire-a-progress-event - * @see https://dom.spec.whatwg.org/#concept-event-fire - * @param {string} e The name of the event - * @param {import('./filereader').FileReader} reader - */ -function fireAProgressEvent (e, reader) { - // The progress event e does not bubble. e.bubbles must be false - // The progress event e is NOT cancelable. e.cancelable must be false - const event = new ProgressEvent(e, { - bubbles: false, - cancelable: false - }) - - reader.dispatchEvent(event) -} - -/** - * @see https://w3c.github.io/FileAPI/#blob-package-data - * @param {Uint8Array[]} bytes - * @param {string} type - * @param {string?} mimeType - * @param {string?} encodingName - */ -function packageData (bytes, type, mimeType, encodingName) { - // 1. A Blob has an associated package data algorithm, given - // bytes, a type, a optional mimeType, and a optional - // encodingName, which switches on type and runs the - // associated steps: - - switch (type) { - case 'DataURL': { - // 1. Return bytes as a DataURL [RFC2397] subject to - // the considerations below: - // * Use mimeType as part of the Data URL if it is - // available in keeping with the Data URL - // specification [RFC2397]. - // * If mimeType is not available return a Data URL - // without a media-type. [RFC2397]. - - // https://datatracker.ietf.org/doc/html/rfc2397#section-3 - // dataurl := "data:" [ mediatype ] [ ";base64" ] "," data - // mediatype := [ type "/" subtype ] *( ";" parameter ) - // data := *urlchar - // parameter := attribute "=" value - let dataURL = 'data:' - - const parsed = parseMIMEType(mimeType || 'application/octet-stream') - - if (parsed !== 'failure') { - dataURL += serializeAMimeType(parsed) - } - - dataURL += ';base64,' - - const decoder = new StringDecoder('latin1') - - for (const chunk of bytes) { - dataURL += btoa(decoder.write(chunk)) - } - - dataURL += btoa(decoder.end()) - - return dataURL - } - case 'Text': { - // 1. Let encoding be failure - let encoding = 'failure' - - // 2. If the encodingName is present, set encoding to the - // result of getting an encoding from encodingName. - if (encodingName) { - encoding = getEncoding(encodingName) - } - - // 3. If encoding is failure, and mimeType is present: - if (encoding === 'failure' && mimeType) { - // 1. Let type be the result of parse a MIME type - // given mimeType. - const type = parseMIMEType(mimeType) - - // 2. If type is not failure, set encoding to the result - // of getting an encoding from type’s parameters["charset"]. - if (type !== 'failure') { - encoding = getEncoding(type.parameters.get('charset')) - } - } - - // 4. If encoding is failure, then set encoding to UTF-8. - if (encoding === 'failure') { - encoding = 'UTF-8' - } - - // 5. Decode bytes using fallback encoding encoding, and - // return the result. - return decode(bytes, encoding) - } - case 'ArrayBuffer': { - // Return a new ArrayBuffer whose contents are bytes. - const sequence = combineByteSequences(bytes) - - return sequence.buffer - } - case 'BinaryString': { - // Return bytes as a binary string, in which every byte - // is represented by a code unit of equal value [0..255]. - let binaryString = '' - - const decoder = new StringDecoder('latin1') - - for (const chunk of bytes) { - binaryString += decoder.write(chunk) - } - - binaryString += decoder.end() - - return binaryString - } - } -} - -/** - * @see https://encoding.spec.whatwg.org/#decode - * @param {Uint8Array[]} ioQueue - * @param {string} encoding - */ -function decode (ioQueue, encoding) { - const bytes = combineByteSequences(ioQueue) - - // 1. Let BOMEncoding be the result of BOM sniffing ioQueue. - const BOMEncoding = BOMSniffing(bytes) - - let slice = 0 - - // 2. If BOMEncoding is non-null: - if (BOMEncoding !== null) { - // 1. Set encoding to BOMEncoding. - encoding = BOMEncoding - - // 2. Read three bytes from ioQueue, if BOMEncoding is - // UTF-8; otherwise read two bytes. - // (Do nothing with those bytes.) - slice = BOMEncoding === 'UTF-8' ? 3 : 2 - } - - // 3. Process a queue with an instance of encoding’s - // decoder, ioQueue, output, and "replacement". - - // 4. Return output. - - const sliced = bytes.slice(slice) - return new TextDecoder(encoding).decode(sliced) -} - -/** - * @see https://encoding.spec.whatwg.org/#bom-sniff - * @param {Uint8Array} ioQueue - */ -function BOMSniffing (ioQueue) { - // 1. Let BOM be the result of peeking 3 bytes from ioQueue, - // converted to a byte sequence. - const [a, b, c] = ioQueue - - // 2. For each of the rows in the table below, starting with - // the first one and going down, if BOM starts with the - // bytes given in the first column, then return the - // encoding given in the cell in the second column of that - // row. Otherwise, return null. - if (a === 0xEF && b === 0xBB && c === 0xBF) { - return 'UTF-8' - } else if (a === 0xFE && b === 0xFF) { - return 'UTF-16BE' - } else if (a === 0xFF && b === 0xFE) { - return 'UTF-16LE' - } - - return null -} - -/** - * @param {Uint8Array[]} sequences - */ -function combineByteSequences (sequences) { - const size = sequences.reduce((a, b) => { - return a + b.byteLength - }, 0) - - let offset = 0 - - return sequences.reduce((a, b) => { - a.set(b, offset) - offset += b.byteLength - return a - }, new Uint8Array(size)) -} - -module.exports = { - staticPropertyDescriptors, - readOperation, - fireAProgressEvent -} - - -/***/ }), - -/***/ 2581: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// We include a version number for the Dispatcher API. In case of breaking changes, -// this version number must be increased to avoid conflicts. -const globalDispatcher = Symbol.for('undici.globalDispatcher.1') -const { InvalidArgumentError } = __nccwpck_require__(8707) -const Agent = __nccwpck_require__(9965) - -if (getGlobalDispatcher() === undefined) { - setGlobalDispatcher(new Agent()) -} - -function setGlobalDispatcher (agent) { - if (!agent || typeof agent.dispatch !== 'function') { - throw new InvalidArgumentError('Argument agent must implement Agent') - } - Object.defineProperty(globalThis, globalDispatcher, { - value: agent, - writable: true, - enumerable: false, - configurable: false - }) -} - -function getGlobalDispatcher () { - return globalThis[globalDispatcher] -} - -module.exports = { - setGlobalDispatcher, - getGlobalDispatcher -} - - -/***/ }), - -/***/ 8840: -/***/ ((module) => { - - - -module.exports = class DecoratorHandler { - constructor (handler) { - this.handler = handler - } - - onConnect (...args) { - return this.handler.onConnect(...args) - } - - onError (...args) { - return this.handler.onError(...args) - } - - onUpgrade (...args) { - return this.handler.onUpgrade(...args) - } - - onHeaders (...args) { - return this.handler.onHeaders(...args) - } - - onData (...args) { - return this.handler.onData(...args) - } - - onComplete (...args) { - return this.handler.onComplete(...args) - } - - onBodySent (...args) { - return this.handler.onBodySent(...args) - } -} - - -/***/ }), - -/***/ 8299: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const util = __nccwpck_require__(3440) -const { kBodyUsed } = __nccwpck_require__(6443) -const assert = __nccwpck_require__(2613) -const { InvalidArgumentError } = __nccwpck_require__(8707) -const EE = __nccwpck_require__(4434) - -const redirectableStatusCodes = [300, 301, 302, 303, 307, 308] - -const kBody = Symbol('body') - -class BodyAsyncIterable { - constructor (body) { - this[kBody] = body - this[kBodyUsed] = false - } - - async * [Symbol.asyncIterator] () { - assert(!this[kBodyUsed], 'disturbed') - this[kBodyUsed] = true - yield * this[kBody] - } -} - -class RedirectHandler { - constructor (dispatch, maxRedirections, opts, handler) { - if (maxRedirections != null && (!Number.isInteger(maxRedirections) || maxRedirections < 0)) { - throw new InvalidArgumentError('maxRedirections must be a positive number') - } - - util.validateHandler(handler, opts.method, opts.upgrade) - - this.dispatch = dispatch - this.location = null - this.abort = null - this.opts = { ...opts, maxRedirections: 0 } // opts must be a copy - this.maxRedirections = maxRedirections - this.handler = handler - this.history = [] - - if (util.isStream(this.opts.body)) { - // TODO (fix): Provide some way for the user to cache the file to e.g. /tmp - // so that it can be dispatched again? - // TODO (fix): Do we need 100-expect support to provide a way to do this properly? - if (util.bodyLength(this.opts.body) === 0) { - this.opts.body - .on('data', function () { - assert(false) - }) - } - - if (typeof this.opts.body.readableDidRead !== 'boolean') { - this.opts.body[kBodyUsed] = false - EE.prototype.on.call(this.opts.body, 'data', function () { - this[kBodyUsed] = true - }) - } - } else if (this.opts.body && typeof this.opts.body.pipeTo === 'function') { - // TODO (fix): We can't access ReadableStream internal state - // to determine whether or not it has been disturbed. This is just - // a workaround. - this.opts.body = new BodyAsyncIterable(this.opts.body) - } else if ( - this.opts.body && - typeof this.opts.body !== 'string' && - !ArrayBuffer.isView(this.opts.body) && - util.isIterable(this.opts.body) - ) { - // TODO: Should we allow re-using iterable if !this.opts.idempotent - // or through some other flag? - this.opts.body = new BodyAsyncIterable(this.opts.body) - } - } - - onConnect (abort) { - this.abort = abort - this.handler.onConnect(abort, { history: this.history }) - } - - onUpgrade (statusCode, headers, socket) { - this.handler.onUpgrade(statusCode, headers, socket) - } - - onError (error) { - this.handler.onError(error) - } - - onHeaders (statusCode, headers, resume, statusText) { - this.location = this.history.length >= this.maxRedirections || util.isDisturbed(this.opts.body) - ? null - : parseLocation(statusCode, headers) - - if (this.opts.origin) { - this.history.push(new URL(this.opts.path, this.opts.origin)) - } - - if (!this.location) { - return this.handler.onHeaders(statusCode, headers, resume, statusText) - } - - const { origin, pathname, search } = util.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))) - const path = search ? `${pathname}${search}` : pathname - - // Remove headers referring to the original URL. - // By default it is Host only, unless it's a 303 (see below), which removes also all Content-* headers. - // https://tools.ietf.org/html/rfc7231#section-6.4 - this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin) - this.opts.path = path - this.opts.origin = origin - this.opts.maxRedirections = 0 - this.opts.query = null - - // https://tools.ietf.org/html/rfc7231#section-6.4.4 - // In case of HTTP 303, always replace method to be either HEAD or GET - if (statusCode === 303 && this.opts.method !== 'HEAD') { - this.opts.method = 'GET' - this.opts.body = null - } - } - - onData (chunk) { - if (this.location) { - /* - https://tools.ietf.org/html/rfc7231#section-6.4 - - TLDR: undici always ignores 3xx response bodies. - - Redirection is used to serve the requested resource from another URL, so it is assumes that - no body is generated (and thus can be ignored). Even though generating a body is not prohibited. - - For status 301, 302, 303, 307 and 308 (the latter from RFC 7238), the specs mention that the body usually - (which means it's optional and not mandated) contain just an hyperlink to the value of - the Location response header, so the body can be ignored safely. - - For status 300, which is "Multiple Choices", the spec mentions both generating a Location - response header AND a response body with the other possible location to follow. - Since the spec explicitily chooses not to specify a format for such body and leave it to - servers and browsers implementors, we ignore the body as there is no specified way to eventually parse it. - */ - } else { - return this.handler.onData(chunk) - } - } - - onComplete (trailers) { - if (this.location) { - /* - https://tools.ietf.org/html/rfc7231#section-6.4 - - TLDR: undici always ignores 3xx response trailers as they are not expected in case of redirections - and neither are useful if present. - - See comment on onData method above for more detailed informations. - */ - - this.location = null - this.abort = null - - this.dispatch(this.opts, this) - } else { - this.handler.onComplete(trailers) - } - } - - onBodySent (chunk) { - if (this.handler.onBodySent) { - this.handler.onBodySent(chunk) - } - } -} - -function parseLocation (statusCode, headers) { - if (redirectableStatusCodes.indexOf(statusCode) === -1) { - return null - } - - for (let i = 0; i < headers.length; i += 2) { - if (headers[i].toString().toLowerCase() === 'location') { - return headers[i + 1] - } - } -} - -// https://tools.ietf.org/html/rfc7231#section-6.4.4 -function shouldRemoveHeader (header, removeContent, unknownOrigin) { - if (header.length === 4) { - return util.headerNameToString(header) === 'host' - } - if (removeContent && util.headerNameToString(header).startsWith('content-')) { - return true - } - if (unknownOrigin && (header.length === 13 || header.length === 6 || header.length === 19)) { - const name = util.headerNameToString(header) - return name === 'authorization' || name === 'cookie' || name === 'proxy-authorization' - } - return false -} - -// https://tools.ietf.org/html/rfc7231#section-6.4 -function cleanRequestHeaders (headers, removeContent, unknownOrigin) { - const ret = [] - if (Array.isArray(headers)) { - for (let i = 0; i < headers.length; i += 2) { - if (!shouldRemoveHeader(headers[i], removeContent, unknownOrigin)) { - ret.push(headers[i], headers[i + 1]) - } - } - } else if (headers && typeof headers === 'object') { - for (const key of Object.keys(headers)) { - if (!shouldRemoveHeader(key, removeContent, unknownOrigin)) { - ret.push(key, headers[key]) - } - } - } else { - assert(headers == null, 'headers must be an object or an array') - } - return ret -} - -module.exports = RedirectHandler - - -/***/ }), - -/***/ 3573: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const assert = __nccwpck_require__(2613) - -const { kRetryHandlerDefaultRetry } = __nccwpck_require__(6443) -const { RequestRetryError } = __nccwpck_require__(8707) -const { isDisturbed, parseHeaders, parseRangeHeader } = __nccwpck_require__(3440) - -function calculateRetryAfterHeader (retryAfter) { - const current = Date.now() - const diff = new Date(retryAfter).getTime() - current - - return diff -} - -class RetryHandler { - constructor (opts, handlers) { - const { retryOptions, ...dispatchOpts } = opts - const { - // Retry scoped - retry: retryFn, - maxRetries, - maxTimeout, - minTimeout, - timeoutFactor, - // Response scoped - methods, - errorCodes, - retryAfter, - statusCodes - } = retryOptions ?? {} - - this.dispatch = handlers.dispatch - this.handler = handlers.handler - this.opts = dispatchOpts - this.abort = null - this.aborted = false - this.retryOpts = { - retry: retryFn ?? RetryHandler[kRetryHandlerDefaultRetry], - retryAfter: retryAfter ?? true, - maxTimeout: maxTimeout ?? 30 * 1000, // 30s, - timeout: minTimeout ?? 500, // .5s - timeoutFactor: timeoutFactor ?? 2, - maxRetries: maxRetries ?? 5, - // What errors we should retry - methods: methods ?? ['GET', 'HEAD', 'OPTIONS', 'PUT', 'DELETE', 'TRACE'], - // Indicates which errors to retry - statusCodes: statusCodes ?? [500, 502, 503, 504, 429], - // List of errors to retry - errorCodes: errorCodes ?? [ - 'ECONNRESET', - 'ECONNREFUSED', - 'ENOTFOUND', - 'ENETDOWN', - 'ENETUNREACH', - 'EHOSTDOWN', - 'EHOSTUNREACH', - 'EPIPE' - ] - } - - this.retryCount = 0 - this.start = 0 - this.end = null - this.etag = null - this.resume = null - - // Handle possible onConnect duplication - this.handler.onConnect(reason => { - this.aborted = true - if (this.abort) { - this.abort(reason) - } else { - this.reason = reason - } - }) - } - - onRequestSent () { - if (this.handler.onRequestSent) { - this.handler.onRequestSent() - } - } - - onUpgrade (statusCode, headers, socket) { - if (this.handler.onUpgrade) { - this.handler.onUpgrade(statusCode, headers, socket) - } - } - - onConnect (abort) { - if (this.aborted) { - abort(this.reason) - } else { - this.abort = abort - } - } - - onBodySent (chunk) { - if (this.handler.onBodySent) return this.handler.onBodySent(chunk) - } - - static [kRetryHandlerDefaultRetry] (err, { state, opts }, cb) { - const { statusCode, code, headers } = err - const { method, retryOptions } = opts - const { - maxRetries, - timeout, - maxTimeout, - timeoutFactor, - statusCodes, - errorCodes, - methods - } = retryOptions - let { counter, currentTimeout } = state - - currentTimeout = - currentTimeout != null && currentTimeout > 0 ? currentTimeout : timeout - - // Any code that is not a Undici's originated and allowed to retry - if ( - code && - code !== 'UND_ERR_REQ_RETRY' && - code !== 'UND_ERR_SOCKET' && - !errorCodes.includes(code) - ) { - cb(err) - return - } - - // If a set of method are provided and the current method is not in the list - if (Array.isArray(methods) && !methods.includes(method)) { - cb(err) - return - } - - // If a set of status code are provided and the current status code is not in the list - if ( - statusCode != null && - Array.isArray(statusCodes) && - !statusCodes.includes(statusCode) - ) { - cb(err) - return - } - - // If we reached the max number of retries - if (counter > maxRetries) { - cb(err) - return - } - - let retryAfterHeader = headers != null && headers['retry-after'] - if (retryAfterHeader) { - retryAfterHeader = Number(retryAfterHeader) - retryAfterHeader = isNaN(retryAfterHeader) - ? calculateRetryAfterHeader(retryAfterHeader) - : retryAfterHeader * 1e3 // Retry-After is in seconds - } - - const retryTimeout = - retryAfterHeader > 0 - ? Math.min(retryAfterHeader, maxTimeout) - : Math.min(currentTimeout * timeoutFactor ** counter, maxTimeout) - - state.currentTimeout = retryTimeout - - setTimeout(() => cb(null), retryTimeout) - } - - onHeaders (statusCode, rawHeaders, resume, statusMessage) { - const headers = parseHeaders(rawHeaders) - - this.retryCount += 1 - - if (statusCode >= 300) { - this.abort( - new RequestRetryError('Request failed', statusCode, { - headers, - count: this.retryCount - }) - ) - return false - } - - // Checkpoint for resume from where we left it - if (this.resume != null) { - this.resume = null - - if (statusCode !== 206) { - return true - } - - const contentRange = parseRangeHeader(headers['content-range']) - // If no content range - if (!contentRange) { - this.abort( - new RequestRetryError('Content-Range mismatch', statusCode, { - headers, - count: this.retryCount - }) - ) - return false - } - - // Let's start with a weak etag check - if (this.etag != null && this.etag !== headers.etag) { - this.abort( - new RequestRetryError('ETag mismatch', statusCode, { - headers, - count: this.retryCount - }) - ) - return false - } - - const { start, size, end = size } = contentRange - - assert(this.start === start, 'content-range mismatch') - assert(this.end == null || this.end === end, 'content-range mismatch') - - this.resume = resume - return true - } - - if (this.end == null) { - if (statusCode === 206) { - // First time we receive 206 - const range = parseRangeHeader(headers['content-range']) - - if (range == null) { - return this.handler.onHeaders( - statusCode, - rawHeaders, - resume, - statusMessage - ) - } - - const { start, size, end = size } = range - - assert( - start != null && Number.isFinite(start) && this.start !== start, - 'content-range mismatch' - ) - assert(Number.isFinite(start)) - assert( - end != null && Number.isFinite(end) && this.end !== end, - 'invalid content-length' - ) - - this.start = start - this.end = end - } - - // We make our best to checkpoint the body for further range headers - if (this.end == null) { - const contentLength = headers['content-length'] - this.end = contentLength != null ? Number(contentLength) : null - } - - assert(Number.isFinite(this.start)) - assert( - this.end == null || Number.isFinite(this.end), - 'invalid content-length' - ) - - this.resume = resume - this.etag = headers.etag != null ? headers.etag : null - - return this.handler.onHeaders( - statusCode, - rawHeaders, - resume, - statusMessage - ) - } - - const err = new RequestRetryError('Request failed', statusCode, { - headers, - count: this.retryCount - }) - - this.abort(err) - - return false - } - - onData (chunk) { - this.start += chunk.length - - return this.handler.onData(chunk) - } - - onComplete (rawTrailers) { - this.retryCount = 0 - return this.handler.onComplete(rawTrailers) - } - - onError (err) { - if (this.aborted || isDisturbed(this.opts.body)) { - return this.handler.onError(err) - } - - this.retryOpts.retry( - err, - { - state: { counter: this.retryCount++, currentTimeout: this.retryAfter }, - opts: { retryOptions: this.retryOpts, ...this.opts } - }, - onRetry.bind(this) - ) - - function onRetry (err) { - if (err != null || this.aborted || isDisturbed(this.opts.body)) { - return this.handler.onError(err) - } - - if (this.start !== 0) { - this.opts = { - ...this.opts, - headers: { - ...this.opts.headers, - range: `bytes=${this.start}-${this.end ?? ''}` - } - } - } - - try { - this.dispatch(this.opts, this) - } catch (err) { - this.handler.onError(err) - } - } - } -} - -module.exports = RetryHandler - - -/***/ }), - -/***/ 4415: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const RedirectHandler = __nccwpck_require__(8299) - -function createRedirectInterceptor ({ maxRedirections: defaultMaxRedirections }) { - return (dispatch) => { - return function Intercept (opts, handler) { - const { maxRedirections = defaultMaxRedirections } = opts - - if (!maxRedirections) { - return dispatch(opts, handler) - } - - const redirectHandler = new RedirectHandler(dispatch, maxRedirections, opts, handler) - opts = { ...opts, maxRedirections: 0 } // Stop sub dispatcher from also redirecting. - return dispatch(opts, redirectHandler) - } - } -} - -module.exports = createRedirectInterceptor - - -/***/ }), - -/***/ 2824: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.SPECIAL_HEADERS = exports.HEADER_STATE = exports.MINOR = exports.MAJOR = exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS = exports.TOKEN = exports.STRICT_TOKEN = exports.HEX = exports.URL_CHAR = exports.STRICT_URL_CHAR = exports.USERINFO_CHARS = exports.MARK = exports.ALPHANUM = exports.NUM = exports.HEX_MAP = exports.NUM_MAP = exports.ALPHA = exports.FINISH = exports.H_METHOD_MAP = exports.METHOD_MAP = exports.METHODS_RTSP = exports.METHODS_ICE = exports.METHODS_HTTP = exports.METHODS = exports.LENIENT_FLAGS = exports.FLAGS = exports.TYPE = exports.ERROR = void 0; -const utils_1 = __nccwpck_require__(172); -// C headers -var ERROR; -(function (ERROR) { - ERROR[ERROR["OK"] = 0] = "OK"; - ERROR[ERROR["INTERNAL"] = 1] = "INTERNAL"; - ERROR[ERROR["STRICT"] = 2] = "STRICT"; - ERROR[ERROR["LF_EXPECTED"] = 3] = "LF_EXPECTED"; - ERROR[ERROR["UNEXPECTED_CONTENT_LENGTH"] = 4] = "UNEXPECTED_CONTENT_LENGTH"; - ERROR[ERROR["CLOSED_CONNECTION"] = 5] = "CLOSED_CONNECTION"; - ERROR[ERROR["INVALID_METHOD"] = 6] = "INVALID_METHOD"; - ERROR[ERROR["INVALID_URL"] = 7] = "INVALID_URL"; - ERROR[ERROR["INVALID_CONSTANT"] = 8] = "INVALID_CONSTANT"; - ERROR[ERROR["INVALID_VERSION"] = 9] = "INVALID_VERSION"; - ERROR[ERROR["INVALID_HEADER_TOKEN"] = 10] = "INVALID_HEADER_TOKEN"; - ERROR[ERROR["INVALID_CONTENT_LENGTH"] = 11] = "INVALID_CONTENT_LENGTH"; - ERROR[ERROR["INVALID_CHUNK_SIZE"] = 12] = "INVALID_CHUNK_SIZE"; - ERROR[ERROR["INVALID_STATUS"] = 13] = "INVALID_STATUS"; - ERROR[ERROR["INVALID_EOF_STATE"] = 14] = "INVALID_EOF_STATE"; - ERROR[ERROR["INVALID_TRANSFER_ENCODING"] = 15] = "INVALID_TRANSFER_ENCODING"; - ERROR[ERROR["CB_MESSAGE_BEGIN"] = 16] = "CB_MESSAGE_BEGIN"; - ERROR[ERROR["CB_HEADERS_COMPLETE"] = 17] = "CB_HEADERS_COMPLETE"; - ERROR[ERROR["CB_MESSAGE_COMPLETE"] = 18] = "CB_MESSAGE_COMPLETE"; - ERROR[ERROR["CB_CHUNK_HEADER"] = 19] = "CB_CHUNK_HEADER"; - ERROR[ERROR["CB_CHUNK_COMPLETE"] = 20] = "CB_CHUNK_COMPLETE"; - ERROR[ERROR["PAUSED"] = 21] = "PAUSED"; - ERROR[ERROR["PAUSED_UPGRADE"] = 22] = "PAUSED_UPGRADE"; - ERROR[ERROR["PAUSED_H2_UPGRADE"] = 23] = "PAUSED_H2_UPGRADE"; - ERROR[ERROR["USER"] = 24] = "USER"; -})(ERROR = exports.ERROR || (exports.ERROR = {})); -var TYPE; -(function (TYPE) { - TYPE[TYPE["BOTH"] = 0] = "BOTH"; - TYPE[TYPE["REQUEST"] = 1] = "REQUEST"; - TYPE[TYPE["RESPONSE"] = 2] = "RESPONSE"; -})(TYPE = exports.TYPE || (exports.TYPE = {})); -var FLAGS; -(function (FLAGS) { - FLAGS[FLAGS["CONNECTION_KEEP_ALIVE"] = 1] = "CONNECTION_KEEP_ALIVE"; - FLAGS[FLAGS["CONNECTION_CLOSE"] = 2] = "CONNECTION_CLOSE"; - FLAGS[FLAGS["CONNECTION_UPGRADE"] = 4] = "CONNECTION_UPGRADE"; - FLAGS[FLAGS["CHUNKED"] = 8] = "CHUNKED"; - FLAGS[FLAGS["UPGRADE"] = 16] = "UPGRADE"; - FLAGS[FLAGS["CONTENT_LENGTH"] = 32] = "CONTENT_LENGTH"; - FLAGS[FLAGS["SKIPBODY"] = 64] = "SKIPBODY"; - FLAGS[FLAGS["TRAILING"] = 128] = "TRAILING"; - // 1 << 8 is unused - FLAGS[FLAGS["TRANSFER_ENCODING"] = 512] = "TRANSFER_ENCODING"; -})(FLAGS = exports.FLAGS || (exports.FLAGS = {})); -var LENIENT_FLAGS; -(function (LENIENT_FLAGS) { - LENIENT_FLAGS[LENIENT_FLAGS["HEADERS"] = 1] = "HEADERS"; - LENIENT_FLAGS[LENIENT_FLAGS["CHUNKED_LENGTH"] = 2] = "CHUNKED_LENGTH"; - LENIENT_FLAGS[LENIENT_FLAGS["KEEP_ALIVE"] = 4] = "KEEP_ALIVE"; -})(LENIENT_FLAGS = exports.LENIENT_FLAGS || (exports.LENIENT_FLAGS = {})); -var METHODS; -(function (METHODS) { - METHODS[METHODS["DELETE"] = 0] = "DELETE"; - METHODS[METHODS["GET"] = 1] = "GET"; - METHODS[METHODS["HEAD"] = 2] = "HEAD"; - METHODS[METHODS["POST"] = 3] = "POST"; - METHODS[METHODS["PUT"] = 4] = "PUT"; - /* pathological */ - METHODS[METHODS["CONNECT"] = 5] = "CONNECT"; - METHODS[METHODS["OPTIONS"] = 6] = "OPTIONS"; - METHODS[METHODS["TRACE"] = 7] = "TRACE"; - /* WebDAV */ - METHODS[METHODS["COPY"] = 8] = "COPY"; - METHODS[METHODS["LOCK"] = 9] = "LOCK"; - METHODS[METHODS["MKCOL"] = 10] = "MKCOL"; - METHODS[METHODS["MOVE"] = 11] = "MOVE"; - METHODS[METHODS["PROPFIND"] = 12] = "PROPFIND"; - METHODS[METHODS["PROPPATCH"] = 13] = "PROPPATCH"; - METHODS[METHODS["SEARCH"] = 14] = "SEARCH"; - METHODS[METHODS["UNLOCK"] = 15] = "UNLOCK"; - METHODS[METHODS["BIND"] = 16] = "BIND"; - METHODS[METHODS["REBIND"] = 17] = "REBIND"; - METHODS[METHODS["UNBIND"] = 18] = "UNBIND"; - METHODS[METHODS["ACL"] = 19] = "ACL"; - /* subversion */ - METHODS[METHODS["REPORT"] = 20] = "REPORT"; - METHODS[METHODS["MKACTIVITY"] = 21] = "MKACTIVITY"; - METHODS[METHODS["CHECKOUT"] = 22] = "CHECKOUT"; - METHODS[METHODS["MERGE"] = 23] = "MERGE"; - /* upnp */ - METHODS[METHODS["M-SEARCH"] = 24] = "M-SEARCH"; - METHODS[METHODS["NOTIFY"] = 25] = "NOTIFY"; - METHODS[METHODS["SUBSCRIBE"] = 26] = "SUBSCRIBE"; - METHODS[METHODS["UNSUBSCRIBE"] = 27] = "UNSUBSCRIBE"; - /* RFC-5789 */ - METHODS[METHODS["PATCH"] = 28] = "PATCH"; - METHODS[METHODS["PURGE"] = 29] = "PURGE"; - /* CalDAV */ - METHODS[METHODS["MKCALENDAR"] = 30] = "MKCALENDAR"; - /* RFC-2068, section 19.6.1.2 */ - METHODS[METHODS["LINK"] = 31] = "LINK"; - METHODS[METHODS["UNLINK"] = 32] = "UNLINK"; - /* icecast */ - METHODS[METHODS["SOURCE"] = 33] = "SOURCE"; - /* RFC-7540, section 11.6 */ - METHODS[METHODS["PRI"] = 34] = "PRI"; - /* RFC-2326 RTSP */ - METHODS[METHODS["DESCRIBE"] = 35] = "DESCRIBE"; - METHODS[METHODS["ANNOUNCE"] = 36] = "ANNOUNCE"; - METHODS[METHODS["SETUP"] = 37] = "SETUP"; - METHODS[METHODS["PLAY"] = 38] = "PLAY"; - METHODS[METHODS["PAUSE"] = 39] = "PAUSE"; - METHODS[METHODS["TEARDOWN"] = 40] = "TEARDOWN"; - METHODS[METHODS["GET_PARAMETER"] = 41] = "GET_PARAMETER"; - METHODS[METHODS["SET_PARAMETER"] = 42] = "SET_PARAMETER"; - METHODS[METHODS["REDIRECT"] = 43] = "REDIRECT"; - METHODS[METHODS["RECORD"] = 44] = "RECORD"; - /* RAOP */ - METHODS[METHODS["FLUSH"] = 45] = "FLUSH"; -})(METHODS = exports.METHODS || (exports.METHODS = {})); -exports.METHODS_HTTP = [ - METHODS.DELETE, - METHODS.GET, - METHODS.HEAD, - METHODS.POST, - METHODS.PUT, - METHODS.CONNECT, - METHODS.OPTIONS, - METHODS.TRACE, - METHODS.COPY, - METHODS.LOCK, - METHODS.MKCOL, - METHODS.MOVE, - METHODS.PROPFIND, - METHODS.PROPPATCH, - METHODS.SEARCH, - METHODS.UNLOCK, - METHODS.BIND, - METHODS.REBIND, - METHODS.UNBIND, - METHODS.ACL, - METHODS.REPORT, - METHODS.MKACTIVITY, - METHODS.CHECKOUT, - METHODS.MERGE, - METHODS['M-SEARCH'], - METHODS.NOTIFY, - METHODS.SUBSCRIBE, - METHODS.UNSUBSCRIBE, - METHODS.PATCH, - METHODS.PURGE, - METHODS.MKCALENDAR, - METHODS.LINK, - METHODS.UNLINK, - METHODS.PRI, - // TODO(indutny): should we allow it with HTTP? - METHODS.SOURCE, -]; -exports.METHODS_ICE = [ - METHODS.SOURCE, -]; -exports.METHODS_RTSP = [ - METHODS.OPTIONS, - METHODS.DESCRIBE, - METHODS.ANNOUNCE, - METHODS.SETUP, - METHODS.PLAY, - METHODS.PAUSE, - METHODS.TEARDOWN, - METHODS.GET_PARAMETER, - METHODS.SET_PARAMETER, - METHODS.REDIRECT, - METHODS.RECORD, - METHODS.FLUSH, - // For AirPlay - METHODS.GET, - METHODS.POST, -]; -exports.METHOD_MAP = utils_1.enumToMap(METHODS); -exports.H_METHOD_MAP = {}; -Object.keys(exports.METHOD_MAP).forEach((key) => { - if (/^H/.test(key)) { - exports.H_METHOD_MAP[key] = exports.METHOD_MAP[key]; - } -}); -var FINISH; -(function (FINISH) { - FINISH[FINISH["SAFE"] = 0] = "SAFE"; - FINISH[FINISH["SAFE_WITH_CB"] = 1] = "SAFE_WITH_CB"; - FINISH[FINISH["UNSAFE"] = 2] = "UNSAFE"; -})(FINISH = exports.FINISH || (exports.FINISH = {})); -exports.ALPHA = []; -for (let i = 'A'.charCodeAt(0); i <= 'Z'.charCodeAt(0); i++) { - // Upper case - exports.ALPHA.push(String.fromCharCode(i)); - // Lower case - exports.ALPHA.push(String.fromCharCode(i + 0x20)); -} -exports.NUM_MAP = { - 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, - 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, -}; -exports.HEX_MAP = { - 0: 0, 1: 1, 2: 2, 3: 3, 4: 4, - 5: 5, 6: 6, 7: 7, 8: 8, 9: 9, - A: 0XA, B: 0XB, C: 0XC, D: 0XD, E: 0XE, F: 0XF, - a: 0xa, b: 0xb, c: 0xc, d: 0xd, e: 0xe, f: 0xf, -}; -exports.NUM = [ - '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', -]; -exports.ALPHANUM = exports.ALPHA.concat(exports.NUM); -exports.MARK = ['-', '_', '.', '!', '~', '*', '\'', '(', ')']; -exports.USERINFO_CHARS = exports.ALPHANUM - .concat(exports.MARK) - .concat(['%', ';', ':', '&', '=', '+', '$', ',']); -// TODO(indutny): use RFC -exports.STRICT_URL_CHAR = [ - '!', '"', '$', '%', '&', '\'', - '(', ')', '*', '+', ',', '-', '.', '/', - ':', ';', '<', '=', '>', - '@', '[', '\\', ']', '^', '_', - '`', - '{', '|', '}', '~', -].concat(exports.ALPHANUM); -exports.URL_CHAR = exports.STRICT_URL_CHAR - .concat(['\t', '\f']); -// All characters with 0x80 bit set to 1 -for (let i = 0x80; i <= 0xff; i++) { - exports.URL_CHAR.push(i); -} -exports.HEX = exports.NUM.concat(['a', 'b', 'c', 'd', 'e', 'f', 'A', 'B', 'C', 'D', 'E', 'F']); -/* Tokens as defined by rfc 2616. Also lowercases them. - * token = 1* - * separators = "(" | ")" | "<" | ">" | "@" - * | "," | ";" | ":" | "\" | <"> - * | "/" | "[" | "]" | "?" | "=" - * | "{" | "}" | SP | HT - */ -exports.STRICT_TOKEN = [ - '!', '#', '$', '%', '&', '\'', - '*', '+', '-', '.', - '^', '_', '`', - '|', '~', -].concat(exports.ALPHANUM); -exports.TOKEN = exports.STRICT_TOKEN.concat([' ']); -/* - * Verify that a char is a valid visible (printable) US-ASCII - * character or %x80-FF - */ -exports.HEADER_CHARS = ['\t']; -for (let i = 32; i <= 255; i++) { - if (i !== 127) { - exports.HEADER_CHARS.push(i); - } -} -// ',' = \x44 -exports.CONNECTION_TOKEN_CHARS = exports.HEADER_CHARS.filter((c) => c !== 44); -exports.MAJOR = exports.NUM_MAP; -exports.MINOR = exports.MAJOR; -var HEADER_STATE; -(function (HEADER_STATE) { - HEADER_STATE[HEADER_STATE["GENERAL"] = 0] = "GENERAL"; - HEADER_STATE[HEADER_STATE["CONNECTION"] = 1] = "CONNECTION"; - HEADER_STATE[HEADER_STATE["CONTENT_LENGTH"] = 2] = "CONTENT_LENGTH"; - HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING"] = 3] = "TRANSFER_ENCODING"; - HEADER_STATE[HEADER_STATE["UPGRADE"] = 4] = "UPGRADE"; - HEADER_STATE[HEADER_STATE["CONNECTION_KEEP_ALIVE"] = 5] = "CONNECTION_KEEP_ALIVE"; - HEADER_STATE[HEADER_STATE["CONNECTION_CLOSE"] = 6] = "CONNECTION_CLOSE"; - HEADER_STATE[HEADER_STATE["CONNECTION_UPGRADE"] = 7] = "CONNECTION_UPGRADE"; - HEADER_STATE[HEADER_STATE["TRANSFER_ENCODING_CHUNKED"] = 8] = "TRANSFER_ENCODING_CHUNKED"; -})(HEADER_STATE = exports.HEADER_STATE || (exports.HEADER_STATE = {})); -exports.SPECIAL_HEADERS = { - 'connection': HEADER_STATE.CONNECTION, - 'content-length': HEADER_STATE.CONTENT_LENGTH, - 'proxy-connection': HEADER_STATE.CONNECTION, - 'transfer-encoding': HEADER_STATE.TRANSFER_ENCODING, - 'upgrade': HEADER_STATE.UPGRADE, -}; -//# sourceMappingURL=constants.js.map - -/***/ }), - -/***/ 3870: -/***/ ((module) => { - -module.exports = 'AGFzbQEAAAABMAhgAX8Bf2ADf39/AX9gBH9/f38Bf2AAAGADf39/AGABfwBgAn9/AGAGf39/f39/AALLAQgDZW52GHdhc21fb25faGVhZGVyc19jb21wbGV0ZQACA2VudhV3YXNtX29uX21lc3NhZ2VfYmVnaW4AAANlbnYLd2FzbV9vbl91cmwAAQNlbnYOd2FzbV9vbl9zdGF0dXMAAQNlbnYUd2FzbV9vbl9oZWFkZXJfZmllbGQAAQNlbnYUd2FzbV9vbl9oZWFkZXJfdmFsdWUAAQNlbnYMd2FzbV9vbl9ib2R5AAEDZW52GHdhc21fb25fbWVzc2FnZV9jb21wbGV0ZQAAA0ZFAwMEAAAFAAAAAAAABQEFAAUFBQAABgAAAAAGBgYGAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQABAAABAQcAAAUFAwABBAUBcAESEgUDAQACBggBfwFBgNQECwfRBSIGbWVtb3J5AgALX2luaXRpYWxpemUACRlfX2luZGlyZWN0X2Z1bmN0aW9uX3RhYmxlAQALbGxodHRwX2luaXQAChhsbGh0dHBfc2hvdWxkX2tlZXBfYWxpdmUAQQxsbGh0dHBfYWxsb2MADAZtYW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ARyEBCyABC1kAIABBGGpCADcDACAAQgA3AwAgAEE4akIANwMAIABBMGpCADcDACAAQShqQgA3AwAgAEEgakIANwMAIABBEGpCADcDACAAQQhqQgA3AwAgAEHdATYCHEEAC3sBAX8CQCAAKAIMIgMNAAJAIAAoAgRFDQAgACABNgIECwJAIAAgASACEMSAgIAAIgMNACAAKAIMDwsgACADNgIcQQAhAyAAKAIEIgFFDQAgACABIAIgACgCCBGBgICAAAAiAUUNACAAIAI2AhQgACABNgIMIAEhAwsgAwvk8wEDDn8DfgR/I4CAgIAAQRBrIgMkgICAgAAgASEEIAEhBSABIQYgASEHIAEhCCABIQkgASEKIAEhCyABIQwgASENIAEhDiABIQ8CQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgACgCHCIQQX9qDt0B2gEB2QECAwQFBgcICQoLDA0O2AEPENcBERLWARMUFRYXGBkaG+AB3wEcHR7VAR8gISIjJCXUASYnKCkqKyzTAdIBLS7RAdABLzAxMjM0NTY3ODk6Ozw9Pj9AQUJDREVG2wFHSEl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QaoBIRAMGgtBqwEhEAwZC0GsASEQDBgLQa0BIRAMFwtBrgEhEAwWC0EBIRAMFQtBrwEhEAwUC0GwASEQDBMLQbEBIRAMEgtBswEhEAwRC0GyASEQDBALQbQBIRAMDwtBtQEhEAwOC0G2ASEQDA0LQbcBIRAMDAtBuAEhEAwLC0G5ASEQDAoLQboBIRAMCQtBuwEhEAwIC0HGASEQDAcLQbwBIRAMBgtBvQEhEAwFC0G+ASEQDAQLQb8BIRAMAwtBwAEhEAwCC0HCASEQDAELQcEBIRALA0ACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJA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EQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMTQsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAysAQsgAEEANgIcIAAgATYCFCAAQdyIgIAANgIQIABBBzYCDEEAIRAMqwELIBBBP0cNASABQQFqIQELQQUhEAyQAQtBACEQIABBADYCHCAAIAE2AhQgAEH9koCAADYCECAAQQc2AgwMqAELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMpwELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEILIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMpgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDEYLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMpQELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0gA2AhwgACAUNgIUIAAgATYCDEEAIRAMpAELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDD8LIABB0wA2AhwgACAUNgIUIAAgATYCDEEAIRAMowELIAAoAgQhASAAQQA2AgQCQCAAIAEgFBCngICAACIBDQAgFCEBDEMLIABB5QA2AhwgACAUNgIUIAAgATYCDEEAIRAMogELIABBADYCHCAAIBQ2AhQgAEHDj4CAADYCECAAQQc2AgxBACEQDKEBCyAAQQA2AhwgACABNgIUIABBw4+AgAA2AhAgAEEHNgIMQQAhEAygAQtBACEQIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgwMnwELIABBADYCHCAAIBQ2AhQgAEGMnICAADYCECAAQQc2AgxBACEQDJ4BCyAAQQA2AhwgACAUNgIUIABB/pGAgAA2AhAgAEEHNgIMQQAhEAydAQsgAEEANgIcIAAgATYCFCAAQY6bgIAANgIQIABBBjYCDEEAIRAMnAELIBBBFUYNVyAAQQA2AhwgACABNgIUIABBzI6AgAA2Ah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JAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIBAOxwEAAQIDBA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AoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFQLIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMswELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0gA2AhwgACABNgIUIAAgEDYCDEEAIRAMsgELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDE0LIABB0wA2AhwgACABNgIUIAAgEDYCDEEAIRAMsQELIAAoAgQhECAAQQA2AgQCQCAAIBAgARCngICAACIQDQAgASEBDFELIABB5QA2AhwgACABNgIUIAAgEDYCDEEAIRAMsAELIABBADYCHCAAIAE2AhQgAEHGioCAADYCECAAQQc2AgxBACEQDK8BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdIANgIcIAAgATYCFCAAIBA2AgxBACEQDK4BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxJCyAAQdMANgIcIAAgATYCFCAAIBA2AgxBACEQDK0BCyAAKAIEIRAgAEEANgIEAkAgACAQIAEQp4CAgAAiEA0AIAEhAQxNCyAAQeUANgIcIAAgATYCFCAAIBA2AgxBACEQDKwBCyAAQQA2AhwgACABNgIUIABB3IiAgAA2AhAgAEEHNgIMQQAhEAyrAQsgEEE/Rw0BIAFBAWohAQtBBSEQDJABC0EAIRAgAEEANgIcIAAgATYCFCAAQf2SgIAANgIQIABBBzYCDAyoAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHSADYCHCAAIAE2AhQgACAQNgIMQQAhEAynAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMQgsgAEHTADYCHCAAIAE2AhQgACAQNgIMQQAhEAymAQsgACgCBCEQIABBADYCBAJAIAAgECABEKeAgIAAIhANACABIQEMRgsgAEHlADYCHCAAIAE2AhQgACAQNgIMQQAhEAylAQsgACgCBCEBIABBADYCBAJAI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AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAEAAAEAAAAAAAAAAAAAAAAAAAAAAAABAAAAAAAAAAAAAgAAAAACAAAAAAAAAAAAAAAAAAAAAAADAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwAAAAAAAAMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAE5PVU5DRUVDS09VVE5FQ1RFVEVDUklCRUxVU0hFVEVBRFNFQVJDSFJHRUNUSVZJVFlMRU5EQVJWRU9USUZZUFRJT05TQ0hTRUFZU1RBVENIR0VPUkRJUkVDVE9SVFJDSFBBUkFNRVRFUlVSQ0VCU0NSSUJFQVJET1dOQUNFSU5ETktDS1VCU0NSSUJFSFRUUC9BRFRQLw==' - - -/***/ }), - -/***/ 172: -/***/ ((__unused_webpack_module, exports) => { - - -Object.defineProperty(exports, "__esModule", ({ value: true })); -exports.enumToMap = void 0; -function enumToMap(obj) { - const res = {}; - Object.keys(obj).forEach((key) => { - const value = obj[key]; - if (typeof value === 'number') { - res[key] = value; - } - }); - return res; -} -exports.enumToMap = enumToMap; -//# sourceMappingURL=utils.js.map - -/***/ }), - -/***/ 7501: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { kClients } = __nccwpck_require__(6443) -const Agent = __nccwpck_require__(9965) -const { - kAgent, - kMockAgentSet, - kMockAgentGet, - kDispatches, - kIsMockActive, - kNetConnect, - kGetNetConnect, - kOptions, - kFactory -} = __nccwpck_require__(1117) -const MockClient = __nccwpck_require__(7365) -const MockPool = __nccwpck_require__(4004) -const { matchValue, buildMockOptions } = __nccwpck_require__(3397) -const { InvalidArgumentError, UndiciError } = __nccwpck_require__(8707) -const Dispatcher = __nccwpck_require__(992) -const Pluralizer = __nccwpck_require__(1529) -const PendingInterceptorsFormatter = __nccwpck_require__(6142) - -class FakeWeakRef { - constructor (value) { - this.value = value - } - - deref () { - return this.value - } -} - -class MockAgent extends Dispatcher { - constructor (opts) { - super(opts) - - this[kNetConnect] = true - this[kIsMockActive] = true - - // Instantiate Agent and encapsulate - if ((opts && opts.agent && typeof opts.agent.dispatch !== 'function')) { - throw new InvalidArgumentError('Argument opts.agent must implement Agent') - } - const agent = opts && opts.agent ? opts.agent : new Agent(opts) - this[kAgent] = agent - - this[kClients] = agent[kClients] - this[kOptions] = buildMockOptions(opts) - } - - get (origin) { - let dispatcher = this[kMockAgentGet](origin) - - if (!dispatcher) { - dispatcher = this[kFactory](origin) - this[kMockAgentSet](origin, dispatcher) - } - return dispatcher - } - - dispatch (opts, handler) { - // Call MockAgent.get to perform additional setup before dispatching as normal - this.get(opts.origin) - return this[kAgent].dispatch(opts, handler) - } - - async close () { - await this[kAgent].close() - this[kClients].clear() - } - - deactivate () { - this[kIsMockActive] = false - } - - activate () { - this[kIsMockActive] = true - } - - enableNetConnect (matcher) { - if (typeof matcher === 'string' || typeof matcher === 'function' || matcher instanceof RegExp) { - if (Array.isArray(this[kNetConnect])) { - this[kNetConnect].push(matcher) - } else { - this[kNetConnect] = [matcher] - } - } else if (typeof matcher === 'undefined') { - this[kNetConnect] = true - } else { - throw new InvalidArgumentError('Unsupported matcher. Must be one of String|Function|RegExp.') - } - } - - disableNetConnect () { - this[kNetConnect] = false - } - - // This is required to bypass issues caused by using global symbols - see: - // https://github.com/nodejs/undici/issues/1447 - get isMockActive () { - return this[kIsMockActive] - } - - [kMockAgentSet] (origin, dispatcher) { - this[kClients].set(origin, new FakeWeakRef(dispatcher)) - } - - [kFactory] (origin) { - const mockOptions = Object.assign({ agent: this }, this[kOptions]) - return this[kOptions] && this[kOptions].connections === 1 - ? new MockClient(origin, mockOptions) - : new MockPool(origin, mockOptions) - } - - [kMockAgentGet] (origin) { - // First check if we can immediately find it - const ref = this[kClients].get(origin) - if (ref) { - return ref.deref() - } - - // If the origin is not a string create a dummy parent pool and return to user - if (typeof origin !== 'string') { - const dispatcher = this[kFactory]('http://localhost:9999') - this[kMockAgentSet](origin, dispatcher) - return dispatcher - } - - // If we match, create a pool and assign the same dispatches - for (const [keyMatcher, nonExplicitRef] of Array.from(this[kClients])) { - const nonExplicitDispatcher = nonExplicitRef.deref() - if (nonExplicitDispatcher && typeof keyMatcher !== 'string' && matchValue(keyMatcher, origin)) { - const dispatcher = this[kFactory](origin) - this[kMockAgentSet](origin, dispatcher) - dispatcher[kDispatches] = nonExplicitDispatcher[kDispatches] - return dispatcher - } - } - } - - [kGetNetConnect] () { - return this[kNetConnect] - } - - pendingInterceptors () { - const mockAgentClients = this[kClients] - - return Array.from(mockAgentClients.entries()) - .flatMap(([origin, scope]) => scope.deref()[kDispatches].map(dispatch => ({ ...dispatch, origin }))) - .filter(({ pending }) => pending) - } - - assertNoPendingInterceptors ({ pendingInterceptorsFormatter = new PendingInterceptorsFormatter() } = {}) { - const pending = this.pendingInterceptors() - - if (pending.length === 0) { - return - } - - const pluralizer = new Pluralizer('interceptor', 'interceptors').pluralize(pending.length) - - throw new UndiciError(` -${pluralizer.count} ${pluralizer.noun} ${pluralizer.is} pending: - -${pendingInterceptorsFormatter.format(pending)} -`.trim()) - } -} - -module.exports = MockAgent - - -/***/ }), - -/***/ 7365: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { promisify } = __nccwpck_require__(9023) -const Client = __nccwpck_require__(6197) -const { buildMockDispatch } = __nccwpck_require__(3397) -const { - kDispatches, - kMockAgent, - kClose, - kOriginalClose, - kOrigin, - kOriginalDispatch, - kConnected -} = __nccwpck_require__(1117) -const { MockInterceptor } = __nccwpck_require__(1511) -const Symbols = __nccwpck_require__(6443) -const { InvalidArgumentError } = __nccwpck_require__(8707) - -/** - * MockClient provides an API that extends the Client to influence the mockDispatches. - */ -class MockClient extends Client { - constructor (origin, opts) { - super(origin, opts) - - if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { - throw new InvalidArgumentError('Argument opts.agent must implement Agent') - } - - this[kMockAgent] = opts.agent - this[kOrigin] = origin - this[kDispatches] = [] - this[kConnected] = 1 - this[kOriginalDispatch] = this.dispatch - this[kOriginalClose] = this.close.bind(this) - - this.dispatch = buildMockDispatch.call(this) - this.close = this[kClose] - } - - get [Symbols.kConnected] () { - return this[kConnected] - } - - /** - * Sets up the base interceptor for mocking replies from undici. - */ - intercept (opts) { - return new MockInterceptor(opts, this[kDispatches]) - } - - async [kClose] () { - await promisify(this[kOriginalClose])() - this[kConnected] = 0 - this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) - } -} - -module.exports = MockClient - - -/***/ }), - -/***/ 2429: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { UndiciError } = __nccwpck_require__(8707) - -class MockNotMatchedError extends UndiciError { - constructor (message) { - super(message) - Error.captureStackTrace(this, MockNotMatchedError) - this.name = 'MockNotMatchedError' - this.message = message || 'The request does not match any registered mock dispatches' - this.code = 'UND_MOCK_ERR_MOCK_NOT_MATCHED' - } -} - -module.exports = { - MockNotMatchedError -} - - -/***/ }), - -/***/ 1511: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { getResponseData, buildKey, addMockDispatch } = __nccwpck_require__(3397) -const { - kDispatches, - kDispatchKey, - kDefaultHeaders, - kDefaultTrailers, - kContentLength, - kMockDispatch -} = __nccwpck_require__(1117) -const { InvalidArgumentError } = __nccwpck_require__(8707) -const { buildURL } = __nccwpck_require__(3440) - -/** - * Defines the scope API for an interceptor reply - */ -class MockScope { - constructor (mockDispatch) { - this[kMockDispatch] = mockDispatch - } - - /** - * Delay a reply by a set amount in ms. - */ - delay (waitInMs) { - if (typeof waitInMs !== 'number' || !Number.isInteger(waitInMs) || waitInMs <= 0) { - throw new InvalidArgumentError('waitInMs must be a valid integer > 0') - } - - this[kMockDispatch].delay = waitInMs - return this - } - - /** - * For a defined reply, never mark as consumed. - */ - persist () { - this[kMockDispatch].persist = true - return this - } - - /** - * Allow one to define a reply for a set amount of matching requests. - */ - times (repeatTimes) { - if (typeof repeatTimes !== 'number' || !Number.isInteger(repeatTimes) || repeatTimes <= 0) { - throw new InvalidArgumentError('repeatTimes must be a valid integer > 0') - } - - this[kMockDispatch].times = repeatTimes - return this - } -} - -/** - * Defines an interceptor for a Mock - */ -class MockInterceptor { - constructor (opts, mockDispatches) { - if (typeof opts !== 'object') { - throw new InvalidArgumentError('opts must be an object') - } - if (typeof opts.path === 'undefined') { - throw new InvalidArgumentError('opts.path must be defined') - } - if (typeof opts.method === 'undefined') { - opts.method = 'GET' - } - // See https://github.com/nodejs/undici/issues/1245 - // As per RFC 3986, clients are not supposed to send URI - // fragments to servers when they retrieve a document, - if (typeof opts.path === 'string') { - if (opts.query) { - opts.path = buildURL(opts.path, opts.query) - } else { - // Matches https://github.com/nodejs/undici/blob/main/lib/fetch/index.js#L1811 - const parsedURL = new URL(opts.path, 'data://') - opts.path = parsedURL.pathname + parsedURL.search - } - } - if (typeof opts.method === 'string') { - opts.method = opts.method.toUpperCase() - } - - this[kDispatchKey] = buildKey(opts) - this[kDispatches] = mockDispatches - this[kDefaultHeaders] = {} - this[kDefaultTrailers] = {} - this[kContentLength] = false - } - - createMockScopeDispatchData (statusCode, data, responseOptions = {}) { - const responseData = getResponseData(data) - const contentLength = this[kContentLength] ? { 'content-length': responseData.length } : {} - const headers = { ...this[kDefaultHeaders], ...contentLength, ...responseOptions.headers } - const trailers = { ...this[kDefaultTrailers], ...responseOptions.trailers } - - return { statusCode, data, headers, trailers } - } - - validateReplyParameters (statusCode, data, responseOptions) { - if (typeof statusCode === 'undefined') { - throw new InvalidArgumentError('statusCode must be defined') - } - if (typeof data === 'undefined') { - throw new InvalidArgumentError('data must be defined') - } - if (typeof responseOptions !== 'object') { - throw new InvalidArgumentError('responseOptions must be an object') - } - } - - /** - * Mock an undici request with a defined reply. - */ - reply (replyData) { - // Values of reply aren't available right now as they - // can only be available when the reply callback is invoked. - if (typeof replyData === 'function') { - // We'll first wrap the provided callback in another function, - // this function will properly resolve the data from the callback - // when invoked. - const wrappedDefaultsCallback = (opts) => { - // Our reply options callback contains the parameter for statusCode, data and options. - const resolvedData = replyData(opts) - - // Check if it is in the right format - if (typeof resolvedData !== 'object') { - throw new InvalidArgumentError('reply options callback must return an object') - } - - const { statusCode, data = '', responseOptions = {} } = resolvedData - this.validateReplyParameters(statusCode, data, responseOptions) - // Since the values can be obtained immediately we return them - // from this higher order function that will be resolved later. - return { - ...this.createMockScopeDispatchData(statusCode, data, responseOptions) - } - } - - // Add usual dispatch data, but this time set the data parameter to function that will eventually provide data. - const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], wrappedDefaultsCallback) - return new MockScope(newMockDispatch) - } - - // We can have either one or three parameters, if we get here, - // we should have 1-3 parameters. So we spread the arguments of - // this function to obtain the parameters, since replyData will always - // just be the statusCode. - const [statusCode, data = '', responseOptions = {}] = [...arguments] - this.validateReplyParameters(statusCode, data, responseOptions) - - // Send in-already provided data like usual - const dispatchData = this.createMockScopeDispatchData(statusCode, data, responseOptions) - const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], dispatchData) - return new MockScope(newMockDispatch) - } - - /** - * Mock an undici request with a defined error. - */ - replyWithError (error) { - if (typeof error === 'undefined') { - throw new InvalidArgumentError('error must be defined') - } - - const newMockDispatch = addMockDispatch(this[kDispatches], this[kDispatchKey], { error }) - return new MockScope(newMockDispatch) - } - - /** - * Set default reply headers on the interceptor for subsequent replies - */ - defaultReplyHeaders (headers) { - if (typeof headers === 'undefined') { - throw new InvalidArgumentError('headers must be defined') - } - - this[kDefaultHeaders] = headers - return this - } - - /** - * Set default reply trailers on the interceptor for subsequent replies - */ - defaultReplyTrailers (trailers) { - if (typeof trailers === 'undefined') { - throw new InvalidArgumentError('trailers must be defined') - } - - this[kDefaultTrailers] = trailers - return this - } - - /** - * Set reply content length header for replies on the interceptor - */ - replyContentLength () { - this[kContentLength] = true - return this - } -} - -module.exports.MockInterceptor = MockInterceptor -module.exports.MockScope = MockScope - - -/***/ }), - -/***/ 4004: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { promisify } = __nccwpck_require__(9023) -const Pool = __nccwpck_require__(5076) -const { buildMockDispatch } = __nccwpck_require__(3397) -const { - kDispatches, - kMockAgent, - kClose, - kOriginalClose, - kOrigin, - kOriginalDispatch, - kConnected -} = __nccwpck_require__(1117) -const { MockInterceptor } = __nccwpck_require__(1511) -const Symbols = __nccwpck_require__(6443) -const { InvalidArgumentError } = __nccwpck_require__(8707) - -/** - * MockPool provides an API that extends the Pool to influence the mockDispatches. - */ -class MockPool extends Pool { - constructor (origin, opts) { - super(origin, opts) - - if (!opts || !opts.agent || typeof opts.agent.dispatch !== 'function') { - throw new InvalidArgumentError('Argument opts.agent must implement Agent') - } - - this[kMockAgent] = opts.agent - this[kOrigin] = origin - this[kDispatches] = [] - this[kConnected] = 1 - this[kOriginalDispatch] = this.dispatch - this[kOriginalClose] = this.close.bind(this) - - this.dispatch = buildMockDispatch.call(this) - this.close = this[kClose] - } - - get [Symbols.kConnected] () { - return this[kConnected] - } - - /** - * Sets up the base interceptor for mocking replies from undici. - */ - intercept (opts) { - return new MockInterceptor(opts, this[kDispatches]) - } - - async [kClose] () { - await promisify(this[kOriginalClose])() - this[kConnected] = 0 - this[kMockAgent][Symbols.kClients].delete(this[kOrigin]) - } -} - -module.exports = MockPool - - -/***/ }), - -/***/ 1117: -/***/ ((module) => { - - - -module.exports = { - kAgent: Symbol('agent'), - kOptions: Symbol('options'), - kFactory: Symbol('factory'), - kDispatches: Symbol('dispatches'), - kDispatchKey: Symbol('dispatch key'), - kDefaultHeaders: Symbol('default headers'), - kDefaultTrailers: Symbol('default trailers'), - kContentLength: Symbol('content length'), - kMockAgent: Symbol('mock agent'), - kMockAgentSet: Symbol('mock agent set'), - kMockAgentGet: Symbol('mock agent get'), - kMockDispatch: Symbol('mock dispatch'), - kClose: Symbol('close'), - kOriginalClose: Symbol('original agent close'), - kOrigin: Symbol('origin'), - kIsMockActive: Symbol('is mock active'), - kNetConnect: Symbol('net connect'), - kGetNetConnect: Symbol('get net connect'), - kConnected: Symbol('connected') -} - - -/***/ }), - -/***/ 3397: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { MockNotMatchedError } = __nccwpck_require__(2429) -const { - kDispatches, - kMockAgent, - kOriginalDispatch, - kOrigin, - kGetNetConnect -} = __nccwpck_require__(1117) -const { buildURL, nop } = __nccwpck_require__(3440) -const { STATUS_CODES } = __nccwpck_require__(8611) -const { - types: { - isPromise - } -} = __nccwpck_require__(9023) - -function matchValue (match, value) { - if (typeof match === 'string') { - return match === value - } - if (match instanceof RegExp) { - return match.test(value) - } - if (typeof match === 'function') { - return match(value) === true - } - return false -} - -function lowerCaseEntries (headers) { - return Object.fromEntries( - Object.entries(headers).map(([headerName, headerValue]) => { - return [headerName.toLocaleLowerCase(), headerValue] - }) - ) -} - -/** - * @param {import('../../index').Headers|string[]|Record} headers - * @param {string} key - */ -function getHeaderByName (headers, key) { - if (Array.isArray(headers)) { - for (let i = 0; i < headers.length; i += 2) { - if (headers[i].toLocaleLowerCase() === key.toLocaleLowerCase()) { - return headers[i + 1] - } - } - - return undefined - } else if (typeof headers.get === 'function') { - return headers.get(key) - } else { - return lowerCaseEntries(headers)[key.toLocaleLowerCase()] - } -} - -/** @param {string[]} headers */ -function buildHeadersFromArray (headers) { // fetch HeadersList - const clone = headers.slice() - const entries = [] - for (let index = 0; index < clone.length; index += 2) { - entries.push([clone[index], clone[index + 1]]) - } - return Object.fromEntries(entries) -} - -function matchHeaders (mockDispatch, headers) { - if (typeof mockDispatch.headers === 'function') { - if (Array.isArray(headers)) { // fetch HeadersList - headers = buildHeadersFromArray(headers) - } - return mockDispatch.headers(headers ? lowerCaseEntries(headers) : {}) - } - if (typeof mockDispatch.headers === 'undefined') { - return true - } - if (typeof headers !== 'object' || typeof mockDispatch.headers !== 'object') { - return false - } - - for (const [matchHeaderName, matchHeaderValue] of Object.entries(mockDispatch.headers)) { - const headerValue = getHeaderByName(headers, matchHeaderName) - - if (!matchValue(matchHeaderValue, headerValue)) { - return false - } - } - return true -} - -function safeUrl (path) { - if (typeof path !== 'string') { - return path - } - - const pathSegments = path.split('?') - - if (pathSegments.length !== 2) { - return path - } - - const qp = new URLSearchParams(pathSegments.pop()) - qp.sort() - return [...pathSegments, qp.toString()].join('?') -} - -function matchKey (mockDispatch, { path, method, body, headers }) { - const pathMatch = matchValue(mockDispatch.path, path) - const methodMatch = matchValue(mockDispatch.method, method) - const bodyMatch = typeof mockDispatch.body !== 'undefined' ? matchValue(mockDispatch.body, body) : true - const headersMatch = matchHeaders(mockDispatch, headers) - return pathMatch && methodMatch && bodyMatch && headersMatch -} - -function getResponseData (data) { - if (Buffer.isBuffer(data)) { - return data - } else if (typeof data === 'object') { - return JSON.stringify(data) - } else { - return data.toString() - } -} - -function getMockDispatch (mockDispatches, key) { - const basePath = key.query ? buildURL(key.path, key.query) : key.path - const resolvedPath = typeof basePath === 'string' ? safeUrl(basePath) : basePath - - // Match path - let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path }) => matchValue(safeUrl(path), resolvedPath)) - if (matchedMockDispatches.length === 0) { - throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`) - } - - // Match method - matchedMockDispatches = matchedMockDispatches.filter(({ method }) => matchValue(method, key.method)) - if (matchedMockDispatches.length === 0) { - throw new MockNotMatchedError(`Mock dispatch not matched for method '${key.method}'`) - } - - // Match body - matchedMockDispatches = matchedMockDispatches.filter(({ body }) => typeof body !== 'undefined' ? matchValue(body, key.body) : true) - if (matchedMockDispatches.length === 0) { - throw new MockNotMatchedError(`Mock dispatch not matched for body '${key.body}'`) - } - - // Match headers - matchedMockDispatches = matchedMockDispatches.filter((mockDispatch) => matchHeaders(mockDispatch, key.headers)) - if (matchedMockDispatches.length === 0) { - throw new MockNotMatchedError(`Mock dispatch not matched for headers '${typeof key.headers === 'object' ? JSON.stringify(key.headers) : key.headers}'`) - } - - return matchedMockDispatches[0] -} - -function addMockDispatch (mockDispatches, key, data) { - const baseData = { timesInvoked: 0, times: 1, persist: false, consumed: false } - const replyData = typeof data === 'function' ? { callback: data } : { ...data } - const newMockDispatch = { ...baseData, ...key, pending: true, data: { error: null, ...replyData } } - mockDispatches.push(newMockDispatch) - return newMockDispatch -} - -function deleteMockDispatch (mockDispatches, key) { - const index = mockDispatches.findIndex(dispatch => { - if (!dispatch.consumed) { - return false - } - return matchKey(dispatch, key) - }) - if (index !== -1) { - mockDispatches.splice(index, 1) - } -} - -function buildKey (opts) { - const { path, method, body, headers, query } = opts - return { - path, - method, - body, - headers, - query - } -} - -function generateKeyValues (data) { - return Object.entries(data).reduce((keyValuePairs, [key, value]) => [ - ...keyValuePairs, - Buffer.from(`${key}`), - Array.isArray(value) ? value.map(x => Buffer.from(`${x}`)) : Buffer.from(`${value}`) - ], []) -} - -/** - * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status - * @param {number} statusCode - */ -function getStatusText (statusCode) { - return STATUS_CODES[statusCode] || 'unknown' -} - -async function getResponse (body) { - const buffers = [] - for await (const data of body) { - buffers.push(data) - } - return Buffer.concat(buffers).toString('utf8') -} - -/** - * Mock dispatch function used to simulate undici dispatches - */ -function mockDispatch (opts, handler) { - // Get mock dispatch from built key - const key = buildKey(opts) - const mockDispatch = getMockDispatch(this[kDispatches], key) - - mockDispatch.timesInvoked++ - - // Here's where we resolve a callback if a callback is present for the dispatch data. - if (mockDispatch.data.callback) { - mockDispatch.data = { ...mockDispatch.data, ...mockDispatch.data.callback(opts) } - } - - // Parse mockDispatch data - const { data: { statusCode, data, headers, trailers, error }, delay, persist } = mockDispatch - const { timesInvoked, times } = mockDispatch - - // If it's used up and not persistent, mark as consumed - mockDispatch.consumed = !persist && timesInvoked >= times - mockDispatch.pending = timesInvoked < times - - // If specified, trigger dispatch error - if (error !== null) { - deleteMockDispatch(this[kDispatches], key) - handler.onError(error) - return true - } - - // Handle the request with a delay if necessary - if (typeof delay === 'number' && delay > 0) { - setTimeout(() => { - handleReply(this[kDispatches]) - }, delay) - } else { - handleReply(this[kDispatches]) - } - - function handleReply (mockDispatches, _data = data) { - // fetch's HeadersList is a 1D string array - const optsHeaders = Array.isArray(opts.headers) - ? buildHeadersFromArray(opts.headers) - : opts.headers - const body = typeof _data === 'function' - ? _data({ ...opts, headers: optsHeaders }) - : _data - - // util.types.isPromise is likely needed for jest. - if (isPromise(body)) { - // If handleReply is asynchronous, throwing an error - // in the callback will reject the promise, rather than - // synchronously throw the error, which breaks some tests. - // Rather, we wait for the callback to resolve if it is a - // promise, and then re-run handleReply with the new body. - body.then((newData) => handleReply(mockDispatches, newData)) - return - } - - const responseData = getResponseData(body) - const responseHeaders = generateKeyValues(headers) - const responseTrailers = generateKeyValues(trailers) - - handler.abort = nop - handler.onHeaders(statusCode, responseHeaders, resume, getStatusText(statusCode)) - handler.onData(Buffer.from(responseData)) - handler.onComplete(responseTrailers) - deleteMockDispatch(mockDispatches, key) - } - - function resume () {} - - return true -} - -function buildMockDispatch () { - const agent = this[kMockAgent] - const origin = this[kOrigin] - const originalDispatch = this[kOriginalDispatch] - - return function dispatch (opts, handler) { - if (agent.isMockActive) { - try { - mockDispatch.call(this, opts, handler) - } catch (error) { - if (error instanceof MockNotMatchedError) { - const netConnect = agent[kGetNetConnect]() - if (netConnect === false) { - throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect disabled)`) - } - if (checkNetConnect(netConnect, origin)) { - originalDispatch.call(this, opts, handler) - } else { - throw new MockNotMatchedError(`${error.message}: subsequent request to origin ${origin} was not allowed (net.connect is not enabled for this origin)`) - } - } else { - throw error - } - } - } else { - originalDispatch.call(this, opts, handler) - } - } -} - -function checkNetConnect (netConnect, origin) { - const url = new URL(origin) - if (netConnect === true) { - return true - } else if (Array.isArray(netConnect) && netConnect.some((matcher) => matchValue(matcher, url.host))) { - return true - } - return false -} - -function buildMockOptions (opts) { - if (opts) { - const { agent, ...mockOptions } = opts - return mockOptions - } -} - -module.exports = { - getResponseData, - getMockDispatch, - addMockDispatch, - deleteMockDispatch, - buildKey, - generateKeyValues, - matchValue, - getResponse, - getStatusText, - mockDispatch, - buildMockDispatch, - checkNetConnect, - buildMockOptions, - getHeaderByName -} - - -/***/ }), - -/***/ 6142: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { Transform } = __nccwpck_require__(2203) -const { Console } = __nccwpck_require__(4236) - -/** - * Gets the output of `console.table(…)` as a string. - */ -module.exports = class PendingInterceptorsFormatter { - constructor ({ disableColors } = {}) { - this.transform = new Transform({ - transform (chunk, _enc, cb) { - cb(null, chunk) - } - }) - - this.logger = new Console({ - stdout: this.transform, - inspectOptions: { - colors: !disableColors && !process.env.CI - } - }) - } - - format (pendingInterceptors) { - const withPrettyHeaders = pendingInterceptors.map( - ({ method, path, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ - Method: method, - Origin: origin, - Path: path, - 'Status code': statusCode, - Persistent: persist ? '✅' : '❌', - Invocations: timesInvoked, - Remaining: persist ? Infinity : times - timesInvoked - })) - - this.logger.table(withPrettyHeaders) - return this.transform.read().toString() - } -} - - -/***/ }), - -/***/ 1529: -/***/ ((module) => { - - - -const singulars = { - pronoun: 'it', - is: 'is', - was: 'was', - this: 'this' -} - -const plurals = { - pronoun: 'they', - is: 'are', - was: 'were', - this: 'these' -} - -module.exports = class Pluralizer { - constructor (singular, plural) { - this.singular = singular - this.plural = plural - } - - pluralize (count) { - const one = count === 1 - const keys = one ? singulars : plurals - const noun = one ? this.singular : this.plural - return { ...keys, count, noun } - } -} - - -/***/ }), - -/***/ 4869: -/***/ ((module) => { - -/* eslint-disable */ - - - -// Extracted from node/lib/internal/fixed_queue.js - -// Currently optimal queue size, tested on V8 6.0 - 6.6. Must be power of two. -const kSize = 2048; -const kMask = kSize - 1; - -// The FixedQueue is implemented as a singly-linked list of fixed-size -// circular buffers. It looks something like this: -// -// head tail -// | | -// v v -// +-----------+ <-----\ +-----------+ <------\ +-----------+ -// | [null] | \----- | next | \------- | next | -// +-----------+ +-----------+ +-----------+ -// | item | <-- bottom | item | <-- bottom | [empty] | -// | item | | item | | [empty] | -// | item | | item | | [empty] | -// | item | | item | | [empty] | -// | item | | item | bottom --> | item | -// | item | | item | | item | -// | ... | | ... | | ... | -// | item | | item | | item | -// | item | | item | | item | -// | [empty] | <-- top | item | | item | -// | [empty] | | item | | item | -// | [empty] | | [empty] | <-- top top --> | [empty] | -// +-----------+ +-----------+ +-----------+ -// -// Or, if there is only one circular buffer, it looks something -// like either of these: -// -// head tail head tail -// | | | | -// v v v v -// +-----------+ +-----------+ -// | [null] | | [null] | -// +-----------+ +-----------+ -// | [empty] | | item | -// | [empty] | | item | -// | item | <-- bottom top --> | [empty] | -// | item | | [empty] | -// | [empty] | <-- top bottom --> | item | -// | [empty] | | item | -// +-----------+ +-----------+ -// -// Adding a value means moving `top` forward by one, removing means -// moving `bottom` forward by one. After reaching the end, the queue -// wraps around. -// -// When `top === bottom` the current queue is empty and when -// `top + 1 === bottom` it's full. This wastes a single space of storage -// but allows much quicker checks. - -class FixedCircularBuffer { - constructor() { - this.bottom = 0; - this.top = 0; - this.list = new Array(kSize); - this.next = null; - } - - isEmpty() { - return this.top === this.bottom; - } - - isFull() { - return ((this.top + 1) & kMask) === this.bottom; - } - - push(data) { - this.list[this.top] = data; - this.top = (this.top + 1) & kMask; - } - - shift() { - const nextItem = this.list[this.bottom]; - if (nextItem === undefined) - return null; - this.list[this.bottom] = undefined; - this.bottom = (this.bottom + 1) & kMask; - return nextItem; - } -} - -module.exports = class FixedQueue { - constructor() { - this.head = this.tail = new FixedCircularBuffer(); - } - - isEmpty() { - return this.head.isEmpty(); - } - - push(data) { - if (this.head.isFull()) { - // Head is full: Creates a new queue, sets the old queue's `.next` to it, - // and sets it as the new main queue. - this.head = this.head.next = new FixedCircularBuffer(); - } - this.head.push(data); - } - - shift() { - const tail = this.tail; - const next = tail.shift(); - if (tail.isEmpty() && tail.next !== null) { - // If there is another queue, it forms the new tail. - this.tail = tail.next; - } - return next; - } -}; - - -/***/ }), - -/***/ 8640: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const DispatcherBase = __nccwpck_require__(1) -const FixedQueue = __nccwpck_require__(4869) -const { kConnected, kSize, kRunning, kPending, kQueued, kBusy, kFree, kUrl, kClose, kDestroy, kDispatch } = __nccwpck_require__(6443) -const PoolStats = __nccwpck_require__(4622) - -const kClients = Symbol('clients') -const kNeedDrain = Symbol('needDrain') -const kQueue = Symbol('queue') -const kClosedResolve = Symbol('closed resolve') -const kOnDrain = Symbol('onDrain') -const kOnConnect = Symbol('onConnect') -const kOnDisconnect = Symbol('onDisconnect') -const kOnConnectionError = Symbol('onConnectionError') -const kGetDispatcher = Symbol('get dispatcher') -const kAddClient = Symbol('add client') -const kRemoveClient = Symbol('remove client') -const kStats = Symbol('stats') - -class PoolBase extends DispatcherBase { - constructor () { - super() - - this[kQueue] = new FixedQueue() - this[kClients] = [] - this[kQueued] = 0 - - const pool = this - - this[kOnDrain] = function onDrain (origin, targets) { - const queue = pool[kQueue] - - let needDrain = false - - while (!needDrain) { - const item = queue.shift() - if (!item) { - break - } - pool[kQueued]-- - needDrain = !this.dispatch(item.opts, item.handler) - } - - this[kNeedDrain] = needDrain - - if (!this[kNeedDrain] && pool[kNeedDrain]) { - pool[kNeedDrain] = false - pool.emit('drain', origin, [pool, ...targets]) - } - - if (pool[kClosedResolve] && queue.isEmpty()) { - Promise - .all(pool[kClients].map(c => c.close())) - .then(pool[kClosedResolve]) - } - } - - this[kOnConnect] = (origin, targets) => { - pool.emit('connect', origin, [pool, ...targets]) - } - - this[kOnDisconnect] = (origin, targets, err) => { - pool.emit('disconnect', origin, [pool, ...targets], err) - } - - this[kOnConnectionError] = (origin, targets, err) => { - pool.emit('connectionError', origin, [pool, ...targets], err) - } - - this[kStats] = new PoolStats(this) - } - - get [kBusy] () { - return this[kNeedDrain] - } - - get [kConnected] () { - return this[kClients].filter(client => client[kConnected]).length - } - - get [kFree] () { - return this[kClients].filter(client => client[kConnected] && !client[kNeedDrain]).length - } - - get [kPending] () { - let ret = this[kQueued] - for (const { [kPending]: pending } of this[kClients]) { - ret += pending - } - return ret - } - - get [kRunning] () { - let ret = 0 - for (const { [kRunning]: running } of this[kClients]) { - ret += running - } - return ret - } - - get [kSize] () { - let ret = this[kQueued] - for (const { [kSize]: size } of this[kClients]) { - ret += size - } - return ret - } - - get stats () { - return this[kStats] - } - - async [kClose] () { - if (this[kQueue].isEmpty()) { - return Promise.all(this[kClients].map(c => c.close())) - } else { - return new Promise((resolve) => { - this[kClosedResolve] = resolve - }) - } - } - - async [kDestroy] (err) { - while (true) { - const item = this[kQueue].shift() - if (!item) { - break - } - item.handler.onError(err) - } - - return Promise.all(this[kClients].map(c => c.destroy(err))) - } - - [kDispatch] (opts, handler) { - const dispatcher = this[kGetDispatcher]() - - if (!dispatcher) { - this[kNeedDrain] = true - this[kQueue].push({ opts, handler }) - this[kQueued]++ - } else if (!dispatcher.dispatch(opts, handler)) { - dispatcher[kNeedDrain] = true - this[kNeedDrain] = !this[kGetDispatcher]() - } - - return !this[kNeedDrain] - } - - [kAddClient] (client) { - client - .on('drain', this[kOnDrain]) - .on('connect', this[kOnConnect]) - .on('disconnect', this[kOnDisconnect]) - .on('connectionError', this[kOnConnectionError]) - - this[kClients].push(client) - - if (this[kNeedDrain]) { - process.nextTick(() => { - if (this[kNeedDrain]) { - this[kOnDrain](client[kUrl], [this, client]) - } - }) - } - - return this - } - - [kRemoveClient] (client) { - client.close(() => { - const idx = this[kClients].indexOf(client) - if (idx !== -1) { - this[kClients].splice(idx, 1) - } - }) - - this[kNeedDrain] = this[kClients].some(dispatcher => ( - !dispatcher[kNeedDrain] && - dispatcher.closed !== true && - dispatcher.destroyed !== true - )) - } -} - -module.exports = { - PoolBase, - kClients, - kNeedDrain, - kAddClient, - kRemoveClient, - kGetDispatcher -} - - -/***/ }), - -/***/ 4622: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -const { kFree, kConnected, kPending, kQueued, kRunning, kSize } = __nccwpck_require__(6443) -const kPool = Symbol('pool') - -class PoolStats { - constructor (pool) { - this[kPool] = pool - } - - get connected () { - return this[kPool][kConnected] - } - - get free () { - return this[kPool][kFree] - } - - get pending () { - return this[kPool][kPending] - } - - get queued () { - return this[kPool][kQueued] - } - - get running () { - return this[kPool][kRunning] - } - - get size () { - return this[kPool][kSize] - } -} - -module.exports = PoolStats - - -/***/ }), - -/***/ 5076: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { - PoolBase, - kClients, - kNeedDrain, - kAddClient, - kGetDispatcher -} = __nccwpck_require__(8640) -const Client = __nccwpck_require__(6197) -const { - InvalidArgumentError -} = __nccwpck_require__(8707) -const util = __nccwpck_require__(3440) -const { kUrl, kInterceptors } = __nccwpck_require__(6443) -const buildConnector = __nccwpck_require__(9136) - -const kOptions = Symbol('options') -const kConnections = Symbol('connections') -const kFactory = Symbol('factory') - -function defaultFactory (origin, opts) { - return new Client(origin, opts) -} - -class Pool extends PoolBase { - constructor (origin, { - connections, - factory = defaultFactory, - connect, - connectTimeout, - tls, - maxCachedSessions, - socketPath, - autoSelectFamily, - autoSelectFamilyAttemptTimeout, - allowH2, - ...options - } = {}) { - super() - - if (connections != null && (!Number.isFinite(connections) || connections < 0)) { - throw new InvalidArgumentError('invalid connections') - } - - if (typeof factory !== 'function') { - throw new InvalidArgumentError('factory must be a function.') - } - - if (connect != null && typeof connect !== 'function' && typeof connect !== 'object') { - throw new InvalidArgumentError('connect must be a function or an object') - } - - if (typeof connect !== 'function') { - connect = buildConnector({ - ...tls, - maxCachedSessions, - allowH2, - socketPath, - timeout: connectTimeout, - ...(util.nodeHasAutoSelectFamily && autoSelectFamily ? { autoSelectFamily, autoSelectFamilyAttemptTimeout } : undefined), - ...connect - }) - } - - this[kInterceptors] = options.interceptors && options.interceptors.Pool && Array.isArray(options.interceptors.Pool) - ? options.interceptors.Pool - : [] - this[kConnections] = connections || null - this[kUrl] = util.parseOrigin(origin) - this[kOptions] = { ...util.deepClone(options), connect, allowH2 } - this[kOptions].interceptors = options.interceptors - ? { ...options.interceptors } - : undefined - this[kFactory] = factory - - this.on('connectionError', (origin, targets, error) => { - // If a connection error occurs, we remove the client from the pool, - // and emit a connectionError event. They will not be re-used. - // Fixes https://github.com/nodejs/undici/issues/3895 - for (const target of targets) { - // Do not use kRemoveClient here, as it will close the client, - // but the client cannot be closed in this state. - const idx = this[kClients].indexOf(target) - if (idx !== -1) { - this[kClients].splice(idx, 1) - } - } - }) - } - - [kGetDispatcher] () { - let dispatcher = this[kClients].find(dispatcher => !dispatcher[kNeedDrain]) - - if (dispatcher) { - return dispatcher - } - - if (!this[kConnections] || this[kClients].length < this[kConnections]) { - dispatcher = this[kFactory](this[kUrl], this[kOptions]) - this[kAddClient](dispatcher) - } - - return dispatcher - } -} - -module.exports = Pool - - -/***/ }), - -/***/ 2720: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { kProxy, kClose, kDestroy, kInterceptors } = __nccwpck_require__(6443) -const { URL } = __nccwpck_require__(7016) -const Agent = __nccwpck_require__(9965) -const Pool = __nccwpck_require__(5076) -const DispatcherBase = __nccwpck_require__(1) -const { InvalidArgumentError, RequestAbortedError } = __nccwpck_require__(8707) -const buildConnector = __nccwpck_require__(9136) - -const kAgent = Symbol('proxy agent') -const kClient = Symbol('proxy client') -const kProxyHeaders = Symbol('proxy headers') -const kRequestTls = Symbol('request tls settings') -const kProxyTls = Symbol('proxy tls settings') -const kConnectEndpoint = Symbol('connect endpoint function') - -function defaultProtocolPort (protocol) { - return protocol === 'https:' ? 443 : 80 -} - -function buildProxyOptions (opts) { - if (typeof opts === 'string') { - opts = { uri: opts } - } - - if (!opts || !opts.uri) { - throw new InvalidArgumentError('Proxy opts.uri is mandatory') - } - - return { - uri: opts.uri, - protocol: opts.protocol || 'https' - } -} - -function defaultFactory (origin, opts) { - return new Pool(origin, opts) -} - -class ProxyAgent extends DispatcherBase { - constructor (opts) { - super(opts) - this[kProxy] = buildProxyOptions(opts) - this[kAgent] = new Agent(opts) - this[kInterceptors] = opts.interceptors && opts.interceptors.ProxyAgent && Array.isArray(opts.interceptors.ProxyAgent) - ? opts.interceptors.ProxyAgent - : [] - - if (typeof opts === 'string') { - opts = { uri: opts } - } - - if (!opts || !opts.uri) { - throw new InvalidArgumentError('Proxy opts.uri is mandatory') - } - - const { clientFactory = defaultFactory } = opts - - if (typeof clientFactory !== 'function') { - throw new InvalidArgumentError('Proxy opts.clientFactory must be a function.') - } - - this[kRequestTls] = opts.requestTls - this[kProxyTls] = opts.proxyTls - this[kProxyHeaders] = opts.headers || {} - - const resolvedUrl = new URL(opts.uri) - const { origin, port, host, username, password } = resolvedUrl - - if (opts.auth && opts.token) { - throw new InvalidArgumentError('opts.auth cannot be used in combination with opts.token') - } else if (opts.auth) { - /* @deprecated in favour of opts.token */ - this[kProxyHeaders]['proxy-authorization'] = `Basic ${opts.auth}` - } else if (opts.token) { - this[kProxyHeaders]['proxy-authorization'] = opts.token - } else if (username && password) { - this[kProxyHeaders]['proxy-authorization'] = `Basic ${Buffer.from(`${decodeURIComponent(username)}:${decodeURIComponent(password)}`).toString('base64')}` - } - - const connect = buildConnector({ ...opts.proxyTls }) - this[kConnectEndpoint] = buildConnector({ ...opts.requestTls }) - this[kClient] = clientFactory(resolvedUrl, { connect }) - this[kAgent] = new Agent({ - ...opts, - connect: async (opts, callback) => { - let requestedHost = opts.host - if (!opts.port) { - requestedHost += `:${defaultProtocolPort(opts.protocol)}` - } - try { - const { socket, statusCode } = await this[kClient].connect({ - origin, - port, - path: requestedHost, - signal: opts.signal, - headers: { - ...this[kProxyHeaders], - host - } - }) - if (statusCode !== 200) { - socket.on('error', () => {}).destroy() - callback(new RequestAbortedError(`Proxy response (${statusCode}) !== 200 when HTTP Tunneling`)) - } - if (opts.protocol !== 'https:') { - callback(null, socket) - return - } - let servername - if (this[kRequestTls]) { - servername = this[kRequestTls].servername - } else { - servername = opts.servername - } - this[kConnectEndpoint]({ ...opts, servername, httpSocket: socket }, callback) - } catch (err) { - callback(err) - } - } - }) - } - - dispatch (opts, handler) { - const { host } = new URL(opts.origin) - const headers = buildHeaders(opts.headers) - throwIfProxyAuthIsSent(headers) - return this[kAgent].dispatch( - { - ...opts, - headers: { - ...headers, - host - } - }, - handler - ) - } - - async [kClose] () { - await this[kAgent].close() - await this[kClient].close() - } - - async [kDestroy] () { - await this[kAgent].destroy() - await this[kClient].destroy() - } -} - -/** - * @param {string[] | Record} headers - * @returns {Record} - */ -function buildHeaders (headers) { - // When using undici.fetch, the headers list is stored - // as an array. - if (Array.isArray(headers)) { - /** @type {Record} */ - const headersPair = {} - - for (let i = 0; i < headers.length; i += 2) { - headersPair[headers[i]] = headers[i + 1] - } - - return headersPair - } - - return headers -} - -/** - * @param {Record} headers - * - * Previous versions of ProxyAgent suggests the Proxy-Authorization in request headers - * Nevertheless, it was changed and to avoid a security vulnerability by end users - * this check was created. - * It should be removed in the next major version for performance reasons - */ -function throwIfProxyAuthIsSent (headers) { - const existProxyAuth = headers && Object.keys(headers) - .find((key) => key.toLowerCase() === 'proxy-authorization') - if (existProxyAuth) { - throw new InvalidArgumentError('Proxy-Authorization should be sent in ProxyAgent constructor') - } -} - -module.exports = ProxyAgent - - -/***/ }), - -/***/ 8804: -/***/ ((module) => { - - - -let fastNow = Date.now() -let fastNowTimeout - -const fastTimers = [] - -function onTimeout () { - fastNow = Date.now() - - let len = fastTimers.length - let idx = 0 - while (idx < len) { - const timer = fastTimers[idx] - - if (timer.state === 0) { - timer.state = fastNow + timer.delay - } else if (timer.state > 0 && fastNow >= timer.state) { - timer.state = -1 - timer.callback(timer.opaque) - } - - if (timer.state === -1) { - timer.state = -2 - if (idx !== len - 1) { - fastTimers[idx] = fastTimers.pop() - } else { - fastTimers.pop() - } - len -= 1 - } else { - idx += 1 - } - } - - if (fastTimers.length > 0) { - refreshTimeout() - } -} - -function refreshTimeout () { - if (fastNowTimeout && fastNowTimeout.refresh) { - fastNowTimeout.refresh() - } else { - clearTimeout(fastNowTimeout) - fastNowTimeout = setTimeout(onTimeout, 1e3) - if (fastNowTimeout.unref) { - fastNowTimeout.unref() - } - } -} - -class Timeout { - constructor (callback, delay, opaque) { - this.callback = callback - this.delay = delay - this.opaque = opaque - - // -2 not in timer list - // -1 in timer list but inactive - // 0 in timer list waiting for time - // > 0 in timer list waiting for time to expire - this.state = -2 - - this.refresh() - } - - refresh () { - if (this.state === -2) { - fastTimers.push(this) - if (!fastNowTimeout || fastTimers.length === 1) { - refreshTimeout() - } - } - - this.state = 0 - } - - clear () { - this.state = -1 - } -} - -module.exports = { - setTimeout (callback, delay, opaque) { - return delay < 1e3 - ? setTimeout(callback, delay, opaque) - : new Timeout(callback, delay, opaque) - }, - clearTimeout (timeout) { - if (timeout instanceof Timeout) { - timeout.clear() - } else { - clearTimeout(timeout) - } - } -} - - -/***/ }), - -/***/ 8550: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const diagnosticsChannel = __nccwpck_require__(1637) -const { uid, states } = __nccwpck_require__(5913) -const { - kReadyState, - kSentClose, - kByteParser, - kReceivedClose -} = __nccwpck_require__(2933) -const { fireEvent, failWebsocketConnection } = __nccwpck_require__(3574) -const { CloseEvent } = __nccwpck_require__(6255) -const { makeRequest } = __nccwpck_require__(5194) -const { fetching } = __nccwpck_require__(2315) -const { Headers } = __nccwpck_require__(6349) -const { getGlobalDispatcher } = __nccwpck_require__(2581) -const { kHeadersList } = __nccwpck_require__(6443) - -const channels = {} -channels.open = diagnosticsChannel.channel('undici:websocket:open') -channels.close = diagnosticsChannel.channel('undici:websocket:close') -channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error') - -/** @type {import('crypto')} */ -let crypto -try { - crypto = __nccwpck_require__(6982) -} catch { - -} - -/** - * @see https://websockets.spec.whatwg.org/#concept-websocket-establish - * @param {URL} url - * @param {string|string[]} protocols - * @param {import('./websocket').WebSocket} ws - * @param {(response: any) => void} onEstablish - * @param {Partial} options - */ -function establishWebSocketConnection (url, protocols, ws, onEstablish, options) { - // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s - // scheme is "ws", and to "https" otherwise. - const requestURL = url - - requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:' - - // 2. Let request be a new request, whose URL is requestURL, client is client, - // service-workers mode is "none", referrer is "no-referrer", mode is - // "websocket", credentials mode is "include", cache mode is "no-store" , - // and redirect mode is "error". - const request = makeRequest({ - urlList: [requestURL], - serviceWorkers: 'none', - referrer: 'no-referrer', - mode: 'websocket', - credentials: 'include', - cache: 'no-store', - redirect: 'error' - }) - - // Note: undici extension, allow setting custom headers. - if (options.headers) { - const headersList = new Headers(options.headers)[kHeadersList] - - request.headersList = headersList - } - - // 3. Append (`Upgrade`, `websocket`) to request’s header list. - // 4. Append (`Connection`, `Upgrade`) to request’s header list. - // Note: both of these are handled by undici currently. - // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397 - - // 5. Let keyValue be a nonce consisting of a randomly selected - // 16-byte value that has been forgiving-base64-encoded and - // isomorphic encoded. - const keyValue = crypto.randomBytes(16).toString('base64') - - // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s - // header list. - request.headersList.append('sec-websocket-key', keyValue) - - // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s - // header list. - request.headersList.append('sec-websocket-version', '13') - - // 8. For each protocol in protocols, combine - // (`Sec-WebSocket-Protocol`, protocol) in request’s header - // list. - for (const protocol of protocols) { - request.headersList.append('sec-websocket-protocol', protocol) - } - - // 9. Let permessageDeflate be a user-agent defined - // "permessage-deflate" extension header value. - // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673 - // TODO: enable once permessage-deflate is supported - const permessageDeflate = '' // 'permessage-deflate; 15' - - // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to - // request’s header list. - // request.headersList.append('sec-websocket-extensions', permessageDeflate) - - // 11. Fetch request with useParallelQueue set to true, and - // processResponse given response being these steps: - const controller = fetching({ - request, - useParallelQueue: true, - dispatcher: options.dispatcher ?? getGlobalDispatcher(), - processResponse (response) { - // 1. If response is a network error or its status is not 101, - // fail the WebSocket connection. - if (response.type === 'error' || response.status !== 101) { - failWebsocketConnection(ws, 'Received network error or non-101 status code.') - return - } - - // 2. If protocols is not the empty list and extracting header - // list values given `Sec-WebSocket-Protocol` and response’s - // header list results in null, failure, or the empty byte - // sequence, then fail the WebSocket connection. - if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) { - failWebsocketConnection(ws, 'Server did not respond with sent protocols.') - return - } - - // 3. Follow the requirements stated step 2 to step 6, inclusive, - // of the last set of steps in section 4.1 of The WebSocket - // Protocol to validate response. This either results in fail - // the WebSocket connection or the WebSocket connection is - // established. - - // 2. If the response lacks an |Upgrade| header field or the |Upgrade| - // header field contains a value that is not an ASCII case- - // insensitive match for the value "websocket", the client MUST - // _Fail the WebSocket Connection_. - if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') { - failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".') - return - } - - // 3. If the response lacks a |Connection| header field or the - // |Connection| header field doesn't contain a token that is an - // ASCII case-insensitive match for the value "Upgrade", the client - // MUST _Fail the WebSocket Connection_. - if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') { - failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".') - return - } - - // 4. If the response lacks a |Sec-WebSocket-Accept| header field or - // the |Sec-WebSocket-Accept| contains a value other than the - // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket- - // Key| (as a string, not base64-decoded) with the string "258EAFA5- - // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and - // trailing whitespace, the client MUST _Fail the WebSocket - // Connection_. - const secWSAccept = response.headersList.get('Sec-WebSocket-Accept') - const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64') - if (secWSAccept !== digest) { - failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.') - return - } - - // 5. If the response includes a |Sec-WebSocket-Extensions| header - // field and this header field indicates the use of an extension - // that was not present in the client's handshake (the server has - // indicated an extension not requested by the client), the client - // MUST _Fail the WebSocket Connection_. (The parsing of this - // header field to determine which extensions are requested is - // discussed in Section 9.1.) - const secExtension = response.headersList.get('Sec-WebSocket-Extensions') - - if (secExtension !== null && secExtension !== permessageDeflate) { - failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.') - return - } - - // 6. If the response includes a |Sec-WebSocket-Protocol| header field - // and this header field indicates the use of a subprotocol that was - // not present in the client's handshake (the server has indicated a - // subprotocol not requested by the client), the client MUST _Fail - // the WebSocket Connection_. - const secProtocol = response.headersList.get('Sec-WebSocket-Protocol') - - if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) { - failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.') - return - } - - response.socket.on('data', onSocketData) - response.socket.on('close', onSocketClose) - response.socket.on('error', onSocketError) - - if (channels.open.hasSubscribers) { - channels.open.publish({ - address: response.socket.address(), - protocol: secProtocol, - extensions: secExtension - }) - } - - onEstablish(response) - } - }) - - return controller -} - -/** - * @param {Buffer} chunk - */ -function onSocketData (chunk) { - if (!this.ws[kByteParser].write(chunk)) { - this.pause() - } -} - -/** - * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol - * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4 - */ -function onSocketClose () { - const { ws } = this - - // If the TCP connection was closed after the - // WebSocket closing handshake was completed, the WebSocket connection - // is said to have been closed _cleanly_. - const wasClean = ws[kSentClose] && ws[kReceivedClose] - - let code = 1005 - let reason = '' - - const result = ws[kByteParser].closingInfo - - if (result) { - code = result.code ?? 1005 - reason = result.reason - } else if (!ws[kSentClose]) { - // If _The WebSocket - // Connection is Closed_ and no Close control frame was received by the - // endpoint (such as could occur if the underlying transport connection - // is lost), _The WebSocket Connection Close Code_ is considered to be - // 1006. - code = 1006 - } - - // 1. Change the ready state to CLOSED (3). - ws[kReadyState] = states.CLOSED - - // 2. If the user agent was required to fail the WebSocket - // connection, or if the WebSocket connection was closed - // after being flagged as full, fire an event named error - // at the WebSocket object. - // TODO - - // 3. Fire an event named close at the WebSocket object, - // using CloseEvent, with the wasClean attribute - // initialized to true if the connection closed cleanly - // and false otherwise, the code attribute initialized to - // the WebSocket connection close code, and the reason - // attribute initialized to the result of applying UTF-8 - // decode without BOM to the WebSocket connection close - // reason. - fireEvent('close', ws, CloseEvent, { - wasClean, code, reason - }) - - if (channels.close.hasSubscribers) { - channels.close.publish({ - websocket: ws, - code, - reason - }) - } -} - -function onSocketError (error) { - const { ws } = this - - ws[kReadyState] = states.CLOSING - - if (channels.socketError.hasSubscribers) { - channels.socketError.publish(error) - } - - this.destroy() -} - -module.exports = { - establishWebSocketConnection -} - - -/***/ }), - -/***/ 5913: -/***/ ((module) => { - - - -// This is a Globally Unique Identifier unique used -// to validate that the endpoint accepts websocket -// connections. -// See https://www.rfc-editor.org/rfc/rfc6455.html#section-1.3 -const uid = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11' - -/** @type {PropertyDescriptor} */ -const staticPropertyDescriptors = { - enumerable: true, - writable: false, - configurable: false -} - -const states = { - CONNECTING: 0, - OPEN: 1, - CLOSING: 2, - CLOSED: 3 -} - -const opcodes = { - CONTINUATION: 0x0, - TEXT: 0x1, - BINARY: 0x2, - CLOSE: 0x8, - PING: 0x9, - PONG: 0xA -} - -const maxUnsigned16Bit = 2 ** 16 - 1 // 65535 - -const parserStates = { - INFO: 0, - PAYLOADLENGTH_16: 2, - PAYLOADLENGTH_64: 3, - READ_DATA: 4 -} - -const emptyBuffer = Buffer.allocUnsafe(0) - -module.exports = { - uid, - staticPropertyDescriptors, - states, - opcodes, - maxUnsigned16Bit, - parserStates, - emptyBuffer -} - - -/***/ }), - -/***/ 6255: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { webidl } = __nccwpck_require__(4222) -const { kEnumerableProperty } = __nccwpck_require__(3440) -const { MessagePort } = __nccwpck_require__(8167) - -/** - * @see https://html.spec.whatwg.org/multipage/comms.html#messageevent - */ -class MessageEvent extends Event { - #eventInit - - constructor (type, eventInitDict = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent constructor' }) - - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.MessageEventInit(eventInitDict) - - super(type, eventInitDict) - - this.#eventInit = eventInitDict - } - - get data () { - webidl.brandCheck(this, MessageEvent) - - return this.#eventInit.data - } - - get origin () { - webidl.brandCheck(this, MessageEvent) - - return this.#eventInit.origin - } - - get lastEventId () { - webidl.brandCheck(this, MessageEvent) - - return this.#eventInit.lastEventId - } - - get source () { - webidl.brandCheck(this, MessageEvent) - - return this.#eventInit.source - } - - get ports () { - webidl.brandCheck(this, MessageEvent) - - if (!Object.isFrozen(this.#eventInit.ports)) { - Object.freeze(this.#eventInit.ports) - } - - return this.#eventInit.ports - } - - initMessageEvent ( - type, - bubbles = false, - cancelable = false, - data = null, - origin = '', - lastEventId = '', - source = null, - ports = [] - ) { - webidl.brandCheck(this, MessageEvent) - - webidl.argumentLengthCheck(arguments, 1, { header: 'MessageEvent.initMessageEvent' }) - - return new MessageEvent(type, { - bubbles, cancelable, data, origin, lastEventId, source, ports - }) - } -} - -/** - * @see https://websockets.spec.whatwg.org/#the-closeevent-interface - */ -class CloseEvent extends Event { - #eventInit - - constructor (type, eventInitDict = {}) { - webidl.argumentLengthCheck(arguments, 1, { header: 'CloseEvent constructor' }) - - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.CloseEventInit(eventInitDict) - - super(type, eventInitDict) - - this.#eventInit = eventInitDict - } - - get wasClean () { - webidl.brandCheck(this, CloseEvent) - - return this.#eventInit.wasClean - } - - get code () { - webidl.brandCheck(this, CloseEvent) - - return this.#eventInit.code - } - - get reason () { - webidl.brandCheck(this, CloseEvent) - - return this.#eventInit.reason - } -} - -// https://html.spec.whatwg.org/multipage/webappapis.html#the-errorevent-interface -class ErrorEvent extends Event { - #eventInit - - constructor (type, eventInitDict) { - webidl.argumentLengthCheck(arguments, 1, { header: 'ErrorEvent constructor' }) - - super(type, eventInitDict) - - type = webidl.converters.DOMString(type) - eventInitDict = webidl.converters.ErrorEventInit(eventInitDict ?? {}) - - this.#eventInit = eventInitDict - } - - get message () { - webidl.brandCheck(this, ErrorEvent) - - return this.#eventInit.message - } - - get filename () { - webidl.brandCheck(this, ErrorEvent) - - return this.#eventInit.filename - } - - get lineno () { - webidl.brandCheck(this, ErrorEvent) - - return this.#eventInit.lineno - } - - get colno () { - webidl.brandCheck(this, ErrorEvent) - - return this.#eventInit.colno - } - - get error () { - webidl.brandCheck(this, ErrorEvent) - - return this.#eventInit.error - } -} - -Object.defineProperties(MessageEvent.prototype, { - [Symbol.toStringTag]: { - value: 'MessageEvent', - configurable: true - }, - data: kEnumerableProperty, - origin: kEnumerableProperty, - lastEventId: kEnumerableProperty, - source: kEnumerableProperty, - ports: kEnumerableProperty, - initMessageEvent: kEnumerableProperty -}) - -Object.defineProperties(CloseEvent.prototype, { - [Symbol.toStringTag]: { - value: 'CloseEvent', - configurable: true - }, - reason: kEnumerableProperty, - code: kEnumerableProperty, - wasClean: kEnumerableProperty -}) - -Object.defineProperties(ErrorEvent.prototype, { - [Symbol.toStringTag]: { - value: 'ErrorEvent', - configurable: true - }, - message: kEnumerableProperty, - filename: kEnumerableProperty, - lineno: kEnumerableProperty, - colno: kEnumerableProperty, - error: kEnumerableProperty -}) - -webidl.converters.MessagePort = webidl.interfaceConverter(MessagePort) - -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.MessagePort -) - -const eventInit = [ - { - key: 'bubbles', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'cancelable', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'composed', - converter: webidl.converters.boolean, - defaultValue: false - } -] - -webidl.converters.MessageEventInit = webidl.dictionaryConverter([ - ...eventInit, - { - key: 'data', - converter: webidl.converters.any, - defaultValue: null - }, - { - key: 'origin', - converter: webidl.converters.USVString, - defaultValue: '' - }, - { - key: 'lastEventId', - converter: webidl.converters.DOMString, - defaultValue: '' - }, - { - key: 'source', - // Node doesn't implement WindowProxy or ServiceWorker, so the only - // valid value for source is a MessagePort. - converter: webidl.nullableConverter(webidl.converters.MessagePort), - defaultValue: null - }, - { - key: 'ports', - converter: webidl.converters['sequence'], - get defaultValue () { - return [] - } - } -]) - -webidl.converters.CloseEventInit = webidl.dictionaryConverter([ - ...eventInit, - { - key: 'wasClean', - converter: webidl.converters.boolean, - defaultValue: false - }, - { - key: 'code', - converter: webidl.converters['unsigned short'], - defaultValue: 0 - }, - { - key: 'reason', - converter: webidl.converters.USVString, - defaultValue: '' - } -]) - -webidl.converters.ErrorEventInit = webidl.dictionaryConverter([ - ...eventInit, - { - key: 'message', - converter: webidl.converters.DOMString, - defaultValue: '' - }, - { - key: 'filename', - converter: webidl.converters.USVString, - defaultValue: '' - }, - { - key: 'lineno', - converter: webidl.converters['unsigned long'], - defaultValue: 0 - }, - { - key: 'colno', - converter: webidl.converters['unsigned long'], - defaultValue: 0 - }, - { - key: 'error', - converter: webidl.converters.any - } -]) - -module.exports = { - MessageEvent, - CloseEvent, - ErrorEvent -} - - -/***/ }), - -/***/ 1237: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { maxUnsigned16Bit } = __nccwpck_require__(5913) - -/** @type {import('crypto')} */ -let crypto -try { - crypto = __nccwpck_require__(6982) -} catch { - -} - -class WebsocketFrameSend { - /** - * @param {Buffer|undefined} data - */ - constructor (data) { - this.frameData = data - this.maskKey = crypto.randomBytes(4) - } - - createFrame (opcode) { - const bodyLength = this.frameData?.byteLength ?? 0 - - /** @type {number} */ - let payloadLength = bodyLength // 0-125 - let offset = 6 - - if (bodyLength > maxUnsigned16Bit) { - offset += 8 // payload length is next 8 bytes - payloadLength = 127 - } else if (bodyLength > 125) { - offset += 2 // payload length is next 2 bytes - payloadLength = 126 - } - - const buffer = Buffer.allocUnsafe(bodyLength + offset) - - // Clear first 2 bytes, everything else is overwritten - buffer[0] = buffer[1] = 0 - buffer[0] |= 0x80 // FIN - buffer[0] = (buffer[0] & 0xF0) + opcode // opcode - - /*! ws. MIT License. Einar Otto Stangvik */ - buffer[offset - 4] = this.maskKey[0] - buffer[offset - 3] = this.maskKey[1] - buffer[offset - 2] = this.maskKey[2] - buffer[offset - 1] = this.maskKey[3] - - buffer[1] = payloadLength - - if (payloadLength === 126) { - buffer.writeUInt16BE(bodyLength, 2) - } else if (payloadLength === 127) { - // Clear extended payload length - buffer[2] = buffer[3] = 0 - buffer.writeUIntBE(bodyLength, 4, 6) - } - - buffer[1] |= 0x80 // MASK - - // mask body - for (let i = 0; i < bodyLength; i++) { - buffer[offset + i] = this.frameData[i] ^ this.maskKey[i % 4] - } - - return buffer - } -} - -module.exports = { - WebsocketFrameSend -} - - -/***/ }), - -/***/ 3171: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { Writable } = __nccwpck_require__(2203) -const diagnosticsChannel = __nccwpck_require__(1637) -const { parserStates, opcodes, states, emptyBuffer } = __nccwpck_require__(5913) -const { kReadyState, kSentClose, kResponse, kReceivedClose } = __nccwpck_require__(2933) -const { isValidStatusCode, failWebsocketConnection, websocketMessageReceived } = __nccwpck_require__(3574) -const { WebsocketFrameSend } = __nccwpck_require__(1237) - -// This code was influenced by ws released under the MIT license. -// Copyright (c) 2011 Einar Otto Stangvik -// Copyright (c) 2013 Arnout Kazemier and contributors -// Copyright (c) 2016 Luigi Pinca and contributors - -const channels = {} -channels.ping = diagnosticsChannel.channel('undici:websocket:ping') -channels.pong = diagnosticsChannel.channel('undici:websocket:pong') - -class ByteParser extends Writable { - #buffers = [] - #byteOffset = 0 - - #state = parserStates.INFO - - #info = {} - #fragments = [] - - constructor (ws) { - super() - - this.ws = ws - } - - /** - * @param {Buffer} chunk - * @param {() => void} callback - */ - _write (chunk, _, callback) { - this.#buffers.push(chunk) - this.#byteOffset += chunk.length - - this.run(callback) - } - - /** - * Runs whenever a new chunk is received. - * Callback is called whenever there are no more chunks buffering, - * or not enough bytes are buffered to parse. - */ - run (callback) { - while (true) { - if (this.#state === parserStates.INFO) { - // If there aren't enough bytes to parse the payload length, etc. - if (this.#byteOffset < 2) { - return callback() - } - - const buffer = this.consume(2) - - this.#info.fin = (buffer[0] & 0x80) !== 0 - this.#info.opcode = buffer[0] & 0x0F - - // If we receive a fragmented message, we use the type of the first - // frame to parse the full message as binary/text, when it's terminated - this.#info.originalOpcode ??= this.#info.opcode - - this.#info.fragmented = !this.#info.fin && this.#info.opcode !== opcodes.CONTINUATION - - if (this.#info.fragmented && this.#info.opcode !== opcodes.BINARY && this.#info.opcode !== opcodes.TEXT) { - // Only text and binary frames can be fragmented - failWebsocketConnection(this.ws, 'Invalid frame type was fragmented.') - return - } - - const payloadLength = buffer[1] & 0x7F - - if (payloadLength <= 125) { - this.#info.payloadLength = payloadLength - this.#state = parserStates.READ_DATA - } else if (payloadLength === 126) { - this.#state = parserStates.PAYLOADLENGTH_16 - } else if (payloadLength === 127) { - this.#state = parserStates.PAYLOADLENGTH_64 - } - - if (this.#info.fragmented && payloadLength > 125) { - // A fragmented frame can't be fragmented itself - failWebsocketConnection(this.ws, 'Fragmented frame exceeded 125 bytes.') - return - } else if ( - (this.#info.opcode === opcodes.PING || - this.#info.opcode === opcodes.PONG || - this.#info.opcode === opcodes.CLOSE) && - payloadLength > 125 - ) { - // Control frames can have a payload length of 125 bytes MAX - failWebsocketConnection(this.ws, 'Payload length for control frame exceeded 125 bytes.') - return - } else if (this.#info.opcode === opcodes.CLOSE) { - if (payloadLength === 1) { - failWebsocketConnection(this.ws, 'Received close frame with a 1-byte body.') - return - } - - const body = this.consume(payloadLength) - - this.#info.closeInfo = this.parseCloseBody(false, body) - - if (!this.ws[kSentClose]) { - // If an endpoint receives a Close frame and did not previously send a - // Close frame, the endpoint MUST send a Close frame in response. (When - // sending a Close frame in response, the endpoint typically echos the - // status code it received.) - const body = Buffer.allocUnsafe(2) - body.writeUInt16BE(this.#info.closeInfo.code, 0) - const closeFrame = new WebsocketFrameSend(body) - - this.ws[kResponse].socket.write( - closeFrame.createFrame(opcodes.CLOSE), - (err) => { - if (!err) { - this.ws[kSentClose] = true - } - } - ) - } - - // Upon either sending or receiving a Close control frame, it is said - // that _The WebSocket Closing Handshake is Started_ and that the - // WebSocket connection is in the CLOSING state. - this.ws[kReadyState] = states.CLOSING - this.ws[kReceivedClose] = true - - this.end() - - return - } else if (this.#info.opcode === opcodes.PING) { - // Upon receipt of a Ping frame, an endpoint MUST send a Pong frame in - // response, unless it already received a Close frame. - // A Pong frame sent in response to a Ping frame must have identical - // "Application data" - - const body = this.consume(payloadLength) - - if (!this.ws[kReceivedClose]) { - const frame = new WebsocketFrameSend(body) - - this.ws[kResponse].socket.write(frame.createFrame(opcodes.PONG)) - - if (channels.ping.hasSubscribers) { - channels.ping.publish({ - payload: body - }) - } - } - - this.#state = parserStates.INFO - - if (this.#byteOffset > 0) { - continue - } else { - callback() - return - } - } else if (this.#info.opcode === opcodes.PONG) { - // A Pong frame MAY be sent unsolicited. This serves as a - // unidirectional heartbeat. A response to an unsolicited Pong frame is - // not expected. - - const body = this.consume(payloadLength) - - if (channels.pong.hasSubscribers) { - channels.pong.publish({ - payload: body - }) - } - - if (this.#byteOffset > 0) { - continue - } else { - callback() - return - } - } - } else if (this.#state === parserStates.PAYLOADLENGTH_16) { - if (this.#byteOffset < 2) { - return callback() - } - - const buffer = this.consume(2) - - this.#info.payloadLength = buffer.readUInt16BE(0) - this.#state = parserStates.READ_DATA - } else if (this.#state === parserStates.PAYLOADLENGTH_64) { - if (this.#byteOffset < 8) { - return callback() - } - - const buffer = this.consume(8) - const upper = buffer.readUInt32BE(0) - - // 2^31 is the maxinimum bytes an arraybuffer can contain - // on 32-bit systems. Although, on 64-bit systems, this is - // 2^53-1 bytes. - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Invalid_array_length - // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/common/globals.h;drc=1946212ac0100668f14eb9e2843bdd846e510a1e;bpv=1;bpt=1;l=1275 - // https://source.chromium.org/chromium/chromium/src/+/main:v8/src/objects/js-array-buffer.h;l=34;drc=1946212ac0100668f14eb9e2843bdd846e510a1e - if (upper > 2 ** 31 - 1) { - failWebsocketConnection(this.ws, 'Received payload length > 2^31 bytes.') - return - } - - const lower = buffer.readUInt32BE(4) - - this.#info.payloadLength = (upper << 8) + lower - this.#state = parserStates.READ_DATA - } else if (this.#state === parserStates.READ_DATA) { - if (this.#byteOffset < this.#info.payloadLength) { - // If there is still more data in this chunk that needs to be read - return callback() - } else if (this.#byteOffset >= this.#info.payloadLength) { - // If the server sent multiple frames in a single chunk - - const body = this.consume(this.#info.payloadLength) - - this.#fragments.push(body) - - // If the frame is unfragmented, or a fragmented frame was terminated, - // a message was received - if (!this.#info.fragmented || (this.#info.fin && this.#info.opcode === opcodes.CONTINUATION)) { - const fullMessage = Buffer.concat(this.#fragments) - - websocketMessageReceived(this.ws, this.#info.originalOpcode, fullMessage) - - this.#info = {} - this.#fragments.length = 0 - } - - this.#state = parserStates.INFO - } - } - - if (this.#byteOffset > 0) { - continue - } else { - callback() - break - } - } - } - - /** - * Take n bytes from the buffered Buffers - * @param {number} n - * @returns {Buffer|null} - */ - consume (n) { - if (n > this.#byteOffset) { - return null - } else if (n === 0) { - return emptyBuffer - } - - if (this.#buffers[0].length === n) { - this.#byteOffset -= this.#buffers[0].length - return this.#buffers.shift() - } - - const buffer = Buffer.allocUnsafe(n) - let offset = 0 - - while (offset !== n) { - const next = this.#buffers[0] - const { length } = next - - if (length + offset === n) { - buffer.set(this.#buffers.shift(), offset) - break - } else if (length + offset > n) { - buffer.set(next.subarray(0, n - offset), offset) - this.#buffers[0] = next.subarray(n - offset) - break - } else { - buffer.set(this.#buffers.shift(), offset) - offset += next.length - } - } - - this.#byteOffset -= n - - return buffer - } - - parseCloseBody (onlyCode, data) { - // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.5 - /** @type {number|undefined} */ - let code - - if (data.length >= 2) { - // _The WebSocket Connection Close Code_ is - // defined as the status code (Section 7.4) contained in the first Close - // control frame received by the application - code = data.readUInt16BE(0) - } - - if (onlyCode) { - if (!isValidStatusCode(code)) { - return null - } - - return { code } - } - - // https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.6 - /** @type {Buffer} */ - let reason = data.subarray(2) - - // Remove BOM - if (reason[0] === 0xEF && reason[1] === 0xBB && reason[2] === 0xBF) { - reason = reason.subarray(3) - } - - if (code !== undefined && !isValidStatusCode(code)) { - return null - } - - try { - // TODO: optimize this - reason = new TextDecoder('utf-8', { fatal: true }).decode(reason) - } catch { - return null - } - - return { code, reason } - } - - get closingInfo () { - return this.#info.closeInfo - } -} - -module.exports = { - ByteParser -} - - -/***/ }), - -/***/ 2933: -/***/ ((module) => { - - - -module.exports = { - kWebSocketURL: Symbol('url'), - kReadyState: Symbol('ready state'), - kController: Symbol('controller'), - kResponse: Symbol('response'), - kBinaryType: Symbol('binary type'), - kSentClose: Symbol('sent close'), - kReceivedClose: Symbol('received close'), - kByteParser: Symbol('byte parser') -} - - -/***/ }), - -/***/ 3574: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = __nccwpck_require__(2933) -const { states, opcodes } = __nccwpck_require__(5913) -const { MessageEvent, ErrorEvent } = __nccwpck_require__(6255) - -/* globals Blob */ - -/** - * @param {import('./websocket').WebSocket} ws - */ -function isEstablished (ws) { - // If the server's response is validated as provided for above, it is - // said that _The WebSocket Connection is Established_ and that the - // WebSocket Connection is in the OPEN state. - return ws[kReadyState] === states.OPEN -} - -/** - * @param {import('./websocket').WebSocket} ws - */ -function isClosing (ws) { - // Upon either sending or receiving a Close control frame, it is said - // that _The WebSocket Closing Handshake is Started_ and that the - // WebSocket connection is in the CLOSING state. - return ws[kReadyState] === states.CLOSING -} - -/** - * @param {import('./websocket').WebSocket} ws - */ -function isClosed (ws) { - return ws[kReadyState] === states.CLOSED -} - -/** - * @see https://dom.spec.whatwg.org/#concept-event-fire - * @param {string} e - * @param {EventTarget} target - * @param {EventInit | undefined} eventInitDict - */ -function fireEvent (e, target, eventConstructor = Event, eventInitDict) { - // 1. If eventConstructor is not given, then let eventConstructor be Event. - - // 2. Let event be the result of creating an event given eventConstructor, - // in the relevant realm of target. - // 3. Initialize event’s type attribute to e. - const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap - - // 4. Initialize any other IDL attributes of event as described in the - // invocation of this algorithm. - - // 5. Return the result of dispatching event at target, with legacy target - // override flag set if set. - target.dispatchEvent(event) -} - -/** - * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol - * @param {import('./websocket').WebSocket} ws - * @param {number} type Opcode - * @param {Buffer} data application data - */ -function websocketMessageReceived (ws, type, data) { - // 1. If ready state is not OPEN (1), then return. - if (ws[kReadyState] !== states.OPEN) { - return - } - - // 2. Let dataForEvent be determined by switching on type and binary type: - let dataForEvent - - if (type === opcodes.TEXT) { - // -> type indicates that the data is Text - // a new DOMString containing data - try { - dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data) - } catch { - failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.') - return - } - } else if (type === opcodes.BINARY) { - if (ws[kBinaryType] === 'blob') { - // -> type indicates that the data is Binary and binary type is "blob" - // a new Blob object, created in the relevant Realm of the WebSocket - // object, that represents data as its raw data - dataForEvent = new Blob([data]) - } else { - // -> type indicates that the data is Binary and binary type is "arraybuffer" - // a new ArrayBuffer object, created in the relevant Realm of the - // WebSocket object, whose contents are data - dataForEvent = new Uint8Array(data).buffer - } - } - - // 3. Fire an event named message at the WebSocket object, using MessageEvent, - // with the origin attribute initialized to the serialization of the WebSocket - // object’s url's origin, and the data attribute initialized to dataForEvent. - fireEvent('message', ws, MessageEvent, { - origin: ws[kWebSocketURL].origin, - data: dataForEvent - }) -} - -/** - * @see https://datatracker.ietf.org/doc/html/rfc6455 - * @see https://datatracker.ietf.org/doc/html/rfc2616 - * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407 - * @param {string} protocol - */ -function isValidSubprotocol (protocol) { - // If present, this value indicates one - // or more comma-separated subprotocol the client wishes to speak, - // ordered by preference. The elements that comprise this value - // MUST be non-empty strings with characters in the range U+0021 to - // U+007E not including separator characters as defined in - // [RFC2616] and MUST all be unique strings. - if (protocol.length === 0) { - return false - } - - for (const char of protocol) { - const code = char.charCodeAt(0) - - if ( - code < 0x21 || - code > 0x7E || - char === '(' || - char === ')' || - char === '<' || - char === '>' || - char === '@' || - char === ',' || - char === ';' || - char === ':' || - char === '\\' || - char === '"' || - char === '/' || - char === '[' || - char === ']' || - char === '?' || - char === '=' || - char === '{' || - char === '}' || - code === 32 || // SP - code === 9 // HT - ) { - return false - } - } - - return true -} - -/** - * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4 - * @param {number} code - */ -function isValidStatusCode (code) { - if (code >= 1000 && code < 1015) { - return ( - code !== 1004 && // reserved - code !== 1005 && // "MUST NOT be set as a status code" - code !== 1006 // "MUST NOT be set as a status code" - ) - } - - return code >= 3000 && code <= 4999 -} - -/** - * @param {import('./websocket').WebSocket} ws - * @param {string|undefined} reason - */ -function failWebsocketConnection (ws, reason) { - const { [kController]: controller, [kResponse]: response } = ws - - controller.abort() - - if (response?.socket && !response.socket.destroyed) { - response.socket.destroy() - } - - if (reason) { - fireEvent('error', ws, ErrorEvent, { - error: new Error(reason) - }) - } -} - -module.exports = { - isEstablished, - isClosing, - isClosed, - fireEvent, - isValidSubprotocol, - isValidStatusCode, - failWebsocketConnection, - websocketMessageReceived -} - - -/***/ }), - -/***/ 5171: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const { webidl } = __nccwpck_require__(4222) -const { DOMException } = __nccwpck_require__(7326) -const { URLSerializer } = __nccwpck_require__(4322) -const { getGlobalOrigin } = __nccwpck_require__(5628) -const { staticPropertyDescriptors, states, opcodes, emptyBuffer } = __nccwpck_require__(5913) -const { - kWebSocketURL, - kReadyState, - kController, - kBinaryType, - kResponse, - kSentClose, - kByteParser -} = __nccwpck_require__(2933) -const { isEstablished, isClosing, isValidSubprotocol, failWebsocketConnection, fireEvent } = __nccwpck_require__(3574) -const { establishWebSocketConnection } = __nccwpck_require__(8550) -const { WebsocketFrameSend } = __nccwpck_require__(1237) -const { ByteParser } = __nccwpck_require__(3171) -const { kEnumerableProperty, isBlobLike } = __nccwpck_require__(3440) -const { getGlobalDispatcher } = __nccwpck_require__(2581) -const { types } = __nccwpck_require__(9023) - -let experimentalWarned = false - -// https://websockets.spec.whatwg.org/#interface-definition -class WebSocket extends EventTarget { - #events = { - open: null, - error: null, - close: null, - message: null - } - - #bufferedAmount = 0 - #protocol = '' - #extensions = '' - - /** - * @param {string} url - * @param {string|string[]} protocols - */ - constructor (url, protocols = []) { - super() - - webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket constructor' }) - - if (!experimentalWarned) { - experimentalWarned = true - process.emitWarning('WebSockets are experimental, expect them to change at any time.', { - code: 'UNDICI-WS' - }) - } - - const options = webidl.converters['DOMString or sequence or WebSocketInit'](protocols) - - url = webidl.converters.USVString(url) - protocols = options.protocols - - // 1. Let baseURL be this's relevant settings object's API base URL. - const baseURL = getGlobalOrigin() - - // 1. Let urlRecord be the result of applying the URL parser to url with baseURL. - let urlRecord - - try { - urlRecord = new URL(url, baseURL) - } catch (e) { - // 3. If urlRecord is failure, then throw a "SyntaxError" DOMException. - throw new DOMException(e, 'SyntaxError') - } - - // 4. If urlRecord’s scheme is "http", then set urlRecord’s scheme to "ws". - if (urlRecord.protocol === 'http:') { - urlRecord.protocol = 'ws:' - } else if (urlRecord.protocol === 'https:') { - // 5. Otherwise, if urlRecord’s scheme is "https", set urlRecord’s scheme to "wss". - urlRecord.protocol = 'wss:' - } - - // 6. If urlRecord’s scheme is not "ws" or "wss", then throw a "SyntaxError" DOMException. - if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') { - throw new DOMException( - `Expected a ws: or wss: protocol, got ${urlRecord.protocol}`, - 'SyntaxError' - ) - } - - // 7. If urlRecord’s fragment is non-null, then throw a "SyntaxError" - // DOMException. - if (urlRecord.hash || urlRecord.href.endsWith('#')) { - throw new DOMException('Got fragment', 'SyntaxError') - } - - // 8. If protocols is a string, set protocols to a sequence consisting - // of just that string. - if (typeof protocols === 'string') { - protocols = [protocols] - } - - // 9. If any of the values in protocols occur more than once or otherwise - // fail to match the requirements for elements that comprise the value - // of `Sec-WebSocket-Protocol` fields as defined by The WebSocket - // protocol, then throw a "SyntaxError" DOMException. - if (protocols.length !== new Set(protocols.map(p => p.toLowerCase())).size) { - throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') - } - - if (protocols.length > 0 && !protocols.every(p => isValidSubprotocol(p))) { - throw new DOMException('Invalid Sec-WebSocket-Protocol value', 'SyntaxError') - } - - // 10. Set this's url to urlRecord. - this[kWebSocketURL] = new URL(urlRecord.href) - - // 11. Let client be this's relevant settings object. - - // 12. Run this step in parallel: - - // 1. Establish a WebSocket connection given urlRecord, protocols, - // and client. - this[kController] = establishWebSocketConnection( - urlRecord, - protocols, - this, - (response) => this.#onConnectionEstablished(response), - options - ) - - // Each WebSocket object has an associated ready state, which is a - // number representing the state of the connection. Initially it must - // be CONNECTING (0). - this[kReadyState] = WebSocket.CONNECTING - - // The extensions attribute must initially return the empty string. - - // The protocol attribute must initially return the empty string. - - // Each WebSocket object has an associated binary type, which is a - // BinaryType. Initially it must be "blob". - this[kBinaryType] = 'blob' - } - - /** - * @see https://websockets.spec.whatwg.org/#dom-websocket-close - * @param {number|undefined} code - * @param {string|undefined} reason - */ - close (code = undefined, reason = undefined) { - webidl.brandCheck(this, WebSocket) - - if (code !== undefined) { - code = webidl.converters['unsigned short'](code, { clamp: true }) - } - - if (reason !== undefined) { - reason = webidl.converters.USVString(reason) - } - - // 1. If code is present, but is neither an integer equal to 1000 nor an - // integer in the range 3000 to 4999, inclusive, throw an - // "InvalidAccessError" DOMException. - if (code !== undefined) { - if (code !== 1000 && (code < 3000 || code > 4999)) { - throw new DOMException('invalid code', 'InvalidAccessError') - } - } - - let reasonByteLength = 0 - - // 2. If reason is present, then run these substeps: - if (reason !== undefined) { - // 1. Let reasonBytes be the result of encoding reason. - // 2. If reasonBytes is longer than 123 bytes, then throw a - // "SyntaxError" DOMException. - reasonByteLength = Buffer.byteLength(reason) - - if (reasonByteLength > 123) { - throw new DOMException( - `Reason must be less than 123 bytes; received ${reasonByteLength}`, - 'SyntaxError' - ) - } - } - - // 3. Run the first matching steps from the following list: - if (this[kReadyState] === WebSocket.CLOSING || this[kReadyState] === WebSocket.CLOSED) { - // If this's ready state is CLOSING (2) or CLOSED (3) - // Do nothing. - } else if (!isEstablished(this)) { - // If the WebSocket connection is not yet established - // Fail the WebSocket connection and set this's ready state - // to CLOSING (2). - failWebsocketConnection(this, 'Connection was closed before it was established.') - this[kReadyState] = WebSocket.CLOSING - } else if (!isClosing(this)) { - // If the WebSocket closing handshake has not yet been started - // Start the WebSocket closing handshake and set this's ready - // state to CLOSING (2). - // - If neither code nor reason is present, the WebSocket Close - // message must not have a body. - // - If code is present, then the status code to use in the - // WebSocket Close message must be the integer given by code. - // - If reason is also present, then reasonBytes must be - // provided in the Close message after the status code. - - const frame = new WebsocketFrameSend() - - // If neither code nor reason is present, the WebSocket Close - // message must not have a body. - - // If code is present, then the status code to use in the - // WebSocket Close message must be the integer given by code. - if (code !== undefined && reason === undefined) { - frame.frameData = Buffer.allocUnsafe(2) - frame.frameData.writeUInt16BE(code, 0) - } else if (code !== undefined && reason !== undefined) { - // If reason is also present, then reasonBytes must be - // provided in the Close message after the status code. - frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength) - frame.frameData.writeUInt16BE(code, 0) - // the body MAY contain UTF-8-encoded data with value /reason/ - frame.frameData.write(reason, 2, 'utf-8') - } else { - frame.frameData = emptyBuffer - } - - /** @type {import('stream').Duplex} */ - const socket = this[kResponse].socket - - socket.write(frame.createFrame(opcodes.CLOSE), (err) => { - if (!err) { - this[kSentClose] = true - } - }) - - // Upon either sending or receiving a Close control frame, it is said - // that _The WebSocket Closing Handshake is Started_ and that the - // WebSocket connection is in the CLOSING state. - this[kReadyState] = states.CLOSING - } else { - // Otherwise - // Set this's ready state to CLOSING (2). - this[kReadyState] = WebSocket.CLOSING - } - } - - /** - * @see https://websockets.spec.whatwg.org/#dom-websocket-send - * @param {NodeJS.TypedArray|ArrayBuffer|Blob|string} data - */ - send (data) { - webidl.brandCheck(this, WebSocket) - - webidl.argumentLengthCheck(arguments, 1, { header: 'WebSocket.send' }) - - data = webidl.converters.WebSocketSendData(data) - - // 1. If this's ready state is CONNECTING, then throw an - // "InvalidStateError" DOMException. - if (this[kReadyState] === WebSocket.CONNECTING) { - throw new DOMException('Sent before connected.', 'InvalidStateError') - } - - // 2. Run the appropriate set of steps from the following list: - // https://datatracker.ietf.org/doc/html/rfc6455#section-6.1 - // https://datatracker.ietf.org/doc/html/rfc6455#section-5.2 - - if (!isEstablished(this) || isClosing(this)) { - return - } - - /** @type {import('stream').Duplex} */ - const socket = this[kResponse].socket - - // If data is a string - if (typeof data === 'string') { - // If the WebSocket connection is established and the WebSocket - // closing handshake has not yet started, then the user agent - // must send a WebSocket Message comprised of the data argument - // using a text frame opcode; if the data cannot be sent, e.g. - // because it would need to be buffered but the buffer is full, - // the user agent must flag the WebSocket as full and then close - // the WebSocket connection. Any invocation of this method with a - // string argument that does not throw an exception must increase - // the bufferedAmount attribute by the number of bytes needed to - // express the argument as UTF-8. - - const value = Buffer.from(data) - const frame = new WebsocketFrameSend(value) - const buffer = frame.createFrame(opcodes.TEXT) - - this.#bufferedAmount += value.byteLength - socket.write(buffer, () => { - this.#bufferedAmount -= value.byteLength - }) - } else if (types.isArrayBuffer(data)) { - // If the WebSocket connection is established, and the WebSocket - // closing handshake has not yet started, then the user agent must - // send a WebSocket Message comprised of data using a binary frame - // opcode; if the data cannot be sent, e.g. because it would need - // to be buffered but the buffer is full, the user agent must flag - // the WebSocket as full and then close the WebSocket connection. - // The data to be sent is the data stored in the buffer described - // by the ArrayBuffer object. Any invocation of this method with an - // ArrayBuffer argument that does not throw an exception must - // increase the bufferedAmount attribute by the length of the - // ArrayBuffer in bytes. - - const value = Buffer.from(data) - const frame = new WebsocketFrameSend(value) - const buffer = frame.createFrame(opcodes.BINARY) - - this.#bufferedAmount += value.byteLength - socket.write(buffer, () => { - this.#bufferedAmount -= value.byteLength - }) - } else if (ArrayBuffer.isView(data)) { - // If the WebSocket connection is established, and the WebSocket - // closing handshake has not yet started, then the user agent must - // send a WebSocket Message comprised of data using a binary frame - // opcode; if the data cannot be sent, e.g. because it would need to - // be buffered but the buffer is full, the user agent must flag the - // WebSocket as full and then close the WebSocket connection. The - // data to be sent is the data stored in the section of the buffer - // described by the ArrayBuffer object that data references. Any - // invocation of this method with this kind of argument that does - // not throw an exception must increase the bufferedAmount attribute - // by the length of data’s buffer in bytes. - - const ab = Buffer.from(data, data.byteOffset, data.byteLength) - - const frame = new WebsocketFrameSend(ab) - const buffer = frame.createFrame(opcodes.BINARY) - - this.#bufferedAmount += ab.byteLength - socket.write(buffer, () => { - this.#bufferedAmount -= ab.byteLength - }) - } else if (isBlobLike(data)) { - // If the WebSocket connection is established, and the WebSocket - // closing handshake has not yet started, then the user agent must - // send a WebSocket Message comprised of data using a binary frame - // opcode; if the data cannot be sent, e.g. because it would need to - // be buffered but the buffer is full, the user agent must flag the - // WebSocket as full and then close the WebSocket connection. The data - // to be sent is the raw data represented by the Blob object. Any - // invocation of this method with a Blob argument that does not throw - // an exception must increase the bufferedAmount attribute by the size - // of the Blob object’s raw data, in bytes. - - const frame = new WebsocketFrameSend() - - data.arrayBuffer().then((ab) => { - const value = Buffer.from(ab) - frame.frameData = value - const buffer = frame.createFrame(opcodes.BINARY) - - this.#bufferedAmount += value.byteLength - socket.write(buffer, () => { - this.#bufferedAmount -= value.byteLength - }) - }) - } - } - - get readyState () { - webidl.brandCheck(this, WebSocket) - - // The readyState getter steps are to return this's ready state. - return this[kReadyState] - } - - get bufferedAmount () { - webidl.brandCheck(this, WebSocket) - - return this.#bufferedAmount - } - - get url () { - webidl.brandCheck(this, WebSocket) - - // The url getter steps are to return this's url, serialized. - return URLSerializer(this[kWebSocketURL]) - } - - get extensions () { - webidl.brandCheck(this, WebSocket) - - return this.#extensions - } - - get protocol () { - webidl.brandCheck(this, WebSocket) - - return this.#protocol - } - - get onopen () { - webidl.brandCheck(this, WebSocket) - - return this.#events.open - } - - set onopen (fn) { - webidl.brandCheck(this, WebSocket) - - if (this.#events.open) { - this.removeEventListener('open', this.#events.open) - } - - if (typeof fn === 'function') { - this.#events.open = fn - this.addEventListener('open', fn) - } else { - this.#events.open = null - } - } - - get onerror () { - webidl.brandCheck(this, WebSocket) - - return this.#events.error - } - - set onerror (fn) { - webidl.brandCheck(this, WebSocket) - - if (this.#events.error) { - this.removeEventListener('error', this.#events.error) - } - - if (typeof fn === 'function') { - this.#events.error = fn - this.addEventListener('error', fn) - } else { - this.#events.error = null - } - } - - get onclose () { - webidl.brandCheck(this, WebSocket) - - return this.#events.close - } - - set onclose (fn) { - webidl.brandCheck(this, WebSocket) - - if (this.#events.close) { - this.removeEventListener('close', this.#events.close) - } - - if (typeof fn === 'function') { - this.#events.close = fn - this.addEventListener('close', fn) - } else { - this.#events.close = null - } - } - - get onmessage () { - webidl.brandCheck(this, WebSocket) - - return this.#events.message - } - - set onmessage (fn) { - webidl.brandCheck(this, WebSocket) - - if (this.#events.message) { - this.removeEventListener('message', this.#events.message) - } - - if (typeof fn === 'function') { - this.#events.message = fn - this.addEventListener('message', fn) - } else { - this.#events.message = null - } - } - - get binaryType () { - webidl.brandCheck(this, WebSocket) - - return this[kBinaryType] - } - - set binaryType (type) { - webidl.brandCheck(this, WebSocket) - - if (type !== 'blob' && type !== 'arraybuffer') { - this[kBinaryType] = 'blob' - } else { - this[kBinaryType] = type - } - } - - /** - * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol - */ - #onConnectionEstablished (response) { - // processResponse is called when the "response’s header list has been received and initialized." - // once this happens, the connection is open - this[kResponse] = response - - const parser = new ByteParser(this) - parser.on('drain', function onParserDrain () { - this.ws[kResponse].socket.resume() - }) - - response.socket.ws = this - this[kByteParser] = parser - - // 1. Change the ready state to OPEN (1). - this[kReadyState] = states.OPEN - - // 2. Change the extensions attribute’s value to the extensions in use, if - // it is not the null value. - // https://datatracker.ietf.org/doc/html/rfc6455#section-9.1 - const extensions = response.headersList.get('sec-websocket-extensions') - - if (extensions !== null) { - this.#extensions = extensions - } - - // 3. Change the protocol attribute’s value to the subprotocol in use, if - // it is not the null value. - // https://datatracker.ietf.org/doc/html/rfc6455#section-1.9 - const protocol = response.headersList.get('sec-websocket-protocol') - - if (protocol !== null) { - this.#protocol = protocol - } - - // 4. Fire an event named open at the WebSocket object. - fireEvent('open', this) - } -} - -// https://websockets.spec.whatwg.org/#dom-websocket-connecting -WebSocket.CONNECTING = WebSocket.prototype.CONNECTING = states.CONNECTING -// https://websockets.spec.whatwg.org/#dom-websocket-open -WebSocket.OPEN = WebSocket.prototype.OPEN = states.OPEN -// https://websockets.spec.whatwg.org/#dom-websocket-closing -WebSocket.CLOSING = WebSocket.prototype.CLOSING = states.CLOSING -// https://websockets.spec.whatwg.org/#dom-websocket-closed -WebSocket.CLOSED = WebSocket.prototype.CLOSED = states.CLOSED - -Object.defineProperties(WebSocket.prototype, { - CONNECTING: staticPropertyDescriptors, - OPEN: staticPropertyDescriptors, - CLOSING: staticPropertyDescriptors, - CLOSED: staticPropertyDescriptors, - url: kEnumerableProperty, - readyState: kEnumerableProperty, - bufferedAmount: kEnumerableProperty, - onopen: kEnumerableProperty, - onerror: kEnumerableProperty, - onclose: kEnumerableProperty, - close: kEnumerableProperty, - onmessage: kEnumerableProperty, - binaryType: kEnumerableProperty, - send: kEnumerableProperty, - extensions: kEnumerableProperty, - protocol: kEnumerableProperty, - [Symbol.toStringTag]: { - value: 'WebSocket', - writable: false, - enumerable: false, - configurable: true - } -}) - -Object.defineProperties(WebSocket, { - CONNECTING: staticPropertyDescriptors, - OPEN: staticPropertyDescriptors, - CLOSING: staticPropertyDescriptors, - CLOSED: staticPropertyDescriptors -}) - -webidl.converters['sequence'] = webidl.sequenceConverter( - webidl.converters.DOMString -) - -webidl.converters['DOMString or sequence'] = function (V) { - if (webidl.util.Type(V) === 'Object' && Symbol.iterator in V) { - return webidl.converters['sequence'](V) - } - - return webidl.converters.DOMString(V) -} - -// This implements the propsal made in https://github.com/whatwg/websockets/issues/42 -webidl.converters.WebSocketInit = webidl.dictionaryConverter([ - { - key: 'protocols', - converter: webidl.converters['DOMString or sequence'], - get defaultValue () { - return [] - } - }, - { - key: 'dispatcher', - converter: (V) => V, - get defaultValue () { - return getGlobalDispatcher() - } - }, - { - key: 'headers', - converter: webidl.nullableConverter(webidl.converters.HeadersInit) - } -]) - -webidl.converters['DOMString or sequence or WebSocketInit'] = function (V) { - if (webidl.util.Type(V) === 'Object' && !(Symbol.iterator in V)) { - return webidl.converters.WebSocketInit(V) - } - - return { protocols: webidl.converters['DOMString or sequence'](V) } -} - -webidl.converters.WebSocketSendData = function (V) { - if (webidl.util.Type(V) === 'Object') { - if (isBlobLike(V)) { - return webidl.converters.Blob(V, { strict: false }) - } - - if (ArrayBuffer.isView(V) || types.isAnyArrayBuffer(V)) { - return webidl.converters.BufferSource(V) - } - } - - return webidl.converters.USVString(V) -} - -module.exports = { - WebSocket -} - - -/***/ }), - -/***/ 3843: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ value: true })); - -function getUserAgent() { - if (typeof navigator === "object" && "userAgent" in navigator) { - return navigator.userAgent; - } - - if (typeof process === "object" && process.version !== undefined) { - return `Node.js/${process.version.substr(1)} (${process.platform}; ${process.arch})`; - } - - return ""; -} - -exports.getUserAgent = getUserAgent; -//# sourceMappingURL=index.js.map - - -/***/ }), - -/***/ 2048: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - -var __webpack_unused_export__; - - -__webpack_unused_export__ = ({ - value: true -}); -Object.defineProperty(exports, "Zu", ({ - enumerable: true, - get: function () { - return _max.default; - } -})); -Object.defineProperty(exports, "wD", ({ - enumerable: true, - get: function () { - return _nil.default; - } -})); -Object.defineProperty(exports, "qg", ({ - enumerable: true, - get: function () { - return _parse.default; - } -})); -Object.defineProperty(exports, "As", ({ - enumerable: true, - get: function () { - return _stringify.default; - } -})); -Object.defineProperty(exports, "v1", ({ - enumerable: true, - get: function () { - return _v.default; - } -})); -Object.defineProperty(exports, "bV", ({ - enumerable: true, - get: function () { - return _v1ToV.default; - } -})); -Object.defineProperty(exports, "v3", ({ - enumerable: true, - get: function () { - return _v2.default; - } -})); -Object.defineProperty(exports, "v4", ({ - enumerable: true, - get: function () { - return _v3.default; - } -})); -Object.defineProperty(exports, "v5", ({ - enumerable: true, - get: function () { - return _v4.default; - } -})); -Object.defineProperty(exports, "v6", ({ - enumerable: true, - get: function () { - return _v5.default; - } -})); -Object.defineProperty(exports, "JE", ({ - enumerable: true, - get: function () { - return _v6ToV.default; - } -})); -Object.defineProperty(exports, "v7", ({ - enumerable: true, - get: function () { - return _v6.default; - } -})); -Object.defineProperty(exports, "tf", ({ - enumerable: true, - get: function () { - return _validate.default; - } -})); -Object.defineProperty(exports, "rE", ({ - enumerable: true, - get: function () { - return _version.default; - } -})); -var _max = _interopRequireDefault(__nccwpck_require__(242)); -var _nil = _interopRequireDefault(__nccwpck_require__(7723)); -var _parse = _interopRequireDefault(__nccwpck_require__(7267)); -var _stringify = _interopRequireDefault(__nccwpck_require__(7597)); -var _v = _interopRequireDefault(__nccwpck_require__(6415)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(9706)); -var _v2 = _interopRequireDefault(__nccwpck_require__(1697)); -var _v3 = _interopRequireDefault(__nccwpck_require__(4676)); -var _v4 = _interopRequireDefault(__nccwpck_require__(9771)); -var _v5 = _interopRequireDefault(__nccwpck_require__(8558)); -var _v6ToV = _interopRequireDefault(__nccwpck_require__(9558)); -var _v6 = _interopRequireDefault(__nccwpck_require__(9261)); -var _validate = _interopRequireDefault(__nccwpck_require__(6200)); -var _version = _interopRequireDefault(__nccwpck_require__(5868)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } - -/***/ }), - -/***/ 242: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = 'ffffffff-ffff-ffff-ffff-ffffffffffff'; - -/***/ }), - -/***/ 216: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function md5(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('md5').update(bytes).digest(); -} -var _default = exports["default"] = md5; - -/***/ }), - -/***/ 4221: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -var _default = exports["default"] = { - randomUUID: _nodeCrypto.default.randomUUID -}; - -/***/ }), - -/***/ 7723: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = '00000000-0000-0000-0000-000000000000'; - -/***/ }), - -/***/ 7267: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(6200)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function parse(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - let v; - const arr = new Uint8Array(16); - - // Parse ########-....-....-....-............ - arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24; - arr[1] = v >>> 16 & 0xff; - arr[2] = v >>> 8 & 0xff; - arr[3] = v & 0xff; - - // Parse ........-####-....-....-............ - arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8; - arr[5] = v & 0xff; - - // Parse ........-....-####-....-............ - arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8; - arr[7] = v & 0xff; - - // Parse ........-....-....-####-............ - arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8; - arr[9] = v & 0xff; - - // Parse ........-....-....-....-############ - // (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes) - arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff; - arr[11] = v / 0x100000000 & 0xff; - arr[12] = v >>> 24 & 0xff; - arr[13] = v >>> 16 & 0xff; - arr[14] = v >>> 8 & 0xff; - arr[15] = v & 0xff; - return arr; -} -var _default = exports["default"] = parse; - -/***/ }), - -/***/ 7879: -/***/ ((__unused_webpack_module, exports) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _default = exports["default"] = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i; - -/***/ }), - -/***/ 2973: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = rng; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate -let poolPtr = rnds8Pool.length; -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - _nodeCrypto.default.randomFillSync(rnds8Pool); - poolPtr = 0; - } - return rnds8Pool.slice(poolPtr, poolPtr += 16); -} - -/***/ }), - -/***/ 507: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _nodeCrypto = _interopRequireDefault(__nccwpck_require__(7598)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function sha1(bytes) { - if (Array.isArray(bytes)) { - bytes = Buffer.from(bytes); - } else if (typeof bytes === 'string') { - bytes = Buffer.from(bytes, 'utf8'); - } - return _nodeCrypto.default.createHash('sha1').update(bytes).digest(); -} -var _default = exports["default"] = sha1; - -/***/ }), - -/***/ 7597: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -exports.unsafeStringify = unsafeStringify; -var _validate = _interopRequireDefault(__nccwpck_require__(6200)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert array of 16 byte values to UUID string format of the form: - * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX - */ -const byteToHex = []; -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} -function unsafeStringify(arr, offset = 0) { - // Note: Be careful editing this code! It's been tuned for performance - // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434 - // - // Note to future-self: No, you can't remove the `toLowerCase()` call. - // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351 - return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase(); -} -function stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); - // Consistency check for valid UUID. If this throws, it's likely due to one - // of the following: - // - One or more input array values don't map to a hex octet (leading to - // "undefined" in the uuid) - // - Invalid input values for the RFC `version` or `variant` fields - if (!(0, _validate.default)(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - return uuid; -} -var _default = exports["default"] = stringify; - -/***/ }), - -/***/ 6415: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(2973)); -var _stringify = __nccwpck_require__(7597); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -// **`v1()` - Generate time-based UUID** -// -// Inspired by https://github.com/LiosK/UUID.js -// and http://docs.python.org/library/uuid.html - -let _nodeId; -let _clockseq; - -// Previous uuid creation time -let _lastMSecs = 0; -let _lastNSecs = 0; - -// See https://github.com/uuidjs/uuid for API details -function v1(options, buf, offset) { - let i = buf && offset || 0; - const b = buf || new Array(16); - options = options || {}; - let node = options.node; - let clockseq = options.clockseq; - - // v1 only: Use cached `node` and `clockseq` values - if (!options._v6) { - if (!node) { - node = _nodeId; - } - if (clockseq == null) { - clockseq = _clockseq; - } - } - - // Handle cases where we need entropy. We do this lazily to minimize issues - // related to insufficient system entropy. See #189 - if (node == null || clockseq == null) { - const seedBytes = options.random || (options.rng || _rng.default)(); - - // Randomize node - if (node == null) { - node = [seedBytes[0], seedBytes[1], seedBytes[2], seedBytes[3], seedBytes[4], seedBytes[5]]; - - // v1 only: cache node value for reuse - if (!_nodeId && !options._v6) { - // per RFC4122 4.5: Set MAC multicast bit (v1 only) - node[0] |= 0x01; // Set multicast bit - - _nodeId = node; - } - } - - // Randomize clockseq - if (clockseq == null) { - // Per 4.2.2, randomize (14 bit) clockseq - clockseq = (seedBytes[6] << 8 | seedBytes[7]) & 0x3fff; - if (_clockseq === undefined && !options._v6) { - _clockseq = clockseq; - } - } - } - - // v1 & v6 timestamps are 100 nano-second units since the Gregorian epoch, - // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so time is - // handled internally as 'msecs' (integer milliseconds) and 'nsecs' - // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. - let msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // Per 4.2.1.2, use count of uuid's generated during the current clock - // cycle to simulate higher resolution clock - let nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; - - // Time since last uuid creation (in msecs) - const dt = msecs - _lastMSecs + (nsecs - _lastNSecs) / 10000; - - // Per 4.2.1.2, Bump clockseq on clock regression - if (dt < 0 && options.clockseq === undefined) { - clockseq = clockseq + 1 & 0x3fff; - } - - // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new - // time interval - if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { - nsecs = 0; - } - - // Per 4.2.1.2 Throw error if too many uuids are requested - if (nsecs >= 10000) { - throw new Error("uuid.v1(): Can't create more than 10M uuids/sec"); - } - _lastMSecs = msecs; - _lastNSecs = nsecs; - _clockseq = clockseq; - - // Per 4.1.4 - Convert from unix epoch to Gregorian epoch - msecs += 12219292800000; - - // `time_low` - const tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; - b[i++] = tl >>> 24 & 0xff; - b[i++] = tl >>> 16 & 0xff; - b[i++] = tl >>> 8 & 0xff; - b[i++] = tl & 0xff; - - // `time_mid` - const tmh = msecs / 0x100000000 * 10000 & 0xfffffff; - b[i++] = tmh >>> 8 & 0xff; - b[i++] = tmh & 0xff; - - // `time_high_and_version` - b[i++] = tmh >>> 24 & 0xf | 0x10; // include version - b[i++] = tmh >>> 16 & 0xff; - - // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) - b[i++] = clockseq >>> 8 | 0x80; - - // `clock_seq_low` - b[i++] = clockseq & 0xff; - - // `node` - for (let n = 0; n < 6; ++n) { - b[i + n] = node[n]; - } - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v1; - -/***/ }), - -/***/ 9706: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v1ToV6; -var _parse = _interopRequireDefault(__nccwpck_require__(7267)); -var _stringify = __nccwpck_require__(7597); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v1 UUID to a v6 UUID - * - * @param {string|Uint8Array} uuid - The v1 UUID to convert to v6 - * @returns {string|Uint8Array} The v6 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v1ToV6(uuid) { - const v1Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v6Bytes = _v1ToV6(v1Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v6Bytes) : v6Bytes; -} - -// Do the field transformation needed for v1 -> v6 -function _v1ToV6(v1Bytes, randomize = false) { - return Uint8Array.of((v1Bytes[6] & 0x0f) << 4 | v1Bytes[7] >> 4 & 0x0f, (v1Bytes[7] & 0x0f) << 4 | (v1Bytes[4] & 0xf0) >> 4, (v1Bytes[4] & 0x0f) << 4 | (v1Bytes[5] & 0xf0) >> 4, (v1Bytes[5] & 0x0f) << 4 | (v1Bytes[0] & 0xf0) >> 4, (v1Bytes[0] & 0x0f) << 4 | (v1Bytes[1] & 0xf0) >> 4, (v1Bytes[1] & 0x0f) << 4 | (v1Bytes[2] & 0xf0) >> 4, 0x60 | v1Bytes[2] & 0x0f, v1Bytes[3], v1Bytes[8], v1Bytes[9], v1Bytes[10], v1Bytes[11], v1Bytes[12], v1Bytes[13], v1Bytes[14], v1Bytes[15]); -} - -/***/ }), - -/***/ 1697: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(2930)); -var _md = _interopRequireDefault(__nccwpck_require__(216)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v3 = (0, _v.default)('v3', 0x30, _md.default); -var _default = exports["default"] = v3; - -/***/ }), - -/***/ 2930: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports.URL = exports.DNS = void 0; -exports["default"] = v35; -var _stringify = __nccwpck_require__(7597); -var _parse = _interopRequireDefault(__nccwpck_require__(7267)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function stringToBytes(str) { - str = unescape(encodeURIComponent(str)); // UTF8 escape - - const bytes = []; - for (let i = 0; i < str.length; ++i) { - bytes.push(str.charCodeAt(i)); - } - return bytes; -} -const DNS = exports.DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8'; -const URL = exports.URL = '6ba7b811-9dad-11d1-80b4-00c04fd430c8'; -function v35(name, version, hashfunc) { - function generateUUID(value, namespace, buf, offset) { - var _namespace; - if (typeof value === 'string') { - value = stringToBytes(value); - } - if (typeof namespace === 'string') { - namespace = (0, _parse.default)(namespace); - } - if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) { - throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)'); - } - - // Compute hash of namespace and value, Per 4.3 - // Future: Use spread syntax when supported on all platforms, e.g. `bytes = - // hashfunc([...namespace, ... value])` - let bytes = new Uint8Array(16 + value.length); - bytes.set(namespace); - bytes.set(value, namespace.length); - bytes = hashfunc(bytes); - bytes[6] = bytes[6] & 0x0f | version; - bytes[8] = bytes[8] & 0x3f | 0x80; - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); - } - - // Function#name is not settable on some platforms (#270) - try { - generateUUID.name = name; - } catch (err) {} - - // For CommonJS default export support - generateUUID.DNS = DNS; - generateUUID.URL = URL; - return generateUUID; -} - -/***/ }), - -/***/ 4676: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _native = _interopRequireDefault(__nccwpck_require__(4221)); -var _rng = _interopRequireDefault(__nccwpck_require__(2973)); -var _stringify = __nccwpck_require__(7597); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function v4(options, buf, offset) { - if (_native.default.randomUUID && !buf && !options) { - return _native.default.randomUUID(); - } - options = options || {}; - const rnds = options.random || (options.rng || _rng.default)(); - - // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` - rnds[6] = rnds[6] & 0x0f | 0x40; - rnds[8] = rnds[8] & 0x3f | 0x80; - - // Copy bytes to buffer, if provided - if (buf) { - offset = offset || 0; - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(rnds); -} -var _default = exports["default"] = v4; - -/***/ }), - -/***/ 9771: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _v = _interopRequireDefault(__nccwpck_require__(2930)); -var _sha = _interopRequireDefault(__nccwpck_require__(507)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -const v5 = (0, _v.default)('v5', 0x50, _sha.default); -var _default = exports["default"] = v5; - -/***/ }), - -/***/ 8558: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6; -var _stringify = __nccwpck_require__(7597); -var _v = _interopRequireDefault(__nccwpck_require__(6415)); -var _v1ToV = _interopRequireDefault(__nccwpck_require__(9706)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * - * @param {object} options - * @param {Uint8Array=} buf - * @param {number=} offset - * @returns - */ -function v6(options = {}, buf, offset = 0) { - // v6 is v1 with different field layout, so we start with a v1 UUID, albeit - // with slightly different behavior around how the clock_seq and node fields - // are randomized, which is why we call v1 with _v6: true. - let bytes = (0, _v.default)({ - ...options, - _v6: true - }, new Uint8Array(16)); - - // Reorder the fields to v6 layout. - bytes = (0, _v1ToV.default)(bytes); - - // Return as a byte array if requested - if (buf) { - for (let i = 0; i < 16; i++) { - buf[offset + i] = bytes[i]; - } - return buf; - } - return (0, _stringify.unsafeStringify)(bytes); -} - -/***/ }), - -/***/ 9558: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = v6ToV1; -var _parse = _interopRequireDefault(__nccwpck_require__(7267)); -var _stringify = __nccwpck_require__(7597); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * Convert a v6 UUID to a v1 UUID - * - * @param {string|Uint8Array} uuid - The v6 UUID to convert to v6 - * @returns {string|Uint8Array} The v1 UUID as the same type as the `uuid` arg - * (string or Uint8Array) - */ -function v6ToV1(uuid) { - const v6Bytes = typeof uuid === 'string' ? (0, _parse.default)(uuid) : uuid; - const v1Bytes = _v6ToV1(v6Bytes); - return typeof uuid === 'string' ? (0, _stringify.unsafeStringify)(v1Bytes) : v1Bytes; -} - -// Do the field transformation needed for v6 -> v1 -function _v6ToV1(v6Bytes) { - return Uint8Array.of((v6Bytes[3] & 0x0f) << 4 | v6Bytes[4] >> 4 & 0x0f, (v6Bytes[4] & 0x0f) << 4 | (v6Bytes[5] & 0xf0) >> 4, (v6Bytes[5] & 0x0f) << 4 | v6Bytes[6] & 0x0f, v6Bytes[7], (v6Bytes[1] & 0x0f) << 4 | (v6Bytes[2] & 0xf0) >> 4, (v6Bytes[2] & 0x0f) << 4 | (v6Bytes[3] & 0xf0) >> 4, 0x10 | (v6Bytes[0] & 0xf0) >> 4, (v6Bytes[0] & 0x0f) << 4 | (v6Bytes[1] & 0xf0) >> 4, v6Bytes[8], v6Bytes[9], v6Bytes[10], v6Bytes[11], v6Bytes[12], v6Bytes[13], v6Bytes[14], v6Bytes[15]); -} - -/***/ }), - -/***/ 9261: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _rng = _interopRequireDefault(__nccwpck_require__(2973)); -var _stringify = __nccwpck_require__(7597); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -/** - * UUID V7 - Unix Epoch time-based UUID - * - * The IETF has published RFC9562, introducing 3 new UUID versions (6,7,8). This - * implementation of V7 is based on the accepted, though not yet approved, - * revisions. - * - * RFC 9562:https://www.rfc-editor.org/rfc/rfc9562.html Universally Unique - * IDentifiers (UUIDs) - - * - * Sample V7 value: - * https://www.rfc-editor.org/rfc/rfc9562.html#name-example-of-a-uuidv7-value - * - * Monotonic Bit Layout: RFC rfc9562.6.2 Method 1, Dedicated Counter Bits ref: - * https://www.rfc-editor.org/rfc/rfc9562.html#section-6.2-5.1 - * - * 0 1 2 3 0 1 2 3 4 5 6 - * 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | unix_ts_ms | ver | seq_hi | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * |var| seq_low | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * | rand | - * +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+ - * - * seq is a 31 bit serialized counter; comprised of 12 bit seq_hi and 19 bit - * seq_low, and randomly initialized upon timestamp change. 31 bit counter size - * was selected as any bitwise operations in node are done as _signed_ 32 bit - * ints. we exclude the sign bit. - */ - -let _seqLow = null; -let _seqHigh = null; -let _msecs = 0; -function v7(options, buf, offset) { - options = options || {}; - - // initialize buffer and pointer - let i = buf && offset || 0; - const b = buf || new Uint8Array(16); - - // rnds is Uint8Array(16) filled with random bytes - const rnds = options.random || (options.rng || _rng.default)(); - - // milliseconds since unix epoch, 1970-01-01 00:00 - const msecs = options.msecs !== undefined ? options.msecs : Date.now(); - - // seq is user provided 31 bit counter - let seq = options.seq !== undefined ? options.seq : null; - - // initialize local seq high/low parts - let seqHigh = _seqHigh; - let seqLow = _seqLow; - - // check if clock has advanced and user has not provided msecs - if (msecs > _msecs && options.msecs === undefined) { - _msecs = msecs; - - // unless user provided seq, reset seq parts - if (seq !== null) { - seqHigh = null; - seqLow = null; - } - } - - // if we have a user provided seq - if (seq !== null) { - // trim provided seq to 31 bits of value, avoiding overflow - if (seq > 0x7fffffff) { - seq = 0x7fffffff; - } - - // split provided seq into high/low parts - seqHigh = seq >>> 19 & 0xfff; - seqLow = seq & 0x7ffff; - } - - // randomly initialize seq - if (seqHigh === null || seqLow === null) { - seqHigh = rnds[6] & 0x7f; - seqHigh = seqHigh << 8 | rnds[7]; - seqLow = rnds[8] & 0x3f; // pad for var - seqLow = seqLow << 8 | rnds[9]; - seqLow = seqLow << 5 | rnds[10] >>> 3; - } - - // increment seq if within msecs window - if (msecs + 10000 > _msecs && seq === null) { - if (++seqLow > 0x7ffff) { - seqLow = 0; - if (++seqHigh > 0xfff) { - seqHigh = 0; - - // increment internal _msecs. this allows us to continue incrementing - // while staying monotonic. Note, once we hit 10k milliseconds beyond system - // clock, we will reset breaking monotonicity (after (2^31)*10000 generations) - _msecs++; - } - } - } else { - // resetting; we have advanced more than - // 10k milliseconds beyond system clock - _msecs = msecs; - } - _seqHigh = seqHigh; - _seqLow = seqLow; - - // [bytes 0-5] 48 bits of local timestamp - b[i++] = _msecs / 0x10000000000 & 0xff; - b[i++] = _msecs / 0x100000000 & 0xff; - b[i++] = _msecs / 0x1000000 & 0xff; - b[i++] = _msecs / 0x10000 & 0xff; - b[i++] = _msecs / 0x100 & 0xff; - b[i++] = _msecs & 0xff; - - // [byte 6] - set 4 bits of version (7) with first 4 bits seq_hi - b[i++] = seqHigh >>> 4 & 0x0f | 0x70; - - // [byte 7] remaining 8 bits of seq_hi - b[i++] = seqHigh & 0xff; - - // [byte 8] - variant (2 bits), first 6 bits seq_low - b[i++] = seqLow >>> 13 & 0x3f | 0x80; - - // [byte 9] 8 bits seq_low - b[i++] = seqLow >>> 5 & 0xff; - - // [byte 10] remaining 5 bits seq_low, 3 bits random - b[i++] = seqLow << 3 & 0xff | rnds[10] & 0x07; - - // [bytes 11-15] always random - b[i++] = rnds[11]; - b[i++] = rnds[12]; - b[i++] = rnds[13]; - b[i++] = rnds[14]; - b[i++] = rnds[15]; - return buf || (0, _stringify.unsafeStringify)(b); -} -var _default = exports["default"] = v7; - -/***/ }), - -/***/ 6200: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _regex = _interopRequireDefault(__nccwpck_require__(7879)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function validate(uuid) { - return typeof uuid === 'string' && _regex.default.test(uuid); -} -var _default = exports["default"] = validate; - -/***/ }), - -/***/ 5868: -/***/ ((__unused_webpack_module, exports, __nccwpck_require__) => { - - - -Object.defineProperty(exports, "__esModule", ({ - value: true -})); -exports["default"] = void 0; -var _validate = _interopRequireDefault(__nccwpck_require__(6200)); -function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; } -function version(uuid) { - if (!(0, _validate.default)(uuid)) { - throw TypeError('Invalid UUID'); - } - return parseInt(uuid.slice(14, 15), 16); -} -var _default = exports["default"] = version; - -/***/ }), - -/***/ 8264: -/***/ ((module) => { - -// Returns a wrapper function that returns a wrapped callback -// The wrapper function should do some stuff, and return a -// presumably different callback function. -// This makes sure that own properties are retained, so that -// decorations and such are not lost along the way. -module.exports = wrappy -function wrappy (fn, cb) { - if (fn && cb) return wrappy(fn)(cb) - - if (typeof fn !== 'function') - throw new TypeError('need wrapper function') - - Object.keys(fn).forEach(function (k) { - wrapper[k] = fn[k] - }) - - return wrapper - - function wrapper() { - var args = new Array(arguments.length) - for (var i = 0; i < args.length; i++) { - args[i] = arguments[i] - } - var ret = fn.apply(this, args) - var cb = args[args.length-1] - if (typeof ret === 'function' && ret !== cb) { - Object.keys(cb).forEach(function (k) { - ret[k] = cb[k] - }) - } - return ret - } -} - - -/***/ }), - -/***/ 2613: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("assert"); - -/***/ }), - -/***/ 290: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("async_hooks"); - -/***/ }), - -/***/ 181: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("buffer"); - -/***/ }), - -/***/ 5317: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("child_process"); - -/***/ }), - -/***/ 4236: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("console"); - -/***/ }), - -/***/ 6982: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("crypto"); - -/***/ }), - -/***/ 1637: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("diagnostics_channel"); - -/***/ }), - -/***/ 4434: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("events"); - -/***/ }), - -/***/ 9896: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("fs"); - -/***/ }), - -/***/ 8611: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http"); - -/***/ }), - -/***/ 5675: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("http2"); - -/***/ }), - -/***/ 5692: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("https"); - -/***/ }), - -/***/ 9278: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("net"); - -/***/ }), - -/***/ 7598: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:crypto"); - -/***/ }), - -/***/ 8474: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:events"); - -/***/ }), - -/***/ 7075: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:stream"); - -/***/ }), - -/***/ 7975: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:util"); - -/***/ }), - -/***/ 857: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("os"); - -/***/ }), - -/***/ 6928: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("path"); - -/***/ }), - -/***/ 2987: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("perf_hooks"); - -/***/ }), - -/***/ 3480: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("querystring"); - -/***/ }), - -/***/ 2203: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream"); - -/***/ }), - -/***/ 3774: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("stream/web"); - -/***/ }), - -/***/ 3193: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("string_decoder"); - -/***/ }), - -/***/ 3557: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("timers"); - -/***/ }), - -/***/ 4756: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("tls"); - -/***/ }), - -/***/ 7016: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("url"); - -/***/ }), - -/***/ 9023: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util"); - -/***/ }), - -/***/ 8253: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("util/types"); - -/***/ }), - -/***/ 8167: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("worker_threads"); - -/***/ }), - -/***/ 3106: -/***/ ((module) => { - -module.exports = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("zlib"); - -/***/ }), - -/***/ 7182: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const WritableStream = (__nccwpck_require__(7075).Writable) -const inherits = (__nccwpck_require__(7975).inherits) - -const StreamSearch = __nccwpck_require__(4136) - -const PartStream = __nccwpck_require__(612) -const HeaderParser = __nccwpck_require__(2271) - -const DASH = 45 -const B_ONEDASH = Buffer.from('-') -const B_CRLF = Buffer.from('\r\n') -const EMPTY_FN = function () {} - -function Dicer (cfg) { - if (!(this instanceof Dicer)) { return new Dicer(cfg) } - WritableStream.call(this, cfg) - - if (!cfg || (!cfg.headerFirst && typeof cfg.boundary !== 'string')) { throw new TypeError('Boundary required') } - - if (typeof cfg.boundary === 'string') { this.setBoundary(cfg.boundary) } else { this._bparser = undefined } - - this._headerFirst = cfg.headerFirst - - this._dashes = 0 - this._parts = 0 - this._finished = false - this._realFinish = false - this._isPreamble = true - this._justMatched = false - this._firstWrite = true - this._inHeader = true - this._part = undefined - this._cb = undefined - this._ignoreData = false - this._partOpts = { highWaterMark: cfg.partHwm } - this._pause = false - - const self = this - this._hparser = new HeaderParser(cfg) - this._hparser.on('header', function (header) { - self._inHeader = false - self._part.emit('header', header) - }) -} -inherits(Dicer, WritableStream) - -Dicer.prototype.emit = function (ev) { - if (ev === 'finish' && !this._realFinish) { - if (!this._finished) { - const self = this - process.nextTick(function () { - self.emit('error', new Error('Unexpected end of multipart data')) - if (self._part && !self._ignoreData) { - const type = (self._isPreamble ? 'Preamble' : 'Part') - self._part.emit('error', new Error(type + ' terminated early due to unexpected end of multipart data')) - self._part.push(null) - process.nextTick(function () { - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) - return - } - self._realFinish = true - self.emit('finish') - self._realFinish = false - }) - } - } else { WritableStream.prototype.emit.apply(this, arguments) } -} - -Dicer.prototype._write = function (data, encoding, cb) { - // ignore unexpected data (e.g. extra trailer data after finished) - if (!this._hparser && !this._bparser) { return cb() } - - if (this._headerFirst && this._isPreamble) { - if (!this._part) { - this._part = new PartStream(this._partOpts) - if (this.listenerCount('preamble') !== 0) { this.emit('preamble', this._part) } else { this._ignore() } - } - const r = this._hparser.push(data) - if (!this._inHeader && r !== undefined && r < data.length) { data = data.slice(r) } else { return cb() } - } - - // allows for "easier" testing - if (this._firstWrite) { - this._bparser.push(B_CRLF) - this._firstWrite = false - } - - this._bparser.push(data) - - if (this._pause) { this._cb = cb } else { cb() } -} - -Dicer.prototype.reset = function () { - this._part = undefined - this._bparser = undefined - this._hparser = undefined -} - -Dicer.prototype.setBoundary = function (boundary) { - const self = this - this._bparser = new StreamSearch('\r\n--' + boundary) - this._bparser.on('info', function (isMatch, data, start, end) { - self._oninfo(isMatch, data, start, end) - }) -} - -Dicer.prototype._ignore = function () { - if (this._part && !this._ignoreData) { - this._ignoreData = true - this._part.on('error', EMPTY_FN) - // we must perform some kind of read on the stream even though we are - // ignoring the data, otherwise node's Readable stream will not emit 'end' - // after pushing null to the stream - this._part.resume() - } -} - -Dicer.prototype._oninfo = function (isMatch, data, start, end) { - let buf; const self = this; let i = 0; let r; let shouldWriteMore = true - - if (!this._part && this._justMatched && data) { - while (this._dashes < 2 && (start + i) < end) { - if (data[start + i] === DASH) { - ++i - ++this._dashes - } else { - if (this._dashes) { buf = B_ONEDASH } - this._dashes = 0 - break - } - } - if (this._dashes === 2) { - if ((start + i) < end && this.listenerCount('trailer') !== 0) { this.emit('trailer', data.slice(start + i, end)) } - this.reset() - this._finished = true - // no more parts will be added - if (self._parts === 0) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } - } - if (this._dashes) { return } - } - if (this._justMatched) { this._justMatched = false } - if (!this._part) { - this._part = new PartStream(this._partOpts) - this._part._read = function (n) { - self._unpause() - } - if (this._isPreamble && this.listenerCount('preamble') !== 0) { - this.emit('preamble', this._part) - } else if (this._isPreamble !== true && this.listenerCount('part') !== 0) { - this.emit('part', this._part) - } else { - this._ignore() - } - if (!this._isPreamble) { this._inHeader = true } - } - if (data && start < end && !this._ignoreData) { - if (this._isPreamble || !this._inHeader) { - if (buf) { shouldWriteMore = this._part.push(buf) } - shouldWriteMore = this._part.push(data.slice(start, end)) - if (!shouldWriteMore) { this._pause = true } - } else if (!this._isPreamble && this._inHeader) { - if (buf) { this._hparser.push(buf) } - r = this._hparser.push(data.slice(start, end)) - if (!this._inHeader && r !== undefined && r < end) { this._oninfo(false, data, start + r, end) } - } - } - if (isMatch) { - this._hparser.reset() - if (this._isPreamble) { this._isPreamble = false } else { - if (start !== end) { - ++this._parts - this._part.on('end', function () { - if (--self._parts === 0) { - if (self._finished) { - self._realFinish = true - self.emit('finish') - self._realFinish = false - } else { - self._unpause() - } - } - }) - } - } - this._part.push(null) - this._part = undefined - this._ignoreData = false - this._justMatched = true - this._dashes = 0 - } -} - -Dicer.prototype._unpause = function () { - if (!this._pause) { return } - - this._pause = false - if (this._cb) { - const cb = this._cb - this._cb = undefined - cb() - } -} - -module.exports = Dicer - - -/***/ }), - -/***/ 2271: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const EventEmitter = (__nccwpck_require__(8474).EventEmitter) -const inherits = (__nccwpck_require__(7975).inherits) -const getLimit = __nccwpck_require__(2393) - -const StreamSearch = __nccwpck_require__(4136) - -const B_DCRLF = Buffer.from('\r\n\r\n') -const RE_CRLF = /\r\n/g -const RE_HDR = /^([^:]+):[ \t]?([\x00-\xFF]+)?$/ // eslint-disable-line no-control-regex - -function HeaderParser (cfg) { - EventEmitter.call(this) - - cfg = cfg || {} - const self = this - this.nread = 0 - this.maxed = false - this.npairs = 0 - this.maxHeaderPairs = getLimit(cfg, 'maxHeaderPairs', 2000) - this.maxHeaderSize = getLimit(cfg, 'maxHeaderSize', 80 * 1024) - this.buffer = '' - this.header = {} - this.finished = false - this.ss = new StreamSearch(B_DCRLF) - this.ss.on('info', function (isMatch, data, start, end) { - if (data && !self.maxed) { - if (self.nread + end - start >= self.maxHeaderSize) { - end = self.maxHeaderSize - self.nread + start - self.nread = self.maxHeaderSize - self.maxed = true - } else { self.nread += (end - start) } - - self.buffer += data.toString('binary', start, end) - } - if (isMatch) { self._finish() } - }) -} -inherits(HeaderParser, EventEmitter) - -HeaderParser.prototype.push = function (data) { - const r = this.ss.push(data) - if (this.finished) { return r } -} - -HeaderParser.prototype.reset = function () { - this.finished = false - this.buffer = '' - this.header = {} - this.ss.reset() -} - -HeaderParser.prototype._finish = function () { - if (this.buffer) { this._parseHeader() } - this.ss.matches = this.ss.maxMatches - const header = this.header - this.header = {} - this.buffer = '' - this.finished = true - this.nread = this.npairs = 0 - this.maxed = false - this.emit('header', header) -} - -HeaderParser.prototype._parseHeader = function () { - if (this.npairs === this.maxHeaderPairs) { return } - - const lines = this.buffer.split(RE_CRLF) - const len = lines.length - let m, h - - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (lines[i].length === 0) { continue } - if (lines[i][0] === '\t' || lines[i][0] === ' ') { - // folded header content - // RFC2822 says to just remove the CRLF and not the whitespace following - // it, so we follow the RFC and include the leading whitespace ... - if (h) { - this.header[h][this.header[h].length - 1] += lines[i] - continue - } - } - - const posColon = lines[i].indexOf(':') - if ( - posColon === -1 || - posColon === 0 - ) { - return - } - m = RE_HDR.exec(lines[i]) - h = m[1].toLowerCase() - this.header[h] = this.header[h] || [] - this.header[h].push((m[2] || '')) - if (++this.npairs === this.maxHeaderPairs) { break } - } -} - -module.exports = HeaderParser - - -/***/ }), - -/***/ 612: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const inherits = (__nccwpck_require__(7975).inherits) -const ReadableStream = (__nccwpck_require__(7075).Readable) - -function PartStream (opts) { - ReadableStream.call(this, opts) -} -inherits(PartStream, ReadableStream) - -PartStream.prototype._read = function (n) {} - -module.exports = PartStream - - -/***/ }), - -/***/ 4136: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -/** - * Copyright Brian White. All rights reserved. - * - * @see https://github.com/mscdex/streamsearch - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to - * deal in the Software without restriction, including without limitation the - * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or - * sell copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING - * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS - * IN THE SOFTWARE. - * - * Based heavily on the Streaming Boyer-Moore-Horspool C++ implementation - * by Hongli Lai at: https://github.com/FooBarWidget/boyer-moore-horspool - */ -const EventEmitter = (__nccwpck_require__(8474).EventEmitter) -const inherits = (__nccwpck_require__(7975).inherits) - -function SBMH (needle) { - if (typeof needle === 'string') { - needle = Buffer.from(needle) - } - - if (!Buffer.isBuffer(needle)) { - throw new TypeError('The needle has to be a String or a Buffer.') - } - - const needleLength = needle.length - - if (needleLength === 0) { - throw new Error('The needle cannot be an empty String/Buffer.') - } - - if (needleLength > 256) { - throw new Error('The needle cannot have a length bigger than 256.') - } - - this.maxMatches = Infinity - this.matches = 0 - - this._occ = new Array(256) - .fill(needleLength) // Initialize occurrence table. - this._lookbehind_size = 0 - this._needle = needle - this._bufpos = 0 - - this._lookbehind = Buffer.alloc(needleLength) - - // Populate occurrence table with analysis of the needle, - // ignoring last letter. - for (var i = 0; i < needleLength - 1; ++i) { // eslint-disable-line no-var - this._occ[needle[i]] = needleLength - 1 - i - } -} -inherits(SBMH, EventEmitter) - -SBMH.prototype.reset = function () { - this._lookbehind_size = 0 - this.matches = 0 - this._bufpos = 0 -} - -SBMH.prototype.push = function (chunk, pos) { - if (!Buffer.isBuffer(chunk)) { - chunk = Buffer.from(chunk, 'binary') - } - const chlen = chunk.length - this._bufpos = pos || 0 - let r - while (r !== chlen && this.matches < this.maxMatches) { r = this._sbmh_feed(chunk) } - return r -} - -SBMH.prototype._sbmh_feed = function (data) { - const len = data.length - const needle = this._needle - const needleLength = needle.length - const lastNeedleChar = needle[needleLength - 1] - - // Positive: points to a position in `data` - // pos == 3 points to data[3] - // Negative: points to a position in the lookbehind buffer - // pos == -2 points to lookbehind[lookbehind_size - 2] - let pos = -this._lookbehind_size - let ch - - if (pos < 0) { - // Lookbehind buffer is not empty. Perform Boyer-Moore-Horspool - // search with character lookup code that considers both the - // lookbehind buffer and the current round's haystack data. - // - // Loop until - // there is a match. - // or until - // we've moved past the position that requires the - // lookbehind buffer. In this case we switch to the - // optimized loop. - // or until - // the character to look at lies outside the haystack. - while (pos < 0 && pos <= len - needleLength) { - ch = this._sbmh_lookup_char(data, pos + needleLength - 1) - - if ( - ch === lastNeedleChar && - this._sbmh_memcmp(data, pos, needleLength - 1) - ) { - this._lookbehind_size = 0 - ++this.matches - this.emit('info', true) - - return (this._bufpos = pos + needleLength) - } - pos += this._occ[ch] - } - - // No match. - - if (pos < 0) { - // There's too few data for Boyer-Moore-Horspool to run, - // so let's use a different algorithm to skip as much as - // we can. - // Forward pos until - // the trailing part of lookbehind + data - // looks like the beginning of the needle - // or until - // pos == 0 - while (pos < 0 && !this._sbmh_memcmp(data, pos, len - pos)) { ++pos } - } - - if (pos >= 0) { - // Discard lookbehind buffer. - this.emit('info', false, this._lookbehind, 0, this._lookbehind_size) - this._lookbehind_size = 0 - } else { - // Cut off part of the lookbehind buffer that has - // been processed and append the entire haystack - // into it. - const bytesToCutOff = this._lookbehind_size + pos - if (bytesToCutOff > 0) { - // The cut off data is guaranteed not to contain the needle. - this.emit('info', false, this._lookbehind, 0, bytesToCutOff) - } - - this._lookbehind.copy(this._lookbehind, 0, bytesToCutOff, - this._lookbehind_size - bytesToCutOff) - this._lookbehind_size -= bytesToCutOff - - data.copy(this._lookbehind, this._lookbehind_size) - this._lookbehind_size += len - - this._bufpos = len - return len - } - } - - pos += (pos >= 0) * this._bufpos - - // Lookbehind buffer is now empty. We only need to check if the - // needle is in the haystack. - if (data.indexOf(needle, pos) !== -1) { - pos = data.indexOf(needle, pos) - ++this.matches - if (pos > 0) { this.emit('info', true, data, this._bufpos, pos) } else { this.emit('info', true) } - - return (this._bufpos = pos + needleLength) - } else { - pos = len - needleLength - } - - // There was no match. If there's trailing haystack data that we cannot - // match yet using the Boyer-Moore-Horspool algorithm (because the trailing - // data is less than the needle size) then match using a modified - // algorithm that starts matching from the beginning instead of the end. - // Whatever trailing data is left after running this algorithm is added to - // the lookbehind buffer. - while ( - pos < len && - ( - data[pos] !== needle[0] || - ( - (Buffer.compare( - data.subarray(pos, pos + len - pos), - needle.subarray(0, len - pos) - ) !== 0) - ) - ) - ) { - ++pos - } - if (pos < len) { - data.copy(this._lookbehind, 0, pos, pos + (len - pos)) - this._lookbehind_size = len - pos - } - - // Everything until pos is guaranteed not to contain needle data. - if (pos > 0) { this.emit('info', false, data, this._bufpos, pos < len ? pos : len) } - - this._bufpos = len - return len -} - -SBMH.prototype._sbmh_lookup_char = function (data, pos) { - return (pos < 0) - ? this._lookbehind[this._lookbehind_size + pos] - : data[pos] -} - -SBMH.prototype._sbmh_memcmp = function (data, pos, len) { - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - if (this._sbmh_lookup_char(data, pos + i) !== this._needle[i]) { return false } - } - return true -} - -module.exports = SBMH - - -/***/ }), - -/***/ 9581: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const WritableStream = (__nccwpck_require__(7075).Writable) -const { inherits } = __nccwpck_require__(7975) -const Dicer = __nccwpck_require__(7182) - -const MultipartParser = __nccwpck_require__(1192) -const UrlencodedParser = __nccwpck_require__(855) -const parseParams = __nccwpck_require__(8929) - -function Busboy (opts) { - if (!(this instanceof Busboy)) { return new Busboy(opts) } - - if (typeof opts !== 'object') { - throw new TypeError('Busboy expected an options-Object.') - } - if (typeof opts.headers !== 'object') { - throw new TypeError('Busboy expected an options-Object with headers-attribute.') - } - if (typeof opts.headers['content-type'] !== 'string') { - throw new TypeError('Missing Content-Type-header.') - } - - const { - headers, - ...streamOptions - } = opts - - this.opts = { - autoDestroy: false, - ...streamOptions - } - WritableStream.call(this, this.opts) - - this._done = false - this._parser = this.getParserByHeaders(headers) - this._finished = false -} -inherits(Busboy, WritableStream) - -Busboy.prototype.emit = function (ev) { - if (ev === 'finish') { - if (!this._done) { - this._parser?.end() - return - } else if (this._finished) { - return - } - this._finished = true - } - WritableStream.prototype.emit.apply(this, arguments) -} - -Busboy.prototype.getParserByHeaders = function (headers) { - const parsed = parseParams(headers['content-type']) - - const cfg = { - defCharset: this.opts.defCharset, - fileHwm: this.opts.fileHwm, - headers, - highWaterMark: this.opts.highWaterMark, - isPartAFile: this.opts.isPartAFile, - limits: this.opts.limits, - parsedConType: parsed, - preservePath: this.opts.preservePath - } - - if (MultipartParser.detect.test(parsed[0])) { - return new MultipartParser(this, cfg) - } - if (UrlencodedParser.detect.test(parsed[0])) { - return new UrlencodedParser(this, cfg) - } - throw new Error('Unsupported Content-Type.') -} - -Busboy.prototype._write = function (chunk, encoding, cb) { - this._parser.write(chunk, cb) -} - -module.exports = Busboy -module.exports["default"] = Busboy -module.exports.Busboy = Busboy - -module.exports.Dicer = Dicer - - -/***/ }), - -/***/ 1192: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -// TODO: -// * support 1 nested multipart level -// (see second multipart example here: -// http://www.w3.org/TR/html401/interact/forms.html#didx-multipartform-data) -// * support limits.fieldNameSize -// -- this will require modifications to utils.parseParams - -const { Readable } = __nccwpck_require__(7075) -const { inherits } = __nccwpck_require__(7975) - -const Dicer = __nccwpck_require__(7182) - -const parseParams = __nccwpck_require__(8929) -const decodeText = __nccwpck_require__(2747) -const basename = __nccwpck_require__(692) -const getLimit = __nccwpck_require__(2393) - -const RE_BOUNDARY = /^boundary$/i -const RE_FIELD = /^form-data$/i -const RE_CHARSET = /^charset$/i -const RE_FILENAME = /^filename$/i -const RE_NAME = /^name$/i - -Multipart.detect = /^multipart\/form-data/i -function Multipart (boy, cfg) { - let i - let len - const self = this - let boundary - const limits = cfg.limits - const isPartAFile = cfg.isPartAFile || ((fieldName, contentType, fileName) => (contentType === 'application/octet-stream' || fileName !== undefined)) - const parsedConType = cfg.parsedConType || [] - const defCharset = cfg.defCharset || 'utf8' - const preservePath = cfg.preservePath - const fileOpts = { highWaterMark: cfg.fileHwm } - - for (i = 0, len = parsedConType.length; i < len; ++i) { - if (Array.isArray(parsedConType[i]) && - RE_BOUNDARY.test(parsedConType[i][0])) { - boundary = parsedConType[i][1] - break - } - } - - function checkFinished () { - if (nends === 0 && finished && !boy._done) { - finished = false - self.end() - } - } - - if (typeof boundary !== 'string') { throw new Error('Multipart: Boundary not found') } - - const fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - const fileSizeLimit = getLimit(limits, 'fileSize', Infinity) - const filesLimit = getLimit(limits, 'files', Infinity) - const fieldsLimit = getLimit(limits, 'fields', Infinity) - const partsLimit = getLimit(limits, 'parts', Infinity) - const headerPairsLimit = getLimit(limits, 'headerPairs', 2000) - const headerSizeLimit = getLimit(limits, 'headerSize', 80 * 1024) - - let nfiles = 0 - let nfields = 0 - let nends = 0 - let curFile - let curField - let finished = false - - this._needDrain = false - this._pause = false - this._cb = undefined - this._nparts = 0 - this._boy = boy - - const parserCfg = { - boundary, - maxHeaderPairs: headerPairsLimit, - maxHeaderSize: headerSizeLimit, - partHwm: fileOpts.highWaterMark, - highWaterMark: cfg.highWaterMark - } - - this.parser = new Dicer(parserCfg) - this.parser.on('drain', function () { - self._needDrain = false - if (self._cb && !self._pause) { - const cb = self._cb - self._cb = undefined - cb() - } - }).on('part', function onPart (part) { - if (++self._nparts > partsLimit) { - self.parser.removeListener('part', onPart) - self.parser.on('part', skipPart) - boy.hitPartsLimit = true - boy.emit('partsLimit') - return skipPart(part) - } - - // hack because streams2 _always_ doesn't emit 'end' until nextTick, so let - // us emit 'end' early since we know the part has ended if we are already - // seeing the next part - if (curField) { - const field = curField - field.emit('end') - field.removeAllListeners('end') - } - - part.on('header', function (header) { - let contype - let fieldname - let parsed - let charset - let encoding - let filename - let nsize = 0 - - if (header['content-type']) { - parsed = parseParams(header['content-type'][0]) - if (parsed[0]) { - contype = parsed[0].toLowerCase() - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_CHARSET.test(parsed[i][0])) { - charset = parsed[i][1].toLowerCase() - break - } - } - } - } - - if (contype === undefined) { contype = 'text/plain' } - if (charset === undefined) { charset = defCharset } - - if (header['content-disposition']) { - parsed = parseParams(header['content-disposition'][0]) - if (!RE_FIELD.test(parsed[0])) { return skipPart(part) } - for (i = 0, len = parsed.length; i < len; ++i) { - if (RE_NAME.test(parsed[i][0])) { - fieldname = parsed[i][1] - } else if (RE_FILENAME.test(parsed[i][0])) { - filename = parsed[i][1] - if (!preservePath) { filename = basename(filename) } - } - } - } else { return skipPart(part) } - - if (header['content-transfer-encoding']) { encoding = header['content-transfer-encoding'][0].toLowerCase() } else { encoding = '7bit' } - - let onData, - onEnd - - if (isPartAFile(fieldname, contype, filename)) { - // file/binary field - if (nfiles === filesLimit) { - if (!boy.hitFilesLimit) { - boy.hitFilesLimit = true - boy.emit('filesLimit') - } - return skipPart(part) - } - - ++nfiles - - if (boy.listenerCount('file') === 0) { - self.parser._ignore() - return - } - - ++nends - const file = new FileStream(fileOpts) - curFile = file - file.on('end', function () { - --nends - self._pause = false - checkFinished() - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } - }) - file._read = function (n) { - if (!self._pause) { return } - self._pause = false - if (self._cb && !self._needDrain) { - const cb = self._cb - self._cb = undefined - cb() - } - } - boy.emit('file', fieldname, file, filename, encoding, contype) - - onData = function (data) { - if ((nsize += data.length) > fileSizeLimit) { - const extralen = fileSizeLimit - nsize + data.length - if (extralen > 0) { file.push(data.slice(0, extralen)) } - file.truncated = true - file.bytesRead = fileSizeLimit - part.removeAllListeners('data') - file.emit('limit') - return - } else if (!file.push(data)) { self._pause = true } - - file.bytesRead = nsize - } - - onEnd = function () { - curFile = undefined - file.push(null) - } - } else { - // non-file field - if (nfields === fieldsLimit) { - if (!boy.hitFieldsLimit) { - boy.hitFieldsLimit = true - boy.emit('fieldsLimit') - } - return skipPart(part) - } - - ++nfields - ++nends - let buffer = '' - let truncated = false - curField = part - - onData = function (data) { - if ((nsize += data.length) > fieldSizeLimit) { - const extralen = (fieldSizeLimit - (nsize - data.length)) - buffer += data.toString('binary', 0, extralen) - truncated = true - part.removeAllListeners('data') - } else { buffer += data.toString('binary') } - } - - onEnd = function () { - curField = undefined - if (buffer.length) { buffer = decodeText(buffer, 'binary', charset) } - boy.emit('field', fieldname, buffer, false, truncated, encoding, contype) - --nends - checkFinished() - } - } - - /* As of node@2efe4ab761666 (v0.10.29+/v0.11.14+), busboy had become - broken. Streams2/streams3 is a huge black box of confusion, but - somehow overriding the sync state seems to fix things again (and still - seems to work for previous node versions). - */ - part._readableState.sync = false - - part.on('data', onData) - part.on('end', onEnd) - }).on('error', function (err) { - if (curFile) { curFile.emit('error', err) } - }) - }).on('error', function (err) { - boy.emit('error', err) - }).on('finish', function () { - finished = true - checkFinished() - }) -} - -Multipart.prototype.write = function (chunk, cb) { - const r = this.parser.write(chunk) - if (r && !this._pause) { - cb() - } else { - this._needDrain = !r - this._cb = cb - } -} - -Multipart.prototype.end = function () { - const self = this - - if (self.parser.writable) { - self.parser.end() - } else if (!self._boy._done) { - process.nextTick(function () { - self._boy._done = true - self._boy.emit('finish') - }) - } -} - -function skipPart (part) { - part.resume() -} - -function FileStream (opts) { - Readable.call(this, opts) - - this.bytesRead = 0 - - this.truncated = false -} - -inherits(FileStream, Readable) - -FileStream.prototype._read = function (n) {} - -module.exports = Multipart - - -/***/ }), - -/***/ 855: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - - - -const Decoder = __nccwpck_require__(1496) -const decodeText = __nccwpck_require__(2747) -const getLimit = __nccwpck_require__(2393) - -const RE_CHARSET = /^charset$/i - -UrlEncoded.detect = /^application\/x-www-form-urlencoded/i -function UrlEncoded (boy, cfg) { - const limits = cfg.limits - const parsedConType = cfg.parsedConType - this.boy = boy - - this.fieldSizeLimit = getLimit(limits, 'fieldSize', 1 * 1024 * 1024) - this.fieldNameSizeLimit = getLimit(limits, 'fieldNameSize', 100) - this.fieldsLimit = getLimit(limits, 'fields', Infinity) - - let charset - for (var i = 0, len = parsedConType.length; i < len; ++i) { // eslint-disable-line no-var - if (Array.isArray(parsedConType[i]) && - RE_CHARSET.test(parsedConType[i][0])) { - charset = parsedConType[i][1].toLowerCase() - break - } - } - - if (charset === undefined) { charset = cfg.defCharset || 'utf8' } - - this.decoder = new Decoder() - this.charset = charset - this._fields = 0 - this._state = 'key' - this._checkingBytes = true - this._bytesKey = 0 - this._bytesVal = 0 - this._key = '' - this._val = '' - this._keyTrunc = false - this._valTrunc = false - this._hitLimit = false -} - -UrlEncoded.prototype.write = function (data, cb) { - if (this._fields === this.fieldsLimit) { - if (!this.boy.hitFieldsLimit) { - this.boy.hitFieldsLimit = true - this.boy.emit('fieldsLimit') - } - return cb() - } - - let idxeq; let idxamp; let i; let p = 0; const len = data.length - - while (p < len) { - if (this._state === 'key') { - idxeq = idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x3D/* = */) { - idxeq = i - break - } else if (data[i] === 0x26/* & */) { - idxamp = i - break - } - if (this._checkingBytes && this._bytesKey === this.fieldNameSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesKey } - } - - if (idxeq !== undefined) { - // key with assignment - if (idxeq > p) { this._key += this.decoder.write(data.toString('binary', p, idxeq)) } - this._state = 'val' - - this._hitLimit = false - this._checkingBytes = true - this._val = '' - this._bytesVal = 0 - this._valTrunc = false - this.decoder.reset() - - p = idxeq + 1 - } else if (idxamp !== undefined) { - // key with no assignment - ++this._fields - let key; const keyTrunc = this._keyTrunc - if (idxamp > p) { key = (this._key += this.decoder.write(data.toString('binary', p, idxamp))) } else { key = this._key } - - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() - - if (key.length) { - this.boy.emit('field', decodeText(key, 'binary', this.charset), - '', - keyTrunc, - false) - } - - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._key += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._bytesKey = this._key.length) === this.fieldNameSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._keyTrunc = true - } - } else { - if (p < len) { this._key += this.decoder.write(data.toString('binary', p)) } - p = len - } - } else { - idxamp = undefined - for (i = p; i < len; ++i) { - if (!this._checkingBytes) { ++p } - if (data[i] === 0x26/* & */) { - idxamp = i - break - } - if (this._checkingBytes && this._bytesVal === this.fieldSizeLimit) { - this._hitLimit = true - break - } else if (this._checkingBytes) { ++this._bytesVal } - } - - if (idxamp !== undefined) { - ++this._fields - if (idxamp > p) { this._val += this.decoder.write(data.toString('binary', p, idxamp)) } - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - this._state = 'key' - - this._hitLimit = false - this._checkingBytes = true - this._key = '' - this._bytesKey = 0 - this._keyTrunc = false - this.decoder.reset() - - p = idxamp + 1 - if (this._fields === this.fieldsLimit) { return cb() } - } else if (this._hitLimit) { - // we may not have hit the actual limit if there are encoded bytes... - if (i > p) { this._val += this.decoder.write(data.toString('binary', p, i)) } - p = i - if ((this._val === '' && this.fieldSizeLimit === 0) || - (this._bytesVal = this._val.length) === this.fieldSizeLimit) { - // yep, we actually did hit the limit - this._checkingBytes = false - this._valTrunc = true - } - } else { - if (p < len) { this._val += this.decoder.write(data.toString('binary', p)) } - p = len - } - } - } - cb() -} - -UrlEncoded.prototype.end = function () { - if (this.boy._done) { return } - - if (this._state === 'key' && this._key.length > 0) { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - '', - this._keyTrunc, - false) - } else if (this._state === 'val') { - this.boy.emit('field', decodeText(this._key, 'binary', this.charset), - decodeText(this._val, 'binary', this.charset), - this._keyTrunc, - this._valTrunc) - } - this.boy._done = true - this.boy.emit('finish') -} - -module.exports = UrlEncoded - - -/***/ }), - -/***/ 1496: -/***/ ((module) => { - - - -const RE_PLUS = /\+/g - -const HEX = [ - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 -] - -function Decoder () { - this.buffer = undefined -} -Decoder.prototype.write = function (str) { - // Replace '+' with ' ' before decoding - str = str.replace(RE_PLUS, ' ') - let res = '' - let i = 0; let p = 0; const len = str.length - for (; i < len; ++i) { - if (this.buffer !== undefined) { - if (!HEX[str.charCodeAt(i)]) { - res += '%' + this.buffer - this.buffer = undefined - --i // retry character - } else { - this.buffer += str[i] - ++p - if (this.buffer.length === 2) { - res += String.fromCharCode(parseInt(this.buffer, 16)) - this.buffer = undefined - } - } - } else if (str[i] === '%') { - if (i > p) { - res += str.substring(p, i) - p = i - } - this.buffer = '' - ++p - } - } - if (p < len && this.buffer === undefined) { res += str.substring(p) } - return res -} -Decoder.prototype.reset = function () { - this.buffer = undefined -} - -module.exports = Decoder - - -/***/ }), - -/***/ 692: -/***/ ((module) => { - - - -module.exports = function basename (path) { - if (typeof path !== 'string') { return '' } - for (var i = path.length - 1; i >= 0; --i) { // eslint-disable-line no-var - switch (path.charCodeAt(i)) { - case 0x2F: // '/' - case 0x5C: // '\' - path = path.slice(i + 1) - return (path === '..' || path === '.' ? '' : path) - } - } - return (path === '..' || path === '.' ? '' : path) -} - - -/***/ }), - -/***/ 2747: -/***/ (function(module) { - - - -// Node has always utf-8 -const utf8Decoder = new TextDecoder('utf-8') -const textDecoders = new Map([ - ['utf-8', utf8Decoder], - ['utf8', utf8Decoder] -]) - -function getDecoder (charset) { - let lc - while (true) { - switch (charset) { - case 'utf-8': - case 'utf8': - return decoders.utf8 - case 'latin1': - case 'ascii': // TODO: Make these a separate, strict decoder? - case 'us-ascii': - case 'iso-8859-1': - case 'iso8859-1': - case 'iso88591': - case 'iso_8859-1': - case 'windows-1252': - case 'iso_8859-1:1987': - case 'cp1252': - case 'x-cp1252': - return decoders.latin1 - case 'utf16le': - case 'utf-16le': - case 'ucs2': - case 'ucs-2': - return decoders.utf16le - case 'base64': - return decoders.base64 - default: - if (lc === undefined) { - lc = true - charset = charset.toLowerCase() - continue - } - return decoders.other.bind(charset) - } - } -} - -const decoders = { - utf8: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - return data.utf8Slice(0, data.length) - }, - - latin1: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - return data - } - return data.latin1Slice(0, data.length) - }, - - utf16le: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - return data.ucs2Slice(0, data.length) - }, - - base64: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - return data.base64Slice(0, data.length) - }, - - other: (data, sourceEncoding) => { - if (data.length === 0) { - return '' - } - if (typeof data === 'string') { - data = Buffer.from(data, sourceEncoding) - } - - if (textDecoders.has(this.toString())) { - try { - return textDecoders.get(this).decode(data) - } catch {} - } - return typeof data === 'string' - ? data - : data.toString() - } -} - -function decodeText (text, sourceEncoding, destEncoding) { - if (text) { - return getDecoder(destEncoding)(text, sourceEncoding) - } - return text -} - -module.exports = decodeText - - -/***/ }), - -/***/ 2393: -/***/ ((module) => { - - - -module.exports = function getLimit (limits, name, defaultLimit) { - if ( - !limits || - limits[name] === undefined || - limits[name] === null - ) { return defaultLimit } - - if ( - typeof limits[name] !== 'number' || - isNaN(limits[name]) - ) { throw new TypeError('Limit ' + name + ' is not a valid number') } - - return limits[name] -} - - -/***/ }), - -/***/ 8929: -/***/ ((module, __unused_webpack_exports, __nccwpck_require__) => { - -/* eslint-disable object-property-newline */ - - -const decodeText = __nccwpck_require__(2747) - -const RE_ENCODED = /%[a-fA-F0-9][a-fA-F0-9]/g - -const EncodedLookup = { - '%00': '\x00', '%01': '\x01', '%02': '\x02', '%03': '\x03', '%04': '\x04', - '%05': '\x05', '%06': '\x06', '%07': '\x07', '%08': '\x08', '%09': '\x09', - '%0a': '\x0a', '%0A': '\x0a', '%0b': '\x0b', '%0B': '\x0b', '%0c': '\x0c', - '%0C': '\x0c', '%0d': '\x0d', '%0D': '\x0d', '%0e': '\x0e', '%0E': '\x0e', - '%0f': '\x0f', '%0F': '\x0f', '%10': '\x10', '%11': '\x11', '%12': '\x12', - '%13': '\x13', '%14': '\x14', '%15': '\x15', '%16': '\x16', '%17': '\x17', - '%18': '\x18', '%19': '\x19', '%1a': '\x1a', '%1A': '\x1a', '%1b': '\x1b', - '%1B': '\x1b', '%1c': '\x1c', '%1C': '\x1c', '%1d': '\x1d', '%1D': '\x1d', - '%1e': '\x1e', '%1E': '\x1e', '%1f': '\x1f', '%1F': '\x1f', '%20': '\x20', - '%21': '\x21', '%22': '\x22', '%23': '\x23', '%24': '\x24', '%25': '\x25', - '%26': '\x26', '%27': '\x27', '%28': '\x28', '%29': '\x29', '%2a': '\x2a', - '%2A': '\x2a', '%2b': '\x2b', '%2B': '\x2b', '%2c': '\x2c', '%2C': '\x2c', - '%2d': '\x2d', '%2D': '\x2d', '%2e': '\x2e', '%2E': '\x2e', '%2f': '\x2f', - '%2F': '\x2f', '%30': '\x30', '%31': '\x31', '%32': '\x32', '%33': '\x33', - '%34': '\x34', '%35': '\x35', '%36': '\x36', '%37': '\x37', '%38': '\x38', - '%39': '\x39', '%3a': '\x3a', '%3A': '\x3a', '%3b': '\x3b', '%3B': '\x3b', - '%3c': '\x3c', '%3C': '\x3c', '%3d': '\x3d', '%3D': '\x3d', '%3e': '\x3e', - '%3E': '\x3e', '%3f': '\x3f', '%3F': '\x3f', '%40': '\x40', '%41': '\x41', - '%42': '\x42', '%43': '\x43', '%44': '\x44', '%45': '\x45', '%46': '\x46', - '%47': '\x47', '%48': '\x48', '%49': '\x49', '%4a': '\x4a', '%4A': '\x4a', - '%4b': '\x4b', '%4B': '\x4b', '%4c': '\x4c', '%4C': '\x4c', '%4d': '\x4d', - '%4D': '\x4d', '%4e': '\x4e', '%4E': '\x4e', '%4f': '\x4f', '%4F': '\x4f', - '%50': '\x50', '%51': '\x51', '%52': '\x52', '%53': '\x53', '%54': '\x54', - '%55': '\x55', '%56': '\x56', '%57': '\x57', '%58': '\x58', '%59': '\x59', - '%5a': '\x5a', '%5A': '\x5a', '%5b': '\x5b', '%5B': '\x5b', '%5c': '\x5c', - '%5C': '\x5c', '%5d': '\x5d', '%5D': '\x5d', '%5e': '\x5e', '%5E': '\x5e', - '%5f': '\x5f', '%5F': '\x5f', '%60': '\x60', '%61': '\x61', '%62': '\x62', - '%63': '\x63', '%64': '\x64', '%65': '\x65', '%66': '\x66', '%67': '\x67', - '%68': '\x68', '%69': '\x69', '%6a': '\x6a', '%6A': '\x6a', '%6b': '\x6b', - '%6B': '\x6b', '%6c': '\x6c', '%6C': '\x6c', '%6d': '\x6d', '%6D': '\x6d', - '%6e': '\x6e', '%6E': '\x6e', '%6f': '\x6f', '%6F': '\x6f', '%70': '\x70', - '%71': '\x71', '%72': '\x72', '%73': '\x73', '%74': '\x74', '%75': '\x75', - '%76': '\x76', '%77': '\x77', '%78': '\x78', '%79': '\x79', '%7a': '\x7a', - '%7A': '\x7a', '%7b': '\x7b', '%7B': '\x7b', '%7c': '\x7c', '%7C': '\x7c', - '%7d': '\x7d', '%7D': '\x7d', '%7e': '\x7e', '%7E': '\x7e', '%7f': '\x7f', - '%7F': '\x7f', '%80': '\x80', '%81': '\x81', '%82': '\x82', '%83': '\x83', - '%84': '\x84', '%85': '\x85', '%86': '\x86', '%87': '\x87', '%88': '\x88', - '%89': '\x89', '%8a': '\x8a', '%8A': '\x8a', '%8b': '\x8b', '%8B': '\x8b', - '%8c': '\x8c', '%8C': '\x8c', '%8d': '\x8d', '%8D': '\x8d', '%8e': '\x8e', - '%8E': '\x8e', '%8f': '\x8f', '%8F': '\x8f', '%90': '\x90', '%91': '\x91', - '%92': '\x92', '%93': '\x93', '%94': '\x94', '%95': '\x95', '%96': '\x96', - '%97': '\x97', '%98': '\x98', '%99': '\x99', '%9a': '\x9a', '%9A': '\x9a', - '%9b': '\x9b', '%9B': '\x9b', '%9c': '\x9c', '%9C': '\x9c', '%9d': '\x9d', - '%9D': '\x9d', '%9e': '\x9e', '%9E': '\x9e', '%9f': '\x9f', '%9F': '\x9f', - '%a0': '\xa0', '%A0': '\xa0', '%a1': '\xa1', '%A1': '\xa1', '%a2': '\xa2', - '%A2': '\xa2', '%a3': '\xa3', '%A3': '\xa3', '%a4': '\xa4', '%A4': '\xa4', - '%a5': '\xa5', '%A5': '\xa5', '%a6': '\xa6', '%A6': '\xa6', '%a7': '\xa7', - '%A7': '\xa7', '%a8': '\xa8', '%A8': '\xa8', '%a9': '\xa9', '%A9': '\xa9', - '%aa': '\xaa', '%Aa': '\xaa', '%aA': '\xaa', '%AA': '\xaa', '%ab': '\xab', - '%Ab': '\xab', '%aB': '\xab', '%AB': '\xab', '%ac': '\xac', '%Ac': '\xac', - '%aC': '\xac', '%AC': '\xac', '%ad': '\xad', '%Ad': '\xad', '%aD': '\xad', - '%AD': '\xad', '%ae': '\xae', '%Ae': '\xae', '%aE': '\xae', '%AE': '\xae', - '%af': '\xaf', '%Af': '\xaf', '%aF': '\xaf', '%AF': '\xaf', '%b0': '\xb0', - '%B0': '\xb0', '%b1': '\xb1', '%B1': '\xb1', '%b2': '\xb2', '%B2': '\xb2', - '%b3': '\xb3', '%B3': '\xb3', '%b4': '\xb4', '%B4': '\xb4', '%b5': '\xb5', - '%B5': '\xb5', '%b6': '\xb6', '%B6': '\xb6', '%b7': '\xb7', '%B7': '\xb7', - '%b8': '\xb8', '%B8': '\xb8', '%b9': '\xb9', '%B9': '\xb9', '%ba': '\xba', - '%Ba': '\xba', '%bA': '\xba', '%BA': '\xba', '%bb': '\xbb', '%Bb': '\xbb', - '%bB': '\xbb', '%BB': '\xbb', '%bc': '\xbc', '%Bc': '\xbc', '%bC': '\xbc', - '%BC': '\xbc', '%bd': '\xbd', '%Bd': '\xbd', '%bD': '\xbd', '%BD': '\xbd', - '%be': '\xbe', '%Be': '\xbe', '%bE': '\xbe', '%BE': '\xbe', '%bf': '\xbf', - '%Bf': '\xbf', '%bF': '\xbf', '%BF': '\xbf', '%c0': '\xc0', '%C0': '\xc0', - '%c1': '\xc1', '%C1': '\xc1', '%c2': '\xc2', '%C2': '\xc2', '%c3': '\xc3', - '%C3': '\xc3', '%c4': '\xc4', '%C4': '\xc4', '%c5': '\xc5', '%C5': '\xc5', - '%c6': '\xc6', '%C6': '\xc6', '%c7': '\xc7', '%C7': '\xc7', '%c8': '\xc8', - '%C8': '\xc8', '%c9': '\xc9', '%C9': '\xc9', '%ca': '\xca', '%Ca': '\xca', - '%cA': '\xca', '%CA': '\xca', '%cb': '\xcb', '%Cb': '\xcb', '%cB': '\xcb', - '%CB': '\xcb', '%cc': '\xcc', '%Cc': '\xcc', '%cC': '\xcc', '%CC': '\xcc', - '%cd': '\xcd', '%Cd': '\xcd', '%cD': '\xcd', '%CD': '\xcd', '%ce': '\xce', - '%Ce': '\xce', '%cE': '\xce', '%CE': '\xce', '%cf': '\xcf', '%Cf': '\xcf', - '%cF': '\xcf', '%CF': '\xcf', '%d0': '\xd0', '%D0': '\xd0', '%d1': '\xd1', - '%D1': '\xd1', '%d2': '\xd2', '%D2': '\xd2', '%d3': '\xd3', '%D3': '\xd3', - '%d4': '\xd4', '%D4': '\xd4', '%d5': '\xd5', '%D5': '\xd5', '%d6': '\xd6', - '%D6': '\xd6', '%d7': '\xd7', '%D7': '\xd7', '%d8': '\xd8', '%D8': '\xd8', - '%d9': '\xd9', '%D9': '\xd9', '%da': '\xda', '%Da': '\xda', '%dA': '\xda', - '%DA': '\xda', '%db': '\xdb', '%Db': '\xdb', '%dB': '\xdb', '%DB': '\xdb', - '%dc': '\xdc', '%Dc': '\xdc', '%dC': '\xdc', '%DC': '\xdc', '%dd': '\xdd', - '%Dd': '\xdd', '%dD': '\xdd', '%DD': '\xdd', '%de': '\xde', '%De': '\xde', - '%dE': '\xde', '%DE': '\xde', '%df': '\xdf', '%Df': '\xdf', '%dF': '\xdf', - '%DF': '\xdf', '%e0': '\xe0', '%E0': '\xe0', '%e1': '\xe1', '%E1': '\xe1', - '%e2': '\xe2', '%E2': '\xe2', '%e3': '\xe3', '%E3': '\xe3', '%e4': '\xe4', - '%E4': '\xe4', '%e5': '\xe5', '%E5': '\xe5', '%e6': '\xe6', '%E6': '\xe6', - '%e7': '\xe7', '%E7': '\xe7', '%e8': '\xe8', '%E8': '\xe8', '%e9': '\xe9', - '%E9': '\xe9', '%ea': '\xea', '%Ea': '\xea', '%eA': '\xea', '%EA': '\xea', - '%eb': '\xeb', '%Eb': '\xeb', '%eB': '\xeb', '%EB': '\xeb', '%ec': '\xec', - '%Ec': '\xec', '%eC': '\xec', '%EC': '\xec', '%ed': '\xed', '%Ed': '\xed', - '%eD': '\xed', '%ED': '\xed', '%ee': '\xee', '%Ee': '\xee', '%eE': '\xee', - '%EE': '\xee', '%ef': '\xef', '%Ef': '\xef', '%eF': '\xef', '%EF': '\xef', - '%f0': '\xf0', '%F0': '\xf0', '%f1': '\xf1', '%F1': '\xf1', '%f2': '\xf2', - '%F2': '\xf2', '%f3': '\xf3', '%F3': '\xf3', '%f4': '\xf4', '%F4': '\xf4', - '%f5': '\xf5', '%F5': '\xf5', '%f6': '\xf6', '%F6': '\xf6', '%f7': '\xf7', - '%F7': '\xf7', '%f8': '\xf8', '%F8': '\xf8', '%f9': '\xf9', '%F9': '\xf9', - '%fa': '\xfa', '%Fa': '\xfa', '%fA': '\xfa', '%FA': '\xfa', '%fb': '\xfb', - '%Fb': '\xfb', '%fB': '\xfb', '%FB': '\xfb', '%fc': '\xfc', '%Fc': '\xfc', - '%fC': '\xfc', '%FC': '\xfc', '%fd': '\xfd', '%Fd': '\xfd', '%fD': '\xfd', - '%FD': '\xfd', '%fe': '\xfe', '%Fe': '\xfe', '%fE': '\xfe', '%FE': '\xfe', - '%ff': '\xff', '%Ff': '\xff', '%fF': '\xff', '%FF': '\xff' -} - -function encodedReplacer (match) { - return EncodedLookup[match] -} - -const STATE_KEY = 0 -const STATE_VALUE = 1 -const STATE_CHARSET = 2 -const STATE_LANG = 3 - -function parseParams (str) { - const res = [] - let state = STATE_KEY - let charset = '' - let inquote = false - let escaping = false - let p = 0 - let tmp = '' - const len = str.length - - for (var i = 0; i < len; ++i) { // eslint-disable-line no-var - const char = str[i] - if (char === '\\' && inquote) { - if (escaping) { escaping = false } else { - escaping = true - continue - } - } else if (char === '"') { - if (!escaping) { - if (inquote) { - inquote = false - state = STATE_KEY - } else { inquote = true } - continue - } else { escaping = false } - } else { - if (escaping && inquote) { tmp += '\\' } - escaping = false - if ((state === STATE_CHARSET || state === STATE_LANG) && char === "'") { - if (state === STATE_CHARSET) { - state = STATE_LANG - charset = tmp.substring(1) - } else { state = STATE_VALUE } - tmp = '' - continue - } else if (state === STATE_KEY && - (char === '*' || char === '=') && - res.length) { - state = char === '*' - ? STATE_CHARSET - : STATE_VALUE - res[p] = [tmp, undefined] - tmp = '' - continue - } else if (!inquote && char === ';') { - state = STATE_KEY - if (charset) { - if (tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } - charset = '' - } else if (tmp.length) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - if (res[p] === undefined) { res[p] = tmp } else { res[p][1] = tmp } - tmp = '' - ++p - continue - } else if (!inquote && (char === ' ' || char === '\t')) { continue } - } - tmp += char - } - if (charset && tmp.length) { - tmp = decodeText(tmp.replace(RE_ENCODED, encodedReplacer), - 'binary', - charset) - } else if (tmp) { - tmp = decodeText(tmp, 'binary', 'utf8') - } - - if (res[p] === undefined) { - if (tmp) { res[p] = tmp } - } else { res[p][1] = tmp } - - return res -} - -module.exports = parseParams - - -/***/ }) - -/******/ }); -/************************************************************************/ -/******/ // The module cache -/******/ var __webpack_module_cache__ = {}; -/******/ -/******/ // The require function -/******/ function __nccwpck_require__(moduleId) { -/******/ // Check if module is in cache -/******/ var cachedModule = __webpack_module_cache__[moduleId]; -/******/ if (cachedModule !== undefined) { -/******/ return cachedModule.exports; -/******/ } -/******/ // Create a new module (and put it into the cache) -/******/ var module = __webpack_module_cache__[moduleId] = { -/******/ id: moduleId, -/******/ loaded: false, -/******/ exports: {} -/******/ }; -/******/ -/******/ // Execute the module function -/******/ var threw = true; -/******/ try { -/******/ __webpack_modules__[moduleId].call(module.exports, module, module.exports, __nccwpck_require__); -/******/ threw = false; -/******/ } finally { -/******/ if(threw) delete __webpack_module_cache__[moduleId]; -/******/ } -/******/ -/******/ // Flag the module as loaded -/******/ module.loaded = true; -/******/ -/******/ // Return the exports of the module -/******/ return module.exports; -/******/ } -/******/ -/************************************************************************/ -/******/ /* webpack/runtime/define property getters */ -/******/ (() => { -/******/ // define getter functions for harmony exports -/******/ __nccwpck_require__.d = (exports, definition) => { -/******/ for(var key in definition) { -/******/ if(__nccwpck_require__.o(definition, key) && !__nccwpck_require__.o(exports, key)) { -/******/ Object.defineProperty(exports, key, { enumerable: true, get: definition[key] }); -/******/ } -/******/ } -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/hasOwnProperty shorthand */ -/******/ (() => { -/******/ __nccwpck_require__.o = (obj, prop) => (Object.prototype.hasOwnProperty.call(obj, prop)) -/******/ })(); -/******/ -/******/ /* webpack/runtime/make namespace object */ -/******/ (() => { -/******/ // define __esModule on exports -/******/ __nccwpck_require__.r = (exports) => { -/******/ if(typeof Symbol !== 'undefined' && Symbol.toStringTag) { -/******/ Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' }); -/******/ } -/******/ Object.defineProperty(exports, '__esModule', { value: true }); -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/node module decorator */ -/******/ (() => { -/******/ __nccwpck_require__.nmd = (module) => { -/******/ module.paths = []; -/******/ if (!module.children) module.children = []; -/******/ return module; -/******/ }; -/******/ })(); -/******/ -/******/ /* webpack/runtime/compat */ -/******/ -/******/ if (typeof __nccwpck_require__ !== 'undefined') __nccwpck_require__.ab = new URL('.', import.meta.url).pathname.slice(import.meta.url.match(/^file:\/\/\/\w:/) ? 1 : 0, -1) + "/"; -/******/ -/************************************************************************/ -var __webpack_exports__ = {}; - -// NAMESPACE OBJECT: ./node_modules/zod/v4/core/regexes.js -var regexes_namespaceObject = {}; -__nccwpck_require__.r(regexes_namespaceObject); -__nccwpck_require__.d(regexes_namespaceObject, { - base64: () => (base64), - base64url: () => (base64url), - bigint: () => (bigint), - boolean: () => (regexes_boolean), - browserEmail: () => (browserEmail), - cidrv4: () => (cidrv4), - cidrv6: () => (cidrv6), - cuid: () => (cuid), - cuid2: () => (cuid2), - date: () => (date), - datetime: () => (datetime), - domain: () => (domain), - duration: () => (duration), - e164: () => (e164), - email: () => (email), - emoji: () => (emoji), - extendedDuration: () => (extendedDuration), - guid: () => (guid), - hex: () => (hex), - hostname: () => (hostname), - html5Email: () => (html5Email), - idnEmail: () => (idnEmail), - integer: () => (integer), - ipv4: () => (ipv4), - ipv6: () => (ipv6), - ksuid: () => (ksuid), - lowercase: () => (lowercase), - mac: () => (mac), - md5_base64: () => (md5_base64), - md5_base64url: () => (md5_base64url), - md5_hex: () => (md5_hex), - nanoid: () => (nanoid), - "null": () => (_null), - number: () => (number), - rfc5322Email: () => (rfc5322Email), - sha1_base64: () => (sha1_base64), - sha1_base64url: () => (sha1_base64url), - sha1_hex: () => (sha1_hex), - sha256_base64: () => (sha256_base64), - sha256_base64url: () => (sha256_base64url), - sha256_hex: () => (sha256_hex), - sha384_base64: () => (sha384_base64), - sha384_base64url: () => (sha384_base64url), - sha384_hex: () => (sha384_hex), - sha512_base64: () => (sha512_base64), - sha512_base64url: () => (sha512_base64url), - sha512_hex: () => (sha512_hex), - string: () => (string), - time: () => (time), - ulid: () => (ulid), - undefined: () => (_undefined), - unicodeEmail: () => (unicodeEmail), - uppercase: () => (uppercase), - uuid: () => (uuid), - uuid4: () => (uuid4), - uuid6: () => (regexes_uuid6), - uuid7: () => (regexes_uuid7), - xid: () => (xid) -}); - -// NAMESPACE OBJECT: ./node_modules/zod/v4/classic/checks.js -var classic_checks_namespaceObject = {}; -__nccwpck_require__.r(classic_checks_namespaceObject); -__nccwpck_require__.d(classic_checks_namespaceObject, { - endsWith: () => (_endsWith), - gt: () => (_gt), - gte: () => (_gte), - includes: () => (_includes), - length: () => (_length), - lowercase: () => (_lowercase), - lt: () => (_lt), - lte: () => (_lte), - maxLength: () => (_maxLength), - maxSize: () => (_maxSize), - mime: () => (_mime), - minLength: () => (_minLength), - minSize: () => (_minSize), - multipleOf: () => (_multipleOf), - negative: () => (_negative), - nonnegative: () => (_nonnegative), - nonpositive: () => (_nonpositive), - normalize: () => (_normalize), - overwrite: () => (_overwrite), - positive: () => (_positive), - property: () => (_property), - regex: () => (_regex), - size: () => (_size), - slugify: () => (_slugify), - startsWith: () => (_startsWith), - toLowerCase: () => (_toLowerCase), - toUpperCase: () => (_toUpperCase), - trim: () => (_trim), - uppercase: () => (_uppercase) -}); - -// NAMESPACE OBJECT: ./node_modules/zod/v4/classic/iso.js -var iso_namespaceObject = {}; -__nccwpck_require__.r(iso_namespaceObject); -__nccwpck_require__.d(iso_namespaceObject, { - ZodISODate: () => (ZodISODate), - ZodISODateTime: () => (ZodISODateTime), - ZodISODuration: () => (ZodISODuration), - ZodISOTime: () => (ZodISOTime), - date: () => (iso_date), - datetime: () => (iso_datetime), - duration: () => (iso_duration), - time: () => (iso_time) -}); - -// NAMESPACE OBJECT: ./node_modules/zod/v4/classic/schemas.js -var classic_schemas_namespaceObject = {}; -__nccwpck_require__.r(classic_schemas_namespaceObject); -__nccwpck_require__.d(classic_schemas_namespaceObject, { - ZodAny: () => (schemas_ZodAny), - ZodArray: () => (schemas_ZodArray), - ZodBase64: () => (ZodBase64), - ZodBase64URL: () => (ZodBase64URL), - ZodBigInt: () => (schemas_ZodBigInt), - ZodBigIntFormat: () => (ZodBigIntFormat), - ZodBoolean: () => (schemas_ZodBoolean), - ZodCIDRv4: () => (ZodCIDRv4), - ZodCIDRv6: () => (ZodCIDRv6), - ZodCUID: () => (ZodCUID), - ZodCUID2: () => (ZodCUID2), - ZodCatch: () => (schemas_ZodCatch), - ZodCodec: () => (ZodCodec), - ZodCustom: () => (ZodCustom), - ZodCustomStringFormat: () => (ZodCustomStringFormat), - ZodDate: () => (schemas_ZodDate), - ZodDefault: () => (schemas_ZodDefault), - ZodDiscriminatedUnion: () => (schemas_ZodDiscriminatedUnion), - ZodE164: () => (ZodE164), - ZodEmail: () => (ZodEmail), - ZodEmoji: () => (ZodEmoji), - ZodEnum: () => (schemas_ZodEnum), - ZodFile: () => (ZodFile), - ZodFunction: () => (schemas_ZodFunction), - ZodGUID: () => (ZodGUID), - ZodIPv4: () => (ZodIPv4), - ZodIPv6: () => (ZodIPv6), - ZodIntersection: () => (schemas_ZodIntersection), - ZodJWT: () => (ZodJWT), - ZodKSUID: () => (ZodKSUID), - ZodLazy: () => (schemas_ZodLazy), - ZodLiteral: () => (schemas_ZodLiteral), - ZodMAC: () => (ZodMAC), - ZodMap: () => (schemas_ZodMap), - ZodNaN: () => (schemas_ZodNaN), - ZodNanoID: () => (ZodNanoID), - ZodNever: () => (schemas_ZodNever), - ZodNonOptional: () => (ZodNonOptional), - ZodNull: () => (schemas_ZodNull), - ZodNullable: () => (schemas_ZodNullable), - ZodNumber: () => (schemas_ZodNumber), - ZodNumberFormat: () => (ZodNumberFormat), - ZodObject: () => (schemas_ZodObject), - ZodOptional: () => (schemas_ZodOptional), - ZodPipe: () => (ZodPipe), - ZodPrefault: () => (ZodPrefault), - ZodPromise: () => (schemas_ZodPromise), - ZodReadonly: () => (schemas_ZodReadonly), - ZodRecord: () => (schemas_ZodRecord), - ZodSet: () => (schemas_ZodSet), - ZodString: () => (schemas_ZodString), - ZodStringFormat: () => (ZodStringFormat), - ZodSuccess: () => (ZodSuccess), - ZodSymbol: () => (schemas_ZodSymbol), - ZodTemplateLiteral: () => (ZodTemplateLiteral), - ZodTransform: () => (ZodTransform), - ZodTuple: () => (schemas_ZodTuple), - ZodType: () => (schemas_ZodType), - ZodULID: () => (ZodULID), - ZodURL: () => (ZodURL), - ZodUUID: () => (ZodUUID), - ZodUndefined: () => (schemas_ZodUndefined), - ZodUnion: () => (schemas_ZodUnion), - ZodUnknown: () => (schemas_ZodUnknown), - ZodVoid: () => (schemas_ZodVoid), - ZodXID: () => (ZodXID), - ZodXor: () => (ZodXor), - _ZodString: () => (_ZodString), - _default: () => (schemas_default), - _function: () => (_function), - any: () => (any), - array: () => (array), - base64: () => (schemas_base64), - base64url: () => (schemas_base64url), - bigint: () => (schemas_bigint), - boolean: () => (schemas_boolean), - "catch": () => (schemas_catch), - check: () => (check), - cidrv4: () => (schemas_cidrv4), - cidrv6: () => (schemas_cidrv6), - codec: () => (codec), - cuid: () => (schemas_cuid), - cuid2: () => (schemas_cuid2), - custom: () => (schemas_custom), - date: () => (schemas_date), - describe: () => (schemas_describe), - discriminatedUnion: () => (discriminatedUnion), - e164: () => (schemas_e164), - email: () => (schemas_email), - emoji: () => (schemas_emoji), - "enum": () => (schemas_enum), - file: () => (file), - float32: () => (float32), - float64: () => (float64), - "function": () => (_function), - guid: () => (schemas_guid), - hash: () => (hash), - hex: () => (schemas_hex), - hostname: () => (schemas_hostname), - httpUrl: () => (httpUrl), - "instanceof": () => (_instanceof), - int: () => (schemas_int), - int32: () => (int32), - int64: () => (int64), - intersection: () => (intersection), - ipv4: () => (schemas_ipv4), - ipv6: () => (schemas_ipv6), - json: () => (json), - jwt: () => (jwt), - keyof: () => (keyof), - ksuid: () => (schemas_ksuid), - lazy: () => (lazy), - literal: () => (literal), - looseObject: () => (looseObject), - looseRecord: () => (looseRecord), - mac: () => (schemas_mac), - map: () => (map), - meta: () => (schemas_meta), - nan: () => (nan), - nanoid: () => (schemas_nanoid), - nativeEnum: () => (nativeEnum), - never: () => (schemas_never), - nonoptional: () => (nonoptional), - "null": () => (schemas_null), - nullable: () => (nullable), - nullish: () => (schemas_nullish), - number: () => (schemas_number), - object: () => (object), - optional: () => (optional), - partialRecord: () => (partialRecord), - pipe: () => (pipe), - prefault: () => (prefault), - preprocess: () => (preprocess), - promise: () => (promise), - readonly: () => (readonly), - record: () => (record), - refine: () => (refine), - set: () => (set), - strictObject: () => (strictObject), - string: () => (schemas_string), - stringFormat: () => (stringFormat), - stringbool: () => (stringbool), - success: () => (success), - superRefine: () => (superRefine), - symbol: () => (symbol), - templateLiteral: () => (templateLiteral), - transform: () => (transform), - tuple: () => (tuple), - uint32: () => (uint32), - uint64: () => (uint64), - ulid: () => (schemas_ulid), - undefined: () => (schemas_undefined), - union: () => (union), - unknown: () => (unknown), - url: () => (url), - uuid: () => (schemas_uuid), - uuidv4: () => (uuidv4), - uuidv6: () => (uuidv6), - uuidv7: () => (schemas_uuidv7), - "void": () => (schemas_void), - xid: () => (schemas_xid), - xor: () => (xor) -}); - -// EXTERNAL MODULE: ./node_modules/@actions/core/lib/core.js -var core = __nccwpck_require__(7484); -// EXTERNAL MODULE: ./node_modules/@actions/github/lib/github.js -var github = __nccwpck_require__(3228); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/_virtual/rolldown_runtime.js -//#region rolldown:runtime -var __defProp = Object.defineProperty; -var __export = (target, all) => { - for (var name in all) __defProp(target, name, { - get: all[name], - enumerable: true - }); -}; - -//#endregion - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/globals.js -//#region src/singletons/async_local_storage/globals.ts -const TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); -const globals_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); -const setGlobalAsyncLocalStorageInstance = (instance) => { - globalThis[TRACING_ALS_KEY] = instance; -}; -const globals_getGlobalAsyncLocalStorageInstance = () => { - return globalThis[TRACING_ALS_KEY]; -}; - -//#endregion - -//# sourceMappingURL=globals.js.map -// EXTERNAL MODULE: ./node_modules/decamelize/index.js -var decamelize = __nccwpck_require__(8203); -// EXTERNAL MODULE: ./node_modules/camelcase/index.js -var camelcase = __nccwpck_require__(9890); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/map_keys.js - - - -//#region src/load/map_keys.ts -function keyToJson(key, map) { - return map?.[key] || decamelize(key); -} -function keyFromJson(key, map) { - return map?.[key] || camelcase(key); -} -function mapKeys(fields, mapper, map) { - const mapped = {}; - for (const key in fields) if (Object.hasOwn(fields, key)) mapped[mapper(key, map)] = fields[key]; - return mapped; -} - -//#endregion - -//# sourceMappingURL=map_keys.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/validation.js -//#region src/load/validation.ts -/** -* Sentinel key used to mark escaped user objects during serialization. -* -* When a plain object contains 'lc' key (which could be confused with LC objects), -* we wrap it as `{"__lc_escaped__": {...original...}}`. -*/ -const LC_ESCAPED_KEY = "__lc_escaped__"; -/** -* Check if an object needs escaping to prevent confusion with LC objects. -* -* An object needs escaping if: -* 1. It has an `'lc'` key (could be confused with LC serialization format) -* 2. It has only the escape key (would be mistaken for an escaped object) -*/ -function needsEscaping(obj) { - return "lc" in obj || Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj; -} -/** -* Wrap an object in the escape marker. -* -* @example -* ```typescript -* {"key": "value"} // becomes {"__lc_escaped__": {"key": "value"}} -* ``` -*/ -function escapeObject(obj) { - return { [LC_ESCAPED_KEY]: obj }; -} -/** -* Check if an object is an escaped user object. -* -* @example -* ```typescript -* {"__lc_escaped__": {...}} // is an escaped object -* ``` -*/ -function isEscapedObject(obj) { - return Object.keys(obj).length === 1 && LC_ESCAPED_KEY in obj; -} -/** -* Check if an object looks like a Serializable instance (duck typing). -*/ -function isSerializableLike(obj) { - return obj !== null && typeof obj === "object" && "lc_serializable" in obj && typeof obj.toJSON === "function"; -} -/** -* Escape a value if it needs escaping (contains `lc` key). -* -* This is a simpler version of `serializeValue` that doesn't handle Serializable -* objects - it's meant to be called on kwargs values that have already been -* processed by `toJSON()`. -* -* @param value - The value to potentially escape. -* @returns The value with any `lc`-containing objects wrapped in escape markers. -*/ -function escapeIfNeeded(value) { - if (value !== null && typeof value === "object" && !Array.isArray(value)) { - if (isSerializableLike(value)) return value; - const record = value; - if (needsEscaping(record)) return escapeObject(record); - const result = {}; - for (const [key, val] of Object.entries(record)) result[key] = escapeIfNeeded(val); - return result; - } - if (Array.isArray(value)) return value.map((item) => escapeIfNeeded(item)); - return value; -} -/** -* Unescape a value, processing escape markers in object values and arrays. -* -* When an escaped object is encountered (`{"__lc_escaped__": ...}`), it's -* unwrapped and the contents are returned AS-IS (no further processing). -* The contents represent user data that should not be modified. -* -* For regular objects and arrays, we recurse to find any nested escape markers. -* -* @param obj - The value to unescape. -* @returns The unescaped value. -*/ -function unescapeValue(obj) { - if (obj !== null && typeof obj === "object" && !Array.isArray(obj)) { - const record = obj; - if (isEscapedObject(record)) return record[LC_ESCAPED_KEY]; - const result = {}; - for (const [key, value] of Object.entries(record)) result[key] = unescapeValue(value); - return result; - } - if (Array.isArray(obj)) return obj.map((item) => unescapeValue(item)); - return obj; -} - -//#endregion - -//# sourceMappingURL=validation.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/serializable.js - - - - -//#region src/load/serializable.ts -var serializable_exports = {}; -__export(serializable_exports, { - Serializable: () => Serializable, - get_lc_unique_name: () => get_lc_unique_name -}); -function shallowCopy(obj) { - return Array.isArray(obj) ? [...obj] : { ...obj }; -} -function replaceSecrets(root, secretsMap) { - const result = shallowCopy(root); - for (const [path, secretId] of Object.entries(secretsMap)) { - const [last, ...partsReverse] = path.split(".").reverse(); - let current = result; - for (const part of partsReverse.reverse()) { - if (current[part] === void 0) break; - current[part] = shallowCopy(current[part]); - current = current[part]; - } - if (current[last] !== void 0) current[last] = { - lc: 1, - type: "secret", - id: [secretId] - }; - } - return result; -} -/** -* Get a unique name for the module, rather than parent class implementations. -* Should not be subclassed, subclass lc_name above instead. -*/ -function get_lc_unique_name(serializableClass) { - const parentClass = Object.getPrototypeOf(serializableClass); - const lcNameIsSubclassed = typeof serializableClass.lc_name === "function" && (typeof parentClass.lc_name !== "function" || serializableClass.lc_name() !== parentClass.lc_name()); - if (lcNameIsSubclassed) return serializableClass.lc_name(); - else return serializableClass.name; -} -var Serializable = class Serializable { - lc_serializable = false; - lc_kwargs; - /** - * The name of the serializable. Override to provide an alias or - * to preserve the serialized module name in minified environments. - * - * Implemented as a static method to support loading logic. - */ - static lc_name() { - return this.name; - } - /** - * The final serialized identifier for the module. - */ - get lc_id() { - return [...this.lc_namespace, get_lc_unique_name(this.constructor)]; - } - /** - * A map of secrets, which will be omitted from serialization. - * Keys are paths to the secret in constructor args, e.g. "foo.bar.baz". - * Values are the secret ids, which will be used when deserializing. - */ - get lc_secrets() { - return void 0; - } - /** - * A map of additional attributes to merge with constructor args. - * Keys are the attribute names, e.g. "foo". - * Values are the attribute values, which will be serialized. - * These attributes need to be accepted by the constructor as arguments. - */ - get lc_attributes() { - return void 0; - } - /** - * A map of aliases for constructor args. - * Keys are the attribute names, e.g. "foo". - * Values are the alias that will replace the key in serialization. - * This is used to eg. make argument names match Python. - */ - get lc_aliases() { - return void 0; - } - /** - * A manual list of keys that should be serialized. - * If not overridden, all fields passed into the constructor will be serialized. - */ - get lc_serializable_keys() { - return void 0; - } - constructor(kwargs, ..._args) { - if (this.lc_serializable_keys !== void 0) this.lc_kwargs = Object.fromEntries(Object.entries(kwargs || {}).filter(([key]) => this.lc_serializable_keys?.includes(key))); - else this.lc_kwargs = kwargs ?? {}; - } - toJSON() { - if (!this.lc_serializable) return this.toJSONNotImplemented(); - if (this.lc_kwargs instanceof Serializable || typeof this.lc_kwargs !== "object" || Array.isArray(this.lc_kwargs)) return this.toJSONNotImplemented(); - const aliases = {}; - const secrets = {}; - const kwargs = Object.keys(this.lc_kwargs).reduce((acc, key) => { - acc[key] = key in this ? this[key] : this.lc_kwargs[key]; - return acc; - }, {}); - for (let current = Object.getPrototypeOf(this); current; current = Object.getPrototypeOf(current)) { - Object.assign(aliases, Reflect.get(current, "lc_aliases", this)); - Object.assign(secrets, Reflect.get(current, "lc_secrets", this)); - Object.assign(kwargs, Reflect.get(current, "lc_attributes", this)); - } - Object.keys(secrets).forEach((keyPath) => { - let read = this; - let write = kwargs; - const [last, ...partsReverse] = keyPath.split(".").reverse(); - for (const key of partsReverse.reverse()) { - if (!(key in read) || read[key] === void 0) return; - if (!(key in write) || write[key] === void 0) { - if (typeof read[key] === "object" && read[key] != null) write[key] = {}; - else if (Array.isArray(read[key])) write[key] = []; - } - read = read[key]; - write = write[key]; - } - if (last in read && read[last] !== void 0) write[last] = write[last] || read[last]; - }); - const escapedKwargs = {}; - for (const [key, value] of Object.entries(kwargs)) escapedKwargs[key] = escapeIfNeeded(value); - const kwargsWithSecrets = Object.keys(secrets).length ? replaceSecrets(escapedKwargs, secrets) : escapedKwargs; - const processedKwargs = mapKeys(kwargsWithSecrets, keyToJson, aliases); - return { - lc: 1, - type: "constructor", - id: this.lc_id, - kwargs: processedKwargs - }; - } - toJSONNotImplemented() { - return { - lc: 1, - type: "not_implemented", - id: this.lc_id - }; - } -}; - -//#endregion - -//# sourceMappingURL=serializable.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/data.js -//#region src/messages/content/data.ts -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function isDataContentBlock(content_block) { - return typeof content_block === "object" && content_block !== null && "type" in content_block && typeof content_block.type === "string" && "source_type" in content_block && (content_block.source_type === "url" || content_block.source_type === "base64" || content_block.source_type === "text" || content_block.source_type === "id"); -} -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function isURLContentBlock(content_block) { - return isDataContentBlock(content_block) && content_block.source_type === "url" && "url" in content_block && typeof content_block.url === "string"; -} -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function isBase64ContentBlock(content_block) { - return isDataContentBlock(content_block) && content_block.source_type === "base64" && "data" in content_block && typeof content_block.data === "string"; -} -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function isPlainTextContentBlock(content_block) { - return isDataContentBlock(content_block) && content_block.source_type === "text" && "text" in content_block && typeof content_block.text === "string"; -} -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function isIDContentBlock(content_block) { - return isDataContentBlock(content_block) && content_block.source_type === "id" && "id" in content_block && typeof content_block.id === "string"; -} -/** -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function convertToOpenAIImageBlock(content_block) { - if (isDataContentBlock(content_block)) { - if (content_block.source_type === "url") return { - type: "image_url", - image_url: { url: content_block.url } - }; - if (content_block.source_type === "base64") { - if (!content_block.mime_type) throw new Error("mime_type key is required for base64 data."); - const mime_type = content_block.mime_type; - return { - type: "image_url", - image_url: { url: `data:${mime_type};base64,${content_block.data}` } - }; - } - } - throw new Error("Unsupported source type. Only 'url' and 'base64' are supported."); -} -/** -* Utility function for ChatModelProviders. Parses a mime type into a type, subtype, and parameters. -* -* @param mime_type - The mime type to parse. -* @returns An object containing the type, subtype, and parameters. -* -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function parseMimeType(mime_type) { - const parts = mime_type.split(";")[0].split("/"); - if (parts.length !== 2) throw new Error(`Invalid mime type: "${mime_type}" - does not match type/subtype format.`); - const type = parts[0].trim(); - const subtype = parts[1].trim(); - if (type === "" || subtype === "") throw new Error(`Invalid mime type: "${mime_type}" - type or subtype is empty.`); - const parameters = {}; - for (const parameterKvp of mime_type.split(";").slice(1)) { - const parameterParts = parameterKvp.split("="); - if (parameterParts.length !== 2) throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); - const key = parameterParts[0].trim(); - const value = parameterParts[1].trim(); - if (key === "") throw new Error(`Invalid parameter syntax in mime type: "${mime_type}".`); - parameters[key] = value; - } - return { - type, - subtype, - parameters - }; -} -/** -* Utility function for ChatModelProviders. Parses a base64 data URL into a typed array or string. -* -* @param dataUrl - The base64 data URL to parse. -* @param asTypedArray - Whether to return the data as a typed array. -* @returns The parsed data and mime type, or undefined if the data URL is invalid. -* -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function parseBase64DataUrl({ dataUrl: data_url, asTypedArray = false }) { - const formatMatch = data_url.match(/^data:(\w+\/\w+);base64,([A-Za-z0-9+/]+=*)$/); - let mime_type; - if (formatMatch) { - mime_type = formatMatch[1].toLowerCase(); - const data = asTypedArray ? Uint8Array.from(atob(formatMatch[2]), (c) => c.charCodeAt(0)) : formatMatch[2]; - return { - mime_type, - data - }; - } - return void 0; -} -/** -* Convert from a standard data content block to a provider's proprietary data content block format. -* -* Don't override this method. Instead, override the more specific conversion methods and use this -* method unmodified. -* -* @param block - The standard data content block to convert. -* @returns The provider data content block. -* @throws An error if the standard data content block type is not supported. -* -* @deprecated Don't use data content blocks. Use {@link ContentBlock.Multimodal.Data} instead. -*/ -function convertToProviderContentBlock(block, converter) { - if (block.type === "text") { - if (!converter.fromStandardTextBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardTextBlock\` method.`); - return converter.fromStandardTextBlock(block); - } - if (block.type === "image") { - if (!converter.fromStandardImageBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardImageBlock\` method.`); - return converter.fromStandardImageBlock(block); - } - if (block.type === "audio") { - if (!converter.fromStandardAudioBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardAudioBlock\` method.`); - return converter.fromStandardAudioBlock(block); - } - if (block.type === "file") { - if (!converter.fromStandardFileBlock) throw new Error(`Converter for ${converter.providerName} does not implement \`fromStandardFileBlock\` method.`); - return converter.fromStandardFileBlock(block); - } - throw new Error(`Unable to convert content block type '${block.type}' to provider-specific format: not recognized.`); -} - -//#endregion - -//# sourceMappingURL=data.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/utils.js -//#region src/messages/block_translators/utils.ts -function _isContentBlock(block, type) { - return _isObject(block) && block.type === type; -} -function _isObject(value) { - return typeof value === "object" && value !== null; -} -function _isArray(value) { - return Array.isArray(value); -} -function _isString(value) { - return typeof value === "string"; -} -function _isNumber(value) { - return typeof value === "number"; -} -function _isBytesArray(value) { - return value instanceof Uint8Array; -} -function safeParseJson(value) { - try { - return JSON.parse(value); - } catch { - return void 0; - } -} -const iife = (fn) => fn(); - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/anthropic.js - - -//#region src/messages/block_translators/anthropic.ts -function convertAnthropicAnnotation(citation) { - if (citation.type === "char_location" && _isString(citation.document_title) && _isNumber(citation.start_char_index) && _isNumber(citation.end_char_index) && _isString(citation.cited_text)) { - const { document_title, start_char_index, end_char_index, cited_text,...rest } = citation; - return { - ...rest, - type: "citation", - source: "char", - title: document_title ?? void 0, - startIndex: start_char_index, - endIndex: end_char_index, - citedText: cited_text - }; - } - if (citation.type === "page_location" && _isString(citation.document_title) && _isNumber(citation.start_page_number) && _isNumber(citation.end_page_number) && _isString(citation.cited_text)) { - const { document_title, start_page_number, end_page_number, cited_text,...rest } = citation; - return { - ...rest, - type: "citation", - source: "page", - title: document_title ?? void 0, - startIndex: start_page_number, - endIndex: end_page_number, - citedText: cited_text - }; - } - if (citation.type === "content_block_location" && _isString(citation.document_title) && _isNumber(citation.start_block_index) && _isNumber(citation.end_block_index) && _isString(citation.cited_text)) { - const { document_title, start_block_index, end_block_index, cited_text,...rest } = citation; - return { - ...rest, - type: "citation", - source: "block", - title: document_title ?? void 0, - startIndex: start_block_index, - endIndex: end_block_index, - citedText: cited_text - }; - } - if (citation.type === "web_search_result_location" && _isString(citation.url) && _isString(citation.title) && _isString(citation.encrypted_index) && _isString(citation.cited_text)) { - const { url, title, encrypted_index, cited_text,...rest } = citation; - return { - ...rest, - type: "citation", - source: "url", - url, - title, - startIndex: Number(encrypted_index), - endIndex: Number(encrypted_index), - citedText: cited_text - }; - } - if (citation.type === "search_result_location" && _isString(citation.source) && _isString(citation.title) && _isNumber(citation.start_block_index) && _isNumber(citation.end_block_index) && _isString(citation.cited_text)) { - const { source, title, start_block_index, end_block_index, cited_text,...rest } = citation; - return { - ...rest, - type: "citation", - source: "search", - url: source, - title: title ?? void 0, - startIndex: start_block_index, - endIndex: end_block_index, - citedText: cited_text - }; - } - return void 0; -} -/** -* Converts an Anthropic content block to a standard V1 content block. -* -* This function handles the conversion of Anthropic-specific content blocks -* (document and image blocks) to the standardized V1 format. It supports -* various source types including base64 data, URLs, file IDs, and text data. -* -* @param block - The Anthropic content block to convert -* @returns A standard V1 content block if conversion is successful, undefined otherwise -* -* @example -* ```typescript -* const anthropicBlock = { -* type: "image", -* source: { -* type: "base64", -* media_type: "image/png", -* data: "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==" -* } -* }; -* -* const standardBlock = convertToV1FromAnthropicContentBlock(anthropicBlock); -* // Returns: { type: "image", mimeType: "image/png", data: "..." } -* ``` -*/ -function convertToV1FromAnthropicContentBlock(block) { - if (_isContentBlock(block, "document") && _isObject(block.source) && "type" in block.source) { - if (block.source.type === "base64" && _isString(block.source.media_type) && _isString(block.source.data)) return { - type: "file", - mimeType: block.source.media_type, - data: block.source.data - }; - else if (block.source.type === "url" && _isString(block.source.url)) return { - type: "file", - url: block.source.url - }; - else if (block.source.type === "file" && _isString(block.source.file_id)) return { - type: "file", - fileId: block.source.file_id - }; - else if (block.source.type === "text" && _isString(block.source.data)) return { - type: "file", - mimeType: String(block.source.media_type ?? "text/plain"), - data: block.source.data - }; - } else if (_isContentBlock(block, "image") && _isObject(block.source) && "type" in block.source) { - if (block.source.type === "base64" && _isString(block.source.media_type) && _isString(block.source.data)) return { - type: "image", - mimeType: block.source.media_type, - data: block.source.data - }; - else if (block.source.type === "url" && _isString(block.source.url)) return { - type: "image", - url: block.source.url - }; - else if (block.source.type === "file" && _isString(block.source.file_id)) return { - type: "image", - fileId: block.source.file_id - }; - } - return void 0; -} -/** -* Converts an array of content blocks from Anthropic format to v1 standard format. -* -* This function processes each content block in the input array, attempting to convert -* Anthropic-specific block formats (like image blocks with source objects, document blocks, etc.) -* to the standardized v1 content block format. If a block cannot be converted, it is -* passed through as-is with a type assertion to ContentBlock.Standard. -* -* @param content - Array of content blocks in Anthropic format to be converted -* @returns Array of content blocks in v1 standard format -*/ -function convertToV1FromAnthropicInput(content) { - function* iterateContent() { - for (const block of content) { - const stdBlock = convertToV1FromAnthropicContentBlock(block); - if (stdBlock) yield stdBlock; - else yield block; - } - } - return Array.from(iterateContent()); -} -/** -* Converts an Anthropic AI message to an array of v1 standard content blocks. -* -* This function processes an AI message containing Anthropic-specific content blocks -* and converts them to the standardized v1 content block format. -* -* @param message - The AI message containing Anthropic-formatted content blocks -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const message = new AIMessage([ -* { type: "text", text: "Hello world" }, -* { type: "thinking", text: "Let me think about this..." }, -* { type: "tool_use", id: "123", name: "calculator", input: { a: 1, b: 2 } } -* ]); -* -* const standardBlocks = convertToV1FromAnthropicMessage(message); -* // Returns: -* // [ -* // { type: "text", text: "Hello world" }, -* // { type: "reasoning", reasoning: "Let me think about this..." }, -* // { type: "tool_call", id: "123", name: "calculator", args: { a: 1, b: 2 } } -* // ] -* ``` -*/ -function convertToV1FromAnthropicMessage(message) { - function* iterateContent() { - const content = typeof message.content === "string" ? [{ - type: "text", - text: message.content - }] : message.content; - for (const block of content) { - if (_isContentBlock(block, "text") && _isString(block.text)) { - const { text, citations,...rest } = block; - if (_isArray(citations) && citations.length) { - const _citations = citations.reduce((acc, item) => { - const citation = convertAnthropicAnnotation(item); - if (citation) return [...acc, citation]; - return acc; - }, []); - yield { - ...rest, - type: "text", - text, - annotations: _citations - }; - continue; - } else { - yield { - ...rest, - type: "text", - text - }; - continue; - } - } else if (_isContentBlock(block, "thinking") && _isString(block.thinking)) { - const { thinking, signature,...rest } = block; - yield { - ...rest, - type: "reasoning", - reasoning: thinking, - signature - }; - continue; - } else if (_isContentBlock(block, "redacted_thinking")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "tool_use") && _isString(block.name) && _isString(block.id)) { - yield { - type: "tool_call", - id: block.id, - name: block.name, - args: block.input - }; - continue; - } else if (_isContentBlock(block, "input_json_delta")) { - if (_isAIMessageChunk(message) && message.tool_call_chunks?.length) { - const tool_call_chunk = message.tool_call_chunks[0]; - yield { - type: "tool_call_chunk", - id: tool_call_chunk.id, - name: tool_call_chunk.name, - args: tool_call_chunk.args, - index: tool_call_chunk.index - }; - continue; - } - } else if (_isContentBlock(block, "server_tool_use") && _isString(block.name) && _isString(block.id)) { - const { name, id } = block; - if (name === "web_search") { - const query = iife(() => { - if (typeof block.input === "string") return block.input; - else if (_isObject(block.input) && _isString(block.input.query)) return block.input.query; - else if (_isString(block.partial_json)) { - const json = safeParseJson(block.partial_json); - if (json?.query) return json.query; - } - return ""; - }); - yield { - id, - type: "server_tool_call", - name: "web_search", - args: { query } - }; - continue; - } else if (block.name === "code_execution") { - const code = iife(() => { - if (typeof block.input === "string") return block.input; - else if (_isObject(block.input) && _isString(block.input.code)) return block.input.code; - else if (_isString(block.partial_json)) { - const json = safeParseJson(block.partial_json); - if (json?.code) return json.code; - } - return ""; - }); - yield { - id, - type: "server_tool_call", - name: "code_execution", - args: { code } - }; - continue; - } - } else if (_isContentBlock(block, "web_search_tool_result") && _isString(block.tool_use_id) && _isArray(block.content)) { - const { content: content$1, tool_use_id } = block; - const urls = content$1.reduce((acc, content$2) => { - if (_isContentBlock(content$2, "web_search_result")) return [...acc, content$2.url]; - return acc; - }, []); - yield { - type: "server_tool_call_result", - name: "web_search", - toolCallId: tool_use_id, - status: "success", - output: { urls } - }; - continue; - } else if (_isContentBlock(block, "code_execution_tool_result") && _isString(block.tool_use_id) && _isObject(block.content)) { - yield { - type: "server_tool_call_result", - name: "code_execution", - toolCallId: block.tool_use_id, - status: "success", - output: block.content - }; - continue; - } else if (_isContentBlock(block, "mcp_tool_use")) { - yield { - id: block.id, - type: "server_tool_call", - name: "mcp_tool_use", - args: block.input - }; - continue; - } else if (_isContentBlock(block, "mcp_tool_result") && _isString(block.tool_use_id) && _isObject(block.content)) { - yield { - type: "server_tool_call_result", - name: "mcp_tool_use", - toolCallId: block.tool_use_id, - status: "success", - output: block.content - }; - continue; - } else if (_isContentBlock(block, "container_upload")) { - yield { - type: "server_tool_call", - name: "container_upload", - args: block.input - }; - continue; - } else if (_isContentBlock(block, "search_result")) { - yield { - id: block.id, - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "tool_result")) { - yield { - id: block.id, - type: "non_standard", - value: block - }; - continue; - } else { - const stdBlock = convertToV1FromAnthropicContentBlock(block); - if (stdBlock) { - yield stdBlock; - continue; - } - } - yield { - type: "non_standard", - value: block - }; - } - } - return Array.from(iterateContent()); -} -const ChatAnthropicTranslator = { - translateContent: convertToV1FromAnthropicMessage, - translateContentChunk: convertToV1FromAnthropicMessage -}; -function _isAIMessageChunk(message) { - return typeof message?._getType === "function" && typeof message.concat === "function" && message._getType() === "ai"; -} - -//#endregion - -//# sourceMappingURL=anthropic.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/data.js - - - -//#region src/messages/block_translators/data.ts -function convertToV1FromDataContentBlock(block) { - if (isURLContentBlock(block)) return { - type: block.type, - mimeType: block.mime_type, - url: block.url, - metadata: block.metadata - }; - if (isBase64ContentBlock(block)) return { - type: block.type, - mimeType: block.mime_type ?? "application/octet-stream", - data: block.data, - metadata: block.metadata - }; - if (isIDContentBlock(block)) return { - type: block.type, - mimeType: block.mime_type, - fileId: block.id, - metadata: block.metadata - }; - return block; -} -function convertToV1FromDataContent(content) { - return content.map(convertToV1FromDataContentBlock); -} -function isOpenAIDataBlock(block) { - if (_isContentBlock(block, "image_url") && _isObject(block.image_url)) return true; - if (_isContentBlock(block, "input_audio") && _isObject(block.input_audio)) return true; - if (_isContentBlock(block, "file") && _isObject(block.file)) return true; - return false; -} -function convertToV1FromOpenAIDataBlock(block) { - if (_isContentBlock(block, "image_url") && _isObject(block.image_url) && _isString(block.image_url.url)) { - const parsed = parseBase64DataUrl({ dataUrl: block.image_url.url }); - if (parsed) return { - type: "image", - mimeType: parsed.mime_type, - data: parsed.data - }; - else return { - type: "image", - url: block.image_url.url - }; - } else if (_isContentBlock(block, "input_audio") && _isObject(block.input_audio) && _isString(block.input_audio.data) && _isString(block.input_audio.format)) return { - type: "audio", - data: block.input_audio.data, - mimeType: `audio/${block.input_audio.format}` - }; - else if (_isContentBlock(block, "file") && _isObject(block.file) && _isString(block.file.data)) { - const parsed = parseBase64DataUrl({ dataUrl: block.file.data }); - if (parsed) return { - type: "file", - data: parsed.data, - mimeType: parsed.mime_type - }; - else if (_isString(block.file.file_id)) return { - type: "file", - fileId: block.file.file_id - }; - } - return block; -} - -//#endregion - -//# sourceMappingURL=data.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/openai.js - - - -//#region src/messages/block_translators/openai.ts -/** -* Converts a ChatOpenAICompletions message to an array of v1 standard content blocks. -* -* This function processes an AI message from ChatOpenAICompletions API format -* and converts it to the standardized v1 content block format. It handles both -* string content and structured content blocks, as well as tool calls. -* -* @param message - The AI message containing ChatOpenAICompletions formatted content -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const message = new AIMessage("Hello world"); -* const standardBlocks = convertToV1FromChatCompletions(message); -* // Returns: [{ type: "text", text: "Hello world" }] -* ``` -* -* @example -* ```typescript -* const message = new AIMessage([ -* { type: "text", text: "Hello" }, -* { type: "image_url", image_url: { url: "https://example.com/image.png" } } -* ]); -* message.tool_calls = [ -* { id: "call_123", name: "calculator", args: { a: 1, b: 2 } } -* ]; -* -* const standardBlocks = convertToV1FromChatCompletions(message); -* // Returns: -* // [ -* // { type: "text", text: "Hello" }, -* // { type: "image", url: "https://example.com/image.png" }, -* // { type: "tool_call", id: "call_123", name: "calculator", args: { a: 1, b: 2 } } -* // ] -* ``` -*/ -function convertToV1FromChatCompletions(message) { - const blocks = []; - if (typeof message.content === "string") blocks.push({ - type: "text", - text: message.content - }); - else blocks.push(...convertToV1FromChatCompletionsInput(message.content)); - for (const toolCall of message.tool_calls ?? []) blocks.push({ - type: "tool_call", - id: toolCall.id, - name: toolCall.name, - args: toolCall.args - }); - return blocks; -} -/** -* Converts a ChatOpenAICompletions message chunk to an array of v1 standard content blocks. -* -* This function processes an AI message chunk from OpenAI's chat completions API and converts -* it to the standardized v1 content block format. It handles both string and array content, -* as well as tool calls that may be present in the chunk. -* -* @param message - The AI message chunk containing OpenAI-formatted content blocks -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const chunk = new AIMessage("Hello"); -* const standardBlocks = convertToV1FromChatCompletionsChunk(chunk); -* // Returns: [{ type: "text", text: "Hello" }] -* ``` -* -* @example -* ```typescript -* const chunk = new AIMessage([ -* { type: "text", text: "Processing..." } -* ]); -* chunk.tool_calls = [ -* { id: "call_456", name: "search", args: { query: "test" } } -* ]; -* -* const standardBlocks = convertToV1FromChatCompletionsChunk(chunk); -* // Returns: -* // [ -* // { type: "text", text: "Processing..." }, -* // { type: "tool_call", id: "call_456", name: "search", args: { query: "test" } } -* // ] -* ``` -*/ -function convertToV1FromChatCompletionsChunk(message) { - const blocks = []; - if (typeof message.content === "string") blocks.push({ - type: "text", - text: message.content - }); - else blocks.push(...convertToV1FromChatCompletionsInput(message.content)); - for (const toolCall of message.tool_calls ?? []) blocks.push({ - type: "tool_call", - id: toolCall.id, - name: toolCall.name, - args: toolCall.args - }); - return blocks; -} -/** -* Converts an array of ChatOpenAICompletions content blocks to v1 standard content blocks. -* -* This function processes content blocks from OpenAI's Chat Completions API format -* and converts them to the standardized v1 content block format. It handles both -* OpenAI-specific data blocks (which require conversion) and standard blocks -* (which are passed through with type assertion). -* -* @param blocks - Array of content blocks in ChatOpenAICompletions format -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const openaiBlocks = [ -* { type: "text", text: "Hello world" }, -* { type: "image_url", image_url: { url: "https://example.com/image.png" } } -* ]; -* -* const standardBlocks = convertToV1FromChatCompletionsInput(openaiBlocks); -* // Returns: -* // [ -* // { type: "text", text: "Hello world" }, -* // { type: "image", url: "https://example.com/image.png" } -* // ] -* ``` -*/ -function convertToV1FromChatCompletionsInput(blocks) { - const convertedBlocks = []; - for (const block of blocks) if (isOpenAIDataBlock(block)) convertedBlocks.push(convertToV1FromOpenAIDataBlock(block)); - else convertedBlocks.push(block); - return convertedBlocks; -} -function convertResponsesAnnotation(annotation) { - if (annotation.type === "url_citation") { - const { url, title, start_index, end_index } = annotation; - return { - type: "citation", - url, - title, - startIndex: start_index, - endIndex: end_index - }; - } - if (annotation.type === "file_citation") { - const { file_id, filename, index } = annotation; - return { - type: "citation", - title: filename, - startIndex: index, - endIndex: index, - fileId: file_id - }; - } - return annotation; -} -/** -* Converts a ChatOpenAIResponses message to an array of v1 standard content blocks. -* -* This function processes an AI message containing OpenAI Responses-specific content blocks -* and converts them to the standardized v1 content block format. It handles reasoning summaries, -* text content with annotations, tool calls, and various tool outputs including code interpreter, -* web search, file search, computer calls, and MCP-related blocks. -* -* @param message - The AI message containing OpenAI Responses-formatted content blocks -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const message = new AIMessage({ -* content: [{ type: "text", text: "Hello world", annotations: [] }], -* tool_calls: [{ id: "123", name: "calculator", args: { a: 1, b: 2 } }], -* additional_kwargs: { -* reasoning: { summary: [{ text: "Let me calculate this..." }] }, -* tool_outputs: [ -* { -* type: "code_interpreter_call", -* code: "print('hello')", -* outputs: [{ type: "logs", logs: "hello" }] -* } -* ] -* } -* }); -* -* const standardBlocks = convertToV1FromResponses(message); -* // Returns: -* // [ -* // { type: "reasoning", reasoning: "Let me calculate this..." }, -* // { type: "text", text: "Hello world", annotations: [] }, -* // { type: "tool_call", id: "123", name: "calculator", args: { a: 1, b: 2 } }, -* // { type: "code_interpreter_call", code: "print('hello')" }, -* // { type: "code_interpreter_result", output: [{ type: "code_interpreter_output", returnCode: 0, stdout: "hello" }] } -* // ] -* ``` -*/ -function convertToV1FromResponses(message) { - function* iterateContent() { - if (_isObject(message.additional_kwargs?.reasoning) && _isArray(message.additional_kwargs.reasoning.summary)) { - const summary = message.additional_kwargs.reasoning.summary.reduce((acc, item) => { - if (_isObject(item) && _isString(item.text)) return `${acc}${item.text}`; - return acc; - }, ""); - yield { - type: "reasoning", - reasoning: summary - }; - } - const content = typeof message.content === "string" ? [{ - type: "text", - text: message.content - }] : message.content; - for (const block of content) if (_isContentBlock(block, "text")) { - const { text, annotations,...rest } = block; - if (Array.isArray(annotations)) yield { - ...rest, - type: "text", - text: String(text), - annotations: annotations.map(convertResponsesAnnotation) - }; - else yield { - ...rest, - type: "text", - text: String(text) - }; - } - for (const toolCall of message.tool_calls ?? []) yield { - type: "tool_call", - id: toolCall.id, - name: toolCall.name, - args: toolCall.args - }; - if (_isObject(message.additional_kwargs) && _isArray(message.additional_kwargs.tool_outputs)) for (const toolOutput of message.additional_kwargs.tool_outputs) { - if (_isContentBlock(toolOutput, "web_search_call")) { - yield { - id: toolOutput.id, - type: "server_tool_call", - name: "web_search", - args: { query: toolOutput.query } - }; - continue; - } else if (_isContentBlock(toolOutput, "file_search_call")) { - yield { - id: toolOutput.id, - type: "server_tool_call", - name: "file_search", - args: { query: toolOutput.query } - }; - continue; - } else if (_isContentBlock(toolOutput, "computer_call")) { - yield { - type: "non_standard", - value: toolOutput - }; - continue; - } else if (_isContentBlock(toolOutput, "code_interpreter_call")) { - if (_isString(toolOutput.code)) yield { - id: toolOutput.id, - type: "server_tool_call", - name: "code_interpreter", - args: { code: toolOutput.code } - }; - if (_isArray(toolOutput.outputs)) { - const returnCode = iife(() => { - if (toolOutput.status === "in_progress") return void 0; - if (toolOutput.status === "completed") return 0; - if (toolOutput.status === "incomplete") return 127; - if (toolOutput.status === "interpreting") return void 0; - if (toolOutput.status === "failed") return 1; - return void 0; - }); - for (const output of toolOutput.outputs) if (_isContentBlock(output, "logs")) { - yield { - type: "server_tool_call_result", - toolCallId: toolOutput.id ?? "", - status: "success", - output: { - type: "code_interpreter_output", - returnCode: returnCode ?? 0, - stderr: [0, void 0].includes(returnCode) ? void 0 : String(output.logs), - stdout: [0, void 0].includes(returnCode) ? String(output.logs) : void 0 - } - }; - continue; - } - } - continue; - } else if (_isContentBlock(toolOutput, "mcp_call")) { - yield { - id: toolOutput.id, - type: "server_tool_call", - name: "mcp_call", - args: toolOutput.input - }; - continue; - } else if (_isContentBlock(toolOutput, "mcp_list_tools")) { - yield { - id: toolOutput.id, - type: "server_tool_call", - name: "mcp_list_tools", - args: toolOutput.input - }; - continue; - } else if (_isContentBlock(toolOutput, "mcp_approval_request")) { - yield { - type: "non_standard", - value: toolOutput - }; - continue; - } else if (_isContentBlock(toolOutput, "image_generation_call")) { - yield { - type: "non_standard", - value: toolOutput - }; - continue; - } - if (_isObject(toolOutput)) yield { - type: "non_standard", - value: toolOutput - }; - } - } - return Array.from(iterateContent()); -} -/** -* Converts a ChatOpenAIResponses message chunk to an array of v1 standard content blocks. -* -* This function processes an AI message chunk containing OpenAI-specific content blocks -* and converts them to the standardized v1 content block format. It handles both the -* regular message content and tool call chunks that are specific to streaming responses. -* -* @param message - The AI message chunk containing OpenAI-formatted content blocks -* @returns Array of content blocks in v1 standard format -* -* @example -* ```typescript -* const messageChunk = new AIMessageChunk({ -* content: [{ type: "text", text: "Hello" }], -* tool_call_chunks: [ -* { id: "call_123", name: "calculator", args: '{"a": 1' } -* ] -* }); -* -* const standardBlocks = convertToV1FromResponsesChunk(messageChunk); -* // Returns: -* // [ -* // { type: "text", text: "Hello" }, -* // { type: "tool_call_chunk", id: "call_123", name: "calculator", args: '{"a": 1' } -* // ] -* ``` -*/ -function convertToV1FromResponsesChunk(message) { - function* iterateContent() { - yield* convertToV1FromResponses(message); - for (const toolCallChunk of message.tool_call_chunks ?? []) yield { - type: "tool_call_chunk", - id: toolCallChunk.id, - name: toolCallChunk.name, - args: toolCallChunk.args - }; - } - return Array.from(iterateContent()); -} -const ChatOpenAITranslator = { - translateContent: (message) => { - if (typeof message.content === "string") return convertToV1FromChatCompletions(message); - return convertToV1FromResponses(message); - }, - translateContentChunk: (message) => { - if (typeof message.content === "string") return convertToV1FromChatCompletionsChunk(message); - return convertToV1FromResponsesChunk(message); - } -}; - -//#endregion - -//# sourceMappingURL=openai.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/message.js -//#region src/messages/message.ts -/** -* Type guard to check if a value is a valid Message object. -* -* @param message - The value to check -* @returns true if the value is a valid Message object, false otherwise -*/ -function isMessage(message) { - return typeof message === "object" && message !== null && "type" in message && "content" in message && (typeof message.content === "string" || Array.isArray(message.content)); -} - -//#endregion - -//# sourceMappingURL=message.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/format.js -//#region src/messages/format.ts -function convertToFormattedString(message, format = "pretty") { - if (format === "pretty") return convertToPrettyString(message); - return JSON.stringify(message); -} -function convertToPrettyString(message) { - const lines = []; - const title = ` ${message.type.charAt(0).toUpperCase() + message.type.slice(1)} Message `; - const sepLen = Math.floor((80 - title.length) / 2); - const sep = "=".repeat(sepLen); - const secondSep = title.length % 2 === 0 ? sep : `${sep}=`; - lines.push(`${sep}${title}${secondSep}`); - if (message.type === "ai") { - const aiMessage = message; - if (aiMessage.tool_calls && aiMessage.tool_calls.length > 0) { - lines.push("Tool Calls:"); - for (const tc of aiMessage.tool_calls) { - lines.push(` ${tc.name} (${tc.id})`); - lines.push(` Call ID: ${tc.id}`); - lines.push(" Args:"); - for (const [key, value] of Object.entries(tc.args)) lines.push(` ${key}: ${typeof value === "object" ? JSON.stringify(value) : value}`); - } - } - } - if (message.type === "tool") { - const toolMessage = message; - if (toolMessage.name) lines.push(`Name: ${toolMessage.name}`); - } - if (typeof message.content === "string" && message.content.trim()) { - if (lines.length > 1) lines.push(""); - lines.push(message.content); - } - return lines.join("\n"); -} - -//#endregion - -//# sourceMappingURL=format.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/base.js - - - - - - - - -//#region src/messages/base.ts -/** @internal */ -const MESSAGE_SYMBOL = Symbol.for("langchain.message"); -function mergeContent(firstContent, secondContent) { - if (typeof firstContent === "string") { - if (firstContent === "") return secondContent; - if (typeof secondContent === "string") return firstContent + secondContent; - else if (Array.isArray(secondContent) && secondContent.length === 0) return firstContent; - else if (Array.isArray(secondContent) && secondContent.some((c) => isDataContentBlock(c))) return [{ - type: "text", - source_type: "text", - text: firstContent - }, ...secondContent]; - else return [{ - type: "text", - text: firstContent - }, ...secondContent]; - } else if (Array.isArray(secondContent)) return _mergeLists(firstContent, secondContent) ?? [...firstContent, ...secondContent]; - else if (secondContent === "") return firstContent; - else if (Array.isArray(firstContent) && firstContent.some((c) => isDataContentBlock(c))) return [...firstContent, { - type: "file", - source_type: "text", - text: secondContent - }]; - else return [...firstContent, { - type: "text", - text: secondContent - }]; -} -/** -* 'Merge' two statuses. If either value passed is 'error', it will return 'error'. Else -* it will return 'success'. -* -* @param {"success" | "error" | undefined} left The existing value to 'merge' with the new value. -* @param {"success" | "error" | undefined} right The new value to 'merge' with the existing value -* @returns {"success" | "error"} The 'merged' value. -*/ -function _mergeStatus(left, right) { - if (left === "error" || right === "error") return "error"; - return "success"; -} -function stringifyWithDepthLimit(obj, depthLimit) { - function helper(obj$1, currentDepth) { - if (typeof obj$1 !== "object" || obj$1 === null || obj$1 === void 0) return obj$1; - if (currentDepth >= depthLimit) { - if (Array.isArray(obj$1)) return "[Array]"; - return "[Object]"; - } - if (Array.isArray(obj$1)) return obj$1.map((item) => helper(item, currentDepth + 1)); - const result = {}; - for (const key of Object.keys(obj$1)) result[key] = helper(obj$1[key], currentDepth + 1); - return result; - } - return JSON.stringify(helper(obj, 0), null, 2); -} -/** -* Base class for all types of messages in a conversation. It includes -* properties like `content`, `name`, and `additional_kwargs`. It also -* includes methods like `toDict()` and `_getType()`. -*/ -var BaseMessage = class extends Serializable { - lc_namespace = ["langchain_core", "messages"]; - lc_serializable = true; - get lc_aliases() { - return { - additional_kwargs: "additional_kwargs", - response_metadata: "response_metadata" - }; - } - [MESSAGE_SYMBOL] = true; - id; - /** @inheritdoc */ - name; - content; - additional_kwargs; - response_metadata; - /** - * @deprecated Use .getType() instead or import the proper typeguard. - * For example: - * - * ```ts - * import { isAIMessage } from "@langchain/core/messages"; - * - * const message = new AIMessage("Hello!"); - * isAIMessage(message); // true - * ``` - */ - _getType() { - return this.type; - } - /** - * @deprecated Use .type instead - * The type of the message. - */ - getType() { - return this._getType(); - } - constructor(arg) { - const fields = typeof arg === "string" || Array.isArray(arg) ? { content: arg } : arg; - if (!fields.additional_kwargs) fields.additional_kwargs = {}; - if (!fields.response_metadata) fields.response_metadata = {}; - super(fields); - this.name = fields.name; - if (fields.content === void 0 && fields.contentBlocks !== void 0) { - this.content = fields.contentBlocks; - this.response_metadata = { - output_version: "v1", - ...fields.response_metadata - }; - } else if (fields.content !== void 0) { - this.content = fields.content ?? []; - this.response_metadata = fields.response_metadata; - } else { - this.content = []; - this.response_metadata = fields.response_metadata; - } - this.additional_kwargs = fields.additional_kwargs; - this.id = fields.id; - } - /** Get text content of the message. */ - get text() { - if (typeof this.content === "string") return this.content; - if (!Array.isArray(this.content)) return ""; - return this.content.map((c) => { - if (typeof c === "string") return c; - if (c.type === "text") return c.text; - return ""; - }).join(""); - } - get contentBlocks() { - const blocks = typeof this.content === "string" ? [{ - type: "text", - text: this.content - }] : this.content; - const parsingSteps = [ - convertToV1FromDataContent, - convertToV1FromChatCompletionsInput, - convertToV1FromAnthropicInput - ]; - const parsedBlocks = parsingSteps.reduce((blocks$1, step) => step(blocks$1), blocks); - return parsedBlocks; - } - toDict() { - return { - type: this.getType(), - data: this.toJSON().kwargs - }; - } - static lc_name() { - return "BaseMessage"; - } - get _printableFields() { - return { - id: this.id, - content: this.content, - name: this.name, - additional_kwargs: this.additional_kwargs, - response_metadata: this.response_metadata - }; - } - static isInstance(obj) { - return typeof obj === "object" && obj !== null && MESSAGE_SYMBOL in obj && obj[MESSAGE_SYMBOL] === true && isMessage(obj); - } - _updateId(value) { - this.id = value; - this.lc_kwargs.id = value; - } - get [Symbol.toStringTag]() { - return this.constructor.lc_name(); - } - [Symbol.for("nodejs.util.inspect.custom")](depth) { - if (depth === null) return this; - const printable = stringifyWithDepthLimit(this._printableFields, Math.max(4, depth)); - return `${this.constructor.lc_name()} ${printable}`; - } - toFormattedString(format = "pretty") { - return convertToFormattedString(this, format); - } -}; -function isOpenAIToolCallArray(value) { - return Array.isArray(value) && value.every((v) => typeof v.index === "number"); -} -function _mergeDicts(left = {}, right = {}) { - const merged = { ...left }; - for (const [key, value] of Object.entries(right)) if (merged[key] == null) merged[key] = value; - else if (value == null) continue; - else if (typeof merged[key] !== typeof value || Array.isArray(merged[key]) !== Array.isArray(value)) throw new Error(`field[${key}] already exists in the message chunk, but with a different type.`); - else if (typeof merged[key] === "string") if (key === "type") continue; - else if ([ - "id", - "name", - "output_version", - "model_provider" - ].includes(key)) { - if (value) merged[key] = value; - } else merged[key] += value; - else if (typeof merged[key] === "object" && !Array.isArray(merged[key])) merged[key] = _mergeDicts(merged[key], value); - else if (Array.isArray(merged[key])) merged[key] = _mergeLists(merged[key], value); - else if (merged[key] === value) continue; - else console.warn(`field[${key}] already exists in this message chunk and value has unsupported type.`); - return merged; -} -function _mergeLists(left, right) { - if (left === void 0 && right === void 0) return void 0; - else if (left === void 0 || right === void 0) return left || right; - else { - const merged = [...left]; - for (const item of right) if (typeof item === "object" && item !== null && "index" in item && typeof item.index === "number") { - const toMerge = merged.findIndex((leftItem) => { - const isObject = typeof leftItem === "object"; - const indiciesMatch = "index" in leftItem && leftItem.index === item.index; - const idsMatch = "id" in leftItem && "id" in item && leftItem?.id === item?.id; - const eitherItemMissingID = !("id" in leftItem) || !leftItem?.id || !("id" in item) || !item?.id; - return isObject && indiciesMatch && (idsMatch || eitherItemMissingID); - }); - if (toMerge !== -1 && typeof merged[toMerge] === "object" && merged[toMerge] !== null) merged[toMerge] = _mergeDicts(merged[toMerge], item); - else merged.push(item); - } else if (typeof item === "object" && item !== null && "text" in item && item.text === "") continue; - else merged.push(item); - return merged; - } -} -function _mergeObj(left, right) { - if (left === void 0 && right === void 0) return void 0; - if (left === void 0 || right === void 0) return left ?? right; - else if (typeof left !== typeof right) throw new Error(`Cannot merge objects of different types.\nLeft ${typeof left}\nRight ${typeof right}`); - else if (typeof left === "string" && typeof right === "string") return left + right; - else if (Array.isArray(left) && Array.isArray(right)) return _mergeLists(left, right); - else if (typeof left === "object" && typeof right === "object") return _mergeDicts(left, right); - else if (left === right) return left; - else throw new Error(`Can not merge objects of different types.\nLeft ${left}\nRight ${right}`); -} -/** -* Represents a chunk of a message, which can be concatenated with other -* message chunks. It includes a method `_merge_kwargs_dict()` for merging -* additional keyword arguments from another `BaseMessageChunk` into this -* one. It also overrides the `__add__()` method to support concatenation -* of `BaseMessageChunk` instances. -*/ -var BaseMessageChunk = class BaseMessageChunk extends BaseMessage { - static isInstance(obj) { - if (!super.isInstance(obj)) return false; - let proto = Object.getPrototypeOf(obj); - while (proto !== null) { - if (proto === BaseMessageChunk.prototype) return true; - proto = Object.getPrototypeOf(proto); - } - return false; - } -}; -function _isMessageFieldWithRole(x) { - return typeof x.role === "string"; -} -/** -* @deprecated Use {@link BaseMessage.isInstance} instead -*/ -function isBaseMessage(messageLike) { - return typeof messageLike?._getType === "function"; -} -/** -* @deprecated Use {@link BaseMessageChunk.isInstance} instead -*/ -function isBaseMessageChunk(messageLike) { - return BaseMessageChunk.isInstance(messageLike); -} - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/tool.js - - - -//#region src/messages/tool.ts -var tool_exports = {}; -__export(tool_exports, { - ToolMessage: () => ToolMessage, - ToolMessageChunk: () => ToolMessageChunk, - defaultToolCallParser: () => defaultToolCallParser, - isDirectToolOutput: () => isDirectToolOutput, - isToolMessage: () => isToolMessage, - isToolMessageChunk: () => isToolMessageChunk -}); -function isDirectToolOutput(x) { - return x != null && typeof x === "object" && "lc_direct_tool_output" in x && x.lc_direct_tool_output === true; -} -/** -* Represents a tool message in a conversation. -*/ -var ToolMessage = class extends BaseMessage { - static lc_name() { - return "ToolMessage"; - } - get lc_aliases() { - return { tool_call_id: "tool_call_id" }; - } - lc_direct_tool_output = true; - type = "tool"; - /** - * Status of the tool invocation. - * @version 0.2.19 - */ - status; - tool_call_id; - metadata; - /** - * Artifact of the Tool execution which is not meant to be sent to the model. - * - * Should only be specified if it is different from the message content, e.g. if only - * a subset of the full tool output is being passed as message content but the full - * output is needed in other parts of the code. - */ - artifact; - constructor(fields, tool_call_id, name) { - const toolMessageFields = typeof fields === "string" || Array.isArray(fields) ? { - content: fields, - name, - tool_call_id - } : fields; - super(toolMessageFields); - this.tool_call_id = toolMessageFields.tool_call_id; - this.artifact = toolMessageFields.artifact; - this.status = toolMessageFields.status; - this.metadata = toolMessageFields.metadata; - } - static isInstance(message) { - return super.isInstance(message) && message.type === "tool"; - } - get _printableFields() { - return { - ...super._printableFields, - tool_call_id: this.tool_call_id, - artifact: this.artifact - }; - } -}; -/** -* Represents a chunk of a tool message, which can be concatenated -* with other tool message chunks. -*/ -var ToolMessageChunk = class extends BaseMessageChunk { - type = "tool"; - tool_call_id; - /** - * Status of the tool invocation. - * @version 0.2.19 - */ - status; - /** - * Artifact of the Tool execution which is not meant to be sent to the model. - * - * Should only be specified if it is different from the message content, e.g. if only - * a subset of the full tool output is being passed as message content but the full - * output is needed in other parts of the code. - */ - artifact; - constructor(fields) { - super(fields); - this.tool_call_id = fields.tool_call_id; - this.artifact = fields.artifact; - this.status = fields.status; - } - static lc_name() { - return "ToolMessageChunk"; - } - concat(chunk) { - const Cls = this.constructor; - return new Cls({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - artifact: _mergeObj(this.artifact, chunk.artifact), - tool_call_id: this.tool_call_id, - id: this.id ?? chunk.id, - status: _mergeStatus(this.status, chunk.status) - }); - } - get _printableFields() { - return { - ...super._printableFields, - tool_call_id: this.tool_call_id, - artifact: this.artifact - }; - } -}; -function defaultToolCallParser(rawToolCalls) { - const toolCalls = []; - const invalidToolCalls = []; - for (const toolCall of rawToolCalls) if (!toolCall.function) continue; - else { - const functionName = toolCall.function.name; - try { - const functionArgs = JSON.parse(toolCall.function.arguments); - toolCalls.push({ - name: functionName || "", - args: functionArgs || {}, - id: toolCall.id - }); - } catch { - invalidToolCalls.push({ - name: functionName, - args: toolCall.function.arguments, - id: toolCall.id, - error: "Malformed args." - }); - } - } - return [toolCalls, invalidToolCalls]; -} -/** -* @deprecated Use {@link ToolMessage.isInstance} instead -*/ -function isToolMessage(x) { - return typeof x === "object" && x !== null && "getType" in x && typeof x.getType === "function" && x.getType() === "tool"; -} -/** -* @deprecated Use {@link ToolMessageChunk.isInstance} instead -*/ -function isToolMessageChunk(x) { - return x._getType() === "tool"; -} - -//#endregion - -//# sourceMappingURL=tool.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/errors/index.js -//#region src/errors/index.ts -function addLangChainErrorFields(error, lc_error_code) { - error.lc_error_code = lc_error_code; - error.message = `${error.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\n`; - return error; -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/utils.js -//#region src/tools/utils.ts -function _isToolCall(toolCall) { - return !!(toolCall && typeof toolCall === "object" && "type" in toolCall && toolCall.type === "tool_call"); -} -function _configHasToolCallId(config) { - return !!(config && typeof config === "object" && "toolCall" in config && config.toolCall != null && typeof config.toolCall === "object" && "id" in config.toolCall && typeof config.toolCall.id === "string"); -} -/** -* Custom error class used to handle exceptions related to tool input parsing. -* It extends the built-in `Error` class and adds an optional `output` -* property that can hold the output that caused the exception. -*/ -var ToolInputParsingException = class extends Error { - output; - constructor(message, output) { - super(message); - this.output = output; - } -}; - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json.js -//#region src/utils/json.ts -function parseJsonMarkdown(s, parser = parsePartialJson) { - s = s.trim(); - const firstFenceIndex = s.indexOf("```"); - if (firstFenceIndex === -1) return parser(s); - let contentAfterFence = s.substring(firstFenceIndex + 3); - if (contentAfterFence.startsWith("json\n")) contentAfterFence = contentAfterFence.substring(5); - else if (contentAfterFence.startsWith("json")) contentAfterFence = contentAfterFence.substring(4); - else if (contentAfterFence.startsWith("\n")) contentAfterFence = contentAfterFence.substring(1); - const closingFenceIndex = contentAfterFence.indexOf("```"); - let finalContent = contentAfterFence; - if (closingFenceIndex !== -1) finalContent = contentAfterFence.substring(0, closingFenceIndex); - return parser(finalContent.trim()); -} -/** -* Recursive descent partial JSON parser. -* @param s - The string to parse. -* @returns The parsed value. -* @throws Error if the input is a malformed JSON string. -*/ -function strictParsePartialJson(s) { - try { - return JSON.parse(s); - } catch {} - const buffer = s.trim(); - if (buffer.length === 0) throw new Error("Unexpected end of JSON input"); - let pos = 0; - function skipWhitespace() { - while (pos < buffer.length && /\s/.test(buffer[pos])) pos += 1; - } - function parseString() { - if (buffer[pos] !== "\"") throw new Error(`Expected '"' at position ${pos}, got '${buffer[pos]}'`); - pos += 1; - let result = ""; - let escaped = false; - while (pos < buffer.length) { - const char = buffer[pos]; - if (escaped) { - if (char === "n") result += "\n"; - else if (char === "t") result += " "; - else if (char === "r") result += "\r"; - else if (char === "\\") result += "\\"; - else if (char === "\"") result += "\""; - else if (char === "b") result += "\b"; - else if (char === "f") result += "\f"; - else if (char === "/") result += "/"; - else if (char === "u") { - const hex = buffer.substring(pos + 1, pos + 5); - if (/^[0-9A-Fa-f]{0,4}$/.test(hex)) { - if (hex.length === 4) result += String.fromCharCode(Number.parseInt(hex, 16)); - else result += `u${hex}`; - pos += hex.length; - } else throw new Error(`Invalid unicode escape sequence '\\u${hex}' at position ${pos}`); - } else throw new Error(`Invalid escape sequence '\\${char}' at position ${pos}`); - escaped = false; - } else if (char === "\\") escaped = true; - else if (char === "\"") { - pos += 1; - return result; - } else result += char; - pos += 1; - } - if (escaped) result += "\\"; - return result; - } - function parseNumber() { - const start = pos; - let numStr = ""; - if (buffer[pos] === "-") { - numStr += "-"; - pos += 1; - } - if (pos < buffer.length && buffer[pos] === "0") { - numStr += "0"; - pos += 1; - if (buffer[pos] >= "0" && buffer[pos] <= "9") throw new Error(`Invalid number at position ${start}`); - } - if (pos < buffer.length && buffer[pos] >= "1" && buffer[pos] <= "9") while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") { - numStr += buffer[pos]; - pos += 1; - } - if (pos < buffer.length && buffer[pos] === ".") { - numStr += "."; - pos += 1; - while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") { - numStr += buffer[pos]; - pos += 1; - } - } - if (pos < buffer.length && (buffer[pos] === "e" || buffer[pos] === "E")) { - numStr += buffer[pos]; - pos += 1; - if (pos < buffer.length && (buffer[pos] === "+" || buffer[pos] === "-")) { - numStr += buffer[pos]; - pos += 1; - } - while (pos < buffer.length && buffer[pos] >= "0" && buffer[pos] <= "9") { - numStr += buffer[pos]; - pos += 1; - } - } - if (numStr === "-") return -0; - const num = Number.parseFloat(numStr); - if (Number.isNaN(num)) { - pos = start; - throw new Error(`Invalid number '${numStr}' at position ${start}`); - } - return num; - } - function parseValue() { - skipWhitespace(); - if (pos >= buffer.length) throw new Error(`Unexpected end of input at position ${pos}`); - const char = buffer[pos]; - if (char === "{") return parseObject(); - if (char === "[") return parseArray(); - if (char === "\"") return parseString(); - if ("null".startsWith(buffer.substring(pos, pos + 4))) { - pos += Math.min(4, buffer.length - pos); - return null; - } - if ("true".startsWith(buffer.substring(pos, pos + 4))) { - pos += Math.min(4, buffer.length - pos); - return true; - } - if ("false".startsWith(buffer.substring(pos, pos + 5))) { - pos += Math.min(5, buffer.length - pos); - return false; - } - if (char === "-" || char >= "0" && char <= "9") return parseNumber(); - throw new Error(`Unexpected character '${char}' at position ${pos}`); - } - function parseArray() { - if (buffer[pos] !== "[") throw new Error(`Expected '[' at position ${pos}, got '${buffer[pos]}'`); - const arr = []; - pos += 1; - skipWhitespace(); - if (pos >= buffer.length) return arr; - if (buffer[pos] === "]") { - pos += 1; - return arr; - } - while (pos < buffer.length) { - skipWhitespace(); - if (pos >= buffer.length) return arr; - arr.push(parseValue()); - skipWhitespace(); - if (pos >= buffer.length) return arr; - if (buffer[pos] === "]") { - pos += 1; - return arr; - } else if (buffer[pos] === ",") { - pos += 1; - continue; - } - throw new Error(`Expected ',' or ']' at position ${pos}, got '${buffer[pos]}'`); - } - return arr; - } - function parseObject() { - if (buffer[pos] !== "{") throw new Error(`Expected '{' at position ${pos}, got '${buffer[pos]}'`); - const obj = {}; - pos += 1; - skipWhitespace(); - if (pos >= buffer.length) return obj; - if (buffer[pos] === "}") { - pos += 1; - return obj; - } - while (pos < buffer.length) { - skipWhitespace(); - if (pos >= buffer.length) return obj; - const key = parseString(); - skipWhitespace(); - if (pos >= buffer.length) return obj; - if (buffer[pos] !== ":") throw new Error(`Expected ':' at position ${pos}, got '${buffer[pos]}'`); - pos += 1; - skipWhitespace(); - if (pos >= buffer.length) return obj; - obj[key] = parseValue(); - skipWhitespace(); - if (pos >= buffer.length) return obj; - if (buffer[pos] === "}") { - pos += 1; - return obj; - } else if (buffer[pos] === ",") { - pos += 1; - continue; - } - throw new Error(`Expected ',' or '}' at position ${pos}, got '${buffer[pos]}'`); - } - return obj; - } - const value = parseValue(); - skipWhitespace(); - if (pos < buffer.length) throw new Error(`Unexpected character '${buffer[pos]}' at position ${pos}`); - return value; -} -function parsePartialJson(s) { - try { - if (typeof s === "undefined") return null; - return strictParsePartialJson(s); - } catch { - return null; - } -} - -//#endregion - -//# sourceMappingURL=json.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/chat.js - - -//#region src/messages/chat.ts -/** -* Represents a chat message in a conversation. -*/ -var ChatMessage = class ChatMessage extends BaseMessage { - static lc_name() { - return "ChatMessage"; - } - type = "generic"; - role; - static _chatMessageClass() { - return ChatMessage; - } - constructor(fields, role) { - if (typeof fields === "string" || Array.isArray(fields)) fields = { - content: fields, - role - }; - super(fields); - this.role = fields.role; - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "generic"; - } - get _printableFields() { - return { - ...super._printableFields, - role: this.role - }; - } -}; -/** -* Represents a chunk of a chat message, which can be concatenated with -* other chat message chunks. -*/ -var ChatMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "ChatMessageChunk"; - } - type = "generic"; - role; - constructor(fields, role) { - if (typeof fields === "string" || Array.isArray(fields)) fields = { - content: fields, - role - }; - super(fields); - this.role = fields.role; - } - concat(chunk) { - const Cls = this.constructor; - return new Cls({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - role: this.role, - id: this.id ?? chunk.id - }); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "generic"; - } - get _printableFields() { - return { - ...super._printableFields, - role: this.role - }; - } -}; -/** -* @deprecated Use {@link ChatMessage.isInstance} instead -*/ -function isChatMessage(x) { - return x._getType() === "generic"; -} -/** -* @deprecated Use {@link ChatMessageChunk.isInstance} instead -*/ -function isChatMessageChunk(x) { - return x._getType() === "generic"; -} - -//#endregion - -//# sourceMappingURL=chat.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/function.js - - -//#region src/messages/function.ts -/** -* Represents a function message in a conversation. -*/ -var FunctionMessage = class extends BaseMessage { - static lc_name() { - return "FunctionMessage"; - } - type = "function"; - name; - constructor(fields) { - super(fields); - this.name = fields.name; - } -}; -/** -* Represents a chunk of a function message, which can be concatenated -* with other function message chunks. -*/ -var FunctionMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "FunctionMessageChunk"; - } - type = "function"; - concat(chunk) { - const Cls = this.constructor; - return new Cls({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - name: this.name ?? "", - id: this.id ?? chunk.id - }); - } -}; -function isFunctionMessage(x) { - return x._getType() === "function"; -} -function isFunctionMessageChunk(x) { - return x._getType() === "function"; -} - -//#endregion - -//# sourceMappingURL=function.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/human.js - - -//#region src/messages/human.ts -/** -* Represents a human message in a conversation. -*/ -var HumanMessage = class extends BaseMessage { - static lc_name() { - return "HumanMessage"; - } - type = "human"; - constructor(fields) { - super(fields); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "human"; - } -}; -/** -* Represents a chunk of a human message, which can be concatenated with -* other human message chunks. -*/ -var HumanMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "HumanMessageChunk"; - } - type = "human"; - constructor(fields) { - super(fields); - } - concat(chunk) { - const Cls = this.constructor; - return new Cls({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - id: this.id ?? chunk.id - }); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "human"; - } -}; -/** -* @deprecated Use {@link HumanMessage.isInstance} instead -*/ -function isHumanMessage(x) { - return x.getType() === "human"; -} -/** -* @deprecated Use {@link HumanMessageChunk.isInstance} instead -*/ -function isHumanMessageChunk(x) { - return x.getType() === "human"; -} - -//#endregion - -//# sourceMappingURL=human.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/modifier.js - - -//#region src/messages/modifier.ts -/** -* Message responsible for deleting other messages. -*/ -var RemoveMessage = class extends BaseMessage { - type = "remove"; - /** - * The ID of the message to remove. - */ - id; - constructor(fields) { - super({ - ...fields, - content: [] - }); - this.id = fields.id; - } - get _printableFields() { - return { - ...super._printableFields, - id: this.id - }; - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "remove"; - } -}; - -//#endregion - -//# sourceMappingURL=modifier.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/system.js - - -//#region src/messages/system.ts -/** -* Represents a system message in a conversation. -*/ -var SystemMessage = class SystemMessage extends BaseMessage { - static lc_name() { - return "SystemMessage"; - } - type = "system"; - constructor(fields) { - super(fields); - } - /** - * Concatenates a string or another system message with the current system message. - * @param chunk - The chunk to concatenate with the system message. - * @returns A new system message with the concatenated content. - */ - concat(chunk) { - if (typeof chunk === "string") return new SystemMessage({ - ...this, - content: mergeContent(this.content, chunk) - }); - if (SystemMessage.isInstance(chunk)) return new SystemMessage({ - ...this, - additional_kwargs: { - ...this.additional_kwargs, - ...chunk.additional_kwargs - }, - response_metadata: { - ...this.response_metadata, - ...chunk.response_metadata - }, - content: mergeContent(this.content, chunk.content) - }); - throw new Error("Unexpected chunk type for system message"); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "system"; - } -}; -/** -* Represents a chunk of a system message, which can be concatenated with -* other system message chunks. -*/ -var SystemMessageChunk = class extends BaseMessageChunk { - static lc_name() { - return "SystemMessageChunk"; - } - type = "system"; - constructor(fields) { - super(fields); - } - concat(chunk) { - const Cls = this.constructor; - return new Cls({ - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: _mergeDicts(this.response_metadata, chunk.response_metadata), - id: this.id ?? chunk.id - }); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "system"; - } -}; -/** -* @deprecated Use {@link SystemMessage.isInstance} instead -*/ -function isSystemMessage(x) { - return x._getType() === "system"; -} -/** -* @deprecated Use {@link SystemMessageChunk.isInstance} instead -*/ -function isSystemMessageChunk(x) { - return x._getType() === "system"; -} - -//#endregion - -//# sourceMappingURL=system.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/bedrock_converse.js - - -//#region src/messages/block_translators/bedrock_converse.ts -function convertFileFormatToMimeType(format) { - switch (format) { - case "csv": return "text/csv"; - case "doc": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; - case "docx": return "application/vnd.openxmlformats-officedocument.wordprocessingml.document"; - case "html": return "text/html"; - case "md": return "text/markdown"; - case "pdf": return "application/pdf"; - case "txt": return "text/plain"; - case "xls": return "application/vnd.ms-excel"; - case "xlsx": return "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"; - case "gif": return "image/gif"; - case "jpeg": return "image/jpeg"; - case "jpg": return "image/jpeg"; - case "png": return "image/png"; - case "webp": return "image/webp"; - case "flv": return "video/flv"; - case "mkv": return "video/mkv"; - case "mov": return "video/mov"; - case "mp4": return "video/mp4"; - case "mpeg": return "video/mpeg"; - case "mpg": return "video/mpg"; - case "three_gp": return "video/three_gp"; - case "webm": return "video/webm"; - case "wmv": return "video/wmv"; - default: return "application/octet-stream"; - } -} -function convertConverseDocumentBlock(block) { - if (_isObject(block.document) && _isObject(block.document.source)) { - const format = _isObject(block.document) && _isString(block.document.format) ? block.document.format : ""; - const mimeType = convertFileFormatToMimeType(format); - if (_isObject(block.document.source)) { - if (_isObject(block.document.source.s3Location) && _isString(block.document.source.s3Location.uri)) return { - type: "file", - mimeType, - fileId: block.document.source.s3Location.uri - }; - if (_isBytesArray(block.document.source.bytes)) return { - type: "file", - mimeType, - data: block.document.source.bytes - }; - if (_isString(block.document.source.text)) return { - type: "file", - mimeType, - data: Buffer.from(block.document.source.text).toString("base64") - }; - if (_isArray(block.document.source.content)) { - const data = block.document.source.content.reduce((acc, item) => { - if (_isObject(item) && _isString(item.text)) return acc + item.text; - return acc; - }, ""); - return { - type: "file", - mimeType, - data - }; - } - } - } - return { - type: "non_standard", - value: block - }; -} -function convertConverseImageBlock(block) { - if (_isContentBlock(block, "image") && _isObject(block.image)) { - const format = _isObject(block.image) && _isString(block.image.format) ? block.image.format : ""; - const mimeType = convertFileFormatToMimeType(format); - if (_isObject(block.image.source)) { - if (_isObject(block.image.source.s3Location) && _isString(block.image.source.s3Location.uri)) return { - type: "image", - mimeType, - fileId: block.image.source.s3Location.uri - }; - if (_isBytesArray(block.image.source.bytes)) return { - type: "image", - mimeType, - data: block.image.source.bytes - }; - } - } - return { - type: "non_standard", - value: block - }; -} -function convertConverseVideoBlock(block) { - if (_isContentBlock(block, "video") && _isObject(block.video)) { - const format = _isObject(block.video) && _isString(block.video.format) ? block.video.format : ""; - const mimeType = convertFileFormatToMimeType(format); - if (_isObject(block.video.source)) { - if (_isObject(block.video.source.s3Location) && _isString(block.video.source.s3Location.uri)) return { - type: "video", - mimeType, - fileId: block.video.source.s3Location.uri - }; - if (_isBytesArray(block.video.source.bytes)) return { - type: "video", - mimeType, - data: block.video.source.bytes - }; - } - } - return { - type: "non_standard", - value: block - }; -} -function convertToV1FromChatBedrockConverseMessage(message) { - function* iterateContent() { - const content = typeof message.content === "string" ? [{ - type: "text", - text: message.content - }] : message.content; - for (const block of content) { - if (_isContentBlock(block, "cache_point")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "citations_content") && _isObject(block.citationsContent)) { - const text = _isArray(block.citationsContent.content) ? block.citationsContent.content.reduce((acc, item) => { - if (_isObject(item) && _isString(item.text)) return acc + item.text; - return acc; - }, "") : ""; - const annotations = _isArray(block.citationsContent.citations) ? block.citationsContent.citations.reduce((acc, item) => { - if (_isObject(item)) { - const citedText = _isArray(item.sourceContent) ? item.sourceContent.reduce((acc$1, item$1) => { - if (_isObject(item$1) && _isString(item$1.text)) return acc$1 + item$1.text; - return acc$1; - }, "") : ""; - const properties = iife(() => { - if (_isObject(item.location)) { - const location = item.location.documentChar || item.location.documentPage || item.location.documentChunk; - if (_isObject(location)) return { - source: _isNumber(location.documentIndex) ? location.documentIndex.toString() : void 0, - startIndex: _isNumber(location.start) ? location.start : void 0, - endIndex: _isNumber(location.end) ? location.end : void 0 - }; - } - return {}; - }); - acc.push({ - type: "citation", - citedText, - ...properties - }); - } - return acc; - }, []) : []; - yield { - type: "text", - text, - annotations - }; - continue; - } else if (_isContentBlock(block, "document") && _isObject(block.document)) { - yield convertConverseDocumentBlock(block); - continue; - } else if (_isContentBlock(block, "guard_content")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "image") && _isObject(block.image)) { - yield convertConverseImageBlock(block); - continue; - } else if (_isContentBlock(block, "reasoning_content") && _isString(block.reasoningText)) { - yield { - type: "reasoning", - reasoning: block.reasoningText - }; - continue; - } else if (_isContentBlock(block, "text") && _isString(block.text)) { - yield { - type: "text", - text: block.text - }; - continue; - } else if (_isContentBlock(block, "tool_result")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "tool_call")) continue; - else if (_isContentBlock(block, "video") && _isObject(block.video)) { - yield convertConverseVideoBlock(block); - continue; - } - yield { - type: "non_standard", - value: block - }; - } - } - return Array.from(iterateContent()); -} -const ChatBedrockConverseTranslator = { - translateContent: convertToV1FromChatBedrockConverseMessage, - translateContentChunk: convertToV1FromChatBedrockConverseMessage -}; - -//#endregion - -//# sourceMappingURL=bedrock_converse.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/google_genai.js - - -//#region src/messages/block_translators/google_genai.ts -function convertToV1FromChatGoogleMessage(message) { - function* iterateContent() { - const content = typeof message.content === "string" ? [{ - type: "text", - text: message.content - }] : message.content; - for (const block of content) { - if (_isContentBlock(block, "text") && _isString(block.text)) { - yield { - type: "text", - text: block.text - }; - continue; - } else if (_isContentBlock(block, "inlineData") && _isObject(block.inlineData) && _isString(block.inlineData.mimeType) && _isString(block.inlineData.data)) { - yield { - type: "file", - mimeType: block.inlineData.mimeType, - data: block.inlineData.data - }; - continue; - } else if (_isContentBlock(block, "functionCall") && _isObject(block.functionCall) && _isString(block.functionCall.name) && _isObject(block.functionCall.args)) { - yield { - type: "tool_call", - id: message.id, - name: block.functionCall.name, - args: block.functionCall.args - }; - continue; - } else if (_isContentBlock(block, "functionResponse")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "fileData") && _isObject(block.fileData) && _isString(block.fileData.mimeType) && _isString(block.fileData.fileUri)) { - yield { - type: "file", - mimeType: block.fileData.mimeType, - fileId: block.fileData.fileUri - }; - continue; - } else if (_isContentBlock(block, "executableCode")) { - yield { - type: "non_standard", - value: block - }; - continue; - } else if (_isContentBlock(block, "codeExecutionResult")) { - yield { - type: "non_standard", - value: block - }; - continue; - } - yield { - type: "non_standard", - value: block - }; - } - } - return Array.from(iterateContent()); -} -const ChatGoogleGenAITranslator = { - translateContent: convertToV1FromChatGoogleMessage, - translateContentChunk: convertToV1FromChatGoogleMessage -}; - -//#endregion - -//# sourceMappingURL=google_genai.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/google_vertexai.js - - -//#region src/messages/block_translators/google_vertexai.ts -function convertToV1FromChatVertexMessage(message) { - function* iterateContent() { - const content = typeof message.content === "string" ? [{ - type: "text", - text: message.content - }] : message.content; - for (const block of content) { - if (_isContentBlock(block, "reasoning") && _isString(block.reasoning)) { - const signature = iife(() => { - const reasoningIndex = content.indexOf(block); - if (_isArray(message.additional_kwargs?.signatures) && reasoningIndex >= 0) return message.additional_kwargs.signatures.at(reasoningIndex); - return void 0; - }); - if (_isString(signature)) yield { - type: "reasoning", - reasoning: block.reasoning, - signature - }; - else yield { - type: "reasoning", - reasoning: block.reasoning - }; - continue; - } else if (_isContentBlock(block, "text") && _isString(block.text)) { - yield { - type: "text", - text: block.text - }; - continue; - } else if (_isContentBlock(block, "image_url")) { - if (_isString(block.image_url)) if (block.image_url.startsWith("data:")) { - const dataUrlRegex = /^data:([^;]+);base64,(.+)$/; - const match = block.image_url.match(dataUrlRegex); - if (match) yield { - type: "image", - data: match[2], - mimeType: match[1] - }; - else yield { - type: "image", - url: block.image_url - }; - } else yield { - type: "image", - url: block.image_url - }; - continue; - } else if (_isContentBlock(block, "media") && _isString(block.mimeType) && _isString(block.data)) { - yield { - type: "file", - mimeType: block.mimeType, - data: block.data - }; - continue; - } - yield { - type: "non_standard", - value: block - }; - } - } - return Array.from(iterateContent()); -} -const ChatVertexTranslator = { - translateContent: convertToV1FromChatVertexMessage, - translateContentChunk: convertToV1FromChatVertexMessage -}; - -//#endregion - -//# sourceMappingURL=google_vertexai.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/block_translators/index.js - - - - - - -//#region src/messages/block_translators/index.ts -globalThis.lc_block_translators_registry ??= new Map([ - ["anthropic", ChatAnthropicTranslator], - ["bedrock-converse", ChatBedrockConverseTranslator], - ["google-genai", ChatGoogleGenAITranslator], - ["google-vertexai", ChatVertexTranslator], - ["openai", ChatOpenAITranslator] -]); -function getTranslator(modelProvider) { - return globalThis.lc_block_translators_registry.get(modelProvider); -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/metadata.js - - -//#region src/messages/metadata.ts -function mergeResponseMetadata(a, b) { - const output = _mergeDicts(a ?? {}, b ?? {}); - return output; -} -function mergeModalitiesTokenDetails(a, b) { - const output = {}; - if (a?.audio !== void 0 || b?.audio !== void 0) output.audio = (a?.audio ?? 0) + (b?.audio ?? 0); - if (a?.image !== void 0 || b?.image !== void 0) output.image = (a?.image ?? 0) + (b?.image ?? 0); - if (a?.video !== void 0 || b?.video !== void 0) output.video = (a?.video ?? 0) + (b?.video ?? 0); - if (a?.document !== void 0 || b?.document !== void 0) output.document = (a?.document ?? 0) + (b?.document ?? 0); - if (a?.text !== void 0 || b?.text !== void 0) output.text = (a?.text ?? 0) + (b?.text ?? 0); - return output; -} -function mergeInputTokenDetails(a, b) { - const output = { ...mergeModalitiesTokenDetails(a, b) }; - if (a?.cache_read !== void 0 || b?.cache_read !== void 0) output.cache_read = (a?.cache_read ?? 0) + (b?.cache_read ?? 0); - if (a?.cache_creation !== void 0 || b?.cache_creation !== void 0) output.cache_creation = (a?.cache_creation ?? 0) + (b?.cache_creation ?? 0); - return output; -} -function mergeOutputTokenDetails(a, b) { - const output = { ...mergeModalitiesTokenDetails(a, b) }; - if (a?.reasoning !== void 0 || b?.reasoning !== void 0) output.reasoning = (a?.reasoning ?? 0) + (b?.reasoning ?? 0); - return output; -} -function mergeUsageMetadata(a, b) { - return { - input_tokens: (a?.input_tokens ?? 0) + (b?.input_tokens ?? 0), - output_tokens: (a?.output_tokens ?? 0) + (b?.output_tokens ?? 0), - total_tokens: (a?.total_tokens ?? 0) + (b?.total_tokens ?? 0), - input_token_details: mergeInputTokenDetails(a?.input_token_details, b?.input_token_details), - output_token_details: mergeOutputTokenDetails(a?.output_token_details, b?.output_token_details) - }; -} - -//#endregion - -//# sourceMappingURL=metadata.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/ai.js - - - - - - -//#region src/messages/ai.ts -var AIMessage = class extends BaseMessage { - type = "ai"; - tool_calls = []; - invalid_tool_calls = []; - usage_metadata; - get lc_aliases() { - return { - ...super.lc_aliases, - tool_calls: "tool_calls", - invalid_tool_calls: "invalid_tool_calls" - }; - } - constructor(fields) { - let initParams; - if (typeof fields === "string" || Array.isArray(fields)) initParams = { - content: fields, - tool_calls: [], - invalid_tool_calls: [], - additional_kwargs: {} - }; - else { - initParams = fields; - const rawToolCalls = initParams.additional_kwargs?.tool_calls; - const toolCalls = initParams.tool_calls; - if (!(rawToolCalls == null) && rawToolCalls.length > 0 && (toolCalls === void 0 || toolCalls.length === 0)) console.warn([ - "New LangChain packages are available that more efficiently handle", - "tool calling.\n\nPlease upgrade your packages to versions that set", - "message tool calls. e.g., `pnpm install @langchain/anthropic`,", - "pnpm install @langchain/openai`, etc." - ].join(" ")); - try { - if (!(rawToolCalls == null) && toolCalls === void 0) { - const [toolCalls$1, invalidToolCalls] = defaultToolCallParser(rawToolCalls); - initParams.tool_calls = toolCalls$1 ?? []; - initParams.invalid_tool_calls = invalidToolCalls ?? []; - } else { - initParams.tool_calls = initParams.tool_calls ?? []; - initParams.invalid_tool_calls = initParams.invalid_tool_calls ?? []; - } - } catch { - initParams.tool_calls = []; - initParams.invalid_tool_calls = []; - } - if (initParams.response_metadata !== void 0 && "output_version" in initParams.response_metadata && initParams.response_metadata.output_version === "v1") { - initParams.contentBlocks = initParams.content; - initParams.content = void 0; - } - if (initParams.contentBlocks !== void 0) { - initParams.contentBlocks.push(...initParams.tool_calls.map((toolCall) => ({ - type: "tool_call", - id: toolCall.id, - name: toolCall.name, - args: toolCall.args - }))); - const missingToolCalls = initParams.contentBlocks.filter((block) => block.type === "tool_call").filter((block) => !initParams.tool_calls?.some((toolCall) => toolCall.id === block.id && toolCall.name === block.name)); - if (missingToolCalls.length > 0) initParams.tool_calls = missingToolCalls.map((block) => ({ - type: "tool_call", - id: block.id, - name: block.name, - args: block.args - })); - } - } - super(initParams); - if (typeof initParams !== "string") { - this.tool_calls = initParams.tool_calls ?? this.tool_calls; - this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; - } - this.usage_metadata = initParams.usage_metadata; - } - static lc_name() { - return "AIMessage"; - } - get contentBlocks() { - if (this.response_metadata && "output_version" in this.response_metadata && this.response_metadata.output_version === "v1") return this.content; - if (this.response_metadata && "model_provider" in this.response_metadata && typeof this.response_metadata.model_provider === "string") { - const translator = getTranslator(this.response_metadata.model_provider); - if (translator) return translator.translateContent(this); - } - const blocks = super.contentBlocks; - if (this.tool_calls) { - const missingToolCalls = this.tool_calls.filter((block) => !blocks.some((b) => b.id === block.id && b.name === block.name)); - blocks.push(...missingToolCalls.map((block) => ({ - ...block, - type: "tool_call", - id: block.id, - name: block.name, - args: block.args - }))); - } - return blocks; - } - get _printableFields() { - return { - ...super._printableFields, - tool_calls: this.tool_calls, - invalid_tool_calls: this.invalid_tool_calls, - usage_metadata: this.usage_metadata - }; - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "ai"; - } -}; -/** -* @deprecated Use {@link AIMessage.isInstance} instead -*/ -function isAIMessage(x) { - return x._getType() === "ai"; -} -/** -* @deprecated Use {@link AIMessageChunk.isInstance} instead -*/ -function isAIMessageChunk(x) { - return x._getType() === "ai"; -} -/** -* Represents a chunk of an AI message, which can be concatenated with -* other AI message chunks. -*/ -var AIMessageChunk = class extends BaseMessageChunk { - type = "ai"; - tool_calls = []; - invalid_tool_calls = []; - tool_call_chunks = []; - usage_metadata; - constructor(fields) { - let initParams; - if (typeof fields === "string" || Array.isArray(fields)) initParams = { - content: fields, - tool_calls: [], - invalid_tool_calls: [], - tool_call_chunks: [] - }; - else if (fields.tool_call_chunks === void 0 || fields.tool_call_chunks.length === 0) initParams = { - ...fields, - tool_calls: fields.tool_calls ?? [], - invalid_tool_calls: [], - tool_call_chunks: [], - usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 - }; - else initParams = { - ...fields, - ...collapseToolCallChunks(fields.tool_call_chunks ?? []), - usage_metadata: fields.usage_metadata !== void 0 ? fields.usage_metadata : void 0 - }; - super(initParams); - this.tool_call_chunks = initParams.tool_call_chunks ?? this.tool_call_chunks; - this.tool_calls = initParams.tool_calls ?? this.tool_calls; - this.invalid_tool_calls = initParams.invalid_tool_calls ?? this.invalid_tool_calls; - this.usage_metadata = initParams.usage_metadata; - } - get lc_aliases() { - return { - ...super.lc_aliases, - tool_calls: "tool_calls", - invalid_tool_calls: "invalid_tool_calls", - tool_call_chunks: "tool_call_chunks" - }; - } - static lc_name() { - return "AIMessageChunk"; - } - get contentBlocks() { - if (this.response_metadata && "output_version" in this.response_metadata && this.response_metadata.output_version === "v1") return this.content; - if (this.response_metadata && "model_provider" in this.response_metadata && typeof this.response_metadata.model_provider === "string") { - const translator = getTranslator(this.response_metadata.model_provider); - if (translator) return translator.translateContent(this); - } - const blocks = super.contentBlocks; - if (this.tool_calls) { - if (typeof this.content !== "string") { - const contentToolCalls = this.content.filter((block) => block.type === "tool_call").map((block) => block.id); - for (const toolCall of this.tool_calls) if (toolCall.id && !contentToolCalls.includes(toolCall.id)) blocks.push({ - ...toolCall, - type: "tool_call", - id: toolCall.id, - name: toolCall.name, - args: toolCall.args - }); - } - } - return blocks; - } - get _printableFields() { - return { - ...super._printableFields, - tool_calls: this.tool_calls, - tool_call_chunks: this.tool_call_chunks, - invalid_tool_calls: this.invalid_tool_calls, - usage_metadata: this.usage_metadata - }; - } - concat(chunk) { - const combinedFields = { - content: mergeContent(this.content, chunk.content), - additional_kwargs: _mergeDicts(this.additional_kwargs, chunk.additional_kwargs), - response_metadata: mergeResponseMetadata(this.response_metadata, chunk.response_metadata), - tool_call_chunks: [], - id: this.id ?? chunk.id - }; - if (this.tool_call_chunks !== void 0 || chunk.tool_call_chunks !== void 0) { - const rawToolCalls = _mergeLists(this.tool_call_chunks, chunk.tool_call_chunks); - if (rawToolCalls !== void 0 && rawToolCalls.length > 0) combinedFields.tool_call_chunks = rawToolCalls; - } - if (this.usage_metadata !== void 0 || chunk.usage_metadata !== void 0) combinedFields.usage_metadata = mergeUsageMetadata(this.usage_metadata, chunk.usage_metadata); - const Cls = this.constructor; - return new Cls(combinedFields); - } - static isInstance(obj) { - return super.isInstance(obj) && obj.type === "ai"; - } -}; - -//#endregion - -//# sourceMappingURL=ai.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/utils.js - - - - - - - - - - - - -//#region src/messages/utils.ts -/** -* Immediately-invoked function expression. -* -* @param fn - The function to execute -* @returns The result of the function -*/ -const utils_iife = (fn) => fn(); -function _coerceToolCall(toolCall) { - if (_isToolCall(toolCall)) return toolCall; - else if (typeof toolCall.id === "string" && toolCall.type === "function" && typeof toolCall.function === "object" && toolCall.function !== null && "arguments" in toolCall.function && typeof toolCall.function.arguments === "string" && "name" in toolCall.function && typeof toolCall.function.name === "string") return { - id: toolCall.id, - args: JSON.parse(toolCall.function.arguments), - name: toolCall.function.name, - type: "tool_call" - }; - else return toolCall; -} -function isSerializedConstructor(x) { - return typeof x === "object" && x != null && x.lc === 1 && Array.isArray(x.id) && x.kwargs != null && typeof x.kwargs === "object"; -} -function _constructMessageFromParams(params) { - let type; - let rest; - if (isSerializedConstructor(params)) { - const className = params.id.at(-1); - if (className === "HumanMessage" || className === "HumanMessageChunk") type = "user"; - else if (className === "AIMessage" || className === "AIMessageChunk") type = "assistant"; - else if (className === "SystemMessage" || className === "SystemMessageChunk") type = "system"; - else if (className === "FunctionMessage" || className === "FunctionMessageChunk") type = "function"; - else if (className === "ToolMessage" || className === "ToolMessageChunk") type = "tool"; - else type = "unknown"; - rest = params.kwargs; - } else { - const { type: extractedType,...otherParams } = params; - type = extractedType; - rest = otherParams; - } - if (type === "human" || type === "user") return new HumanMessage(rest); - else if (type === "ai" || type === "assistant") { - const { tool_calls: rawToolCalls,...other } = rest; - if (!Array.isArray(rawToolCalls)) return new AIMessage(rest); - const tool_calls = rawToolCalls.map(_coerceToolCall); - return new AIMessage({ - ...other, - tool_calls - }); - } else if (type === "system") return new SystemMessage(rest); - else if (type === "developer") return new SystemMessage({ - ...rest, - additional_kwargs: { - ...rest.additional_kwargs, - __openai_role__: "developer" - } - }); - else if (type === "tool" && "tool_call_id" in rest) return new ToolMessage({ - ...rest, - content: rest.content, - tool_call_id: rest.tool_call_id, - name: rest.name - }); - else if (type === "remove" && "id" in rest && typeof rest.id === "string") return new RemoveMessage({ - ...rest, - id: rest.id - }); - else { - const error = addLangChainErrorFields(/* @__PURE__ */ new Error(`Unable to coerce message from array: only human, AI, system, developer, or tool message coercion is currently supported.\n\nReceived: ${JSON.stringify(params, null, 2)}`), "MESSAGE_COERCION_FAILURE"); - throw error; - } -} -function utils_coerceMessageLikeToMessage(messageLike) { - if (typeof messageLike === "string") return new HumanMessage(messageLike); - else if (isBaseMessage(messageLike)) return messageLike; - if (Array.isArray(messageLike)) { - const [type, content] = messageLike; - return _constructMessageFromParams({ - type, - content - }); - } else if (_isMessageFieldWithRole(messageLike)) { - const { role: type,...rest } = messageLike; - return _constructMessageFromParams({ - ...rest, - type - }); - } else return _constructMessageFromParams(messageLike); -} -/** -* This function is used by memory classes to get a string representation -* of the chat message history, based on the message content and role. -*/ -function getBufferString(messages, humanPrefix = "Human", aiPrefix = "AI") { - const string_messages = []; - for (const m of messages) { - let role; - if (m._getType() === "human") role = humanPrefix; - else if (m._getType() === "ai") role = aiPrefix; - else if (m._getType() === "system") role = "System"; - else if (m._getType() === "tool") role = "Tool"; - else if (m._getType() === "generic") role = m.role; - else throw new Error(`Got unsupported message type: ${m._getType()}`); - const nameStr = m.name ? `${m.name}, ` : ""; - const readableContent = typeof m.content === "string" ? m.content : JSON.stringify(m.content, null, 2); - string_messages.push(`${role}: ${nameStr}${readableContent}`); - } - return string_messages.join("\n"); -} -/** -* Maps messages from an older format (V1) to the current `StoredMessage` -* format. If the message is already in the `StoredMessage` format, it is -* returned as is. Otherwise, it transforms the V1 message into a -* `StoredMessage`. This function is important for maintaining -* compatibility with older message formats. -*/ -function mapV1MessageToStoredMessage(message) { - if (message.data !== void 0) return message; - else { - const v1Message = message; - return { - type: v1Message.type, - data: { - content: v1Message.text, - role: v1Message.role, - name: void 0, - tool_call_id: void 0 - } - }; - } -} -function mapStoredMessageToChatMessage(message) { - const storedMessage = mapV1MessageToStoredMessage(message); - switch (storedMessage.type) { - case "human": return new HumanMessage(storedMessage.data); - case "ai": return new AIMessage(storedMessage.data); - case "system": return new SystemMessage(storedMessage.data); - case "function": - if (storedMessage.data.name === void 0) throw new Error("Name must be defined for function messages"); - return new FunctionMessage(storedMessage.data); - case "tool": - if (storedMessage.data.tool_call_id === void 0) throw new Error("Tool call ID must be defined for tool messages"); - return new ToolMessage(storedMessage.data); - case "generic": - if (storedMessage.data.role === void 0) throw new Error("Role must be defined for chat messages"); - return new ChatMessage(storedMessage.data); - default: throw new Error(`Got unexpected type: ${storedMessage.type}`); - } -} -/** -* Transforms an array of `StoredMessage` instances into an array of -* `BaseMessage` instances. It uses the `mapV1MessageToStoredMessage` -* function to ensure all messages are in the `StoredMessage` format, then -* creates new instances of the appropriate `BaseMessage` subclass based -* on the type of each message. This function is used to prepare stored -* messages for use in a chat context. -*/ -function mapStoredMessagesToChatMessages(messages) { - return messages.map(mapStoredMessageToChatMessage); -} -/** -* Transforms an array of `BaseMessage` instances into an array of -* `StoredMessage` instances. It does this by calling the `toDict` method -* on each `BaseMessage`, which returns a `StoredMessage`. This function -* is used to prepare chat messages for storage. -*/ -function mapChatMessagesToStoredMessages(messages) { - return messages.map((message) => message.toDict()); -} -function convertToChunk(message) { - const type = message._getType(); - if (type === "human") return new HumanMessageChunk({ ...message }); - else if (type === "ai") { - let aiChunkFields = { ...message }; - if ("tool_calls" in aiChunkFields) aiChunkFields = { - ...aiChunkFields, - tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ - ...tc, - type: "tool_call_chunk", - index: void 0, - args: JSON.stringify(tc.args) - })) - }; - return new AIMessageChunk({ ...aiChunkFields }); - } else if (type === "system") return new SystemMessageChunk({ ...message }); - else if (type === "function") return new FunctionMessageChunk({ ...message }); - else if (ChatMessage.isInstance(message)) return new ChatMessageChunk({ ...message }); - else throw new Error("Unknown message type."); -} -/** -* Collapses an array of tool call chunks into complete tool calls. -* -* This function groups tool call chunks by their id and/or index, then attempts to -* parse and validate the accumulated arguments for each group. Successfully parsed -* tool calls are returned as valid `ToolCall` objects, while malformed ones are -* returned as `InvalidToolCall` objects. -* -* @param chunks - An array of `ToolCallChunk` objects to collapse -* @returns An object containing: -* - `tool_call_chunks`: The original input chunks -* - `tool_calls`: An array of successfully parsed and validated tool calls -* - `invalid_tool_calls`: An array of tool calls that failed parsing or validation -* -* @remarks -* Chunks are grouped using the following matching logic: -* - If a chunk has both an id and index, it matches chunks with the same id and index -* - If a chunk has only an id, it matches chunks with the same id -* - If a chunk has only an index, it matches chunks with the same index -* -* For each group, the function: -* 1. Concatenates all `args` strings from the chunks -* 2. Attempts to parse the concatenated string as JSON -* 3. Validates that the result is a non-null object with a valid id -* 4. Creates either a `ToolCall` (if valid) or `InvalidToolCall` (if invalid) -*/ -function collapseToolCallChunks(chunks) { - const groupedToolCallChunks = chunks.reduce((acc, chunk) => { - const matchedChunkIndex = acc.findIndex(([match]) => { - if ("id" in chunk && chunk.id && "index" in chunk && chunk.index !== void 0) return chunk.id === match.id && chunk.index === match.index; - if ("id" in chunk && chunk.id) return chunk.id === match.id; - if ("index" in chunk && chunk.index !== void 0) return chunk.index === match.index; - return false; - }); - if (matchedChunkIndex !== -1) acc[matchedChunkIndex].push(chunk); - else acc.push([chunk]); - return acc; - }, []); - const toolCalls = []; - const invalidToolCalls = []; - for (const chunks$1 of groupedToolCallChunks) { - let parsedArgs = null; - const name = chunks$1[0]?.name ?? ""; - const joinedArgs = chunks$1.map((c) => c.args || "").join("").trim(); - const argsStr = joinedArgs.length ? joinedArgs : "{}"; - const id = chunks$1[0]?.id; - try { - parsedArgs = parsePartialJson(argsStr); - if (!id || parsedArgs === null || typeof parsedArgs !== "object" || Array.isArray(parsedArgs)) throw new Error("Malformed tool call chunk args."); - toolCalls.push({ - name, - args: parsedArgs, - id, - type: "tool_call" - }); - } catch { - invalidToolCalls.push({ - name, - args: argsStr, - id, - error: "Malformed args.", - type: "invalid_tool_call" - }); - } - } - return { - tool_call_chunks: chunks, - tool_calls: toolCalls, - invalid_tool_calls: invalidToolCalls - }; -} - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/env.js - - -//#region src/utils/env.ts -var env_exports = {}; -__export(env_exports, { - getEnv: () => getEnv, - getEnvironmentVariable: () => getEnvironmentVariable, - getRuntimeEnvironment: () => getRuntimeEnvironment, - isBrowser: () => isBrowser, - isDeno: () => isDeno, - isJsDom: () => isJsDom, - isNode: () => isNode, - isWebWorker: () => isWebWorker -}); -const isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; -const isWebWorker = () => typeof globalThis === "object" && globalThis.constructor && globalThis.constructor.name === "DedicatedWorkerGlobalScope"; -const isJsDom = () => typeof window !== "undefined" && window.name === "nodejs" || typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom"); -const isDeno = () => typeof Deno !== "undefined"; -const isNode = () => typeof process !== "undefined" && typeof process.versions !== "undefined" && typeof process.versions.node !== "undefined" && !isDeno(); -const getEnv = () => { - let env; - if (isBrowser()) env = "browser"; - else if (isNode()) env = "node"; - else if (isWebWorker()) env = "webworker"; - else if (isJsDom()) env = "jsdom"; - else if (isDeno()) env = "deno"; - else env = "other"; - return env; -}; -let runtimeEnvironment; -function getRuntimeEnvironment() { - if (runtimeEnvironment === void 0) { - const env = getEnv(); - runtimeEnvironment = { - library: "langchain-js", - runtime: env - }; - } - return runtimeEnvironment; -} -function getEnvironmentVariable(name) { - try { - if (typeof process !== "undefined") return process.env?.[name]; - else if (isDeno()) return Deno?.env.get(name); - else return void 0; - } catch { - return void 0; - } -} - -//#endregion - -//# sourceMappingURL=env.js.map -// EXTERNAL MODULE: ./node_modules/uuid/dist/index.js -var dist = __nccwpck_require__(2048); -;// CONCATENATED MODULE: ./node_modules/uuid/wrapper.mjs - -const v1 = dist.v1; -const v1ToV6 = dist/* v1ToV6 */.bV; -const v3 = dist.v3; -const v4 = dist.v4; -const v5 = dist.v5; -const v6 = dist.v6; -const v6ToV1 = dist/* v6ToV1 */.JE; -const v7 = dist.v7; -const NIL = dist/* NIL */.wD; -const MAX = dist/* MAX */.Zu; -const version = dist/* version */.rE; -const wrapper_validate = dist/* validate */.tf; -const stringify = dist/* stringify */.As; -const parse = dist/* parse */.qg; - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/base.js - - - - - -//#region src/callbacks/base.ts -var base_exports = {}; -__export(base_exports, { - BaseCallbackHandler: () => BaseCallbackHandler, - callbackHandlerPrefersStreaming: () => callbackHandlerPrefersStreaming, - isBaseCallbackHandler: () => isBaseCallbackHandler -}); -/** -* Abstract class that provides a set of optional methods that can be -* overridden in derived classes to handle various events during the -* execution of a LangChain application. -*/ -var BaseCallbackHandlerMethodsClass = class {}; -function callbackHandlerPrefersStreaming(x) { - return "lc_prefer_streaming" in x && x.lc_prefer_streaming; -} -/** -* Abstract base class for creating callback handlers in the LangChain -* framework. It provides a set of optional methods that can be overridden -* in derived classes to handle various events during the execution of a -* LangChain application. -*/ -var BaseCallbackHandler = class extends BaseCallbackHandlerMethodsClass { - lc_serializable = false; - get lc_namespace() { - return [ - "langchain_core", - "callbacks", - this.name - ]; - } - get lc_secrets() { - return void 0; - } - get lc_attributes() { - return void 0; - } - get lc_aliases() { - return void 0; - } - get lc_serializable_keys() { - return void 0; - } - /** - * The name of the serializable. Override to provide an alias or - * to preserve the serialized module name in minified environments. - * - * Implemented as a static method to support loading logic. - */ - static lc_name() { - return this.name; - } - /** - * The final serialized identifier for the module. - */ - get lc_id() { - return [...this.lc_namespace, get_lc_unique_name(this.constructor)]; - } - lc_kwargs; - ignoreLLM = false; - ignoreChain = false; - ignoreAgent = false; - ignoreRetriever = false; - ignoreCustomEvent = false; - raiseError = false; - awaitHandlers = getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false"; - constructor(input) { - super(); - this.lc_kwargs = input || {}; - if (input) { - this.ignoreLLM = input.ignoreLLM ?? this.ignoreLLM; - this.ignoreChain = input.ignoreChain ?? this.ignoreChain; - this.ignoreAgent = input.ignoreAgent ?? this.ignoreAgent; - this.ignoreRetriever = input.ignoreRetriever ?? this.ignoreRetriever; - this.ignoreCustomEvent = input.ignoreCustomEvent ?? this.ignoreCustomEvent; - this.raiseError = input.raiseError ?? this.raiseError; - this.awaitHandlers = this.raiseError || (input._awaitHandler ?? this.awaitHandlers); - } - } - copy() { - return new this.constructor(this); - } - toJSON() { - return Serializable.prototype.toJSON.call(this); - } - toJSONNotImplemented() { - return Serializable.prototype.toJSONNotImplemented.call(this); - } - static fromMethods(methods) { - class Handler extends BaseCallbackHandler { - name = v7(); - constructor() { - super(); - Object.assign(this, methods); - } - } - return new Handler(); - } -}; -const isBaseCallbackHandler = (x) => { - const callbackHandler = x; - return callbackHandler !== void 0 && typeof callbackHandler.copy === "function" && typeof callbackHandler.name === "string" && typeof callbackHandler.awaitHandlers === "boolean"; -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/experimental/otel/constants.js -// OpenTelemetry GenAI semantic convention attribute names -const GEN_AI_OPERATION_NAME = "gen_ai.operation.name"; -const GEN_AI_SYSTEM = "gen_ai.system"; -const GEN_AI_REQUEST_MODEL = "gen_ai.request.model"; -const GEN_AI_RESPONSE_MODEL = "gen_ai.response.model"; -const GEN_AI_USAGE_INPUT_TOKENS = "gen_ai.usage.input_tokens"; -const GEN_AI_USAGE_OUTPUT_TOKENS = "gen_ai.usage.output_tokens"; -const GEN_AI_USAGE_TOTAL_TOKENS = "gen_ai.usage.total_tokens"; -const GEN_AI_REQUEST_MAX_TOKENS = "gen_ai.request.max_tokens"; -const GEN_AI_REQUEST_TEMPERATURE = "gen_ai.request.temperature"; -const GEN_AI_REQUEST_TOP_P = "gen_ai.request.top_p"; -const GEN_AI_REQUEST_FREQUENCY_PENALTY = "gen_ai.request.frequency_penalty"; -const GEN_AI_REQUEST_PRESENCE_PENALTY = "gen_ai.request.presence_penalty"; -const GEN_AI_RESPONSE_FINISH_REASONS = "gen_ai.response.finish_reasons"; -const GENAI_PROMPT = "gen_ai.prompt"; -const GENAI_COMPLETION = "gen_ai.completion"; -const GEN_AI_REQUEST_EXTRA_QUERY = "gen_ai.request.extra_query"; -const GEN_AI_REQUEST_EXTRA_BODY = "gen_ai.request.extra_body"; -const GEN_AI_SERIALIZED_NAME = "gen_ai.serialized.name"; -const GEN_AI_SERIALIZED_SIGNATURE = "gen_ai.serialized.signature"; -const GEN_AI_SERIALIZED_DOC = "gen_ai.serialized.doc"; -const GEN_AI_RESPONSE_ID = "gen_ai.response.id"; -const GEN_AI_RESPONSE_SERVICE_TIER = "gen_ai.response.service_tier"; -const GEN_AI_RESPONSE_SYSTEM_FINGERPRINT = "gen_ai.response.system_fingerprint"; -const GEN_AI_USAGE_INPUT_TOKEN_DETAILS = "gen_ai.usage.input_token_details"; -const GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS = "gen_ai.usage.output_token_details"; -// LangSmith custom attributes -const LANGSMITH_SESSION_ID = "langsmith.trace.session_id"; -const LANGSMITH_SESSION_NAME = "langsmith.trace.session_name"; -const LANGSMITH_RUN_TYPE = "langsmith.span.kind"; -const LANGSMITH_NAME = "langsmith.trace.name"; -const LANGSMITH_METADATA = "langsmith.metadata"; -const LANGSMITH_TAGS = "langsmith.span.tags"; -const LANGSMITH_RUNTIME = "langsmith.span.runtime"; -const LANGSMITH_REQUEST_STREAMING = "langsmith.request.streaming"; -const LANGSMITH_REQUEST_HEADERS = "langsmith.request.headers"; -const LANGSMITH_RUN_ID = "langsmith.span.id"; -const LANGSMITH_TRACE_ID = "langsmith.trace.id"; -const LANGSMITH_DOTTED_ORDER = "langsmith.span.dotted_order"; -const LANGSMITH_PARENT_RUN_ID = "langsmith.span.parent_id"; -const LANGSMITH_USAGE_METADATA = "langsmith.usage_metadata"; -const LANGSMITH_REFERENCE_EXAMPLE_ID = "langsmith.reference_example_id"; -const LANGSMITH_TRACEABLE = "langsmith.traceable"; -const LANGSMITH_IS_ROOT = "langsmith.is_root"; -const LANGSMITH_TRACEABLE_PARENT_OTEL_SPAN_ID = "langsmith.traceable_parent_otel_span_id"; -// GenAI event names -const GEN_AI_SYSTEM_MESSAGE = "gen_ai.system.message"; -const GEN_AI_USER_MESSAGE = "gen_ai.user.message"; -const GEN_AI_ASSISTANT_MESSAGE = "gen_ai.assistant.message"; -const GEN_AI_CHOICE = "gen_ai.choice"; -const AI_SDK_LLM_OPERATIONS = (/* unused pure expression or super */ null && ([ - "ai.generateText.doGenerate", - "ai.streamText.doStream", - "ai.generateObject.doGenerate", - "ai.streamObject.doStream", -])); -const AI_SDK_TOOL_OPERATIONS = (/* unused pure expression or super */ null && (["ai.toolCall"])); - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/fetch.js - -// Wrap the default fetch call due to issues with illegal invocations -// in some environments: -// https://stackoverflow.com/questions/69876859/why-does-bind-fix-failed-to-execute-fetch-on-window-illegal-invocation-err -// @ts-expect-error Broad typing to support a range of fetch implementations -const DEFAULT_FETCH_IMPLEMENTATION = (...args) => fetch(...args); -const LANGSMITH_FETCH_IMPLEMENTATION_KEY = Symbol.for("ls:fetch_implementation"); -/** - * Overrides the fetch implementation used for LangSmith calls. - * You should use this if you need to use an implementation of fetch - * other than the default global (e.g. for dealing with proxies). - * @param fetch The new fetch functino to use. - */ -const overrideFetchImplementation = (fetch) => { - globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] = fetch; -}; -const clearFetchImplementation = () => { - delete globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; -}; -const _globalFetchImplementationIsNodeFetch = () => { - const fetchImpl = globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY]; - if (!fetchImpl) - return false; - // Check if the implementation has node-fetch specific properties - return (typeof fetchImpl === "function" && - "Headers" in fetchImpl && - "Request" in fetchImpl && - "Response" in fetchImpl); -}; -/** - * @internal - */ -const _getFetchImplementation = (debug) => { - return async (...args) => { - if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { - const [url, options] = args; - console.log(`→ ${options?.method || "GET"} ${url}`); - } - const res = await (globalThis[LANGSMITH_FETCH_IMPLEMENTATION_KEY] ?? - DEFAULT_FETCH_IMPLEMENTATION)(...args); - if (debug || getLangSmithEnvironmentVariable("DEBUG") === "true") { - console.log(`← ${res.status} ${res.statusText} ${res.url}`); - } - return res; - }; -}; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/project.js - -const getDefaultProjectName = () => { - return (getLangSmithEnvironmentVariable("PROJECT") ?? - env_getEnvironmentVariable("LANGCHAIN_SESSION") ?? // TODO: Deprecate - "default"); -}; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/warn.js -const warnedMessages = {}; -function warn_warnOnce(message) { - if (!warnedMessages[message]) { - console.warn(message); - warnedMessages[message] = true; - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/_uuid.js -// Relaxed UUID validation regex (allows any valid UUID format including nil UUIDs) -const UUID_REGEX = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; - - -let UUID7_WARNING_EMITTED = false; -function assertUuid(str, which) { - // Use relaxed regex validation instead of strict uuid.validate() - // This allows edge cases like nil UUIDs or test UUIDs that might not pass strict validation - if (!UUID_REGEX.test(str)) { - const msg = which !== undefined - ? `Invalid UUID for ${which}: ${str}` - : `Invalid UUID: ${str}`; - throw new Error(msg); - } - return str; -} -/** - * Generate a UUID v7 from a timestamp. - * - * @param timestamp - The timestamp in milliseconds - * @returns A UUID v7 string - */ -function uuid7FromTime(timestamp) { - const msecs = typeof timestamp === "string" ? Date.parse(timestamp) : timestamp; - // Work around uuid@10 behavior where providing only { msecs } - // may not set the internal timestamp used for stringification. - // Providing a seq ensures the implementation updates its internal state - // and encodes the provided milliseconds into the UUID bytes. - return v7({ msecs, seq: 0 }); -} -/** - * Get the version of a UUID string. - * @param uuidStr - The UUID string to check - * @returns The version number (1-7) or null if invalid - */ -function getUuidVersion(uuidStr) { - if (!UUID_REGEX.test(uuidStr)) { - return null; - } - // Version is in bits 48-51 - // Format: xxxxxxxx-xxxx-Vxxx-xxxx-xxxxxxxxxxxx - const versionChar = uuidStr[14]; - return parseInt(versionChar, 16); -} -/** - * Warn if a UUID is not version 7. - * - * @param uuidStr - The UUID string to check - * @param idType - The type of ID (e.g., "run_id", "trace_id") for the warning message - */ -function warnIfNotUuidV7(uuidStr, _idType) { - const version = getUuidVersion(uuidStr); - if (version !== null && version !== 7 && !UUID7_WARNING_EMITTED) { - UUID7_WARNING_EMITTED = true; - warnOnce(`LangSmith now uses UUID v7 for run and trace identifiers. ` + - `This warning appears when passing custom IDs. ` + - `Please use: import { uuidv7 } from 'langsmith'; const id = uuidv7(); ` + - `Future versions will require UUID v7.`); - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/uuid.js - - -/** - * Generate a random UUID v7 string. - */ -function uuid7() { - return uuidv7(); -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/index.js - - - - - -// Update using yarn bump-version -const __version__ = "0.4.2"; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/env.js -// Inlined from https://github.com/flexdinesh/browser-or-node - -let globalEnv; -const env_isBrowser = () => typeof window !== "undefined" && typeof window.document !== "undefined"; -const env_isWebWorker = () => typeof globalThis === "object" && - globalThis.constructor && - globalThis.constructor.name === "DedicatedWorkerGlobalScope"; -const env_isJsDom = () => (typeof window !== "undefined" && window.name === "nodejs") || - (typeof navigator !== "undefined" && navigator.userAgent.includes("jsdom")); -// Supabase Edge Function provides a `Deno` global object -// without `version` property -const env_isDeno = () => typeof Deno !== "undefined"; -// Mark not-as-node if in Supabase Edge Function -const env_isNode = () => typeof process !== "undefined" && - typeof process.versions !== "undefined" && - typeof process.versions.node !== "undefined" && - !env_isDeno(); -const env_getEnv = () => { - if (globalEnv) { - return globalEnv; - } - // @ts-expect-error Bun types are not imported due to conflicts with Node types - if (typeof Bun !== "undefined") { - globalEnv = "bun"; - } - else if (env_isBrowser()) { - globalEnv = "browser"; - } - else if (env_isNode()) { - globalEnv = "node"; - } - else if (env_isWebWorker()) { - globalEnv = "webworker"; - } - else if (env_isJsDom()) { - globalEnv = "jsdom"; - } - else if (env_isDeno()) { - globalEnv = "deno"; - } - else { - globalEnv = "other"; - } - return globalEnv; -}; -let env_runtimeEnvironment; -function env_getRuntimeEnvironment() { - if (env_runtimeEnvironment === undefined) { - const env = env_getEnv(); - const releaseEnv = getShas(); - env_runtimeEnvironment = { - library: "langsmith", - runtime: env, - sdk: "langsmith-js", - sdk_version: __version__, - ...releaseEnv, - }; - } - return env_runtimeEnvironment; -} -/** - * Retrieves the LangSmith-specific metadata from the current runtime environment. - * - * @returns {Record} - * - A record of LangSmith-specific metadata environment variables. - */ -function getLangSmithEnvVarsMetadata() { - const allEnvVars = getLangSmithEnvironmentVariables(); - const envVars = {}; - const excluded = [ - "LANGCHAIN_API_KEY", - "LANGCHAIN_ENDPOINT", - "LANGCHAIN_TRACING_V2", - "LANGCHAIN_PROJECT", - "LANGCHAIN_SESSION", - "LANGSMITH_API_KEY", - "LANGSMITH_ENDPOINT", - "LANGSMITH_TRACING_V2", - "LANGSMITH_PROJECT", - "LANGSMITH_SESSION", - ]; - for (const [key, value] of Object.entries(allEnvVars)) { - if (typeof value === "string" && - !excluded.includes(key) && - !key.toLowerCase().includes("key") && - !key.toLowerCase().includes("secret") && - !key.toLowerCase().includes("token")) { - if (key === "LANGCHAIN_REVISION_ID") { - envVars["revision_id"] = value; - } - else { - envVars[key] = value; - } - } - } - return envVars; -} -/** - * Retrieves only the LangChain/LangSmith-prefixed environment variables from the current runtime environment. - * This is more efficient than copying all environment variables. - * - * @returns {Record} - * - A record of LangChain/LangSmith environment variables. - */ -function getLangSmithEnvironmentVariables() { - const envVars = {}; - try { - // Check for Node.js environment - // eslint-disable-next-line no-process-env - if (typeof process !== "undefined" && process.env) { - // eslint-disable-next-line no-process-env - for (const [key, value] of Object.entries(process.env)) { - if ((key.startsWith("LANGCHAIN_") || key.startsWith("LANGSMITH_")) && - value != null) { - if ((key.toLowerCase().includes("key") || - key.toLowerCase().includes("secret") || - key.toLowerCase().includes("token")) && - typeof value === "string") { - envVars[key] = - value.slice(0, 2) + - "*".repeat(value.length - 4) + - value.slice(-2); - } - else { - envVars[key] = value; - } - } - } - } - } - catch (e) { - // Catch any errors that might occur while trying to access environment variables - } - return envVars; -} -function env_getEnvironmentVariable(name) { - // Certain Deno setups will throw an error if you try to access environment variables - // https://github.com/hwchase17/langchainjs/issues/1412 - try { - return typeof process !== "undefined" - ? // eslint-disable-next-line no-process-env - process.env?.[name] - : undefined; - } - catch (e) { - return undefined; - } -} -function getLangSmithEnvironmentVariable(name) { - return (env_getEnvironmentVariable(`LANGSMITH_${name}`) || - env_getEnvironmentVariable(`LANGCHAIN_${name}`)); -} -function setEnvironmentVariable(name, value) { - if (typeof process !== "undefined") { - // eslint-disable-next-line no-process-env - process.env[name] = value; - } -} -let cachedCommitSHAs; -/** - * Get the Git commit SHA from common environment variables - * used by different CI/CD platforms. - * @returns {string | undefined} The Git commit SHA or undefined if not found. - */ -function getShas() { - if (cachedCommitSHAs !== undefined) { - return cachedCommitSHAs; - } - const common_release_envs = [ - "VERCEL_GIT_COMMIT_SHA", - "NEXT_PUBLIC_VERCEL_GIT_COMMIT_SHA", - "COMMIT_REF", - "RENDER_GIT_COMMIT", - "CI_COMMIT_SHA", - "CIRCLE_SHA1", - "CF_PAGES_COMMIT_SHA", - "REACT_APP_GIT_SHA", - "SOURCE_VERSION", - "GITHUB_SHA", - "TRAVIS_COMMIT", - "GIT_COMMIT", - "BUILD_VCS_NUMBER", - "bamboo_planRepository_revision", - "Build.SourceVersion", - "BITBUCKET_COMMIT", - "DRONE_COMMIT_SHA", - "SEMAPHORE_GIT_SHA", - "BUILDKITE_COMMIT", - ]; - const shas = {}; - for (const env of common_release_envs) { - const envVar = env_getEnvironmentVariable(env); - if (envVar !== undefined) { - shas[env] = envVar; - } - } - cachedCommitSHAs = shas; - return shas; -} -function getOtelEnabled() { - return (env_getEnvironmentVariable("OTEL_ENABLED") === "true" || - getLangSmithEnvironmentVariable("OTEL_ENABLED") === "true"); -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/otel.js -// Should not import any OTEL packages to avoid pulling in optional deps. - -class MockTracer { - constructor() { - Object.defineProperty(this, "hasWarned", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - } - startActiveSpan(_name, ...args) { - if (!this.hasWarned && getOtelEnabled()) { - console.warn("You have enabled OTEL export via the `OTEL_ENABLED` or `LANGSMITH_OTEL_ENABLED` environment variable, but have not initialized the required OTEL instances. " + - 'Please add:\n```\nimport { initializeOTEL } from "langsmith/experimental/otel/setup";\ninitializeOTEL();\n```\nat the beginning of your code.'); - this.hasWarned = true; - } - // Handle different overloads: - // startActiveSpan(name, fn) - // startActiveSpan(name, options, fn) - // startActiveSpan(name, options, context, fn) - let fn; - if (args.length === 1 && typeof args[0] === "function") { - fn = args[0]; - } - else if (args.length === 2 && typeof args[1] === "function") { - fn = args[1]; - } - else if (args.length === 3 && typeof args[2] === "function") { - fn = args[2]; - } - if (typeof fn === "function") { - return fn(); - } - return undefined; - } -} -class MockOTELTrace { - constructor() { - Object.defineProperty(this, "mockTracer", { - enumerable: true, - configurable: true, - writable: true, - value: new MockTracer() - }); - } - getTracer(_name, _version) { - return this.mockTracer; - } - getActiveSpan() { - return undefined; - } - setSpan(context, _span) { - return context; - } - getSpan(_context) { - return undefined; - } - setSpanContext(context, _spanContext) { - return context; - } - getTracerProvider() { - return undefined; - } - setGlobalTracerProvider(_tracerProvider) { - return false; - } -} -class MockOTELContext { - active() { - return {}; - } - with(_context, fn) { - return fn(); - } -} -const OTEL_TRACE_KEY = Symbol.for("ls:otel_trace"); -const OTEL_CONTEXT_KEY = Symbol.for("ls:otel_context"); -const OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY = Symbol.for("ls:otel_get_default_otlp_tracer_provider"); -const mockOTELTrace = new MockOTELTrace(); -const mockOTELContext = new MockOTELContext(); -class OTELProvider { - getTraceInstance() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return globalThis[OTEL_TRACE_KEY] ?? mockOTELTrace; - } - getContextInstance() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return globalThis[OTEL_CONTEXT_KEY] ?? mockOTELContext; - } - initializeGlobalInstances(otel) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (globalThis[OTEL_TRACE_KEY] === undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - globalThis[OTEL_TRACE_KEY] = otel.trace; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (globalThis[OTEL_CONTEXT_KEY] === undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - globalThis[OTEL_CONTEXT_KEY] = otel.context; - } - } - setDefaultOTLPTracerComponents(components) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] = components; - } - getDefaultOTLPTracerComponents() { - return (globalThis[OTEL_GET_DEFAULT_OTLP_TRACER_PROVIDER_KEY] ?? - undefined); - } -} -const OTELProviderSingleton = new OTELProvider(); -/** - * Get the current OTEL trace instance. - * Returns a mock implementation if OTEL is not available. - */ -function getOTELTrace() { - return OTELProviderSingleton.getTraceInstance(); -} -/** - * Get the current OTEL context instance. - * Returns a mock implementation if OTEL is not available. - */ -function getOTELContext() { - return OTELProviderSingleton.getContextInstance(); -} -/** - * Initialize the global OTEL instances. - * Should be called once when OTEL packages are available. - */ -function setOTELInstances(otel) { - OTELProviderSingleton.initializeGlobalInstances(otel); -} -/** - * Set a getter function for the default OTLP tracer provider. - * This allows lazy initialization of the tracer provider. - */ -function setDefaultOTLPTracerComponents(components) { - OTELProviderSingleton.setDefaultOTLPTracerComponents(components); -} -/** - * Get the default OTLP tracer provider instance. - * Returns undefined if not set. - */ -function getDefaultOTLPTracerComponents() { - return OTELProviderSingleton.getDefaultOTLPTracerComponents(); -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/experimental/otel/translator.js - - -const WELL_KNOWN_OPERATION_NAMES = { - llm: "chat", - tool: "execute_tool", - retriever: "embeddings", - embedding: "embeddings", - prompt: "chat", -}; -function getOperationName(runType) { - return WELL_KNOWN_OPERATION_NAMES[runType] || runType; -} -class LangSmithToOTELTranslator { - constructor() { - Object.defineProperty(this, "spans", { - enumerable: true, - configurable: true, - writable: true, - value: new Map() - }); - } - exportBatch(operations, otelContextMap) { - for (const op of operations) { - try { - if (!op.run) { - continue; - } - if (op.operation === "post") { - const span = this.createSpanForRun(op, op.run, otelContextMap.get(op.id)); - if (span && !op.run.end_time) { - this.spans.set(op.id, span); - } - } - else { - this.updateSpanForRun(op, op.run); - } - } - catch (e) { - console.error(`Error processing operation ${op.id}:`, e); - } - } - } - createSpanForRun(op, runInfo, otelContext) { - const activeSpan = otelContext && getOTELTrace().getSpan(otelContext); - if (!activeSpan) { - return; - } - try { - return this.finishSpanSetup(activeSpan, runInfo, op); - } - catch (e) { - console.error(`Failed to create span for run ${op.id}:`, e); - return undefined; - } - } - finishSpanSetup(span, runInfo, op) { - // Set all attributes - this.setSpanAttributes(span, runInfo, op); - // Set status based on error - if (runInfo.error) { - span.setStatus({ code: 2 }); // ERROR status - span.recordException(new Error(runInfo.error)); - } - else { - span.setStatus({ code: 1 }); // OK status - } - // End the span if end_time is present - if (runInfo.end_time) { - span.end(new Date(runInfo.end_time)); - } - return span; - } - updateSpanForRun(op, runInfo) { - try { - const span = this.spans.get(op.id); - if (!span) { - console.debug(`No span found for run ${op.id} during update`); - return; - } - // Update attributes - this.setSpanAttributes(span, runInfo, op); - // Update status based on error - if (runInfo.error) { - span.setStatus({ code: 2 }); // ERROR status - span.recordException(new Error(runInfo.error)); - } - else { - span.setStatus({ code: 1 }); // OK status - } - // End the span if end_time is present - const endTime = runInfo.end_time; - if (endTime) { - span.end(new Date(endTime)); - this.spans.delete(op.id); - } - } - catch (e) { - console.error(`Failed to update span for run ${op.id}:`, e); - } - } - extractModelName(runInfo) { - // Try to get model name from metadata - if (runInfo.extra?.metadata) { - const metadata = runInfo.extra.metadata; - // First check for ls_model_name in metadata - if (metadata.ls_model_name) { - return metadata.ls_model_name; - } - // Then check invocation_params for model info - if (metadata.invocation_params) { - const invocationParams = metadata.invocation_params; - if (invocationParams.model) { - return invocationParams.model; - } - else if (invocationParams.model_name) { - return invocationParams.model_name; - } - } - } - return; - } - setSpanAttributes(span, runInfo, op) { - if ("run_type" in runInfo && runInfo.run_type) { - span.setAttribute(LANGSMITH_RUN_TYPE, runInfo.run_type); - // Set GenAI attributes according to OTEL semantic conventions - const operationName = getOperationName(runInfo.run_type || "chain"); - span.setAttribute(GEN_AI_OPERATION_NAME, operationName); - } - if ("name" in runInfo && runInfo.name) { - span.setAttribute(LANGSMITH_NAME, runInfo.name); - } - if ("session_id" in runInfo && runInfo.session_id) { - span.setAttribute(LANGSMITH_SESSION_ID, runInfo.session_id); - } - if ("session_name" in runInfo && runInfo.session_name) { - span.setAttribute(LANGSMITH_SESSION_NAME, runInfo.session_name); - } - // Set gen_ai.system - this.setGenAiSystem(span, runInfo); - // Set model name if available - const modelName = this.extractModelName(runInfo); - if (modelName) { - span.setAttribute(GEN_AI_REQUEST_MODEL, modelName); - } - // Set token usage information - if ("prompt_tokens" in runInfo && - typeof runInfo.prompt_tokens === "number") { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, runInfo.prompt_tokens); - } - if ("completion_tokens" in runInfo && - typeof runInfo.completion_tokens === "number") { - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, runInfo.completion_tokens); - } - if ("total_tokens" in runInfo && typeof runInfo.total_tokens === "number") { - span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, runInfo.total_tokens); - } - // Set other parameters from invocation_params - this.setInvocationParameters(span, runInfo); - // Set metadata and tags if available - const metadata = runInfo.extra?.metadata || {}; - for (const [key, value] of Object.entries(metadata)) { - if (value !== null && value !== undefined) { - span.setAttribute(`${LANGSMITH_METADATA}.${key}`, String(value)); - } - } - const tags = runInfo.tags; - if (tags && Array.isArray(tags)) { - span.setAttribute(LANGSMITH_TAGS, tags.join(", ")); - } - else if (tags) { - span.setAttribute(LANGSMITH_TAGS, String(tags)); - } - // Support additional serialized attributes, if present - if ("serialized" in runInfo && typeof runInfo.serialized === "object") { - const serialized = runInfo.serialized; - if (serialized.name) { - span.setAttribute(GEN_AI_SERIALIZED_NAME, String(serialized.name)); - } - if (serialized.signature) { - span.setAttribute(GEN_AI_SERIALIZED_SIGNATURE, String(serialized.signature)); - } - if (serialized.doc) { - span.setAttribute(GEN_AI_SERIALIZED_DOC, String(serialized.doc)); - } - } - // Set inputs/outputs if available - this.setIOAttributes(span, op); - } - setGenAiSystem(span, runInfo) { - // Default to "langchain" if we can't determine the system - let system = "langchain"; - // Extract model name to determine the system - const modelName = this.extractModelName(runInfo); - if (modelName) { - const modelLower = modelName.toLowerCase(); - if (modelLower.includes("anthropic") || modelLower.startsWith("claude")) { - system = "anthropic"; - } - else if (modelLower.includes("bedrock")) { - system = "aws.bedrock"; - } - else if (modelLower.includes("azure") && - modelLower.includes("openai")) { - system = "az.ai.openai"; - } - else if (modelLower.includes("azure") && - modelLower.includes("inference")) { - system = "az.ai.inference"; - } - else if (modelLower.includes("cohere")) { - system = "cohere"; - } - else if (modelLower.includes("deepseek")) { - system = "deepseek"; - } - else if (modelLower.includes("gemini")) { - system = "gemini"; - } - else if (modelLower.includes("groq")) { - system = "groq"; - } - else if (modelLower.includes("watson") || modelLower.includes("ibm")) { - system = "ibm.watsonx.ai"; - } - else if (modelLower.includes("mistral")) { - system = "mistral_ai"; - } - else if (modelLower.includes("gpt") || modelLower.includes("openai")) { - system = "openai"; - } - else if (modelLower.includes("perplexity") || - modelLower.includes("sonar")) { - system = "perplexity"; - } - else if (modelLower.includes("vertex")) { - system = "vertex_ai"; - } - else if (modelLower.includes("xai") || modelLower.includes("grok")) { - system = "xai"; - } - } - span.setAttribute(GEN_AI_SYSTEM, system); - } - setInvocationParameters(span, runInfo) { - if (!runInfo.extra?.metadata?.invocation_params) { - return; - } - const invocationParams = runInfo.extra.metadata.invocation_params; - // Set relevant invocation parameters - if (invocationParams.max_tokens !== undefined) { - span.setAttribute(GEN_AI_REQUEST_MAX_TOKENS, invocationParams.max_tokens); - } - if (invocationParams.temperature !== undefined) { - span.setAttribute(GEN_AI_REQUEST_TEMPERATURE, invocationParams.temperature); - } - if (invocationParams.top_p !== undefined) { - span.setAttribute(GEN_AI_REQUEST_TOP_P, invocationParams.top_p); - } - if (invocationParams.frequency_penalty !== undefined) { - span.setAttribute(GEN_AI_REQUEST_FREQUENCY_PENALTY, invocationParams.frequency_penalty); - } - if (invocationParams.presence_penalty !== undefined) { - span.setAttribute(GEN_AI_REQUEST_PRESENCE_PENALTY, invocationParams.presence_penalty); - } - } - setIOAttributes(span, op) { - if (op.run.inputs) { - try { - const inputs = op.run.inputs; - if (typeof inputs === "object" && inputs !== null) { - if (inputs.model && Array.isArray(inputs.messages)) { - span.setAttribute(GEN_AI_REQUEST_MODEL, inputs.model); - } - // Set additional request attributes if available - if (inputs.stream !== undefined) { - span.setAttribute(LANGSMITH_REQUEST_STREAMING, inputs.stream); - } - if (inputs.extra_headers) { - span.setAttribute(LANGSMITH_REQUEST_HEADERS, JSON.stringify(inputs.extra_headers)); - } - if (inputs.extra_query) { - span.setAttribute(GEN_AI_REQUEST_EXTRA_QUERY, JSON.stringify(inputs.extra_query)); - } - if (inputs.extra_body) { - span.setAttribute(GEN_AI_REQUEST_EXTRA_BODY, JSON.stringify(inputs.extra_body)); - } - } - span.setAttribute(GENAI_PROMPT, JSON.stringify(inputs)); - } - catch (e) { - console.debug(`Failed to process inputs for run ${op.id}`, e); - } - } - if (op.run.outputs) { - try { - const outputs = op.run.outputs; - // Extract token usage from outputs (for LLM runs) - const tokenUsage = this.getUnifiedRunTokens(outputs); - if (tokenUsage) { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKENS, tokenUsage[0]); - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKENS, tokenUsage[1]); - span.setAttribute(GEN_AI_USAGE_TOTAL_TOKENS, tokenUsage[0] + tokenUsage[1]); - } - if (outputs && typeof outputs === "object") { - if (outputs.model) { - span.setAttribute(GEN_AI_RESPONSE_MODEL, String(outputs.model)); - } - // Extract additional response attributes - if (outputs.id) { - span.setAttribute(GEN_AI_RESPONSE_ID, outputs.id); - } - if (outputs.choices && Array.isArray(outputs.choices)) { - const finishReasons = outputs.choices - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .map((choice) => choice.finish_reason) - // eslint-disable-next-line @typescript-eslint/no-explicit-any - .filter((reason) => reason) - .map(String); - if (finishReasons.length > 0) { - span.setAttribute(GEN_AI_RESPONSE_FINISH_REASONS, finishReasons.join(", ")); - } - } - if (outputs.service_tier) { - span.setAttribute(GEN_AI_RESPONSE_SERVICE_TIER, outputs.service_tier); - } - if (outputs.system_fingerprint) { - span.setAttribute(GEN_AI_RESPONSE_SYSTEM_FINGERPRINT, outputs.system_fingerprint); - } - if (outputs.usage_metadata && - typeof outputs.usage_metadata === "object") { - const usageMetadata = outputs.usage_metadata; - if (usageMetadata.input_token_details) { - span.setAttribute(GEN_AI_USAGE_INPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.input_token_details)); - } - if (usageMetadata.output_token_details) { - span.setAttribute(GEN_AI_USAGE_OUTPUT_TOKEN_DETAILS, JSON.stringify(usageMetadata.output_token_details)); - } - } - } - span.setAttribute(GENAI_COMPLETION, JSON.stringify(outputs)); - } - catch (e) { - console.debug(`Failed to process outputs for run ${op.id}`, e); - } - } - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - getUnifiedRunTokens(outputs) { - if (!outputs) { - return null; - } - // Search in non-generations lists - let tokenUsage = this.extractUnifiedRunTokens(outputs.usage_metadata); - if (tokenUsage) { - return tokenUsage; - } - // Find if direct kwarg in outputs - const keys = Object.keys(outputs); - for (const key of keys) { - const haystack = outputs[key]; - if (!haystack || typeof haystack !== "object") { - continue; - } - tokenUsage = this.extractUnifiedRunTokens(haystack.usage_metadata); - if (tokenUsage) { - return tokenUsage; - } - if (haystack.lc === 1 && - haystack.kwargs && - typeof haystack.kwargs === "object") { - tokenUsage = this.extractUnifiedRunTokens(haystack.kwargs.usage_metadata); - if (tokenUsage) { - return tokenUsage; - } - } - } - // Find in generations - const generations = outputs.generations || []; - if (!Array.isArray(generations)) { - return null; - } - const flatGenerations = Array.isArray(generations[0]) - ? generations.flat() - : generations; - for (const generation of flatGenerations) { - if (typeof generation === "object" && - generation.message && - typeof generation.message === "object" && - generation.message.kwargs && - typeof generation.message.kwargs === "object") { - tokenUsage = this.extractUnifiedRunTokens(generation.message.kwargs.usage_metadata); - if (tokenUsage) { - return tokenUsage; - } - } - } - return null; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - extractUnifiedRunTokens(outputs) { - if (!outputs || typeof outputs !== "object") { - return null; - } - if (typeof outputs.input_tokens !== "number" || - typeof outputs.output_tokens !== "number") { - return null; - } - return [outputs.input_tokens, outputs.output_tokens]; - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/is-network-error/index.js -/* eslint-disable */ -// @ts-nocheck -// is-network-error vendored to avoid import issues -// Source: https://github.com/sindresorhus/is-network-error -const objectToString = Object.prototype.toString; -const isError = (value) => objectToString.call(value) === "[object Error]"; -const errorMessages = new Set([ - "network error", // Chrome - "Failed to fetch", // Chrome - "NetworkError when attempting to fetch resource.", // Firefox - "The Internet connection appears to be offline.", // Safari 16 - "Network request failed", // `cross-fetch` - "fetch failed", // Undici (Node.js) - "terminated", // Undici (Node.js) - " A network error occurred.", // Bun (WebKit) - "Network connection lost", // Cloudflare Workers (fetch) -]); -function isNetworkError(error) { - const isValid = error && - isError(error) && - error.name === "TypeError" && - typeof error.message === "string"; - if (!isValid) { - return false; - } - const { message, stack } = error; - // Safari 17+ has generic message but no stack for network errors - if (message === "Load failed") { - return (stack === undefined || - // Sentry adds its own stack trace to the fetch error, so also check for that - "__sentry_captured__" in error); - } - // Deno network errors start with specific text - if (message.startsWith("error sending request for url")) { - return true; - } - // Standard network error messages - return errorMessages.has(message); -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/p-retry/index.js -/* eslint-disable */ -// @ts-nocheck -// p-retry code vendored to avoid import issues -// Source: https://github.com/sindresorhus/p-retry - -function validateRetries(retries) { - if (typeof retries === "number") { - if (retries < 0) { - throw new TypeError("Expected `retries` to be a non-negative number."); - } - if (Number.isNaN(retries)) { - throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN."); - } - } - else if (retries !== undefined) { - throw new TypeError("Expected `retries` to be a number or Infinity."); - } -} -function validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) { - if (value === undefined) { - return; - } - if (typeof value !== "number" || Number.isNaN(value)) { - throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`); - } - if (!allowInfinity && !Number.isFinite(value)) { - throw new TypeError(`Expected \`${name}\` to be a finite number.`); - } - if (value < min) { - throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`); - } -} -class AbortError extends Error { - constructor(message) { - super(); - if (message instanceof Error) { - this.originalError = message; - ({ message } = message); - } - else { - this.originalError = new Error(message); - this.originalError.stack = this.stack; - } - this.name = "AbortError"; - this.message = message; - } -} -function calculateDelay(retriesConsumed, options) { - const attempt = Math.max(1, retriesConsumed + 1); - const random = options.randomize ? Math.random() + 1 : 1; - let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1)); - timeout = Math.min(timeout, options.maxTimeout); - return timeout; -} -function calculateRemainingTime(start, max) { - if (!Number.isFinite(max)) { - return max; - } - return max - (performance.now() - start); -} -async function onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options, }) { - const normalizedError = error instanceof Error - ? error - : new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`); - if (normalizedError instanceof AbortError) { - throw normalizedError.originalError; - } - const retriesLeft = Number.isFinite(options.retries) - ? Math.max(0, options.retries - retriesConsumed) - : options.retries; - const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY; - const context = Object.freeze({ - error: normalizedError, - attemptNumber, - retriesLeft, - retriesConsumed, - }); - await options.onFailedAttempt(context); - if (calculateRemainingTime(startTime, maxRetryTime) <= 0) { - throw normalizedError; - } - const consumeRetry = await options.shouldConsumeRetry(context); - const remainingTime = calculateRemainingTime(startTime, maxRetryTime); - if (remainingTime <= 0 || retriesLeft <= 0) { - throw normalizedError; - } - if (normalizedError instanceof TypeError && - !isNetworkError(normalizedError)) { - if (consumeRetry) { - throw normalizedError; - } - options.signal?.throwIfAborted(); - return false; - } - if (!(await options.shouldRetry(context))) { - throw normalizedError; - } - if (!consumeRetry) { - options.signal?.throwIfAborted(); - return false; - } - const delayTime = calculateDelay(retriesConsumed, options); - const finalDelay = Math.min(delayTime, remainingTime); - if (finalDelay > 0) { - await new Promise((resolve, reject) => { - const onAbort = () => { - clearTimeout(timeoutToken); - options.signal?.removeEventListener("abort", onAbort); - reject(options.signal.reason); - }; - const timeoutToken = setTimeout(() => { - options.signal?.removeEventListener("abort", onAbort); - resolve(); - }, finalDelay); - if (options.unref) { - timeoutToken.unref?.(); - } - options.signal?.addEventListener("abort", onAbort, { once: true }); - }); - } - options.signal?.throwIfAborted(); - return true; -} -async function pRetry(input, options = {}) { - options = { ...options }; - validateRetries(options.retries); - if (Object.hasOwn(options, "forever")) { - throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead."); - } - options.retries ??= 10; - options.factor ??= 2; - options.minTimeout ??= 1000; - options.maxTimeout ??= Number.POSITIVE_INFINITY; - options.maxRetryTime ??= Number.POSITIVE_INFINITY; - options.randomize ??= false; - options.onFailedAttempt ??= () => { }; - options.shouldRetry ??= () => true; - options.shouldConsumeRetry ??= () => true; - // Validate numeric options and normalize edge cases - validateNumberOption("factor", options.factor, { - min: 0, - allowInfinity: false, - }); - validateNumberOption("minTimeout", options.minTimeout, { - min: 0, - allowInfinity: false, - }); - validateNumberOption("maxTimeout", options.maxTimeout, { - min: 0, - allowInfinity: true, - }); - validateNumberOption("maxRetryTime", options.maxRetryTime, { - min: 0, - allowInfinity: true, - }); - // Treat non-positive factor as 1 to avoid zero backoff or negative behavior - if (!(options.factor > 0)) { - options.factor = 1; - } - options.signal?.throwIfAborted(); - let attemptNumber = 0; - let retriesConsumed = 0; - const startTime = performance.now(); - while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) { - attemptNumber++; - try { - options.signal?.throwIfAborted(); - const result = await input(attemptNumber); - options.signal?.throwIfAborted(); - return result; - } - catch (error) { - if (await onAttemptFailure({ - error, - attemptNumber, - retriesConsumed, - startTime, - options, - })) { - retriesConsumed++; - } - } - } - // Should not reach here, but in case it does, throw an error - throw new Error("Retry attempts exhausted without throwing an error."); -} -function makeRetriable(function_, options) { - return function (...arguments_) { - return pRetry(() => function_.apply(this, arguments_), options); - }; -} - -// EXTERNAL MODULE: ./node_modules/p-queue/dist/index.js -var p_queue_dist = __nccwpck_require__(6459); -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/async_caller.js - - -const STATUS_RETRYABLE = [ - 408, // Request Timeout - 425, // Too Early - 429, // Too Many Requests - 500, // Internal Server Error - 502, // Bad Gateway - 503, // Service Unavailable - 504, // Gateway Timeout -]; -/** - * A class that can be used to make async calls with concurrency and retry logic. - * - * This is useful for making calls to any kind of "expensive" external resource, - * be it because it's rate-limited, subject to network issues, etc. - * - * Concurrent calls are limited by the `maxConcurrency` parameter, which defaults - * to `Infinity`. This means that by default, all calls will be made in parallel. - * - * Retries are limited by the `maxRetries` parameter, which defaults to 6. This - * means that by default, each call will be retried up to 6 times, with an - * exponential backoff between each attempt. - */ -class AsyncCaller { - constructor(params) { - Object.defineProperty(this, "maxConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "maxRetries", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "maxQueueSizeBytes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "queue", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "onFailedResponseHook", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "queueSizeBytes", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - this.maxQueueSizeBytes = params.maxQueueSizeBytes; - if ( true) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.queue = new p_queue_dist["default"]({ - concurrency: this.maxConcurrency, - }); - } - else { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - this.queue = new p_queue_dist({ concurrency: this.maxConcurrency }); - } - this.onFailedResponseHook = params?.onFailedResponseHook; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - call(callable, ...args) { - return this.callWithOptions({}, callable, ...args); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - callWithOptions(options, callable, ...args) { - const sizeBytes = options.sizeBytes ?? 0; - // Check if adding this call would exceed the byte size limit - if (this.maxQueueSizeBytes !== undefined && - sizeBytes > 0 && - this.queueSizeBytes + sizeBytes > this.maxQueueSizeBytes) { - return Promise.reject(new Error(`Queue size limit (${this.maxQueueSizeBytes} bytes) exceeded. ` + - `Current queue size: ${this.queueSizeBytes} bytes, attempted addition: ${sizeBytes} bytes.`)); - } - // Add to queue size tracking - if (sizeBytes > 0) { - this.queueSizeBytes += sizeBytes; - } - const onFailedResponseHook = this.onFailedResponseHook; - let promise = this.queue.add(() => pRetry(() => callable(...args).catch((error) => { - // eslint-disable-next-line no-instanceof/no-instanceof - if (error instanceof Error) { - throw error; - } - else { - throw new Error(error); - } - }), { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - async onFailedAttempt({ error }) { - if (error.message.startsWith("Cancel") || - error.message.startsWith("TimeoutError") || - error.name === "TimeoutError" || - error.message.startsWith("AbortError")) { - throw error; - } - if (error?.code === "ECONNABORTED") { - throw error; - } - const response = error?.response; - if (onFailedResponseHook) { - const handled = await onFailedResponseHook(response); - if (handled) { - return; - } - } - const status = response?.status ?? error?.status; - if (status) { - if (!STATUS_RETRYABLE.includes(+status)) { - throw error; - } - } - }, - retries: this.maxRetries, - randomize: true, - }), { throwOnTimeout: true }); - // Decrement queue size when the call completes (success or failure) - if (sizeBytes > 0) { - promise = promise.finally(() => { - this.queueSizeBytes -= sizeBytes; - }); - } - // Handle signal cancellation - if (options.signal) { - return Promise.race([ - promise, - new Promise((_, reject) => { - options.signal?.addEventListener("abort", () => { - reject(new Error("AbortError")); - }); - }), - ]); - } - return promise; - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/messages.js -function isLangChainMessage( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -message) { - return typeof message?._getType === "function"; -} -function convertLangChainMessageToExample(message) { - const converted = { - type: message._getType(), - data: { content: message.content }, - }; - // Check for presence of keys in additional_kwargs - if (message?.additional_kwargs && - Object.keys(message.additional_kwargs).length > 0) { - converted.data.additional_kwargs = { ...message.additional_kwargs }; - } - return converted; -} - -// EXTERNAL MODULE: ./node_modules/langsmith/node_modules/semver/index.js -var semver = __nccwpck_require__(1727); -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/prompts.js - -function isVersionGreaterOrEqual(current_version, target_version) { - const current = parseVersion(current_version); - const target = parseVersion(target_version); - if (!current || !target) { - throw new Error("Invalid version format."); - } - return current.compare(target) >= 0; -} -function parsePromptIdentifier(identifier) { - if (!identifier || - identifier.split("/").length > 2 || - identifier.startsWith("/") || - identifier.endsWith("/") || - identifier.split(":").length > 2) { - throw new Error(`Invalid identifier format: ${identifier}`); - } - const [ownerNamePart, commitPart] = identifier.split(":"); - const commit = commitPart || "latest"; - if (ownerNamePart.includes("/")) { - const [owner, name] = ownerNamePart.split("/", 2); - if (!owner || !name) { - throw new Error(`Invalid identifier format: ${identifier}`); - } - return [owner, name, commit]; - } - else { - if (!ownerNamePart) { - throw new Error(`Invalid identifier format: ${identifier}`); - } - return ["-", ownerNamePart, commit]; - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/error.js -function getErrorStackTrace(e) { - if (typeof e !== "object" || e == null) - return undefined; - if (!("stack" in e) || typeof e.stack !== "string") - return undefined; - let stack = e.stack; - const prevLine = `${e}`; - if (stack.startsWith(prevLine)) { - stack = stack.slice(prevLine.length); - } - if (stack.startsWith("\n")) { - stack = stack.slice(1); - } - return stack; -} -function printErrorStackTrace(e) { - const stack = getErrorStackTrace(e); - if (stack == null) - return; - console.error(stack); -} -/** - * LangSmithConflictError - * - * Represents an error that occurs when there's a conflict during an operation, - * typically corresponding to HTTP 409 status code responses. - * - * This error is thrown when an attempt to create or modify a resource conflicts - * with the current state of the resource on the server. Common scenarios include: - * - Attempting to create a resource that already exists - * - Trying to update a resource that has been modified by another process - * - Violating a uniqueness constraint in the data - * - * @extends Error - * - * @example - * try { - * await createProject("existingProject"); - * } catch (error) { - * if (error instanceof ConflictError) { - * console.log("A conflict occurred:", error.message); - * // Handle the conflict, e.g., by suggesting a different project name - * } else { - * // Handle other types of errors - * } - * } - * - * @property {string} name - Always set to 'ConflictError' for easy identification - * @property {string} message - Detailed error message including server response - * - * @see https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409 - */ -class LangSmithConflictError extends Error { - constructor(message) { - super(message); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.name = "LangSmithConflictError"; - this.status = 409; - } -} -/** - * LangSmithNotFoundError - * - * Represents an error that occurs when a requested resource is not found, - * typically corresponding to HTTP 404 status code responses. - * - * @extends Error - */ -class LangSmithNotFoundError extends Error { - constructor(message) { - super(message); - Object.defineProperty(this, "status", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.name = "LangSmithNotFoundError"; - this.status = 404; - } -} -function isLangSmithNotFoundError(error) { - return (error != null && - typeof error === "object" && - "name" in error && - error?.name === "LangSmithNotFoundError"); -} -/** - * Throws an appropriate error based on the response status and body. - * - * @param response - The fetch Response object - * @param context - Additional context to include in the error message (e.g., operation being performed) - * @throws {LangSmithConflictError} When the response status is 409 - * @throws {Error} For all other non-ok responses - */ -async function raiseForStatus(response, context, consumeOnSuccess) { - let errorBody; - if (response.ok) { - // consume the response body to release the connection - // https://undici.nodejs.org/#/?id=garbage-collection - if (consumeOnSuccess) { - errorBody = await response.text(); - } - return; - } - if (response.status === 403) { - try { - const errorData = await response.json(); - const errorCode = errorData?.error; - if (errorCode === "org_scoped_key_requires_workspace") { - errorBody = - "This API key is org-scoped and requires workspace specification. " + - "Please provide 'workspaceId' parameter, " + - "or set LANGSMITH_WORKSPACE_ID environment variable."; - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - catch (e) { - const errorWithStatus = new Error(`${response.status} ${response.statusText}`); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - errorWithStatus.status = response?.status; - throw errorWithStatus; - } - } - if (errorBody === undefined) { - try { - errorBody = await response.text(); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - catch (e) { - errorBody = ""; - } - } - const fullMessage = `Failed to ${context}. Received status [${response.status}]: ${response.statusText}. Message: ${errorBody}`; - if (response.status === 404) { - throw new LangSmithNotFoundError(fullMessage); - } - if (response.status === 409) { - throw new LangSmithConflictError(fullMessage); - } - const err = new Error(fullMessage); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - err.status = response.status; - throw err; -} -const ERR_CONFLICTING_ENDPOINTS = "ERR_CONFLICTING_ENDPOINTS"; -class ConflictingEndpointsError extends Error { - constructor() { - super("You cannot provide both LANGSMITH_ENDPOINT / LANGCHAIN_ENDPOINT " + - "and LANGSMITH_RUNS_ENDPOINTS."); - Object.defineProperty(this, "code", { - enumerable: true, - configurable: true, - writable: true, - value: ERR_CONFLICTING_ENDPOINTS - }); - this.name = "ConflictingEndpointsError"; // helpful in logs - } -} -function isConflictingEndpointsError(err) { - return (typeof err === "object" && - err !== null && - err.code === ERR_CONFLICTING_ENDPOINTS); -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/fast-safe-stringify/index.js -/* eslint-disable */ -// @ts-nocheck - -var LIMIT_REPLACE_NODE = "[...]"; -var CIRCULAR_REPLACE_NODE = { result: "[Circular]" }; -var arr = []; -var replacerStack = []; -const encoder = new TextEncoder(); -function defaultOptions() { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER, - }; -} -function encodeString(str) { - return encoder.encode(str); -} -// Shared function to handle well-known types -function serializeWellKnownTypes(val) { - if (val && typeof val === "object" && val !== null) { - if (val instanceof Map) { - return Object.fromEntries(val); - } - else if (val instanceof Set) { - return Array.from(val); - } - else if (val instanceof Date) { - return val.toISOString(); - } - else if (val instanceof RegExp) { - return val.toString(); - } - else if (val instanceof Error) { - return { - name: val.name, - message: val.message, - }; - } - } - else if (typeof val === "bigint") { - return val.toString(); - } - return val; -} -// Default replacer function to handle well-known types -function createDefaultReplacer(userReplacer) { - return function (key, val) { - // Apply user replacer first if provided - if (userReplacer) { - const userResult = userReplacer.call(this, key, val); - // If user replacer returned undefined, fall back to our serialization - if (userResult !== undefined) { - return userResult; - } - } - // Fall back to our well-known type handling - return serializeWellKnownTypes(val); - }; -} -// Regular stringify -function serialize(obj, errorContext, replacer, spacer, options) { - try { - const str = JSON.stringify(obj, createDefaultReplacer(replacer), spacer); - return encodeString(str); - } - catch (e) { - // Fall back to more complex stringify if circular reference - if (!e.message?.includes("Converting circular structure to JSON")) { - console.warn(`[WARNING]: LangSmith received unserializable value.${errorContext ? `\nContext: ${errorContext}` : ""}`); - return encodeString("[Unserializable]"); - } - getLangSmithEnvironmentVariable("SUPPRESS_CIRCULAR_JSON_WARNINGS") !== - "true" && - console.warn(`[WARNING]: LangSmith received circular JSON. This will decrease tracer performance. ${errorContext ? `\nContext: ${errorContext}` : ""}`); - if (typeof options === "undefined") { - options = defaultOptions(); - } - decirc(obj, "", 0, [], undefined, 0, options); - let res; - try { - if (replacerStack.length === 0) { - res = JSON.stringify(obj, replacer, spacer); - } - else { - res = JSON.stringify(obj, replaceGetterValues(replacer), spacer); - } - } - catch (_) { - return encodeString("[unable to serialize, circular reference is too complex to analyze]"); - } - finally { - while (arr.length !== 0) { - const part = arr.pop(); - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]); - } - else { - part[0][part[1]] = part[2]; - } - } - } - return encodeString(res); - } -} -function setReplace(replace, val, k, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); - if (propertyDescriptor.get !== undefined) { - if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: replace }); - arr.push([parent, k, val, propertyDescriptor]); - } - else { - replacerStack.push([val, k, replace]); - } - } - else { - parent[k] = replace; - arr.push([parent, k, val]); - } -} -function decirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); - return; - } - } - if (typeof options.depthLimit !== "undefined" && - depth > options.depthLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; - } - if (typeof options.edgesLimit !== "undefined" && - edgeIndex + 1 > options.edgesLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; - } - stack.push(val); - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - decirc(val[i], i, i, stack, val, depth, options); - } - } - else { - // Handle well-known types before Object.keys iteration - val = serializeWellKnownTypes(val); - var keys = Object.keys(val); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - decirc(val[key], key, i, stack, val, depth, options); - } - } - stack.pop(); - } -} -// Stable-stringify -function compareFunction(a, b) { - if (a < b) { - return -1; - } - if (a > b) { - return 1; - } - return 0; -} -function deterministicStringify(obj, replacer, spacer, options) { - if (typeof options === "undefined") { - options = defaultOptions(); - } - var tmp = deterministicDecirc(obj, "", 0, [], undefined, 0, options) || obj; - var res; - try { - if (replacerStack.length === 0) { - res = JSON.stringify(tmp, replacer, spacer); - } - else { - res = JSON.stringify(tmp, replaceGetterValues(replacer), spacer); - } - } - catch (_) { - return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); - } - finally { - // Ensure that we restore the object as it was. - while (arr.length !== 0) { - var part = arr.pop(); - if (part.length === 4) { - Object.defineProperty(part[0], part[1], part[3]); - } - else { - part[0][part[1]] = part[2]; - } - } - } - return res; -} -function deterministicDecirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) { - if (stack[i] === val) { - setReplace(CIRCULAR_REPLACE_NODE, val, k, parent); - return; - } - } - try { - if (typeof val.toJSON === "function") { - return; - } - } - catch (_) { - return; - } - if (typeof options.depthLimit !== "undefined" && - depth > options.depthLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; - } - if (typeof options.edgesLimit !== "undefined" && - edgeIndex + 1 > options.edgesLimit) { - setReplace(LIMIT_REPLACE_NODE, val, k, parent); - return; - } - stack.push(val); - // Optimize for Arrays. Big arrays could kill the performance otherwise! - if (Array.isArray(val)) { - for (i = 0; i < val.length; i++) { - deterministicDecirc(val[i], i, i, stack, val, depth, options); - } - } - else { - // Handle well-known types before Object.keys iteration - val = serializeWellKnownTypes(val); - // Create a temporary object in the required way - var tmp = {}; - var keys = Object.keys(val).sort(compareFunction); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - deterministicDecirc(val[key], key, i, stack, val, depth, options); - tmp[key] = val[key]; - } - if (typeof parent !== "undefined") { - arr.push([parent, k, val]); - parent[k] = tmp; - } - else { - return tmp; - } - } - stack.pop(); - } -} -// wraps replacer function to handle values we couldn't replace -// and mark them as replaced value -function replaceGetterValues(replacer) { - replacer = - typeof replacer !== "undefined" - ? replacer - : function (k, v) { - return v; - }; - return function (key, val) { - if (replacerStack.length > 0) { - for (var i = 0; i < replacerStack.length; i++) { - var part = replacerStack[i]; - if (part[1] === key && part[0] === val) { - val = part[2]; - replacerStack.splice(i, 1); - break; - } - } - } - return replacer.call(this, key, val); - }; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/client.js - - - - - - - - - - - - - -function mergeRuntimeEnvIntoRun(run, cachedEnvVars, omitTracedRuntimeInfo) { - if (omitTracedRuntimeInfo) { - return run; - } - const runtimeEnv = env_getRuntimeEnvironment(); - const envVars = cachedEnvVars ?? getLangSmithEnvVarsMetadata(); - const extra = run.extra ?? {}; - const metadata = extra.metadata; - run.extra = { - ...extra, - runtime: { - ...runtimeEnv, - ...extra?.runtime, - }, - metadata: { - ...envVars, - ...(envVars.revision_id || ("revision_id" in run && run.revision_id) - ? { - revision_id: ("revision_id" in run ? run.revision_id : undefined) ?? - envVars.revision_id, - } - : {}), - ...metadata, - }, - }; - return run; -} -const getTracingSamplingRate = (configRate) => { - const samplingRateStr = configRate?.toString() ?? - getLangSmithEnvironmentVariable("TRACING_SAMPLING_RATE"); - if (samplingRateStr === undefined) { - return undefined; - } - const samplingRate = parseFloat(samplingRateStr); - if (samplingRate < 0 || samplingRate > 1) { - throw new Error(`LANGSMITH_TRACING_SAMPLING_RATE must be between 0 and 1 if set. Got: ${samplingRate}`); - } - return samplingRate; -}; -// utility functions -const isLocalhost = (url) => { - const strippedUrl = url.replace("http://", "").replace("https://", ""); - const hostname = strippedUrl.split("/")[0].split(":")[0]; - return (hostname === "localhost" || hostname === "127.0.0.1" || hostname === "::1"); -}; -async function toArray(iterable) { - const result = []; - for await (const item of iterable) { - result.push(item); - } - return result; -} -function trimQuotes(str) { - if (str === undefined) { - return undefined; - } - return str - .trim() - .replace(/^"(.*)"$/, "$1") - .replace(/^'(.*)'$/, "$1"); -} -const handle429 = async (response) => { - if (response?.status === 429) { - const retryAfter = parseInt(response.headers.get("retry-after") ?? "10", 10) * 1000; - if (retryAfter > 0) { - await new Promise((resolve) => setTimeout(resolve, retryAfter)); - // Return directly after calling this check - return true; - } - } - // Fall back to existing status checks - return false; -}; -function _formatFeedbackScore(score) { - if (typeof score === "number") { - // Truncate at 4 decimal places - return Number(score.toFixed(4)); - } - return score; -} -const DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES = 24 * 1024 * 1024; -/** Default maximum memory (1GB) for queue size limits. */ -const DEFAULT_MAX_SIZE_BYTES = 1024 * 1024 * 1024; // 1GB -const SERVER_INFO_REQUEST_TIMEOUT_MS = 10000; -/** Maximum number of operations to batch in a single request. */ -const DEFAULT_BATCH_SIZE_LIMIT = 100; -const DEFAULT_API_URL = "https://api.smith.langchain.com"; -class AutoBatchQueue { - constructor(maxSizeBytes) { - Object.defineProperty(this, "items", { - enumerable: true, - configurable: true, - writable: true, - value: [] - }); - Object.defineProperty(this, "sizeBytes", { - enumerable: true, - configurable: true, - writable: true, - value: 0 - }); - Object.defineProperty(this, "maxSizeBytes", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.maxSizeBytes = maxSizeBytes ?? DEFAULT_MAX_SIZE_BYTES; - } - peek() { - return this.items[0]; - } - push(item) { - let itemPromiseResolve; - const itemPromise = new Promise((resolve) => { - // Setting itemPromiseResolve is synchronous with promise creation: - // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/Promise - itemPromiseResolve = resolve; - }); - const size = serialize(item.item, `Serializing run with id: ${item.item.id}`).length; - // Check if adding this item would exceed the size limit - // Allow the run if the queue is empty (to support large single traces) - if (this.sizeBytes + size > this.maxSizeBytes && this.items.length > 0) { - console.warn(`AutoBatchQueue size limit (${this.maxSizeBytes} bytes) exceeded. Dropping run with id: ${item.item.id}. ` + - `Current queue size: ${this.sizeBytes} bytes, attempted addition: ${size} bytes.`); - // Resolve immediately to avoid blocking caller - itemPromiseResolve(); - return itemPromise; - } - this.items.push({ - action: item.action, - payload: item.item, - otelContext: item.otelContext, - apiKey: item.apiKey, - apiUrl: item.apiUrl, - // eslint-disable-next-line @typescript-eslint/no-non-null-assertion - itemPromiseResolve: itemPromiseResolve, - itemPromise, - size, - }); - this.sizeBytes += size; - return itemPromise; - } - pop({ upToSizeBytes, upToSize, }) { - if (upToSizeBytes < 1) { - throw new Error("Number of bytes to pop off may not be less than 1."); - } - const popped = []; - let poppedSizeBytes = 0; - // Pop items until we reach or exceed the size limit - while (poppedSizeBytes + (this.peek()?.size ?? 0) < upToSizeBytes && - this.items.length > 0 && - popped.length < upToSize) { - const item = this.items.shift(); - if (item) { - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; - } - } - // If there is an item on the queue we were unable to pop, - // just return it as a single batch. - if (popped.length === 0 && this.items.length > 0) { - const item = this.items.shift(); - popped.push(item); - poppedSizeBytes += item.size; - this.sizeBytes -= item.size; - } - return [ - popped.map((it) => ({ - action: it.action, - item: it.payload, - otelContext: it.otelContext, - apiKey: it.apiKey, - apiUrl: it.apiUrl, - size: it.size, - })), - () => popped.forEach((it) => it.itemPromiseResolve()), - ]; - } -} -class Client { - get _fetch() { - return this.fetchImplementation || _getFetchImplementation(this.debug); - } - constructor(config = {}) { - Object.defineProperty(this, "apiKey", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "apiUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "webUrl", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "workspaceId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "caller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "batchIngestCaller", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "timeout_ms", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_tenantId", { - enumerable: true, - configurable: true, - writable: true, - value: null - }); - Object.defineProperty(this, "hideInputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "hideOutputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "omitTracedRuntimeInfo", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tracingSampleRate", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "filteredPostUuids", { - enumerable: true, - configurable: true, - writable: true, - value: new Set() - }); - Object.defineProperty(this, "autoBatchTracing", { - enumerable: true, - configurable: true, - writable: true, - value: true - }); - Object.defineProperty(this, "autoBatchQueue", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "autoBatchTimeout", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "autoBatchAggregationDelayMs", { - enumerable: true, - configurable: true, - writable: true, - value: 250 - }); - Object.defineProperty(this, "batchSizeBytesLimit", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "batchSizeLimit", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "fetchOptions", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "settings", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "blockOnRootRunFinalization", { - enumerable: true, - configurable: true, - writable: true, - value: env_getEnvironmentVariable("LANGSMITH_TRACING_BACKGROUND") === "false" - }); - Object.defineProperty(this, "traceBatchConcurrency", { - enumerable: true, - configurable: true, - writable: true, - value: 5 - }); - Object.defineProperty(this, "_serverInfo", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - Object.defineProperty(this, "_getServerInfoPromise", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "manualFlushMode", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "langSmithToOTELTranslator", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "fetchImplementation", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "cachedLSEnvVarsForMetadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "multipartStreamingDisabled", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "_multipartDisabled", { - enumerable: true, - configurable: true, - writable: true, - value: false - }); - Object.defineProperty(this, "debug", { - enumerable: true, - configurable: true, - writable: true, - value: env_getEnvironmentVariable("LANGSMITH_DEBUG") === "true" - }); - const defaultConfig = Client.getDefaultClientConfig(); - this.tracingSampleRate = getTracingSamplingRate(config.tracingSamplingRate); - this.apiUrl = trimQuotes(config.apiUrl ?? defaultConfig.apiUrl) ?? ""; - if (this.apiUrl.endsWith("/")) { - this.apiUrl = this.apiUrl.slice(0, -1); - } - this.apiKey = trimQuotes(config.apiKey ?? defaultConfig.apiKey); - this.webUrl = trimQuotes(config.webUrl ?? defaultConfig.webUrl); - if (this.webUrl?.endsWith("/")) { - this.webUrl = this.webUrl.slice(0, -1); - } - this.workspaceId = trimQuotes(config.workspaceId ?? getLangSmithEnvironmentVariable("WORKSPACE_ID")); - this.timeout_ms = config.timeout_ms ?? 90_000; - this.caller = new AsyncCaller({ - ...(config.callerOptions ?? {}), - maxRetries: 4, - debug: config.debug ?? this.debug, - }); - this.traceBatchConcurrency = - config.traceBatchConcurrency ?? this.traceBatchConcurrency; - if (this.traceBatchConcurrency < 1) { - throw new Error("Trace batch concurrency must be positive."); - } - this.debug = config.debug ?? this.debug; - this.fetchImplementation = config.fetchImplementation; - // Use maxIngestMemoryBytes for both queues - const maxMemory = config.maxIngestMemoryBytes ?? DEFAULT_MAX_SIZE_BYTES; - this.batchIngestCaller = new AsyncCaller({ - maxRetries: 4, - maxConcurrency: this.traceBatchConcurrency, - maxQueueSizeBytes: maxMemory, - ...(config.callerOptions ?? {}), - onFailedResponseHook: handle429, - debug: config.debug ?? this.debug, - }); - this.hideInputs = - config.hideInputs ?? config.anonymizer ?? defaultConfig.hideInputs; - this.hideOutputs = - config.hideOutputs ?? config.anonymizer ?? defaultConfig.hideOutputs; - this.omitTracedRuntimeInfo = config.omitTracedRuntimeInfo ?? false; - this.autoBatchTracing = config.autoBatchTracing ?? this.autoBatchTracing; - this.autoBatchQueue = new AutoBatchQueue(maxMemory); - this.blockOnRootRunFinalization = - config.blockOnRootRunFinalization ?? this.blockOnRootRunFinalization; - this.batchSizeBytesLimit = config.batchSizeBytesLimit; - this.batchSizeLimit = config.batchSizeLimit; - this.fetchOptions = config.fetchOptions || {}; - this.manualFlushMode = config.manualFlushMode ?? this.manualFlushMode; - if (getOtelEnabled()) { - this.langSmithToOTELTranslator = new LangSmithToOTELTranslator(); - } - // Cache metadata env vars once during construction to avoid repeatedly scanning process.env - this.cachedLSEnvVarsForMetadata = getLangSmithEnvVarsMetadata(); - } - static getDefaultClientConfig() { - const apiKey = getLangSmithEnvironmentVariable("API_KEY"); - const apiUrl = getLangSmithEnvironmentVariable("ENDPOINT") ?? DEFAULT_API_URL; - const hideInputs = getLangSmithEnvironmentVariable("HIDE_INPUTS") === "true"; - const hideOutputs = getLangSmithEnvironmentVariable("HIDE_OUTPUTS") === "true"; - return { - apiUrl: apiUrl, - apiKey: apiKey, - webUrl: undefined, - hideInputs: hideInputs, - hideOutputs: hideOutputs, - }; - } - getHostUrl() { - if (this.webUrl) { - return this.webUrl; - } - else if (isLocalhost(this.apiUrl)) { - this.webUrl = "http://localhost:3000"; - return this.webUrl; - } - else if (this.apiUrl.endsWith("/api/v1")) { - this.webUrl = this.apiUrl.replace("/api/v1", ""); - return this.webUrl; - } - else if (this.apiUrl.includes("/api") && - !this.apiUrl.split(".", 1)[0].endsWith("api")) { - this.webUrl = this.apiUrl.replace("/api", ""); - return this.webUrl; - } - else if (this.apiUrl.split(".", 1)[0].includes("dev")) { - this.webUrl = "https://dev.smith.langchain.com"; - return this.webUrl; - } - else if (this.apiUrl.split(".", 1)[0].includes("eu")) { - this.webUrl = "https://eu.smith.langchain.com"; - return this.webUrl; - } - else if (this.apiUrl.split(".", 1)[0].includes("beta")) { - this.webUrl = "https://beta.smith.langchain.com"; - return this.webUrl; - } - else { - this.webUrl = "https://smith.langchain.com"; - return this.webUrl; - } - } - get headers() { - const headers = { - "User-Agent": `langsmith-js/${__version__}`, - }; - if (this.apiKey) { - headers["x-api-key"] = `${this.apiKey}`; - } - if (this.workspaceId) { - headers["x-tenant-id"] = this.workspaceId; - } - return headers; - } - _getPlatformEndpointPath(path) { - // Check if apiUrl already ends with /v1 or /v1/ to avoid double /v1/v1/ paths - const needsV1Prefix = this.apiUrl.slice(-3) !== "/v1" && this.apiUrl.slice(-4) !== "/v1/"; - return needsV1Prefix ? `/v1/platform/${path}` : `/platform/${path}`; - } - async processInputs(inputs) { - if (this.hideInputs === false) { - return inputs; - } - if (this.hideInputs === true) { - return {}; - } - if (typeof this.hideInputs === "function") { - return this.hideInputs(inputs); - } - return inputs; - } - async processOutputs(outputs) { - if (this.hideOutputs === false) { - return outputs; - } - if (this.hideOutputs === true) { - return {}; - } - if (typeof this.hideOutputs === "function") { - return this.hideOutputs(outputs); - } - return outputs; - } - async prepareRunCreateOrUpdateInputs(run) { - const runParams = { ...run }; - if (runParams.inputs !== undefined) { - runParams.inputs = await this.processInputs(runParams.inputs); - } - if (runParams.outputs !== undefined) { - runParams.outputs = await this.processOutputs(runParams.outputs); - } - return runParams; - } - async _getResponse(path, queryParams) { - const paramsString = queryParams?.toString() ?? ""; - const url = `${this.apiUrl}${path}?${paramsString}`; - const response = await this.caller.call(async () => { - const res = await this._fetch(url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `fetch ${path}`); - return res; - }); - return response; - } - async _get(path, queryParams) { - const response = await this._getResponse(path, queryParams); - return response.json(); - } - async *_getPaginated(path, queryParams = new URLSearchParams(), transform) { - let offset = Number(queryParams.get("offset")) || 0; - const limit = Number(queryParams.get("limit")) || 100; - while (true) { - queryParams.set("offset", String(offset)); - queryParams.set("limit", String(limit)); - const url = `${this.apiUrl}${path}?${queryParams}`; - const response = await this.caller.call(async () => { - const res = await this._fetch(url, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `fetch ${path}`); - return res; - }); - const items = transform - ? transform(await response.json()) - : await response.json(); - if (items.length === 0) { - break; - } - yield items; - if (items.length < limit) { - break; - } - offset += items.length; - } - } - async *_getCursorPaginatedList(path, body = null, requestMethod = "POST", dataKey = "runs") { - const bodyParams = body ? { ...body } : {}; - while (true) { - const body = JSON.stringify(bodyParams); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}${path}`, { - method: requestMethod, - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, `fetch ${path}`); - return res; - }); - const responseBody = await response.json(); - if (!responseBody) { - break; - } - if (!responseBody[dataKey]) { - break; - } - yield responseBody[dataKey]; - const cursors = responseBody.cursors; - if (!cursors) { - break; - } - if (!cursors.next) { - break; - } - bodyParams.cursor = cursors.next; - } - } - // Allows mocking for tests - _shouldSample() { - if (this.tracingSampleRate === undefined) { - return true; - } - return Math.random() < this.tracingSampleRate; - } - _filterForSampling(runs, patch = false) { - if (this.tracingSampleRate === undefined) { - return runs; - } - if (patch) { - const sampled = []; - for (const run of runs) { - if (!this.filteredPostUuids.has(run.trace_id)) { - sampled.push(run); - } - else if (run.id === run.trace_id) { - this.filteredPostUuids.delete(run.trace_id); - } - } - return sampled; - } - else { - // For new runs, sample at trace level to maintain consistency - const sampled = []; - for (const run of runs) { - const traceId = run.trace_id ?? run.id; - // If we've already made a decision about this trace, follow it - if (this.filteredPostUuids.has(traceId)) { - continue; - } - // For new traces, apply sampling - if (run.id === traceId) { - if (this._shouldSample()) { - sampled.push(run); - } - else { - this.filteredPostUuids.add(traceId); - } - } - else { - // Child runs follow their trace's sampling decision - sampled.push(run); - } - } - return sampled; - } - } - async _getBatchSizeLimitBytes() { - const serverInfo = await this._ensureServerInfo(); - return (this.batchSizeBytesLimit ?? - serverInfo?.batch_ingest_config?.size_limit_bytes ?? - DEFAULT_UNCOMPRESSED_BATCH_SIZE_LIMIT_BYTES); - } - /** - * Get the maximum number of operations to batch in a single request. - */ - async _getBatchSizeLimit() { - const serverInfo = await this._ensureServerInfo(); - return (this.batchSizeLimit ?? - serverInfo?.batch_ingest_config?.size_limit ?? - DEFAULT_BATCH_SIZE_LIMIT); - } - async _getDatasetExamplesMultiPartSupport() { - const serverInfo = await this._ensureServerInfo(); - return (serverInfo.instance_flags?.dataset_examples_multipart_enabled ?? false); - } - drainAutoBatchQueue({ batchSizeLimitBytes, batchSizeLimit, }) { - const promises = []; - while (this.autoBatchQueue.items.length > 0) { - const [batch, done] = this.autoBatchQueue.pop({ - upToSizeBytes: batchSizeLimitBytes, - upToSize: batchSizeLimit, - }); - if (!batch.length) { - done(); - break; - } - const batchesByDestination = batch.reduce((acc, item) => { - const apiUrl = item.apiUrl ?? this.apiUrl; - const apiKey = item.apiKey ?? this.apiKey; - const isDefault = item.apiKey === this.apiKey && item.apiUrl === this.apiUrl; - const batchKey = isDefault ? "default" : `${apiUrl}|${apiKey}`; - if (!acc[batchKey]) { - acc[batchKey] = []; - } - acc[batchKey].push(item); - return acc; - }, {}); - const batchPromises = []; - for (const [batchKey, batch] of Object.entries(batchesByDestination)) { - const batchPromise = this._processBatch(batch, { - apiUrl: batchKey === "default" ? undefined : batchKey.split("|")[0], - apiKey: batchKey === "default" ? undefined : batchKey.split("|")[1], - }); - batchPromises.push(batchPromise); - } - // Wait for all batches to complete, then call the overall done callback - const allBatchesPromise = Promise.all(batchPromises).finally(done); - promises.push(allBatchesPromise); - } - return Promise.all(promises); - } - async _processBatch(batch, options) { - if (!batch.length) { - return; - } - // Calculate total batch size for queue tracking - const batchSizeBytes = batch.reduce((sum, item) => sum + (item.size ?? 0), 0); - try { - if (this.langSmithToOTELTranslator !== undefined) { - this._sendBatchToOTELTranslator(batch); - } - else { - const ingestParams = { - runCreates: batch - .filter((item) => item.action === "create") - .map((item) => item.item), - runUpdates: batch - .filter((item) => item.action === "update") - .map((item) => item.item), - }; - const serverInfo = await this._ensureServerInfo(); - const useMultipart = !this._multipartDisabled && - (serverInfo?.batch_ingest_config?.use_multipart_endpoint ?? true); - if (useMultipart) { - const useGzip = serverInfo?.instance_flags?.gzip_body_enabled; - try { - await this.multipartIngestRuns(ingestParams, { - ...options, - useGzip, - sizeBytes: batchSizeBytes, - }); - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - catch (e) { - if (isLangSmithNotFoundError(e)) { - // Fallback to batch ingest if multipart endpoint returns 404 - // Disable multipart for future requests - this._multipartDisabled = true; - await this.batchIngestRuns(ingestParams, { - ...options, - sizeBytes: batchSizeBytes, - }); - } - else { - throw e; - } - } - } - else { - await this.batchIngestRuns(ingestParams, { - ...options, - sizeBytes: batchSizeBytes, - }); - } - } - } - catch (e) { - console.error("Error exporting batch:", e); - } - } - _sendBatchToOTELTranslator(batch) { - if (this.langSmithToOTELTranslator !== undefined) { - const otelContextMap = new Map(); - const operations = []; - for (const item of batch) { - if (item.item.id && item.otelContext) { - otelContextMap.set(item.item.id, item.otelContext); - if (item.action === "create") { - operations.push({ - operation: "post", - id: item.item.id, - trace_id: item.item.trace_id ?? item.item.id, - run: item.item, - }); - } - else { - operations.push({ - operation: "patch", - id: item.item.id, - trace_id: item.item.trace_id ?? item.item.id, - run: item.item, - }); - } - } - } - this.langSmithToOTELTranslator.exportBatch(operations, otelContextMap); - } - } - async processRunOperation(item) { - clearTimeout(this.autoBatchTimeout); - this.autoBatchTimeout = undefined; - item.item = mergeRuntimeEnvIntoRun(item.item, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo); - const itemPromise = this.autoBatchQueue.push(item); - if (this.manualFlushMode) { - // Rely on manual flushing in serverless environments - return itemPromise; - } - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - const sizeLimit = await this._getBatchSizeLimit(); - if (this.autoBatchQueue.sizeBytes > sizeLimitBytes || - this.autoBatchQueue.items.length > sizeLimit) { - void this.drainAutoBatchQueue({ - batchSizeLimitBytes: sizeLimitBytes, - batchSizeLimit: sizeLimit, - }); - } - if (this.autoBatchQueue.items.length > 0) { - this.autoBatchTimeout = setTimeout(() => { - this.autoBatchTimeout = undefined; - void this.drainAutoBatchQueue({ - batchSizeLimitBytes: sizeLimitBytes, - batchSizeLimit: sizeLimit, - }); - }, this.autoBatchAggregationDelayMs); - } - return itemPromise; - } - async _getServerInfo() { - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/info`, { - method: "GET", - headers: { Accept: "application/json" }, - signal: AbortSignal.timeout(SERVER_INFO_REQUEST_TIMEOUT_MS), - ...this.fetchOptions, - }); - await raiseForStatus(res, "get server info"); - return res; - }); - const json = await response.json(); - if (this.debug) { - console.log("\n=== LangSmith Server Configuration ===\n" + - JSON.stringify(json, null, 2) + - "\n"); - } - return json; - } - async _ensureServerInfo() { - if (this._getServerInfoPromise === undefined) { - this._getServerInfoPromise = (async () => { - if (this._serverInfo === undefined) { - try { - this._serverInfo = await this._getServerInfo(); - } - catch (e) { - console.warn(`[LANGSMITH]: Failed to fetch info on supported operations. Falling back to batch operations and default limits. Info: ${e.status ?? "Unspecified status code"} ${e.message}`); - } - } - return this._serverInfo ?? {}; - })(); - } - return this._getServerInfoPromise.then((serverInfo) => { - if (this._serverInfo === undefined) { - this._getServerInfoPromise = undefined; - } - return serverInfo; - }); - } - async _getSettings() { - if (!this.settings) { - this.settings = this._get("/settings"); - } - return await this.settings; - } - /** - * Flushes current queued traces. - */ - async flush() { - const sizeLimitBytes = await this._getBatchSizeLimitBytes(); - const sizeLimit = await this._getBatchSizeLimit(); - await this.drainAutoBatchQueue({ - batchSizeLimitBytes: sizeLimitBytes, - batchSizeLimit: sizeLimit, - }); - } - _cloneCurrentOTELContext() { - const otel_trace = getOTELTrace(); - const otel_context = getOTELContext(); - if (this.langSmithToOTELTranslator !== undefined) { - const currentSpan = otel_trace.getActiveSpan(); - if (currentSpan) { - return otel_trace.setSpan(otel_context.active(), currentSpan); - } - } - return undefined; - } - async createRun(run, options) { - if (!this._filterForSampling([run]).length) { - return; - } - const headers = { - ...this.headers, - "Content-Type": "application/json", - }; - const session_name = run.project_name; - delete run.project_name; - const runCreate = await this.prepareRunCreateOrUpdateInputs({ - session_name, - ...run, - start_time: run.start_time ?? Date.now(), - }); - if (this.autoBatchTracing && - runCreate.trace_id !== undefined && - runCreate.dotted_order !== undefined) { - const otelContext = this._cloneCurrentOTELContext(); - void this.processRunOperation({ - action: "create", - item: runCreate, - otelContext, - apiKey: options?.apiKey, - apiUrl: options?.apiUrl, - }).catch(console.error); - return; - } - const mergedRunCreateParam = mergeRuntimeEnvIntoRun(runCreate, this.cachedLSEnvVarsForMetadata, this.omitTracedRuntimeInfo); - if (options?.apiKey !== undefined) { - headers["x-api-key"] = options.apiKey; - } - if (options?.workspaceId !== undefined) { - headers["x-tenant-id"] = options.workspaceId; - } - const body = serialize(mergedRunCreateParam, `Creating run with id: ${mergedRunCreateParam.id}`); - await this.caller.call(async () => { - const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs`, { - method: "POST", - headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "create run", true); - return res; - }); - } - /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs - */ - async batchIngestRuns({ runCreates, runUpdates, }, options) { - if (runCreates === undefined && runUpdates === undefined) { - return; - } - let preparedCreateParams = await Promise.all(runCreates?.map((create) => this.prepareRunCreateOrUpdateInputs(create)) ?? []); - let preparedUpdateParams = await Promise.all(runUpdates?.map((update) => this.prepareRunCreateOrUpdateInputs(update)) ?? []); - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; - } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== undefined && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam, - }; - } - else { - standaloneUpdates.push(updateParam); - } - } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; - } - const rawBatch = { - post: preparedCreateParams, - patch: preparedUpdateParams, - }; - if (!rawBatch.post.length && !rawBatch.patch.length) { - return; - } - const batchChunks = { - post: [], - patch: [], - }; - for (const k of ["post", "patch"]) { - const key = k; - const batchItems = rawBatch[key].reverse(); - let batchItem = batchItems.pop(); - while (batchItem !== undefined) { - // Type is wrong but this is a deprecated code path anyway - batchChunks[key].push(batchItem); - batchItem = batchItems.pop(); - } - } - if (batchChunks.post.length > 0 || batchChunks.patch.length > 0) { - const runIds = batchChunks.post - .map((item) => item.id) - .concat(batchChunks.patch.map((item) => item.id)) - .join(","); - await this._postBatchIngestRuns(serialize(batchChunks, `Ingesting runs with ids: ${runIds}`), options); - } - } - async _postBatchIngestRuns(body, options) { - const headers = { - ...this.headers, - "Content-Type": "application/json", - Accept: "application/json", - }; - if (options?.apiKey !== undefined) { - headers["x-api-key"] = options.apiKey; - } - await this.batchIngestCaller.callWithOptions({ sizeBytes: options?.sizeBytes }, async () => { - const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/batch`, { - method: "POST", - headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "batch create run", true); - return res; - }); - } - /** - * Batch ingest/upsert multiple runs in the Langsmith system. - * @param runs - */ - async multipartIngestRuns({ runCreates, runUpdates, }, options) { - if (runCreates === undefined && runUpdates === undefined) { - return; - } - // transform and convert to dicts - const allAttachments = {}; - let preparedCreateParams = []; - for (const create of runCreates ?? []) { - const preparedCreate = await this.prepareRunCreateOrUpdateInputs(create); - if (preparedCreate.id !== undefined && - preparedCreate.attachments !== undefined) { - allAttachments[preparedCreate.id] = preparedCreate.attachments; - } - delete preparedCreate.attachments; - preparedCreateParams.push(preparedCreate); - } - let preparedUpdateParams = []; - for (const update of runUpdates ?? []) { - preparedUpdateParams.push(await this.prepareRunCreateOrUpdateInputs(update)); - } - // require trace_id and dotted_order - const invalidRunCreate = preparedCreateParams.find((runCreate) => { - return (runCreate.trace_id === undefined || runCreate.dotted_order === undefined); - }); - if (invalidRunCreate !== undefined) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when creating a run`); - } - const invalidRunUpdate = preparedUpdateParams.find((runUpdate) => { - return (runUpdate.trace_id === undefined || runUpdate.dotted_order === undefined); - }); - if (invalidRunUpdate !== undefined) { - throw new Error(`Multipart ingest requires "trace_id" and "dotted_order" to be set when updating a run`); - } - // combine post and patch dicts where possible - if (preparedCreateParams.length > 0 && preparedUpdateParams.length > 0) { - const createById = preparedCreateParams.reduce((params, run) => { - if (!run.id) { - return params; - } - params[run.id] = run; - return params; - }, {}); - const standaloneUpdates = []; - for (const updateParam of preparedUpdateParams) { - if (updateParam.id !== undefined && createById[updateParam.id]) { - createById[updateParam.id] = { - ...createById[updateParam.id], - ...updateParam, - }; - } - else { - standaloneUpdates.push(updateParam); - } - } - preparedCreateParams = Object.values(createById); - preparedUpdateParams = standaloneUpdates; - } - if (preparedCreateParams.length === 0 && - preparedUpdateParams.length === 0) { - return; - } - // send the runs in multipart requests - const accumulatedContext = []; - const accumulatedParts = []; - for (const [method, payloads] of [ - ["post", preparedCreateParams], - ["patch", preparedUpdateParams], - ]) { - for (const originalPayload of payloads) { - // collect fields to be sent as separate parts - const { inputs, outputs, events, extra, error, serialized, attachments, ...payload } = originalPayload; - const fields = { inputs, outputs, events, extra, error, serialized }; - // encode the main run payload - const stringifiedPayload = serialize(payload, `Serializing for multipart ingestion of run with id: ${payload.id}`); - accumulatedParts.push({ - name: `${method}.${payload.id}`, - payload: new Blob([stringifiedPayload], { - type: `application/json; length=${stringifiedPayload.length}`, // encoding=gzip - }), - }); - // encode the fields we collected - for (const [key, value] of Object.entries(fields)) { - if (value === undefined) { - continue; - } - const stringifiedValue = serialize(value, `Serializing ${key} for multipart ingestion of run with id: ${payload.id}`); - accumulatedParts.push({ - name: `${method}.${payload.id}.${key}`, - payload: new Blob([stringifiedValue], { - type: `application/json; length=${stringifiedValue.length}`, - }), - }); - } - // encode the attachments - if (payload.id !== undefined) { - const attachments = allAttachments[payload.id]; - if (attachments) { - delete allAttachments[payload.id]; - for (const [name, attachment] of Object.entries(attachments)) { - let contentType; - let content; - if (Array.isArray(attachment)) { - [contentType, content] = attachment; - } - else { - contentType = attachment.mimeType; - content = attachment.data; - } - // Validate that the attachment name doesn't contain a '.' - if (name.includes(".")) { - console.warn(`Skipping attachment '${name}' for run ${payload.id}: Invalid attachment name. ` + - `Attachment names must not contain periods ('.'). Please rename the attachment and try again.`); - continue; - } - accumulatedParts.push({ - name: `attachment.${payload.id}.${name}`, - payload: new Blob([content], { - type: `${contentType}; length=${content.byteLength}`, - }), - }); - } - } - } - // compute context - accumulatedContext.push(`trace=${payload.trace_id},id=${payload.id}`); - } - } - await this._sendMultipartRequest(accumulatedParts, accumulatedContext.join("; "), options); - } - async _createNodeFetchBody(parts, boundary) { - // Create multipart form data manually using Blobs - const chunks = []; - for (const part of parts) { - // Add field boundary - chunks.push(new Blob([`--${boundary}\r\n`])); - chunks.push(new Blob([ - `Content-Disposition: form-data; name="${part.name}"\r\n`, - `Content-Type: ${part.payload.type}\r\n\r\n`, - ])); - chunks.push(part.payload); - chunks.push(new Blob(["\r\n"])); - } - // Add final boundary - chunks.push(new Blob([`--${boundary}--\r\n`])); - // Combine all chunks into a single Blob - const body = new Blob(chunks); - // Convert Blob to ArrayBuffer for compatibility - const arrayBuffer = await body.arrayBuffer(); - return arrayBuffer; - } - async _createMultipartStream(parts, boundary) { - const encoder = new TextEncoder(); - // Create a ReadableStream for streaming the multipart data - // Only do special handling if we're using node-fetch - const stream = new ReadableStream({ - async start(controller) { - // Helper function to write a chunk to the stream - const writeChunk = async (chunk) => { - if (typeof chunk === "string") { - controller.enqueue(encoder.encode(chunk)); - } - else { - controller.enqueue(chunk); - } - }; - // Write each part to the stream - for (const part of parts) { - // Write boundary and headers - await writeChunk(`--${boundary}\r\n`); - await writeChunk(`Content-Disposition: form-data; name="${part.name}"\r\n`); - await writeChunk(`Content-Type: ${part.payload.type}\r\n\r\n`); - // Write the payload - const payloadStream = part.payload.stream(); - const reader = payloadStream.getReader(); - try { - let result; - while (!(result = await reader.read()).done) { - controller.enqueue(result.value); - } - } - finally { - reader.releaseLock(); - } - await writeChunk("\r\n"); - } - // Write final boundary - await writeChunk(`--${boundary}--\r\n`); - controller.close(); - }, - }); - return stream; - } - async _sendMultipartRequest(parts, context, options) { - // Create multipart form data boundary - const boundary = "----LangSmithFormBoundary" + Math.random().toString(36).slice(2); - const isNodeFetch = _globalFetchImplementationIsNodeFetch(); - const buildBuffered = () => this._createNodeFetchBody(parts, boundary); - const buildStream = () => this._createMultipartStream(parts, boundary); - const sendWithRetry = async (bodyFactory) => { - return this.batchIngestCaller.callWithOptions({ sizeBytes: options?.sizeBytes }, async () => { - const body = await bodyFactory(); - const headers = { - ...this.headers, - "Content-Type": `multipart/form-data; boundary=${boundary}`, - }; - if (options?.apiKey !== undefined) { - headers["x-api-key"] = options.apiKey; - } - let transformedBody = body; - if (options?.useGzip && - typeof body === "object" && - "pipeThrough" in body) { - transformedBody = body.pipeThrough(new CompressionStream("gzip")); - headers["Content-Encoding"] = "gzip"; - } - const response = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/multipart`, { - method: "POST", - headers, - body: transformedBody, - duplex: "half", - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(response, `Failed to send multipart request`, true); - return response; - }); - }; - try { - let res; - let streamedAttempt = false; - // attempt stream only if not disabled and not using node-fetch or Bun - if (!isNodeFetch && - !this.multipartStreamingDisabled && - env_getEnv() !== "bun") { - streamedAttempt = true; - res = await sendWithRetry(buildStream); - } - else { - res = await sendWithRetry(buildBuffered); - } - // if stream fails, fallback to buffered body - if ((!this.multipartStreamingDisabled || streamedAttempt) && - res.status === 422 && - (options?.apiUrl ?? this.apiUrl) !== DEFAULT_API_URL) { - console.warn(`Streaming multipart upload to ${options?.apiUrl ?? this.apiUrl}/runs/multipart failed. ` + - `This usually means the host does not support chunked uploads. ` + - `Retrying with a buffered upload for operation "${context}".`); - // Disable streaming for future requests - this.multipartStreamingDisabled = true; - // retry with fully-buffered body - res = await sendWithRetry(buildBuffered); - } - // eslint-disable-next-line @typescript-eslint/no-explicit-any - } - catch (e) { - // Re-throw 404 errors so caller can fall back to batch ingest - if (isLangSmithNotFoundError(e)) { - throw e; - } - console.warn(`${e.message.trim()}\n\nContext: ${context}`); - } - } - async updateRun(runId, run, options) { - assertUuid(runId); - if (run.inputs) { - run.inputs = await this.processInputs(run.inputs); - } - if (run.outputs) { - run.outputs = await this.processOutputs(run.outputs); - } - // TODO: Untangle types - const data = { ...run, id: runId }; - if (!this._filterForSampling([data], true).length) { - return; - } - if (this.autoBatchTracing && - data.trace_id !== undefined && - data.dotted_order !== undefined) { - const otelContext = this._cloneCurrentOTELContext(); - if (run.end_time !== undefined && - data.parent_run_id === undefined && - this.blockOnRootRunFinalization && - !this.manualFlushMode) { - // Trigger batches as soon as a root trace ends and wait to ensure trace finishes - // in serverless environments. - await this.processRunOperation({ - action: "update", - item: data, - otelContext, - apiKey: options?.apiKey, - apiUrl: options?.apiUrl, - }).catch(console.error); - return; - } - else { - void this.processRunOperation({ - action: "update", - item: data, - otelContext, - apiKey: options?.apiKey, - apiUrl: options?.apiUrl, - }).catch(console.error); - } - return; - } - const headers = { - ...this.headers, - "Content-Type": "application/json", - }; - if (options?.apiKey !== undefined) { - headers["x-api-key"] = options.apiKey; - } - if (options?.workspaceId !== undefined) { - headers["x-tenant-id"] = options.workspaceId; - } - const body = serialize(run, `Serializing payload to update run with id: ${runId}`); - await this.caller.call(async () => { - const res = await this._fetch(`${options?.apiUrl ?? this.apiUrl}/runs/${runId}`, { - method: "PATCH", - headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update run", true); - return res; - }); - } - async readRun(runId, { loadChildRuns } = { loadChildRuns: false }) { - assertUuid(runId); - let run = await this._get(`/runs/${runId}`); - if (loadChildRuns) { - run = await this._loadChildRuns(run); - } - return run; - } - async getRunUrl({ runId, run, projectOpts, }) { - if (run !== undefined) { - let sessionId; - if (run.session_id) { - sessionId = run.session_id; - } - else if (projectOpts?.projectName) { - sessionId = (await this.readProject({ projectName: projectOpts?.projectName })).id; - } - else if (projectOpts?.projectId) { - sessionId = projectOpts?.projectId; - } - else { - const project = await this.readProject({ - projectName: getLangSmithEnvironmentVariable("PROJECT") || "default", - }); - sessionId = project.id; - } - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${sessionId}/r/${run.id}?poll=true`; - } - else if (runId !== undefined) { - const run_ = await this.readRun(runId); - if (!run_.app_path) { - throw new Error(`Run ${runId} has no app_path`); - } - const baseUrl = this.getHostUrl(); - return `${baseUrl}${run_.app_path}`; - } - else { - throw new Error("Must provide either runId or run"); - } - } - async _loadChildRuns(run) { - const childRuns = await toArray(this.listRuns({ - isRoot: false, - projectId: run.session_id, - traceId: run.trace_id, - })); - const treemap = {}; - const runs = {}; - // TODO: make dotted order required when the migration finishes - childRuns.sort((a, b) => (a?.dotted_order ?? "").localeCompare(b?.dotted_order ?? "")); - for (const childRun of childRuns) { - if (childRun.parent_run_id === null || - childRun.parent_run_id === undefined) { - throw new Error(`Child run ${childRun.id} has no parent`); - } - if (childRun.dotted_order?.startsWith(run.dotted_order ?? "") && - childRun.id !== run.id) { - if (!(childRun.parent_run_id in treemap)) { - treemap[childRun.parent_run_id] = []; - } - treemap[childRun.parent_run_id].push(childRun); - runs[childRun.id] = childRun; - } - } - run.child_runs = treemap[run.id] || []; - for (const runId in treemap) { - if (runId !== run.id) { - runs[runId].child_runs = treemap[runId]; - } - } - return run; - } - /** - * List runs from the LangSmith server. - * @param projectId - The ID of the project to filter by. - * @param projectName - The name of the project to filter by. - * @param parentRunId - The ID of the parent run to filter by. - * @param traceId - The ID of the trace to filter by. - * @param referenceExampleId - The ID of the reference example to filter by. - * @param startTime - The start time to filter by. - * @param isRoot - Indicates whether to only return root runs. - * @param runType - The run type to filter by. - * @param error - Indicates whether to filter by error runs. - * @param id - The ID of the run to filter by. - * @param query - The query string to filter by. - * @param filter - The filter string to apply to the run spans. - * @param traceFilter - The filter string to apply on the root run of the trace. - * @param treeFilter - The filter string to apply on other runs in the trace. - * @param limit - The maximum number of runs to retrieve. - * @returns {AsyncIterable} - The runs. - * - * @example - * // List all runs in a project - * const projectRuns = client.listRuns({ projectName: "" }); - * - * @example - * // List LLM and Chat runs in the last 24 hours - * const todaysLLMRuns = client.listRuns({ - * projectName: "", - * start_time: new Date(Date.now() - 24 * 60 * 60 * 1000), - * run_type: "llm", - * }); - * - * @example - * // List traces in a project - * const rootRuns = client.listRuns({ - * projectName: "", - * execution_order: 1, - * }); - * - * @example - * // List runs without errors - * const correctRuns = client.listRuns({ - * projectName: "", - * error: false, - * }); - * - * @example - * // List runs by run ID - * const runIds = [ - * "a36092d2-4ad5-4fb4-9c0d-0dba9a2ed836", - * "9398e6be-964f-4aa4-8ae9-ad78cd4b7074", - * ]; - * const selectedRuns = client.listRuns({ run_ids: runIds }); - * - * @example - * // List all "chain" type runs that took more than 10 seconds and had `total_tokens` greater than 5000 - * const chainRuns = client.listRuns({ - * projectName: "", - * filter: 'and(eq(run_type, "chain"), gt(latency, 10), gt(total_tokens, 5000))', - * }); - * - * @example - * // List all runs called "extractor" whose root of the trace was assigned feedback "user_score" score of 1 - * const goodExtractorRuns = client.listRuns({ - * projectName: "", - * filter: 'eq(name, "extractor")', - * traceFilter: 'and(eq(feedback_key, "user_score"), eq(feedback_score, 1))', - * }); - * - * @example - * // List all runs that started after a specific timestamp and either have "error" not equal to null or a "Correctness" feedback score equal to 0 - * const complexRuns = client.listRuns({ - * projectName: "", - * filter: 'and(gt(start_time, "2023-07-15T12:34:56Z"), or(neq(error, null), and(eq(feedback_key, "Correctness"), eq(feedback_score, 0.0))))', - * }); - * - * @example - * // List all runs where `tags` include "experimental" or "beta" and `latency` is greater than 2 seconds - * const taggedRuns = client.listRuns({ - * projectName: "", - * filter: 'and(or(has(tags, "experimental"), has(tags, "beta")), gt(latency, 2))', - * }); - */ - async *listRuns(props) { - const { projectId, projectName, parentRunId, traceId, referenceExampleId, startTime, executionOrder, isRoot, runType, error, id, query, filter, traceFilter, treeFilter, limit, select, order, } = props; - let projectIds = []; - if (projectId) { - projectIds = Array.isArray(projectId) ? projectId : [projectId]; - } - if (projectName) { - const projectNames = Array.isArray(projectName) - ? projectName - : [projectName]; - const projectIds_ = await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id))); - projectIds.push(...projectIds_); - } - const default_select = [ - "app_path", - "completion_cost", - "completion_tokens", - "dotted_order", - "end_time", - "error", - "events", - "extra", - "feedback_stats", - "first_token_time", - "id", - "inputs", - "name", - "outputs", - "parent_run_id", - "parent_run_ids", - "prompt_cost", - "prompt_tokens", - "reference_example_id", - "run_type", - "session_id", - "start_time", - "status", - "tags", - "total_cost", - "total_tokens", - "trace_id", - ]; - const body = { - session: projectIds.length ? projectIds : null, - run_type: runType, - reference_example: referenceExampleId, - query, - filter, - trace_filter: traceFilter, - tree_filter: treeFilter, - execution_order: executionOrder, - parent_run: parentRunId, - start_time: startTime ? startTime.toISOString() : null, - error, - id, - limit, - trace: traceId, - select: select ? select : default_select, - is_root: isRoot, - order, - }; - if (body.select.includes("child_run_ids")) { - warn_warnOnce("Deprecated: 'child_run_ids' in the listRuns select parameter is deprecated and will be removed in a future version."); - } - let runsYielded = 0; - for await (const runs of this._getCursorPaginatedList("/runs/query", body)) { - if (limit) { - if (runsYielded >= limit) { - break; - } - if (runs.length + runsYielded > limit) { - const newRuns = runs.slice(0, limit - runsYielded); - yield* newRuns; - break; - } - runsYielded += runs.length; - yield* runs; - } - else { - yield* runs; - } - } - } - async *listGroupRuns(props) { - const { projectId, projectName, groupBy, filter, startTime, endTime, limit, offset, } = props; - const sessionId = projectId || (await this.readProject({ projectName })).id; - const baseBody = { - session_id: sessionId, - group_by: groupBy, - filter, - start_time: startTime ? startTime.toISOString() : null, - end_time: endTime ? endTime.toISOString() : null, - limit: Number(limit) || 100, - }; - let currentOffset = Number(offset) || 0; - const path = "/runs/group"; - const url = `${this.apiUrl}${path}`; - while (true) { - const currentBody = { - ...baseBody, - offset: currentOffset, - }; - // Remove undefined values from the payload - const filteredPayload = Object.fromEntries(Object.entries(currentBody).filter(([_, value]) => value !== undefined)); - const body = JSON.stringify(filteredPayload); - const response = await this.caller.call(async () => { - const res = await this._fetch(url, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, `Failed to fetch ${path}`); - return res; - }); - const items = await response.json(); - const { groups, total } = items; - if (groups.length === 0) { - break; - } - for (const thread of groups) { - yield thread; - } - currentOffset += groups.length; - if (currentOffset >= total) { - break; - } - } - } - async getRunStats({ id, trace, parentRun, runType, projectNames, projectIds, referenceExampleIds, startTime, endTime, error, query, filter, traceFilter, treeFilter, isRoot, dataSourceType, }) { - let projectIds_ = projectIds || []; - if (projectNames) { - projectIds_ = [ - ...(projectIds || []), - ...(await Promise.all(projectNames.map((name) => this.readProject({ projectName: name }).then((project) => project.id)))), - ]; - } - const payload = { - id, - trace, - parent_run: parentRun, - run_type: runType, - session: projectIds_, - reference_example: referenceExampleIds, - start_time: startTime, - end_time: endTime, - error, - query, - filter, - trace_filter: traceFilter, - tree_filter: treeFilter, - is_root: isRoot, - data_source_type: dataSourceType, - }; - // Remove undefined values from the payload - const filteredPayload = Object.fromEntries(Object.entries(payload).filter(([_, value]) => value !== undefined)); - const body = JSON.stringify(filteredPayload); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/runs/stats`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "get run stats"); - return res; - }); - const result = await response.json(); - return result; - } - async shareRun(runId, { shareId } = {}) { - const data = { - run_id: runId, - share_token: shareId || v4(), - }; - assertUuid(runId); - const body = JSON.stringify(data); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { - method: "PUT", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "share run"); - return res; - }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - throw new Error("Invalid response from server"); - } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; - } - async unshareRun(runId) { - assertUuid(runId); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "unshare run", true); - return res; - }); - } - async readRunSharedLink(runId) { - assertUuid(runId); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/runs/${runId}/share`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "read run shared link"); - return res; - }); - const result = await response.json(); - if (result === null || !("share_token" in result)) { - return undefined; - } - return `${this.getHostUrl()}/public/${result["share_token"]}/r`; - } - async listSharedRuns(shareToken, { runIds, } = {}) { - const queryParams = new URLSearchParams({ - share_token: shareToken, - }); - if (runIds !== undefined) { - for (const runId of runIds) { - queryParams.append("id", runId); - } - } - assertUuid(shareToken); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/runs${queryParams}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "list shared runs"); - return res; - }); - const runs = await response.json(); - return runs; - } - async readDatasetSharedSchema(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); - } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; - } - assertUuid(datasetId); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "read dataset shared schema"); - return res; - }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; - } - async shareDataset(datasetId, datasetName) { - if (!datasetId && !datasetName) { - throw new Error("Either datasetId or datasetName must be given"); - } - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - datasetId = dataset.id; - } - const data = { - dataset_id: datasetId, - }; - assertUuid(datasetId); - const body = JSON.stringify(data); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { - method: "PUT", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "share dataset"); - return res; - }); - const shareSchema = await response.json(); - shareSchema.url = `${this.getHostUrl()}/public/${shareSchema.share_token}/d`; - return shareSchema; - } - async unshareDataset(datasetId) { - assertUuid(datasetId); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/share`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "unshare dataset", true); - return res; - }); - } - async readSharedDataset(shareToken) { - assertUuid(shareToken); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/datasets`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "read shared dataset"); - return res; - }); - const dataset = await response.json(); - return dataset; - } - /** - * Get shared examples. - * - * @param {string} shareToken The share token to get examples for. A share token is the UUID (or LangSmith URL, including UUID) generated when explicitly marking an example as public. - * @param {Object} [options] Additional options for listing the examples. - * @param {string[] | undefined} [options.exampleIds] A list of example IDs to filter by. - * @returns {Promise} The shared examples. - */ - async listSharedExamples(shareToken, options) { - const params = {}; - if (options?.exampleIds) { - params.id = options.exampleIds; - } - const urlParams = new URLSearchParams(); - Object.entries(params).forEach(([key, value]) => { - if (Array.isArray(value)) { - value.forEach((v) => urlParams.append(key, v)); - } - else { - urlParams.append(key, value); - } - }); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/public/${shareToken}/examples?${urlParams.toString()}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "list shared examples"); - return res; - }); - const result = await response.json(); - if (!response.ok) { - if ("detail" in result) { - throw new Error(`Failed to list shared examples.\nStatus: ${response.status}\nMessage: ${Array.isArray(result.detail) - ? result.detail.join("\n") - : "Unspecified error"}`); - } - throw new Error(`Failed to list shared examples: ${response.status} ${response.statusText}`); - } - return result.map((example) => ({ - ...example, - _hostUrl: this.getHostUrl(), - })); - } - async createProject({ projectName, description = null, metadata = null, upsert = false, projectExtra = null, referenceDatasetId = null, }) { - const upsert_ = upsert ? `?upsert=true` : ""; - const endpoint = `${this.apiUrl}/sessions${upsert_}`; - const extra = projectExtra || {}; - if (metadata) { - extra["metadata"] = metadata; - } - const body = { - name: projectName, - extra, - description, - }; - if (referenceDatasetId !== null) { - body["reference_dataset_id"] = referenceDatasetId; - } - const serializedBody = JSON.stringify(body); - const response = await this.caller.call(async () => { - const res = await this._fetch(endpoint, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: serializedBody, - }); - await raiseForStatus(res, "create project"); - return res; - }); - const result = await response.json(); - return result; - } - async updateProject(projectId, { name = null, description = null, metadata = null, projectExtra = null, endTime = null, }) { - const endpoint = `${this.apiUrl}/sessions/${projectId}`; - let extra = projectExtra; - if (metadata) { - extra = { ...(extra || {}), metadata }; - } - const body = JSON.stringify({ - name, - extra, - description, - end_time: endTime ? new Date(endTime).toISOString() : null, - }); - const response = await this.caller.call(async () => { - const res = await this._fetch(endpoint, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update project"); - return res; - }); - const result = await response.json(); - return result; - } - async hasProject({ projectId, projectName, }) { - // TODO: Add a head request - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId !== undefined) { - assertUuid(projectId); - path += `/${projectId}`; - } - else if (projectName !== undefined) { - params.append("name", projectName); - } - else { - throw new Error("Must provide projectName or projectId"); - } - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}${path}?${params}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "has project"); - return res; - }); - // consume the response body to release the connection - // https://undici.nodejs.org/#/?id=garbage-collection - try { - const result = await response.json(); - if (!response.ok) { - return false; - } - // If it's OK and we're querying by name, need to check the list is not empty - if (Array.isArray(result)) { - return result.length > 0; - } - // projectId querying - return true; - } - catch (e) { - return false; - } - } - async readProject({ projectId, projectName, includeStats, }) { - let path = "/sessions"; - const params = new URLSearchParams(); - if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId !== undefined) { - assertUuid(projectId); - path += `/${projectId}`; - } - else if (projectName !== undefined) { - params.append("name", projectName); - } - else { - throw new Error("Must provide projectName or projectId"); - } - if (includeStats !== undefined) { - params.append("include_stats", includeStats.toString()); - } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Project[id=${projectId}, name=${projectName}] not found`); - } - result = response[0]; - } - else { - result = response; - } - return result; - } - async getProjectUrl({ projectId, projectName, }) { - if (projectId === undefined && projectName === undefined) { - throw new Error("Must provide either projectName or projectId"); - } - const project = await this.readProject({ projectId, projectName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/projects/p/${project.id}`; - } - async getDatasetUrl({ datasetId, datasetName, }) { - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - const dataset = await this.readDataset({ datasetId, datasetName }); - const tenantId = await this._getTenantId(); - return `${this.getHostUrl()}/o/${tenantId}/datasets/${dataset.id}`; - } - async _getTenantId() { - if (this._tenantId !== null) { - return this._tenantId; - } - const queryParams = new URLSearchParams({ limit: "1" }); - for await (const projects of this._getPaginated("/sessions", queryParams)) { - this._tenantId = projects[0].tenant_id; - return projects[0].tenant_id; - } - throw new Error("No projects found to resolve tenant."); - } - async *listProjects({ projectIds, name, nameContains, referenceDatasetId, referenceDatasetName, includeStats, datasetVersion, referenceFree, metadata, } = {}) { - const params = new URLSearchParams(); - if (projectIds !== undefined) { - for (const projectId of projectIds) { - params.append("id", projectId); - } - } - if (name !== undefined) { - params.append("name", name); - } - if (nameContains !== undefined) { - params.append("name_contains", nameContains); - } - if (referenceDatasetId !== undefined) { - params.append("reference_dataset", referenceDatasetId); - } - else if (referenceDatasetName !== undefined) { - const dataset = await this.readDataset({ - datasetName: referenceDatasetName, - }); - params.append("reference_dataset", dataset.id); - } - if (includeStats !== undefined) { - params.append("include_stats", includeStats.toString()); - } - if (datasetVersion !== undefined) { - params.append("dataset_version", datasetVersion); - } - if (referenceFree !== undefined) { - params.append("reference_free", referenceFree.toString()); - } - if (metadata !== undefined) { - params.append("metadata", JSON.stringify(metadata)); - } - for await (const projects of this._getPaginated("/sessions", params)) { - yield* projects; - } - } - async deleteProject({ projectId, projectName, }) { - let projectId_; - if (projectId === undefined && projectName === undefined) { - throw new Error("Must provide projectName or projectId"); - } - else if (projectId !== undefined && projectName !== undefined) { - throw new Error("Must provide either projectName or projectId, not both"); - } - else if (projectId === undefined) { - projectId_ = (await this.readProject({ projectName })).id; - } - else { - projectId_ = projectId; - } - assertUuid(projectId_); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/sessions/${projectId_}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `delete session ${projectId_} (${projectName})`, true); - return res; - }); - } - async uploadCsv({ csvFile, fileName, inputKeys, outputKeys, description, dataType, name, }) { - const url = `${this.apiUrl}/datasets/upload`; - const formData = new FormData(); - formData.append("file", csvFile, fileName); - inputKeys.forEach((key) => { - formData.append("input_keys", key); - }); - outputKeys.forEach((key) => { - formData.append("output_keys", key); - }); - if (description) { - formData.append("description", description); - } - if (dataType) { - formData.append("data_type", dataType); - } - if (name) { - formData.append("name", name); - } - const response = await this.caller.call(async () => { - const res = await this._fetch(url, { - method: "POST", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: formData, - }); - await raiseForStatus(res, "upload CSV"); - return res; - }); - const result = await response.json(); - return result; - } - async createDataset(name, { description, dataType, inputsSchema, outputsSchema, metadata, } = {}) { - const body = { - name, - description, - extra: metadata ? { metadata } : undefined, - }; - if (dataType) { - body.data_type = dataType; - } - if (inputsSchema) { - body.inputs_schema_definition = inputsSchema; - } - if (outputsSchema) { - body.outputs_schema_definition = outputsSchema; - } - const serializedBody = JSON.stringify(body); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: serializedBody, - }); - await raiseForStatus(res, "create dataset"); - return res; - }); - const result = await response.json(); - return result; - } - async readDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - // limit to 1 result - const params = new URLSearchParams({ limit: "1" }); - if (datasetId && datasetName) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId) { - assertUuid(datasetId); - path += `/${datasetId}`; - } - else if (datasetName) { - params.append("name", datasetName); - } - else { - throw new Error("Must provide datasetName or datasetId"); - } - const response = await this._get(path, params); - let result; - if (Array.isArray(response)) { - if (response.length === 0) { - throw new Error(`Dataset[id=${datasetId}, name=${datasetName}] not found`); - } - result = response[0]; - } - else { - result = response; - } - return result; - } - async hasDataset({ datasetId, datasetName, }) { - try { - await this.readDataset({ datasetId, datasetName }); - return true; - } - catch (e) { - if ( - // eslint-disable-next-line no-instanceof/no-instanceof - e instanceof Error && - e.message.toLocaleLowerCase().includes("not found")) { - return false; - } - throw e; - } - } - async diffDatasetVersions({ datasetId, datasetName, fromVersion, toVersion, }) { - let datasetId_ = datasetId; - if (datasetId_ === undefined && datasetName === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - const urlParams = new URLSearchParams({ - from_version: typeof fromVersion === "string" - ? fromVersion - : fromVersion.toISOString(), - to_version: typeof toVersion === "string" ? toVersion : toVersion.toISOString(), - }); - const response = await this._get(`/datasets/${datasetId_}/versions/diff`, urlParams); - return response; - } - async readDatasetOpenaiFinetuning({ datasetId, datasetName, }) { - const path = "/datasets"; - if (datasetId !== undefined) { - // do nothing - } - else if (datasetName !== undefined) { - datasetId = (await this.readDataset({ datasetName })).id; - } - else { - throw new Error("Must provide either datasetName or datasetId"); - } - const response = await this._getResponse(`${path}/${datasetId}/openai_ft`); - const datasetText = await response.text(); - const dataset = datasetText - .trim() - .split("\n") - .map((line) => JSON.parse(line)); - return dataset; - } - async *listDatasets({ limit = 100, offset = 0, datasetIds, datasetName, datasetNameContains, metadata, } = {}) { - const path = "/datasets"; - const params = new URLSearchParams({ - limit: limit.toString(), - offset: offset.toString(), - }); - if (datasetIds !== undefined) { - for (const id_ of datasetIds) { - params.append("id", id_); - } - } - if (datasetName !== undefined) { - params.append("name", datasetName); - } - if (datasetNameContains !== undefined) { - params.append("name_contains", datasetNameContains); - } - if (metadata !== undefined) { - params.append("metadata", JSON.stringify(metadata)); - } - for await (const datasets of this._getPaginated(path, params)) { - yield* datasets; - } - } - /** - * Update a dataset - * @param props The dataset details to update - * @returns The updated dataset - */ - async updateDataset(props) { - const { datasetId, datasetName, ...update } = props; - if (!datasetId && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); - } - const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; - assertUuid(_datasetId); - const body = JSON.stringify(update); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update dataset"); - return res; - }); - return (await response.json()); - } - /** - * Updates a tag on a dataset. - * - * If the tag is already assigned to a different version of this dataset, - * the tag will be moved to the new version. The as_of parameter is used to - * determine which version of the dataset to apply the new tags to. - * - * It must be an exact version of the dataset to succeed. You can - * use the "readDatasetVersion" method to find the exact version - * to apply the tags to. - * @param params.datasetId The ID of the dataset to update. Must be provided if "datasetName" is not provided. - * @param params.datasetName The name of the dataset to update. Must be provided if "datasetId" is not provided. - * @param params.asOf The timestamp of the dataset to apply the new tags to. - * @param params.tag The new tag to apply to the dataset. - */ - async updateDatasetTag(props) { - const { datasetId, datasetName, asOf, tag } = props; - if (!datasetId && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); - } - const _datasetId = datasetId ?? (await this.readDataset({ datasetName })).id; - assertUuid(_datasetId); - const body = JSON.stringify({ - as_of: typeof asOf === "string" ? asOf : asOf.toISOString(), - tag, - }); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${_datasetId}/tags`, { - method: "PUT", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update dataset tags", true); - return res; - }); - } - async deleteDataset({ datasetId, datasetName, }) { - let path = "/datasets"; - let datasetId_ = datasetId; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - if (datasetId_ !== undefined) { - assertUuid(datasetId_); - path += `/${datasetId_}`; - } - else { - throw new Error("Must provide datasetName or datasetId"); - } - await this.caller.call(async () => { - const res = await this._fetch(this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `delete ${path}`, true); - return res; - }); - } - async indexDataset({ datasetId, datasetName, tag, }) { - let datasetId_ = datasetId; - if (!datasetId_ && !datasetName) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ && datasetName) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (!datasetId_) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - assertUuid(datasetId_); - const data = { - tag: tag, - }; - const body = JSON.stringify(data); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId_}/index`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "index dataset"); - return res; - }); - await response.json(); - } - /** - * Lets you run a similarity search query on a dataset. - * - * Requires the dataset to be indexed. Please see the `indexDataset` method to set up indexing. - * - * @param inputs The input on which to run the similarity search. Must have the - * same schema as the dataset. - * - * @param datasetId The dataset to search for similar examples. - * - * @param limit The maximum number of examples to return. Will return the top `limit` most - * similar examples in order of most similar to least similar. If no similar - * examples are found, random examples will be returned. - * - * @param filter A filter string to apply to the search. Only examples will be returned that - * match the filter string. Some examples of filters - * - * - eq(metadata.mykey, "value") - * - and(neq(metadata.my.nested.key, "value"), neq(metadata.mykey, "value")) - * - or(eq(metadata.mykey, "value"), eq(metadata.mykey, "othervalue")) - * - * @returns A list of similar examples. - * - * - * @example - * dataset_id = "123e4567-e89b-12d3-a456-426614174000" - * inputs = {"text": "How many people live in Berlin?"} - * limit = 5 - * examples = await client.similarExamples(inputs, dataset_id, limit) - */ - async similarExamples(inputs, datasetId, limit, { filter, } = {}) { - const data = { - limit: limit, - inputs: inputs, - }; - if (filter !== undefined) { - data["filter"] = filter; - } - assertUuid(datasetId); - const body = JSON.stringify(data); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId}/search`, { - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - method: "POST", - body, - }); - await raiseForStatus(res, "fetch similar examples"); - return res; - }); - const result = await response.json(); - return result["examples"]; - } - async createExample(inputsOrUpdate, outputs, options) { - if (isExampleCreate(inputsOrUpdate)) { - if (outputs !== undefined || options !== undefined) { - throw new Error("Cannot provide outputs or options when using ExampleCreate object"); - } - } - let datasetId_ = outputs ? options?.datasetId : inputsOrUpdate.dataset_id; - const datasetName_ = outputs - ? options?.datasetName - : inputsOrUpdate.dataset_name; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; - } - const createdAt_ = (outputs ? options?.createdAt : inputsOrUpdate.created_at) || new Date(); - let data; - if (!isExampleCreate(inputsOrUpdate)) { - data = { - inputs: inputsOrUpdate, - outputs, - created_at: createdAt_?.toISOString(), - id: options?.exampleId, - metadata: options?.metadata, - split: options?.split, - source_run_id: options?.sourceRunId, - use_source_run_io: options?.useSourceRunIO, - use_source_run_attachments: options?.useSourceRunAttachments, - attachments: options?.attachments, - }; - } - else { - data = inputsOrUpdate; - } - const response = await this._uploadExamplesMultipart(datasetId_, [data]); - const example = await this.readExample(response.example_ids?.[0] ?? v4()); - return example; - } - async createExamples(propsOrUploads) { - if (Array.isArray(propsOrUploads)) { - if (propsOrUploads.length === 0) { - return []; - } - const uploads = propsOrUploads; - let datasetId_ = uploads[0].dataset_id; - const datasetName_ = uploads[0].dataset_name; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; - } - const response = await this._uploadExamplesMultipart(datasetId_, uploads); - const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); - return examples; - } - const { inputs, outputs, metadata, splits, sourceRunIds, useSourceRunIOs, useSourceRunAttachments, attachments, exampleIds, datasetId, datasetName, } = propsOrUploads; - if (inputs === undefined) { - throw new Error("Must provide inputs when using legacy parameters"); - } - let datasetId_ = datasetId; - const datasetName_ = datasetName; - if (datasetId_ === undefined && datasetName_ === undefined) { - throw new Error("Must provide either datasetName or datasetId"); - } - else if (datasetId_ !== undefined && datasetName_ !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId_ === undefined) { - const dataset = await this.readDataset({ datasetName: datasetName_ }); - datasetId_ = dataset.id; - } - const formattedExamples = inputs.map((input, idx) => { - return { - dataset_id: datasetId_, - inputs: input, - outputs: outputs?.[idx], - metadata: metadata?.[idx], - split: splits?.[idx], - id: exampleIds?.[idx], - attachments: attachments?.[idx], - source_run_id: sourceRunIds?.[idx], - use_source_run_io: useSourceRunIOs?.[idx], - use_source_run_attachments: useSourceRunAttachments?.[idx], - }; - }); - const response = await this._uploadExamplesMultipart(datasetId_, formattedExamples); - const examples = await Promise.all(response.example_ids.map((id) => this.readExample(id))); - return examples; - } - async createLLMExample(input, generation, options) { - return this.createExample({ input }, { output: generation }, options); - } - async createChatExample(input, generations, options) { - const finalInput = input.map((message) => { - if (isLangChainMessage(message)) { - return convertLangChainMessageToExample(message); - } - return message; - }); - const finalOutput = isLangChainMessage(generations) - ? convertLangChainMessageToExample(generations) - : generations; - return this.createExample({ input: finalInput }, { output: finalOutput }, options); - } - async readExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - const rawExample = await this._get(path); - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url, - mime_type: value.mime_type, - }; - return acc; - }, {}); - } - return example; - } - async *listExamples({ datasetId, datasetName, exampleIds, asOf, splits, inlineS3Urls, metadata, limit, offset, filter, includeAttachments, } = {}) { - let datasetId_; - if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId !== undefined) { - datasetId_ = datasetId; - } - else if (datasetName !== undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - else { - throw new Error("Must provide a datasetName or datasetId"); - } - const params = new URLSearchParams({ dataset: datasetId_ }); - const dataset_version = asOf - ? typeof asOf === "string" - ? asOf - : asOf?.toISOString() - : undefined; - if (dataset_version) { - params.append("as_of", dataset_version); - } - const inlineS3Urls_ = inlineS3Urls ?? true; - params.append("inline_s3_urls", inlineS3Urls_.toString()); - if (exampleIds !== undefined) { - for (const id_ of exampleIds) { - params.append("id", id_); - } - } - if (splits !== undefined) { - for (const split of splits) { - params.append("splits", split); - } - } - if (metadata !== undefined) { - const serializedMetadata = JSON.stringify(metadata); - params.append("metadata", serializedMetadata); - } - if (limit !== undefined) { - params.append("limit", limit.toString()); - } - if (offset !== undefined) { - params.append("offset", offset.toString()); - } - if (filter !== undefined) { - params.append("filter", filter); - } - if (includeAttachments === true) { - ["attachment_urls", "outputs", "metadata"].forEach((field) => params.append("select", field)); - } - let i = 0; - for await (const rawExamples of this._getPaginated("/examples", params)) { - for (const rawExample of rawExamples) { - const { attachment_urls, ...rest } = rawExample; - const example = rest; - if (attachment_urls) { - example.attachments = Object.entries(attachment_urls).reduce((acc, [key, value]) => { - acc[key.slice("attachment.".length)] = { - presigned_url: value.presigned_url, - mime_type: value.mime_type || undefined, - }; - return acc; - }, {}); - } - yield example; - i++; - } - if (limit !== undefined && i >= limit) { - break; - } - } - } - async deleteExample(exampleId) { - assertUuid(exampleId); - const path = `/examples/${exampleId}`; - await this.caller.call(async () => { - const res = await this._fetch(this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `delete ${path}`, true); - return res; - }); - } - /** - * Delete multiple examples by ID. - * @param exampleIds - The IDs of the examples to delete - * @param options - Optional settings for deletion - * @param options.hardDelete - If true, permanently delete examples. If false (default), soft delete them. - */ - async deleteExamples(exampleIds, options) { - // Validate all UUIDs - exampleIds.forEach((id) => assertUuid(id)); - if (options?.hardDelete) { - // Hard delete uses POST to a different platform endpoint - const path = this._getPlatformEndpointPath("datasets/examples/delete"); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}${path}`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - body: JSON.stringify({ - example_ids: exampleIds, - hard_delete: true, - }), - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "hard delete examples", true); - return res; - }); - } - else { - // Soft delete uses DELETE with query params - const params = new URLSearchParams(); - exampleIds.forEach((id) => params.append("example_ids", id)); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/examples?${params.toString()}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "delete examples", true); - return res; - }); - } - } - async updateExample(exampleIdOrUpdate, update) { - let exampleId; - if (update) { - exampleId = exampleIdOrUpdate; - } - else { - exampleId = exampleIdOrUpdate.id; - } - assertUuid(exampleId); - let updateToUse; - if (update) { - updateToUse = { id: exampleId, ...update }; - } - else { - updateToUse = exampleIdOrUpdate; - } - let datasetId; - if (updateToUse.dataset_id !== undefined) { - datasetId = updateToUse.dataset_id; - } - else { - const example = await this.readExample(exampleId); - datasetId = example.dataset_id; - } - return this._updateExamplesMultipart(datasetId, [updateToUse]); - } - async updateExamples(update) { - // We will naively get dataset id from first example and assume it works for all - let datasetId; - if (update[0].dataset_id === undefined) { - const example = await this.readExample(update[0].id); - datasetId = example.dataset_id; - } - else { - datasetId = update[0].dataset_id; - } - return this._updateExamplesMultipart(datasetId, update); - } - /** - * Get dataset version by closest date or exact tag. - * - * Use this to resolve the nearest version to a given timestamp or for a given tag. - * - * @param options The options for getting the dataset version - * @param options.datasetId The ID of the dataset - * @param options.datasetName The name of the dataset - * @param options.asOf The timestamp of the dataset to retrieve - * @param options.tag The tag of the dataset to retrieve - * @returns The dataset version - */ - async readDatasetVersion({ datasetId, datasetName, asOf, tag, }) { - let resolvedDatasetId; - if (!datasetId) { - const dataset = await this.readDataset({ datasetName }); - resolvedDatasetId = dataset.id; - } - else { - resolvedDatasetId = datasetId; - } - assertUuid(resolvedDatasetId); - if ((asOf && tag) || (!asOf && !tag)) { - throw new Error("Exactly one of asOf and tag must be specified."); - } - const params = new URLSearchParams(); - if (asOf !== undefined) { - params.append("as_of", typeof asOf === "string" ? asOf : asOf.toISOString()); - } - if (tag !== undefined) { - params.append("tag", tag); - } - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${resolvedDatasetId}/version?${params.toString()}`, { - method: "GET", - headers: { ...this.headers }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "read dataset version"); - return res; - }); - return await response.json(); - } - async listDatasetSplits({ datasetId, datasetName, asOf, }) { - let datasetId_; - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide dataset name or ID"); - } - else if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - else { - datasetId_ = datasetId; - } - assertUuid(datasetId_); - const params = new URLSearchParams(); - const dataset_version = asOf - ? typeof asOf === "string" - ? asOf - : asOf?.toISOString() - : undefined; - if (dataset_version) { - params.append("as_of", dataset_version); - } - const response = await this._get(`/datasets/${datasetId_}/splits`, params); - return response; - } - async updateDatasetSplits({ datasetId, datasetName, splitName, exampleIds, remove = false, }) { - let datasetId_; - if (datasetId === undefined && datasetName === undefined) { - throw new Error("Must provide dataset name or ID"); - } - else if (datasetId !== undefined && datasetName !== undefined) { - throw new Error("Must provide either datasetName or datasetId, not both"); - } - else if (datasetId === undefined) { - const dataset = await this.readDataset({ datasetName }); - datasetId_ = dataset.id; - } - else { - datasetId_ = datasetId; - } - assertUuid(datasetId_); - const data = { - split_name: splitName, - examples: exampleIds.map((id) => { - assertUuid(id); - return id; - }), - remove, - }; - const body = JSON.stringify(data); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/${datasetId_}/splits`, { - method: "PUT", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update dataset splits", true); - return res; - }); - } - async createFeedback(runId, key, { score, value, correction, comment, sourceInfo, feedbackSourceType = "api", sourceRunId, feedbackId, feedbackConfig, projectId, comparativeExperimentId, }) { - if (!runId && !projectId) { - throw new Error("One of runId or projectId must be provided"); - } - if (runId && projectId) { - throw new Error("Only one of runId or projectId can be provided"); - } - const feedback_source = { - type: feedbackSourceType ?? "api", - metadata: sourceInfo ?? {}, - }; - if (sourceRunId !== undefined && - feedback_source?.metadata !== undefined && - !feedback_source.metadata["__run"]) { - feedback_source.metadata["__run"] = { run_id: sourceRunId }; - } - if (feedback_source?.metadata !== undefined && - feedback_source.metadata["__run"]?.run_id !== undefined) { - assertUuid(feedback_source.metadata["__run"].run_id); - } - const feedback = { - id: feedbackId ?? v4(), - run_id: runId, - key, - score: _formatFeedbackScore(score), - value, - correction, - comment, - feedback_source: feedback_source, - comparative_experiment_id: comparativeExperimentId, - feedbackConfig, - session_id: projectId, - }; - const body = JSON.stringify(feedback); - const url = `${this.apiUrl}/feedback`; - await this.caller.call(async () => { - const res = await this._fetch(url, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "create feedback", true); - return res; - }); - return feedback; - } - async updateFeedback(feedbackId, { score, value, correction, comment, }) { - const feedbackUpdate = {}; - if (score !== undefined && score !== null) { - feedbackUpdate["score"] = _formatFeedbackScore(score); - } - if (value !== undefined && value !== null) { - feedbackUpdate["value"] = value; - } - if (correction !== undefined && correction !== null) { - feedbackUpdate["correction"] = correction; - } - if (comment !== undefined && comment !== null) { - feedbackUpdate["comment"] = comment; - } - assertUuid(feedbackId); - const body = JSON.stringify(feedbackUpdate); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/feedback/${feedbackId}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update feedback", true); - return res; - }); - } - async readFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - const response = await this._get(path); - return response; - } - async deleteFeedback(feedbackId) { - assertUuid(feedbackId); - const path = `/feedback/${feedbackId}`; - await this.caller.call(async () => { - const res = await this._fetch(this.apiUrl + path, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, `delete ${path}`, true); - return res; - }); - } - async *listFeedback({ runIds, feedbackKeys, feedbackSourceTypes, } = {}) { - const queryParams = new URLSearchParams(); - if (runIds) { - for (const runId of runIds) { - assertUuid(runId); - queryParams.append("run", runId); - } - } - if (feedbackKeys) { - for (const key of feedbackKeys) { - queryParams.append("key", key); - } - } - if (feedbackSourceTypes) { - for (const type of feedbackSourceTypes) { - queryParams.append("source", type); - } - } - for await (const feedbacks of this._getPaginated("/feedback", queryParams)) { - yield* feedbacks; - } - } - /** - * Creates a presigned feedback token and URL. - * - * The token can be used to authorize feedback metrics without - * needing an API key. This is useful for giving browser-based - * applications the ability to submit feedback without needing - * to expose an API key. - * - * @param runId The ID of the run. - * @param feedbackKey The feedback key. - * @param options Additional options for the token. - * @param options.expiration The expiration time for the token. - * - * @returns A promise that resolves to a FeedbackIngestToken. - */ - async createPresignedFeedbackToken(runId, feedbackKey, { expiration, feedbackConfig, } = {}) { - const body = { - run_id: runId, - feedback_key: feedbackKey, - feedback_config: feedbackConfig, - }; - if (expiration) { - if (typeof expiration === "string") { - body["expires_at"] = expiration; - } - else if (expiration?.hours || expiration?.minutes || expiration?.days) { - body["expires_in"] = expiration; - } - } - else { - body["expires_in"] = { - hours: 3, - }; - } - const serializedBody = JSON.stringify(body); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/feedback/tokens`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: serializedBody, - }); - await raiseForStatus(res, "create presigned feedback token"); - return res; - }); - return await response.json(); - } - async createComparativeExperiment({ name, experimentIds, referenceDatasetId, createdAt, description, metadata, id, }) { - if (experimentIds.length === 0) { - throw new Error("At least one experiment is required"); - } - if (!referenceDatasetId) { - referenceDatasetId = (await this.readProject({ - projectId: experimentIds[0], - })).reference_dataset_id; - } - if (!referenceDatasetId == null) { - throw new Error("A reference dataset is required"); - } - const body = { - id, - name, - experiment_ids: experimentIds, - reference_dataset_id: referenceDatasetId, - description, - created_at: (createdAt ?? new Date())?.toISOString(), - extra: {}, - }; - if (metadata) - body.extra["metadata"] = metadata; - const serializedBody = JSON.stringify(body); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/datasets/comparative`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: serializedBody, - }); - await raiseForStatus(res, "create comparative experiment"); - return res; - }); - return response.json(); - } - /** - * Retrieves a list of presigned feedback tokens for a given run ID. - * @param runId The ID of the run. - * @returns An async iterable of FeedbackIngestToken objects. - */ - async *listPresignedFeedbackTokens(runId) { - assertUuid(runId); - const params = new URLSearchParams({ run_id: runId }); - for await (const tokens of this._getPaginated("/feedback/tokens", params)) { - yield* tokens; - } - } - _selectEvalResults(results) { - let results_; - if ("results" in results) { - results_ = results.results; - } - else if (Array.isArray(results)) { - results_ = results; - } - else { - results_ = [results]; - } - return results_; - } - async _logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const evalResults = this._selectEvalResults(evaluatorResponse); - const feedbacks = []; - for (const res of evalResults) { - let sourceInfo_ = sourceInfo || {}; - if (res.evaluatorInfo) { - sourceInfo_ = { ...res.evaluatorInfo, ...sourceInfo_ }; - } - let runId_ = null; - if (res.targetRunId) { - runId_ = res.targetRunId; - } - else if (run) { - runId_ = run.id; - } - feedbacks.push(await this.createFeedback(runId_, res.key, { - score: res.score, - value: res.value, - comment: res.comment, - correction: res.correction, - sourceInfo: sourceInfo_, - sourceRunId: res.sourceRunId, - feedbackConfig: res.feedbackConfig, - feedbackSourceType: "model", - })); - } - return [evalResults, feedbacks]; - } - async logEvaluationFeedback(evaluatorResponse, run, sourceInfo) { - const [results] = await this._logEvaluationFeedback(evaluatorResponse, run, sourceInfo); - return results; - } - /** - * API for managing annotation queues - */ - /** - * List the annotation queues on the LangSmith API. - * @param options - The options for listing annotation queues - * @param options.queueIds - The IDs of the queues to filter by - * @param options.name - The name of the queue to filter by - * @param options.nameContains - The substring that the queue name should contain - * @param options.limit - The maximum number of queues to return - * @returns An iterator of AnnotationQueue objects - */ - async *listAnnotationQueues(options = {}) { - const { queueIds, name, nameContains, limit } = options; - const params = new URLSearchParams(); - if (queueIds) { - queueIds.forEach((id, i) => { - assertUuid(id, `queueIds[${i}]`); - params.append("ids", id); - }); - } - if (name) - params.append("name", name); - if (nameContains) - params.append("name_contains", nameContains); - params.append("limit", (limit !== undefined ? Math.min(limit, 100) : 100).toString()); - let count = 0; - for await (const queues of this._getPaginated("/annotation-queues", params)) { - yield* queues; - count++; - if (limit !== undefined && count >= limit) - break; - } - } - /** - * Create an annotation queue on the LangSmith API. - * @param options - The options for creating an annotation queue - * @param options.name - The name of the annotation queue - * @param options.description - The description of the annotation queue - * @param options.queueId - The ID of the annotation queue - * @returns The created AnnotationQueue object - */ - async createAnnotationQueue(options) { - const { name, description, queueId, rubricInstructions } = options; - const body = { - name, - description, - id: queueId || v4(), - rubric_instructions: rubricInstructions, - }; - const serializedBody = JSON.stringify(Object.fromEntries(Object.entries(body).filter(([_, v]) => v !== undefined))); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: serializedBody, - }); - await raiseForStatus(res, "create annotation queue"); - return res; - }); - return response.json(); - } - /** - * Read an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to read - * @returns The AnnotationQueueWithDetails object - */ - async readAnnotationQueue(queueId) { - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "read annotation queue"); - return res; - }); - return response.json(); - } - /** - * Update an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to update - * @param options - The options for updating the annotation queue - * @param options.name - The new name for the annotation queue - * @param options.description - The new description for the annotation queue - */ - async updateAnnotationQueue(queueId, options) { - const { name, description, rubricInstructions } = options; - const body = JSON.stringify({ - name, - description, - rubric_instructions: rubricInstructions, - }); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "PATCH", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update annotation queue", true); - return res; - }); - } - /** - * Delete an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue to delete - */ - async deleteAnnotationQueue(queueId) { - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}`, { - method: "DELETE", - headers: { ...this.headers, Accept: "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "delete annotation queue", true); - return res; - }); - } - /** - * Add runs to an annotation queue with the specified queue ID. - * @param queueId - The ID of the annotation queue - * @param runIds - The IDs of the runs to be added to the annotation queue - */ - async addRunsToAnnotationQueue(queueId, runIds) { - const body = JSON.stringify(runIds.map((id, i) => assertUuid(id, `runIds[${i}]`).toString())); - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "add runs to annotation queue", true); - return res; - }); - } - /** - * Get a run from an annotation queue at the specified index. - * @param queueId - The ID of the annotation queue - * @param index - The index of the run to retrieve - * @returns A Promise that resolves to a RunWithAnnotationQueueInfo object - * @throws {Error} If the run is not found at the given index or for other API-related errors - */ - async getRunFromAnnotationQueue(queueId, index) { - const baseUrl = `/annotation-queues/${assertUuid(queueId, "queueId")}/run`; - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}${baseUrl}/${index}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "get run from annotation queue"); - return res; - }); - return response.json(); - } - /** - * Delete a run from an an annotation queue. - * @param queueId - The ID of the annotation queue to delete the run from - * @param queueRunId - The ID of the run to delete from the annotation queue - */ - async deleteRunFromAnnotationQueue(queueId, queueRunId) { - await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/runs/${assertUuid(queueRunId, "queueRunId")}`, { - method: "DELETE", - headers: { ...this.headers, Accept: "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "delete run from annotation queue", true); - return res; - }); - } - /** - * Get the size of an annotation queue. - * @param queueId - The ID of the annotation queue - */ - async getSizeFromAnnotationQueue(queueId) { - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/annotation-queues/${assertUuid(queueId, "queueId")}/size`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "get size from annotation queue"); - return res; - }); - return response.json(); - } - async _currentTenantIsOwner(owner) { - const settings = await this._getSettings(); - return owner == "-" || settings.tenant_handle === owner; - } - async _ownerConflictError(action, owner) { - const settings = await this._getSettings(); - return new Error(`Cannot ${action} for another tenant.\n - Current tenant: ${settings.tenant_handle}\n - Requested tenant: ${owner}`); - } - async _getLatestCommitHash(promptOwnerAndName) { - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/commits/${promptOwnerAndName}/?limit=${1}&offset=${0}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "get latest commit hash"); - return res; - }); - const json = await response.json(); - if (json.commits.length === 0) { - return undefined; - } - return json.commits[0].commit_hash; - } - async _likeOrUnlikePrompt(promptIdentifier, like) { - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const body = JSON.stringify({ like: like }); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/likes/${owner}/${promptName}`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, `${like ? "like" : "unlike"} prompt`); - return res; - }); - return response.json(); - } - async _getPromptUrl(promptIdentifier) { - const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - if (commitHash !== "latest") { - return `${this.getHostUrl()}/hub/${owner}/${promptName}/${commitHash.substring(0, 8)}`; - } - else { - return `${this.getHostUrl()}/hub/${owner}/${promptName}`; - } - } - else { - const settings = await this._getSettings(); - if (commitHash !== "latest") { - return `${this.getHostUrl()}/prompts/${promptName}/${commitHash.substring(0, 8)}?organizationId=${settings.id}`; - } - else { - return `${this.getHostUrl()}/prompts/${promptName}?organizationId=${settings.id}`; - } - } - } - async promptExists(promptIdentifier) { - const prompt = await this.getPrompt(promptIdentifier); - return !!prompt; - } - async likePrompt(promptIdentifier) { - return this._likeOrUnlikePrompt(promptIdentifier, true); - } - async unlikePrompt(promptIdentifier) { - return this._likeOrUnlikePrompt(promptIdentifier, false); - } - async *listCommits(promptOwnerAndName) { - for await (const commits of this._getPaginated(`/commits/${promptOwnerAndName}/`, new URLSearchParams(), (res) => res.commits)) { - yield* commits; - } - } - async *listPrompts(options) { - const params = new URLSearchParams(); - params.append("sort_field", options?.sortField ?? "updated_at"); - params.append("sort_direction", "desc"); - params.append("is_archived", (!!options?.isArchived).toString()); - if (options?.isPublic !== undefined) { - params.append("is_public", options.isPublic.toString()); - } - if (options?.query) { - params.append("query", options.query); - } - for await (const prompts of this._getPaginated("/repos", params, (res) => res.repos)) { - yield* prompts; - } - } - async getPrompt(promptIdentifier) { - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - if (res?.status === 404) { - return null; - } - await raiseForStatus(res, "get prompt"); - return res; - }); - const result = await response?.json(); - if (result?.repo) { - return result.repo; - } - else { - return null; - } - } - async createPrompt(promptIdentifier, options) { - const settings = await this._getSettings(); - if (options?.isPublic && !settings.tenant_handle) { - throw new Error(`Cannot create a public prompt without first\n - creating a LangChain Hub handle. - You can add a handle by creating a public prompt at:\n - https://smith.langchain.com/prompts`); - } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("create a prompt", owner); - } - const data = { - repo_handle: promptName, - ...(options?.description && { description: options.description }), - ...(options?.readme && { readme: options.readme }), - ...(options?.tags && { tags: options.tags }), - is_public: !!options?.isPublic, - }; - const body = JSON.stringify(data); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/repos/`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "create prompt"); - return res; - }); - const { repo } = await response.json(); - return repo; - } - async createCommit(promptIdentifier, object, options) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - const resolvedParentCommitHash = options?.parentCommitHash === "latest" || !options?.parentCommitHash - ? await this._getLatestCommitHash(`${owner}/${promptName}`) - : options?.parentCommitHash; - const payload = { - manifest: JSON.parse(JSON.stringify(object)), - parent_commit: resolvedParentCommitHash, - }; - const body = JSON.stringify(payload); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}`, { - method: "POST", - headers: { ...this.headers, "Content-Type": "application/json" }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "create commit"); - return res; - }); - const result = await response.json(); - return this._getPromptUrl(`${owner}/${promptName}${result.commit_hash ? `:${result.commit_hash}` : ""}`); - } - /** - * Update examples with attachments using multipart form data. - * @param updates List of ExampleUpdateWithAttachments objects to upsert - * @returns Promise with the update response - */ - async updateExamplesMultipart(datasetId, updates = []) { - return this._updateExamplesMultipart(datasetId, updates); - } - async _updateExamplesMultipart(datasetId, updates = []) { - if (!(await this._getDatasetExamplesMultiPartSupport())) { - throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); - } - const formData = new FormData(); - for (const example of updates) { - const exampleId = example.id; - // Prepare the main example body - const exampleBody = { - ...(example.metadata && { metadata: example.metadata }), - ...(example.split && { split: example.split }), - }; - // Add main example data - const stringifiedExample = serialize(exampleBody, `Serializing body for example with id: ${exampleId}`); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json", - }); - formData.append(exampleId, exampleBlob); - // Add inputs if present - if (example.inputs) { - const stringifiedInputs = serialize(example.inputs, `Serializing inputs for example with id: ${exampleId}`); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json", - }); - formData.append(`${exampleId}.inputs`, inputsBlob); - } - // Add outputs if present - if (example.outputs) { - const stringifiedOutputs = serialize(example.outputs, `Serializing outputs whle updating example with id: ${exampleId}`); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json", - }); - formData.append(`${exampleId}.outputs`, outputsBlob); - } - // Add attachments if present - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; - } - else { - mimeType = attachment.mimeType; - data = attachment.data; - } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}`, - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); - } - } - if (example.attachments_operations) { - const stringifiedAttachmentsOperations = serialize(example.attachments_operations, `Serializing attachments while updating example with id: ${exampleId}`); - const attachmentsOperationsBlob = new Blob([stringifiedAttachmentsOperations], { - type: "application/json", - }); - formData.append(`${exampleId}.attachments_operations`, attachmentsOperationsBlob); - } - } - const datasetIdToUse = datasetId ?? updates[0]?.dataset_id; - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetIdToUse}/examples`)}`, { - method: "PATCH", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: formData, - }); - await raiseForStatus(res, "update examples"); - return res; - }); - return response.json(); - } - /** - * Upload examples with attachments using multipart form data. - * @param uploads List of ExampleUploadWithAttachments objects to upload - * @returns Promise with the upload response - * @deprecated This method is deprecated and will be removed in future LangSmith versions, please use `createExamples` instead - */ - async uploadExamplesMultipart(datasetId, uploads = []) { - return this._uploadExamplesMultipart(datasetId, uploads); - } - async _uploadExamplesMultipart(datasetId, uploads = []) { - if (!(await this._getDatasetExamplesMultiPartSupport())) { - throw new Error("Your LangSmith deployment does not allow using the multipart examples endpoint, please upgrade your deployment to the latest version."); - } - const formData = new FormData(); - for (const example of uploads) { - const exampleId = (example.id ?? v4()).toString(); - // Prepare the main example body - const exampleBody = { - created_at: example.created_at, - ...(example.metadata && { metadata: example.metadata }), - ...(example.split && { split: example.split }), - ...(example.source_run_id && { source_run_id: example.source_run_id }), - ...(example.use_source_run_io && { - use_source_run_io: example.use_source_run_io, - }), - ...(example.use_source_run_attachments && { - use_source_run_attachments: example.use_source_run_attachments, - }), - }; - // Add main example data - const stringifiedExample = serialize(exampleBody, `Serializing body for uploaded example with id: ${exampleId}`); - const exampleBlob = new Blob([stringifiedExample], { - type: "application/json", - }); - formData.append(exampleId, exampleBlob); - // Add inputs if present - if (example.inputs) { - const stringifiedInputs = serialize(example.inputs, `Serializing inputs for uploaded example with id: ${exampleId}`); - const inputsBlob = new Blob([stringifiedInputs], { - type: "application/json", - }); - formData.append(`${exampleId}.inputs`, inputsBlob); - } - // Add outputs if present - if (example.outputs) { - const stringifiedOutputs = serialize(example.outputs, `Serializing outputs for uploaded example with id: ${exampleId}`); - const outputsBlob = new Blob([stringifiedOutputs], { - type: "application/json", - }); - formData.append(`${exampleId}.outputs`, outputsBlob); - } - // Add attachments if present - if (example.attachments) { - for (const [name, attachment] of Object.entries(example.attachments)) { - let mimeType; - let data; - if (Array.isArray(attachment)) { - [mimeType, data] = attachment; - } - else { - mimeType = attachment.mimeType; - data = attachment.data; - } - const attachmentBlob = new Blob([data], { - type: `${mimeType}; length=${data.byteLength}`, - }); - formData.append(`${exampleId}.attachment.${name}`, attachmentBlob); - } - } - } - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}${this._getPlatformEndpointPath(`datasets/${datasetId}/examples`)}`, { - method: "POST", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body: formData, - }); - await raiseForStatus(res, "upload examples"); - return res; - }); - return response.json(); - } - async updatePrompt(promptIdentifier, options) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("update a prompt", owner); - } - const payload = {}; - if (options?.description !== undefined) - payload.description = options.description; - if (options?.readme !== undefined) - payload.readme = options.readme; - if (options?.tags !== undefined) - payload.tags = options.tags; - if (options?.isPublic !== undefined) - payload.is_public = options.isPublic; - if (options?.isArchived !== undefined) - payload.is_archived = options.isArchived; - // Check if payload is empty - if (Object.keys(payload).length === 0) { - throw new Error("No valid update options provided"); - } - const body = JSON.stringify(payload); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "PATCH", - headers: { - ...this.headers, - "Content-Type": "application/json", - }, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - body, - }); - await raiseForStatus(res, "update prompt"); - return res; - }); - return response.json(); - } - async deletePrompt(promptIdentifier) { - if (!(await this.promptExists(promptIdentifier))) { - throw new Error("Prompt does not exist, you must create it first."); - } - const [owner, promptName, _] = parsePromptIdentifier(promptIdentifier); - if (!(await this._currentTenantIsOwner(owner))) { - throw await this._ownerConflictError("delete a prompt", owner); - } - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/repos/${owner}/${promptName}`, { - method: "DELETE", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "delete prompt"); - return res; - }); - return response.json(); - } - async pullPromptCommit(promptIdentifier, options) { - const [owner, promptName, commitHash] = parsePromptIdentifier(promptIdentifier); - const response = await this.caller.call(async () => { - const res = await this._fetch(`${this.apiUrl}/commits/${owner}/${promptName}/${commitHash}${options?.includeModel ? "?include_model=true" : ""}`, { - method: "GET", - headers: this.headers, - signal: AbortSignal.timeout(this.timeout_ms), - ...this.fetchOptions, - }); - await raiseForStatus(res, "pull prompt commit"); - return res; - }); - const result = await response.json(); - return { - owner, - repo: promptName, - commit_hash: result.commit_hash, - manifest: result.manifest, - examples: result.examples, - }; - } - /** - * This method should not be used directly, use `import { pull } from "langchain/hub"` instead. - * Using this method directly returns the JSON string of the prompt rather than a LangChain object. - * @private - */ - async _pullPrompt(promptIdentifier, options) { - const promptObject = await this.pullPromptCommit(promptIdentifier, { - includeModel: options?.includeModel, - }); - const prompt = JSON.stringify(promptObject.manifest); - return prompt; - } - async pushPrompt(promptIdentifier, options) { - // Create or update prompt metadata - if (await this.promptExists(promptIdentifier)) { - if (options && Object.keys(options).some((key) => key !== "object")) { - await this.updatePrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic, - }); - } - } - else { - await this.createPrompt(promptIdentifier, { - description: options?.description, - readme: options?.readme, - tags: options?.tags, - isPublic: options?.isPublic, - }); - } - if (!options?.object) { - return await this._getPromptUrl(promptIdentifier); - } - // Create a commit with the new manifest - const url = await this.createCommit(promptIdentifier, options?.object, { - parentCommitHash: options?.parentCommitHash, - }); - return url; - } - /** - * Clone a public dataset to your own langsmith tenant. - * This operation is idempotent. If you already have a dataset with the given name, - * this function will do nothing. - - * @param {string} tokenOrUrl The token of the public dataset to clone. - * @param {Object} [options] Additional options for cloning the dataset. - * @param {string} [options.sourceApiUrl] The URL of the langsmith server where the data is hosted. Defaults to the API URL of your current client. - * @param {string} [options.datasetName] The name of the dataset to create in your tenant. Defaults to the name of the public dataset. - * @returns {Promise} - */ - async clonePublicDataset(tokenOrUrl, options = {}) { - const { sourceApiUrl = this.apiUrl, datasetName } = options; - const [parsedApiUrl, tokenUuid] = this.parseTokenOrUrl(tokenOrUrl, sourceApiUrl); - const sourceClient = new Client({ - apiUrl: parsedApiUrl, - // Placeholder API key not needed anymore in most cases, but - // some private deployments may have API key-based rate limiting - // that would cause this to fail if we provide no value. - apiKey: "placeholder", - }); - const ds = await sourceClient.readSharedDataset(tokenUuid); - const finalDatasetName = datasetName || ds.name; - try { - if (await this.hasDataset({ datasetId: finalDatasetName })) { - console.log(`Dataset ${finalDatasetName} already exists in your tenant. Skipping.`); - return; - } - } - catch (_) { - // `.hasDataset` will throw an error if the dataset does not exist. - // no-op in that case - } - // Fetch examples first, then create the dataset - const examples = await sourceClient.listSharedExamples(tokenUuid); - const dataset = await this.createDataset(finalDatasetName, { - description: ds.description, - dataType: ds.data_type || "kv", - inputsSchema: ds.inputs_schema_definition ?? undefined, - outputsSchema: ds.outputs_schema_definition ?? undefined, - }); - try { - await this.createExamples({ - inputs: examples.map((e) => e.inputs), - outputs: examples.flatMap((e) => (e.outputs ? [e.outputs] : [])), - datasetId: dataset.id, - }); - } - catch (e) { - console.error(`An error occurred while creating dataset ${finalDatasetName}. ` + - "You should delete it manually."); - throw e; - } - } - parseTokenOrUrl(urlOrToken, apiUrl, numParts = 2, kind = "dataset") { - // Try parsing as UUID - try { - assertUuid(urlOrToken); // Will throw if it's not a UUID. - return [apiUrl, urlOrToken]; - } - catch (_) { - // no-op if it's not a uuid - } - // Parse as URL - try { - const parsedUrl = new URL(urlOrToken); - const pathParts = parsedUrl.pathname - .split("/") - .filter((part) => part !== ""); - if (pathParts.length >= numParts) { - const tokenUuid = pathParts[pathParts.length - numParts]; - return [apiUrl, tokenUuid]; - } - else { - throw new Error(`Invalid public ${kind} URL: ${urlOrToken}`); - } - } - catch (error) { - throw new Error(`Invalid public ${kind} URL or token: ${urlOrToken}`); - } - } - /** - * Awaits all pending trace batches. Useful for environments where - * you need to be sure that all tracing requests finish before execution ends, - * such as serverless environments. - * - * @example - * ``` - * import { Client } from "langsmith"; - * - * const client = new Client(); - * - * try { - * // Tracing happens here - * ... - * } finally { - * await client.awaitPendingTraceBatches(); - * } - * ``` - * - * @returns A promise that resolves once all currently pending traces have sent. - */ - async awaitPendingTraceBatches() { - if (this.manualFlushMode) { - console.warn("[WARNING]: When tracing in manual flush mode, you must call `await client.flush()` manually to submit trace batches."); - return Promise.resolve(); - } - /** - * traceables use a backgrounded promise before updating runs to avoid blocking - * and to allow waiting for child runs to end. Waiting a small amount of time - * here ensures that they are able to enqueue their run operation before we await - * queued run operations below: - * - * ```ts - * const run = await traceable(async () => { - * return "Hello, world!"; - * }, { client })(); - * - * await client.awaitPendingTraceBatches(); - * ``` - */ - await new Promise((resolve) => setTimeout(resolve, 1)); - await Promise.all([ - ...this.autoBatchQueue.items.map(({ itemPromise }) => itemPromise), - this.batchIngestCaller.queue.onIdle(), - ]); - if (this.langSmithToOTELTranslator !== undefined) { - await getDefaultOTLPTracerComponents()?.DEFAULT_LANGSMITH_SPAN_PROCESSOR?.forceFlush(); - } - } -} -function isExampleCreate(input) { - return "dataset_id" in input || "dataset_name" in input; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/env.js - -const isTracingEnabled = (tracingEnabled) => { - if (tracingEnabled !== undefined) { - return tracingEnabled; - } - const envVars = ["TRACING_V2", "TRACING"]; - return !!envVars.find((envVar) => getLangSmithEnvironmentVariable(envVar) === "true"); -}; - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/constants.js -const _LC_CONTEXT_VARIABLES_KEY = Symbol.for("lc:context_variables"); -const _LC_CHILD_RUN_END_PROMISES_KEY = Symbol.for("lc:child_run_end_promises"); -const _REPLICA_TRACE_ROOTS_KEY = Symbol.for("langsmith:replica_trace_roots"); - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/utils/context_vars.js - -/** - * Get a context variable from a run tree instance - */ -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function getContextVar(runTree, key) { - if (_LC_CONTEXT_VARIABLES_KEY in runTree) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - const contextVars = runTree[_LC_CONTEXT_VARIABLES_KEY]; - return contextVars[key]; - } - return undefined; -} -/** - * Set a context variable on a run tree instance - */ -function setContextVar( -// eslint-disable-next-line @typescript-eslint/no-explicit-any -runTree, key, value) { - const contextVars = _LC_CONTEXT_VARIABLES_KEY in runTree - ? // eslint-disable-next-line @typescript-eslint/no-explicit-any - runTree[_LC_CONTEXT_VARIABLES_KEY] - : {}; - contextVars[key] = value; - // eslint-disable-next-line @typescript-eslint/no-explicit-any - runTree[_LC_CONTEXT_VARIABLES_KEY] = contextVars; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/run_trees.js - - - - - - - - - - - -const TIMESTAMP_LENGTH = 36; -// DNS namespace for UUID v5 (same as Python's uuid.NAMESPACE_DNS) -const UUID_NAMESPACE_DNS = "6ba7b810-9dad-11d1-80b4-00c04fd430c8"; -function getReplicaKey(replica) { - // Generate a unique key by hashing the replica's identifying properties - // This ensures each unique replica (combination of projectName, apiUrl, workspaceId, apiKey) gets a unique key - // Sort keys to ensure consistent hashing - const sortedKeys = Object.keys(replica).sort(); - const keyData = sortedKeys - .map((key) => `${key}:${replica[key] ?? ""}`) - .join("|"); - return v5(keyData, UUID_NAMESPACE_DNS); -} -function stripNonAlphanumeric(input) { - return input.replace(/[-:.]/g, ""); -} -function getMicrosecondPrecisionDatestring(epoch, executionOrder = 1) { - // Date only has millisecond precision, so we use the microseconds to break - // possible ties, avoiding incorrect run order - const paddedOrder = executionOrder.toFixed(0).slice(0, 3).padStart(3, "0"); - return `${new Date(epoch).toISOString().slice(0, -1)}${paddedOrder}Z`; -} -function convertToDottedOrderFormat(epoch, runId, executionOrder = 1) { - const microsecondPrecisionDatestring = getMicrosecondPrecisionDatestring(epoch, executionOrder); - return { - dottedOrder: stripNonAlphanumeric(microsecondPrecisionDatestring) + runId, - microsecondPrecisionDatestring, - }; -} -/** - * Baggage header information - */ -class Baggage { - constructor(metadata, tags, project_name, replicas) { - Object.defineProperty(this, "metadata", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "replicas", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - this.metadata = metadata; - this.tags = tags; - this.project_name = project_name; - this.replicas = replicas; - } - static fromHeader(value) { - const items = value.split(","); - let metadata = {}; - let tags = []; - let project_name; - let replicas; - for (const item of items) { - const [key, uriValue] = item.split("="); - const value = decodeURIComponent(uriValue); - if (key === "langsmith-metadata") { - metadata = JSON.parse(value); - } - else if (key === "langsmith-tags") { - tags = value.split(","); - } - else if (key === "langsmith-project") { - project_name = value; - } - else if (key === "langsmith-replicas") { - replicas = JSON.parse(value); - } - } - return new Baggage(metadata, tags, project_name, replicas); - } - toHeader() { - const items = []; - if (this.metadata && Object.keys(this.metadata).length > 0) { - items.push(`langsmith-metadata=${encodeURIComponent(JSON.stringify(this.metadata))}`); - } - if (this.tags && this.tags.length > 0) { - items.push(`langsmith-tags=${encodeURIComponent(this.tags.join(","))}`); - } - if (this.project_name) { - items.push(`langsmith-project=${encodeURIComponent(this.project_name)}`); - } - return items.join(","); - } -} -class run_trees_RunTree { - constructor(originalConfig) { - Object.defineProperty(this, "id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "run_type", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "project_name", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "parent_run", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "parent_run_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_runs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "start_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "end_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "extra", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tags", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "error", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "serialized", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "inputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "outputs", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "reference_example_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "client", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "events", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "trace_id", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "dotted_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "tracingEnabled", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "execution_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "child_execution_order", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** - * Attachments associated with the run. - * Each entry is a tuple of [mime_type, bytes] - */ - Object.defineProperty(this, "attachments", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - /** - * Projects to replicate this run to with optional updates. - */ - Object.defineProperty(this, "replicas", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "distributedParentId", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - Object.defineProperty(this, "_serialized_start_time", { - enumerable: true, - configurable: true, - writable: true, - value: void 0 - }); - // If you pass in a run tree directly, return a shallow clone - if (run_trees_isRunTree(originalConfig)) { - Object.assign(this, { ...originalConfig }); - return; - } - const defaultConfig = run_trees_RunTree.getDefaultConfig(); - const { metadata, ...config } = originalConfig; - const client = config.client ?? run_trees_RunTree.getSharedClient(); - const dedupedMetadata = { - ...metadata, - ...config?.extra?.metadata, - }; - config.extra = { ...config.extra, metadata: dedupedMetadata }; - if ("id" in config && config.id == null) { - delete config.id; - } - Object.assign(this, { ...defaultConfig, ...config, client }); - this.execution_order ??= 1; - this.child_execution_order ??= 1; - // Generate serialized start time for ID generation - if (!this.dotted_order) { - this._serialized_start_time = getMicrosecondPrecisionDatestring(this.start_time, this.execution_order); - } - // Generate id from serialized start_time if not provided - if (!this.id) { - this.id = uuid7FromTime(this._serialized_start_time ?? this.start_time); - } - if (!this.trace_id) { - if (this.parent_run) { - this.trace_id = this.parent_run.trace_id ?? this.id; - } - else { - this.trace_id = this.id; - } - } - this.replicas = _ensureWriteReplicas(this.replicas); - // Now set the dotted order with the actual ID - if (!this.dotted_order) { - const { dottedOrder } = convertToDottedOrderFormat(this.start_time, this.id, this.execution_order); - if (this.parent_run) { - this.dotted_order = this.parent_run.dotted_order + "." + dottedOrder; - } - else { - this.dotted_order = dottedOrder; - } - } - } - set metadata(metadata) { - this.extra = { - ...this.extra, - metadata: { - ...this.extra?.metadata, - ...metadata, - }, - }; - } - get metadata() { - return this.extra?.metadata; - } - static getDefaultConfig() { - const start_time = Date.now(); - return { - run_type: "chain", - project_name: getDefaultProjectName(), - child_runs: [], - api_url: env_getEnvironmentVariable("LANGCHAIN_ENDPOINT") ?? "http://localhost:1984", - api_key: env_getEnvironmentVariable("LANGCHAIN_API_KEY"), - caller_options: {}, - start_time, - serialized: {}, - inputs: {}, - extra: {}, - }; - } - static getSharedClient() { - if (!run_trees_RunTree.sharedClient) { - run_trees_RunTree.sharedClient = new Client(); - } - return run_trees_RunTree.sharedClient; - } - createChild(config) { - const child_execution_order = this.child_execution_order + 1; - // Handle replicas: if child has its own replicas, use those; otherwise inherit parent's (with reroot stripped) - // Reroot should only apply to the run where it's explicitly configured, not propagate down - const inheritedReplicas = this.replicas?.map((replica) => { - const { reroot, ...rest } = replica; - return rest; - }); - const childReplicas = config.replicas ?? inheritedReplicas; - const child = new run_trees_RunTree({ - ...config, - parent_run: this, - project_name: this.project_name, - replicas: childReplicas, - client: this.client, - tracingEnabled: this.tracingEnabled, - execution_order: child_execution_order, - child_execution_order: child_execution_order, - }); - // Copy context vars over into the new run tree. - if (_LC_CONTEXT_VARIABLES_KEY in this) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - child[_LC_CONTEXT_VARIABLES_KEY] = - this[_LC_CONTEXT_VARIABLES_KEY]; - } - const LC_CHILD = Symbol.for("lc:child_config"); - const presentConfig = config.extra?.[LC_CHILD] ?? - this.extra[LC_CHILD]; - // tracing for LangChain is defined by the _parentRunId and runMap of the tracer - if (isRunnableConfigLike(presentConfig)) { - const newConfig = { ...presentConfig }; - const callbacks = isCallbackManagerLike(newConfig.callbacks) - ? newConfig.callbacks.copy?.() - : undefined; - if (callbacks) { - // update the parent run id - Object.assign(callbacks, { _parentRunId: child.id }); - // only populate if we're in a newer LC.JS version - callbacks.handlers - ?.find(isLangChainTracerLike) - ?.updateFromRunTree?.(child); - newConfig.callbacks = callbacks; - } - child.extra[LC_CHILD] = newConfig; - } - // propagate child_execution_order upwards - const visited = new Set(); - let current = this; - while (current != null && !visited.has(current.id)) { - visited.add(current.id); - current.child_execution_order = Math.max(current.child_execution_order, child_execution_order); - current = current.parent_run; - } - this.child_runs.push(child); - return child; - } - async end(outputs, error, endTime = Date.now(), metadata) { - this.outputs = this.outputs ?? outputs; - this.error = this.error ?? error; - this.end_time = this.end_time ?? endTime; - if (metadata && Object.keys(metadata).length > 0) { - this.extra = this.extra - ? { ...this.extra, metadata: { ...this.extra.metadata, ...metadata } } - : { metadata }; - } - } - _convertToCreate(run, runtimeEnv, excludeChildRuns = true) { - const runExtra = run.extra ?? {}; - // Avoid overwriting the runtime environment if it's already set - if (runExtra?.runtime?.library === undefined) { - if (!runExtra.runtime) { - runExtra.runtime = {}; - } - if (runtimeEnv) { - for (const [k, v] of Object.entries(runtimeEnv)) { - if (!runExtra.runtime[k]) { - runExtra.runtime[k] = v; - } - } - } - } - let child_runs; - let parent_run_id; - if (!excludeChildRuns) { - child_runs = run.child_runs.map((child_run) => this._convertToCreate(child_run, runtimeEnv, excludeChildRuns)); - parent_run_id = undefined; - } - else { - parent_run_id = run.parent_run?.id ?? run.parent_run_id; - child_runs = []; - } - return { - id: run.id, - name: run.name, - start_time: run._serialized_start_time ?? run.start_time, - end_time: run.end_time, - run_type: run.run_type, - reference_example_id: run.reference_example_id, - extra: runExtra, - serialized: run.serialized, - error: run.error, - inputs: run.inputs, - outputs: run.outputs, - session_name: run.project_name, - child_runs: child_runs, - parent_run_id: parent_run_id, - trace_id: run.trace_id, - dotted_order: run.dotted_order, - tags: run.tags, - attachments: run.attachments, - events: run.events, - }; - } - _sliceParentId(parentId, run) { - /** - * Slice the parent id from dotted order. - * Additionally check if the current run is a child of the parent. If so, update - * the parent_run_id to undefined, and set the trace id to the new root id after - * parent_id. - */ - if (run.dotted_order) { - const segs = run.dotted_order.split("."); - let startIdx = null; - // Find the index of the parent ID in the dotted order - for (let idx = 0; idx < segs.length; idx++) { - const segId = segs[idx].slice(-TIMESTAMP_LENGTH); - if (segId === parentId) { - startIdx = idx; - break; - } - } - if (startIdx !== null) { - // Trim segments to start after parent_id (exclusive) - const trimmedSegs = segs.slice(startIdx + 1); - // Rebuild dotted_order - run.dotted_order = trimmedSegs.join("."); - if (trimmedSegs.length > 0) { - run.trace_id = trimmedSegs[0].slice(-TIMESTAMP_LENGTH); - } - else { - run.trace_id = run.id; - } - } - } - if (run.parent_run_id === parentId) { - // We've found the new root node. - run.parent_run_id = undefined; - } - } - _setReplicaTraceRoot(replicaKey, traceRootId) { - // Set the replica trace root in context vars on this run and all descendants - const replicaTraceRoots = getContextVar(this, _REPLICA_TRACE_ROOTS_KEY) ?? {}; - replicaTraceRoots[replicaKey] = traceRootId; - setContextVar(this, _REPLICA_TRACE_ROOTS_KEY, replicaTraceRoots); - // Recursively update all descendants to avoid race conditions - // around run tree creation vs processing time - for (const child of this.child_runs) { - child._setReplicaTraceRoot(replicaKey, traceRootId); - } - } - _remapForProject(params) { - const { projectName, runtimeEnv, excludeChildRuns = true, reroot = false, distributedParentId, apiUrl, apiKey, workspaceId, } = params; - const baseRun = this._convertToCreate(this, runtimeEnv, excludeChildRuns); - // Skip remapping if project name is the same - if (projectName === this.project_name) { - return { - ...baseRun, - session_name: projectName, - }; - } - // Apply reroot logic before ID remapping - if (reroot) { - if (distributedParentId) { - // If we have a distributed parent ID, slice at that point - this._sliceParentId(distributedParentId, baseRun); - } - else { - // If no distributed parent ID, simply make this run a root run - // by removing parent_run_id and resetting trace info - baseRun.parent_run_id = undefined; - // Keep the current run as the trace root - if (baseRun.dotted_order) { - // Reset dotted order to just this run - const segs = baseRun.dotted_order.split("."); - if (segs.length > 0) { - baseRun.dotted_order = segs[segs.length - 1]; - baseRun.trace_id = baseRun.id; - } - } - } - // Store this run's original ID in context vars so descendants know the new trace root - // We store the original ID (before remapping) so it can be found in dotted_order - const replicaKey = getReplicaKey({ - projectName, - apiUrl, - apiKey, - workspaceId, - }); - this._setReplicaTraceRoot(replicaKey, baseRun.id); - } - // If an ancestor was rerooted for this replica, update trace_id and dotted_order - // to reflect the new trace hierarchy. This is tracked via context variables. - let ancestorRerootedTraceId; - if (!reroot) { - const replicaTraceRoots = getContextVar(this, _REPLICA_TRACE_ROOTS_KEY) ?? {}; - const replicaKey = getReplicaKey({ - projectName, - apiUrl, - apiKey, - workspaceId, - }); - ancestorRerootedTraceId = replicaTraceRoots[replicaKey]; - if (ancestorRerootedTraceId) { - // An ancestor was rerooted for this replica, so set our trace_id - // to the ancestor's original (unmapped) ID. It will be remapped along with other IDs. - baseRun.trace_id = ancestorRerootedTraceId; - // Also slice the dotted_order to start from the new trace root - // This ensures descendants of a rerooted ancestor have correct hierarchy - if (baseRun.dotted_order) { - const segs = baseRun.dotted_order.split("."); - let rootIdx = null; - // Find the new trace root's segment in dotted_order - for (let idx = 0; idx < segs.length; idx++) { - const segId = segs[idx].slice(-TIMESTAMP_LENGTH); - if (segId === ancestorRerootedTraceId) { - rootIdx = idx; - break; - } - } - if (rootIdx !== null) { - // Keep segments from new trace root onwards - const trimmedSegs = segs.slice(rootIdx); - baseRun.dotted_order = trimmedSegs.join("."); - } - } - } - } - // Remap IDs for the replica using uuid5 (deterministic) - // This ensures consistency across runs in the same replica - const oldId = baseRun.id; - const newId = v5(`${oldId}:${projectName}`, UUID_NAMESPACE_DNS); - // Remap trace_id - let newTraceId; - if (baseRun.trace_id) { - newTraceId = v5(`${baseRun.trace_id}:${projectName}`, UUID_NAMESPACE_DNS); - } - else { - newTraceId = newId; - } - // Remap parent_run_id - let newParentId; - if (baseRun.parent_run_id) { - newParentId = v5(`${baseRun.parent_run_id}:${projectName}`, UUID_NAMESPACE_DNS); - } - // Remap dotted_order segments - let newDottedOrder; - if (baseRun.dotted_order) { - const segs = baseRun.dotted_order.split("."); - const remappedSegs = segs.map((seg) => { - // Extract the UUID from the segment (last TIMESTAMP_LENGTH characters) - const segId = seg.slice(-TIMESTAMP_LENGTH); - const remappedId = v5(`${segId}:${projectName}`, UUID_NAMESPACE_DNS); - // Replace the UUID part while keeping the timestamp prefix - return seg.slice(0, -TIMESTAMP_LENGTH) + remappedId; - }); - newDottedOrder = remappedSegs.join("."); - } - return { - ...baseRun, - id: newId, - trace_id: newTraceId, - parent_run_id: newParentId, - dotted_order: newDottedOrder, - session_name: projectName, - }; - } - async postRun(excludeChildRuns = true) { - try { - const runtimeEnv = env_getRuntimeEnvironment(); - if (this.replicas && this.replicas.length > 0) { - for (const { projectName, apiKey, apiUrl, workspaceId, reroot } of this - .replicas) { - const runCreate = this._remapForProject({ - projectName: projectName ?? this.project_name, - runtimeEnv, - excludeChildRuns: true, - reroot, - distributedParentId: this.distributedParentId, - apiUrl, - apiKey, - workspaceId, - }); - await this.client.createRun(runCreate, { - apiKey, - apiUrl, - workspaceId, - }); - } - } - else { - const runCreate = this._convertToCreate(this, runtimeEnv, excludeChildRuns); - await this.client.createRun(runCreate); - } - if (!excludeChildRuns) { - warn_warnOnce("Posting with excludeChildRuns=false is deprecated and will be removed in a future version."); - for (const childRun of this.child_runs) { - await childRun.postRun(false); - } - } - this.child_runs = []; - } - catch (error) { - console.error(`Error in postRun for run ${this.id}:`, error); - } - } - async patchRun(options) { - if (this.replicas && this.replicas.length > 0) { - for (const { projectName, apiKey, apiUrl, workspaceId, updates, reroot, } of this.replicas) { - const runData = this._remapForProject({ - projectName: projectName ?? this.project_name, - runtimeEnv: undefined, - excludeChildRuns: true, - reroot, - distributedParentId: this.distributedParentId, - apiUrl, - apiKey, - workspaceId, - }); - const updatePayload = { - id: runData.id, - name: runData.name, - run_type: runData.run_type, - start_time: runData.start_time, - outputs: runData.outputs, - error: runData.error, - parent_run_id: runData.parent_run_id, - session_name: runData.session_name, - reference_example_id: runData.reference_example_id, - end_time: runData.end_time, - dotted_order: runData.dotted_order, - trace_id: runData.trace_id, - events: runData.events, - tags: runData.tags, - extra: runData.extra, - attachments: this.attachments, - ...updates, - }; - // Important that inputs is not a key in the run update - // if excluded because it will overwrite the run create if the - // two operations are merged during batching - if (!options?.excludeInputs) { - updatePayload.inputs = runData.inputs; - } - await this.client.updateRun(runData.id, updatePayload, { - apiKey, - apiUrl, - workspaceId, - }); - } - } - else { - try { - const runUpdate = { - name: this.name, - run_type: this.run_type, - start_time: this._serialized_start_time ?? this.start_time, - end_time: this.end_time, - error: this.error, - outputs: this.outputs, - parent_run_id: this.parent_run?.id ?? this.parent_run_id, - reference_example_id: this.reference_example_id, - extra: this.extra, - events: this.events, - dotted_order: this.dotted_order, - trace_id: this.trace_id, - tags: this.tags, - attachments: this.attachments, - session_name: this.project_name, - }; - // Important that inputs is not a key in the run update - // if excluded because it will overwrite the run create if the - // two operations are merged during batching - if (!options?.excludeInputs) { - runUpdate.inputs = this.inputs; - } - await this.client.updateRun(this.id, runUpdate); - } - catch (error) { - console.error(`Error in patchRun for run ${this.id}`, error); - } - } - this.child_runs = []; - } - toJSON() { - return this._convertToCreate(this, undefined, false); - } - /** - * Add an event to the run tree. - * @param event - A single event or string to add - */ - addEvent(event) { - if (!this.events) { - this.events = []; - } - if (typeof event === "string") { - this.events.push({ - name: "event", - time: new Date().toISOString(), - message: event, - }); - } - else { - this.events.push({ - ...event, - time: event.time ?? new Date().toISOString(), - }); - } - } - static fromRunnableConfig(parentConfig, props) { - // We only handle the callback manager case for now - const callbackManager = parentConfig?.callbacks; - let parentRun; - let projectName; - let client; - let tracingEnabled = isTracingEnabled(); - if (callbackManager) { - const parentRunId = callbackManager?.getParentRunId?.() ?? ""; - const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name == "langchain_tracer"); - parentRun = langChainTracer?.getRun?.(parentRunId); - projectName = langChainTracer?.projectName; - client = langChainTracer?.client; - tracingEnabled = tracingEnabled || !!langChainTracer; - } - if (!parentRun) { - return new run_trees_RunTree({ - ...props, - client, - tracingEnabled, - project_name: projectName, - }); - } - const parentRunTree = new run_trees_RunTree({ - name: parentRun.name, - id: parentRun.id, - trace_id: parentRun.trace_id, - dotted_order: parentRun.dotted_order, - client, - tracingEnabled, - project_name: projectName, - tags: [ - ...new Set((parentRun?.tags ?? []).concat(parentConfig?.tags ?? [])), - ], - extra: { - metadata: { - ...parentRun?.extra?.metadata, - ...parentConfig?.metadata, - }, - }, - }); - return parentRunTree.createChild(props); - } - static fromDottedOrder(dottedOrder) { - return this.fromHeaders({ "langsmith-trace": dottedOrder }); - } - static fromHeaders(headers, inheritArgs) { - const rawHeaders = "get" in headers && typeof headers.get === "function" - ? { - "langsmith-trace": headers.get("langsmith-trace"), - baggage: headers.get("baggage"), - } - : headers; - const headerTrace = rawHeaders["langsmith-trace"]; - if (!headerTrace || typeof headerTrace !== "string") - return undefined; - const parentDottedOrder = headerTrace.trim(); - const parsedDottedOrder = parentDottedOrder.split(".").map((part) => { - const [strTime, uuid] = part.split("Z"); - return { strTime, time: Date.parse(strTime + "Z"), uuid }; - }); - const traceId = parsedDottedOrder[0].uuid; - const config = { - ...inheritArgs, - name: inheritArgs?.["name"] ?? "parent", - run_type: inheritArgs?.["run_type"] ?? "chain", - start_time: inheritArgs?.["start_time"] ?? Date.now(), - id: parsedDottedOrder.at(-1)?.uuid, - trace_id: traceId, - dotted_order: parentDottedOrder, - }; - if (rawHeaders["baggage"] && typeof rawHeaders["baggage"] === "string") { - const baggage = Baggage.fromHeader(rawHeaders["baggage"]); - config.metadata = baggage.metadata; - config.tags = baggage.tags; - config.project_name = baggage.project_name; - config.replicas = baggage.replicas; - } - const runTree = new run_trees_RunTree(config); - // Set the distributed parent ID to this run's ID for rerooting - runTree.distributedParentId = runTree.id; - return runTree; - } - toHeaders(headers) { - const result = { - "langsmith-trace": this.dotted_order, - baggage: new Baggage(this.extra?.metadata, this.tags, this.project_name, this.replicas).toHeader(), - }; - if (headers) { - for (const [key, value] of Object.entries(result)) { - headers.set(key, value); - } - } - return result; - } -} -Object.defineProperty(run_trees_RunTree, "sharedClient", { - enumerable: true, - configurable: true, - writable: true, - value: null -}); -function run_trees_isRunTree(x) { - return (x != null && - typeof x.createChild === "function" && - typeof x.postRun === "function"); -} -function isLangChainTracerLike(x) { - return (typeof x === "object" && - x != null && - typeof x.name === "string" && - x.name === "langchain_tracer"); -} -function containsLangChainTracerLike(x) { - return (Array.isArray(x) && x.some((callback) => isLangChainTracerLike(callback))); -} -function isCallbackManagerLike(x) { - return (typeof x === "object" && - x != null && - Array.isArray(x.handlers)); -} -function isRunnableConfigLike(x) { - // Check that it's an object with a callbacks arg - // that has either a CallbackManagerLike object with a langchain tracer within it - // or an array with a LangChainTracerLike object within it - const callbacks = x?.callbacks; - return (x != null && - typeof callbacks === "object" && - // Callback manager with a langchain tracer - // eslint-disable-next-line @typescript-eslint/no-explicit-any - (containsLangChainTracerLike(callbacks?.handlers) || - // Or it's an array with a LangChainTracerLike object within it - containsLangChainTracerLike(callbacks))); -} -function _getWriteReplicasFromEnv() { - const envVar = env_getEnvironmentVariable("LANGSMITH_RUNS_ENDPOINTS"); - if (!envVar) - return []; - try { - const parsed = JSON.parse(envVar); - if (Array.isArray(parsed)) { - const replicas = []; - for (const item of parsed) { - if (typeof item !== "object" || item === null) { - console.warn(`Invalid item type in LANGSMITH_RUNS_ENDPOINTS: ` + - `expected object, got ${typeof item}`); - continue; - } - if (typeof item.api_url !== "string") { - console.warn(`Invalid api_url type in LANGSMITH_RUNS_ENDPOINTS: ` + - `expected string, got ${typeof item.api_url}`); - continue; - } - if (typeof item.api_key !== "string") { - console.warn(`Invalid api_key type in LANGSMITH_RUNS_ENDPOINTS: ` + - `expected string, got ${typeof item.api_key}`); - continue; - } - replicas.push({ - apiUrl: item.api_url.replace(/\/$/, ""), - apiKey: item.api_key, - }); - } - return replicas; - } - else if (typeof parsed === "object" && parsed !== null) { - _checkEndpointEnvUnset(parsed); - const replicas = []; - for (const [url, key] of Object.entries(parsed)) { - const cleanUrl = url.replace(/\/$/, ""); - if (typeof key === "string") { - replicas.push({ - apiUrl: cleanUrl, - apiKey: key, - }); - } - else { - console.warn(`Invalid value type in LANGSMITH_RUNS_ENDPOINTS for URL ${url}: ` + - `expected string, got ${typeof key}`); - continue; - } - } - return replicas; - } - else { - console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of " + - `objects with api_url and api_key properties, or object mapping url->apiKey, got ${typeof parsed}`); - return []; - } - } - catch (e) { - if (isConflictingEndpointsError(e)) { - throw e; - } - console.warn("Invalid LANGSMITH_RUNS_ENDPOINTS – must be valid JSON array of " + - "objects with api_url and api_key properties, or object mapping url->apiKey"); - return []; - } -} -function _ensureWriteReplicas(replicas) { - // If null -> fetch from env - if (replicas) { - return replicas.map((replica) => { - if (Array.isArray(replica)) { - return { - projectName: replica[0], - updates: replica[1], - }; - } - return replica; - }); - } - return _getWriteReplicasFromEnv(); -} -function _checkEndpointEnvUnset(parsed) { - if (Object.keys(parsed).length > 0 && - getLangSmithEnvironmentVariable("ENDPOINT")) { - throw new ConflictingEndpointsError(); - } -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/run_trees.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/base.js - - - - - -//#region src/tracers/base.ts -var base_base_exports = {}; -__export(base_base_exports, { - BaseTracer: () => BaseTracer, - isBaseTracer: () => isBaseTracer -}); -const convertRunTreeToRun = (runTree) => { - if (!runTree) return void 0; - runTree.events = runTree.events ?? []; - runTree.child_runs = runTree.child_runs ?? []; - return runTree; -}; -function convertRunToRunTree(run, parentRun) { - if (!run) return void 0; - return new run_trees_RunTree({ - ...run, - start_time: run._serialized_start_time ?? run.start_time, - parent_run: convertRunToRunTree(parentRun), - child_runs: run.child_runs.map((r) => convertRunToRunTree(r)).filter((r) => r !== void 0), - extra: { - ...run.extra, - runtime: getRuntimeEnvironment() - }, - tracingEnabled: false - }); -} -function _coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && typeof value === "object" ? value : { [defaultKey]: value }; -} -function isBaseTracer(x) { - return typeof x._addRunToRunMap === "function"; -} -var BaseTracer = class extends BaseCallbackHandler { - /** @deprecated Use `runTreeMap` instead. */ - runMap = /* @__PURE__ */ new Map(); - runTreeMap = /* @__PURE__ */ new Map(); - usesRunTreeMap = false; - constructor(_fields) { - super(...arguments); - } - copy() { - return this; - } - getRunById(runId) { - if (runId === void 0) return void 0; - return this.usesRunTreeMap ? convertRunTreeToRun(this.runTreeMap.get(runId)) : this.runMap.get(runId); - } - stringifyError(error) { - if (error instanceof Error) return error.message + (error?.stack ? `\n\n${error.stack}` : ""); - if (typeof error === "string") return error; - return `${error}`; - } - _addChildRun(parentRun, childRun) { - parentRun.child_runs.push(childRun); - } - _addRunToRunMap(run) { - const { dottedOrder: currentDottedOrder, microsecondPrecisionDatestring } = convertToDottedOrderFormat(new Date(run.start_time).getTime(), run.id, run.execution_order); - const storedRun = { ...run }; - const parentRun = this.getRunById(storedRun.parent_run_id); - if (storedRun.parent_run_id !== void 0) if (parentRun) { - this._addChildRun(parentRun, storedRun); - parentRun.child_execution_order = Math.max(parentRun.child_execution_order, storedRun.child_execution_order); - storedRun.trace_id = parentRun.trace_id; - if (parentRun.dotted_order !== void 0) { - storedRun.dotted_order = [parentRun.dotted_order, currentDottedOrder].join("."); - storedRun._serialized_start_time = microsecondPrecisionDatestring; - } - } else storedRun.parent_run_id = void 0; - else { - storedRun.trace_id = storedRun.id; - storedRun.dotted_order = currentDottedOrder; - storedRun._serialized_start_time = microsecondPrecisionDatestring; - } - if (this.usesRunTreeMap) { - const runTree = convertRunToRunTree(storedRun, parentRun); - if (runTree !== void 0) this.runTreeMap.set(storedRun.id, runTree); - } else this.runMap.set(storedRun.id, storedRun); - return storedRun; - } - async _endTrace(run) { - const parentRun = run.parent_run_id !== void 0 && this.getRunById(run.parent_run_id); - if (parentRun) parentRun.child_execution_order = Math.max(parentRun.child_execution_order, run.child_execution_order); - else await this.persistRun(run); - await this.onRunUpdate?.(run); - if (this.usesRunTreeMap) this.runTreeMap.delete(run.id); - else this.runMap.delete(run.id); - } - _getExecutionOrder(parentRunId) { - const parentRun = parentRunId !== void 0 && this.getRunById(parentRunId); - if (!parentRun) return 1; - return parentRun.child_execution_order + 1; - } - /** - * Create and add a run to the run map for LLM start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata ? { - ...extraParams, - metadata - } : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [{ - name: "start", - time: new Date(start_time).toISOString() - }], - inputs: { prompts }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.getRunById(runId) ?? this._createRunForLLMStart(llm, prompts, runId, parentRunId, extraParams, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onLLMStart?.(run); - return run; - } - /** - * Create and add a run to the run map for chat model start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const finalExtraParams = metadata ? { - ...extraParams, - metadata - } : extraParams; - const run = { - id: runId, - name: name ?? llm.id[llm.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: llm, - events: [{ - name: "start", - time: new Date(start_time).toISOString() - }], - inputs: { messages }, - execution_order, - child_runs: [], - child_execution_order: execution_order, - run_type: "llm", - extra: finalExtraParams ?? {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name) { - const run = this.getRunById(runId) ?? this._createRunForChatModelStart(llm, messages, runId, parentRunId, extraParams, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onLLMStart?.(run); - return run; - } - async handleLLMEnd(output, runId, _parentRunId, _tags, extraParams) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "llm") throw new Error("No LLM run to end."); - run.end_time = Date.now(); - run.outputs = output; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - run.extra = { - ...run.extra, - ...extraParams - }; - await this.onLLMEnd?.(run); - await this._endTrace(run); - return run; - } - async handleLLMError(error, runId, _parentRunId, _tags, extraParams) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "llm") throw new Error("No LLM run to end."); - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - run.extra = { - ...run.extra, - ...extraParams - }; - await this.onLLMError?.(run); - await this._endTrace(run); - return run; - } - /** - * Create and add a run to the run map for chain start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name, extra) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? chain.id[chain.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: chain, - events: [{ - name: "start", - time: new Date(start_time).toISOString() - }], - inputs, - execution_order, - child_execution_order: execution_order, - run_type: runType ?? "chain", - child_runs: [], - extra: metadata ? { - ...extra, - metadata - } : { ...extra }, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name) { - const run = this.getRunById(runId) ?? this._createRunForChainStart(chain, inputs, runId, parentRunId, tags, metadata, runType, name); - await this.onRunCreate?.(run); - await this.onChainStart?.(run); - return run; - } - async handleChainEnd(outputs, runId, _parentRunId, _tags, kwargs) { - const run = this.getRunById(runId); - if (!run) throw new Error("No chain run to end."); - run.end_time = Date.now(); - run.outputs = _coerceToDict(outputs, "output"); - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - if (kwargs?.inputs !== void 0) run.inputs = _coerceToDict(kwargs.inputs, "input"); - await this.onChainEnd?.(run); - await this._endTrace(run); - return run; - } - async handleChainError(error, runId, _parentRunId, _tags, kwargs) { - const run = this.getRunById(runId); - if (!run) throw new Error("No chain run to end."); - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - if (kwargs?.inputs !== void 0) run.inputs = _coerceToDict(kwargs.inputs, "input"); - await this.onChainError?.(run); - await this._endTrace(run); - return run; - } - /** - * Create and add a run to the run map for tool start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? tool.id[tool.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: tool, - events: [{ - name: "start", - time: new Date(start_time).toISOString() - }], - inputs: { input }, - execution_order, - child_execution_order: execution_order, - run_type: "tool", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleToolStart(tool, input, runId, parentRunId, tags, metadata, name) { - const run = this.getRunById(runId) ?? this._createRunForToolStart(tool, input, runId, parentRunId, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onToolStart?.(run); - return run; - } - async handleToolEnd(output, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "tool") throw new Error("No tool run to end"); - run.end_time = Date.now(); - run.outputs = { output }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - await this.onToolEnd?.(run); - await this._endTrace(run); - return run; - } - async handleToolError(error, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "tool") throw new Error("No tool run to end"); - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - await this.onToolError?.(run); - await this._endTrace(run); - return run; - } - async handleAgentAction(action, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "chain") return; - const agentRun = run; - agentRun.actions = agentRun.actions || []; - agentRun.actions.push(action); - agentRun.events.push({ - name: "agent_action", - time: (/* @__PURE__ */ new Date()).toISOString(), - kwargs: { action } - }); - await this.onAgentAction?.(run); - } - async handleAgentEnd(action, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "chain") return; - run.events.push({ - name: "agent_end", - time: (/* @__PURE__ */ new Date()).toISOString(), - kwargs: { action } - }); - await this.onAgentEnd?.(run); - } - /** - * Create and add a run to the run map for retriever start events. - * This must sometimes be done synchronously to avoid race conditions - * when callbacks are backgrounded, so we expose it as a separate method here. - */ - _createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const execution_order = this._getExecutionOrder(parentRunId); - const start_time = Date.now(); - const run = { - id: runId, - name: name ?? retriever.id[retriever.id.length - 1], - parent_run_id: parentRunId, - start_time, - serialized: retriever, - events: [{ - name: "start", - time: new Date(start_time).toISOString() - }], - inputs: { query }, - execution_order, - child_execution_order: execution_order, - run_type: "retriever", - child_runs: [], - extra: metadata ? { metadata } : {}, - tags: tags || [] - }; - return this._addRunToRunMap(run); - } - async handleRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name) { - const run = this.getRunById(runId) ?? this._createRunForRetrieverStart(retriever, query, runId, parentRunId, tags, metadata, name); - await this.onRunCreate?.(run); - await this.onRetrieverStart?.(run); - return run; - } - async handleRetrieverEnd(documents, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "retriever") throw new Error("No retriever run to end"); - run.end_time = Date.now(); - run.outputs = { documents }; - run.events.push({ - name: "end", - time: new Date(run.end_time).toISOString() - }); - await this.onRetrieverEnd?.(run); - await this._endTrace(run); - return run; - } - async handleRetrieverError(error, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "retriever") throw new Error("No retriever run to end"); - run.end_time = Date.now(); - run.error = this.stringifyError(error); - run.events.push({ - name: "error", - time: new Date(run.end_time).toISOString() - }); - await this.onRetrieverError?.(run); - await this._endTrace(run); - return run; - } - async handleText(text, runId) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "chain") return; - run.events.push({ - name: "text", - time: (/* @__PURE__ */ new Date()).toISOString(), - kwargs: { text } - }); - await this.onText?.(run); - } - async handleLLMNewToken(token, idx, runId, _parentRunId, _tags, fields) { - const run = this.getRunById(runId); - if (!run || run?.run_type !== "llm") throw new Error(`Invalid "runId" provided to "handleLLMNewToken" callback.`); - run.events.push({ - name: "new_token", - time: (/* @__PURE__ */ new Date()).toISOString(), - kwargs: { - token, - idx, - chunk: fields?.chunk - } - }); - await this.onLLMNewToken?.(run, token, { chunk: fields?.chunk }); - return run; - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -// EXTERNAL MODULE: ./node_modules/ansi-styles/index.js -var ansi_styles = __nccwpck_require__(4412); -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/console.js - - - - -//#region src/tracers/console.ts -var console_exports = {}; -__export(console_exports, { ConsoleCallbackHandler: () => ConsoleCallbackHandler }); -function wrap(style, text) { - return `${style.open}${text}${style.close}`; -} -function tryJsonStringify(obj, fallback) { - try { - return JSON.stringify(obj, null, 2); - } catch { - return fallback; - } -} -function formatKVMapItem(value) { - if (typeof value === "string") return value.trim(); - if (value === null || value === void 0) return value; - return tryJsonStringify(value, value.toString()); -} -function elapsed(run) { - if (!run.end_time) return ""; - const elapsed$1 = run.end_time - run.start_time; - if (elapsed$1 < 1e3) return `${elapsed$1}ms`; - return `${(elapsed$1 / 1e3).toFixed(2)}s`; -} -const { color } = ansi_styles; -/** -* A tracer that logs all events to the console. It extends from the -* `BaseTracer` class and overrides its methods to provide custom logging -* functionality. -* @example -* ```typescript -* -* const llm = new ChatAnthropic({ -* temperature: 0, -* tags: ["example", "callbacks", "constructor"], -* callbacks: [new ConsoleCallbackHandler()], -* }); -* -* ``` -*/ -var ConsoleCallbackHandler = class extends BaseTracer { - name = "console_callback_handler"; - /** - * Method used to persist the run. In this case, it simply returns a - * resolved promise as there's no persistence logic. - * @param _run The run to persist. - * @returns A resolved promise. - */ - persistRun(_run) { - return Promise.resolve(); - } - /** - * Method used to get all the parent runs of a given run. - * @param run The run whose parents are to be retrieved. - * @returns An array of parent runs. - */ - getParents(run) { - const parents = []; - let currentRun = run; - while (currentRun.parent_run_id) { - const parent = this.runMap.get(currentRun.parent_run_id); - if (parent) { - parents.push(parent); - currentRun = parent; - } else break; - } - return parents; - } - /** - * Method used to get a string representation of the run's lineage, which - * is used in logging. - * @param run The run whose lineage is to be retrieved. - * @returns A string representation of the run's lineage. - */ - getBreadcrumbs(run) { - const parents = this.getParents(run).reverse(); - const string = [...parents, run].map((parent, i, arr) => { - const name = `${parent.execution_order}:${parent.run_type}:${parent.name}`; - return i === arr.length - 1 ? wrap(ansi_styles.bold, name) : name; - }).join(" > "); - return wrap(color.grey, string); - } - /** - * Method used to log the start of a chain run. - * @param run The chain run that has started. - * @returns void - */ - onChainStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[chain/start]")} [${crumbs}] Entering Chain run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); - } - /** - * Method used to log the end of a chain run. - * @param run The chain run that has ended. - * @returns void - */ - onChainEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[chain/end]")} [${crumbs}] [${elapsed(run)}] Exiting Chain run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); - } - /** - * Method used to log any errors of a chain run. - * @param run The chain run that has errored. - * @returns void - */ - onChainError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[chain/error]")} [${crumbs}] [${elapsed(run)}] Chain run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of an LLM run. - * @param run The LLM run that has started. - * @returns void - */ - onLLMStart(run) { - const crumbs = this.getBreadcrumbs(run); - const inputs = "prompts" in run.inputs ? { prompts: run.inputs.prompts.map((p) => p.trim()) } : run.inputs; - console.log(`${wrap(color.green, "[llm/start]")} [${crumbs}] Entering LLM run with input: ${tryJsonStringify(inputs, "[inputs]")}`); - } - /** - * Method used to log the end of an LLM run. - * @param run The LLM run that has ended. - * @returns void - */ - onLLMEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[llm/end]")} [${crumbs}] [${elapsed(run)}] Exiting LLM run with output: ${tryJsonStringify(run.outputs, "[response]")}`); - } - /** - * Method used to log any errors of an LLM run. - * @param run The LLM run that has errored. - * @returns void - */ - onLLMError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[llm/error]")} [${crumbs}] [${elapsed(run)}] LLM run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of a tool run. - * @param run The tool run that has started. - * @returns void - */ - onToolStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[tool/start]")} [${crumbs}] Entering Tool run with input: "${formatKVMapItem(run.inputs.input)}"`); - } - /** - * Method used to log the end of a tool run. - * @param run The tool run that has ended. - * @returns void - */ - onToolEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[tool/end]")} [${crumbs}] [${elapsed(run)}] Exiting Tool run with output: "${formatKVMapItem(run.outputs?.output)}"`); - } - /** - * Method used to log any errors of a tool run. - * @param run The tool run that has errored. - * @returns void - */ - onToolError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[tool/error]")} [${crumbs}] [${elapsed(run)}] Tool run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the start of a retriever run. - * @param run The retriever run that has started. - * @returns void - */ - onRetrieverStart(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.green, "[retriever/start]")} [${crumbs}] Entering Retriever run with input: ${tryJsonStringify(run.inputs, "[inputs]")}`); - } - /** - * Method used to log the end of a retriever run. - * @param run The retriever run that has ended. - * @returns void - */ - onRetrieverEnd(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.cyan, "[retriever/end]")} [${crumbs}] [${elapsed(run)}] Exiting Retriever run with output: ${tryJsonStringify(run.outputs, "[outputs]")}`); - } - /** - * Method used to log any errors of a retriever run. - * @param run The retriever run that has errored. - * @returns void - */ - onRetrieverError(run) { - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.red, "[retriever/error]")} [${crumbs}] [${elapsed(run)}] Retriever run errored with error: ${tryJsonStringify(run.error, "[error]")}`); - } - /** - * Method used to log the action selected by the agent. - * @param run The run in which the agent action occurred. - * @returns void - */ - onAgentAction(run) { - const agentRun = run; - const crumbs = this.getBreadcrumbs(run); - console.log(`${wrap(color.blue, "[agent/action]")} [${crumbs}] Agent selected action: ${tryJsonStringify(agentRun.actions[agentRun.actions.length - 1], "[action]")}`); - } -}; - -//#endregion - -//# sourceMappingURL=console.js.map -;// CONCATENATED MODULE: ./node_modules/langsmith/index.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/tracer.js - - - -//#region src/singletons/tracer.ts -let client; -const getDefaultLangChainClientSingleton = () => { - if (client === void 0) { - const clientParams = getEnvironmentVariable("LANGCHAIN_CALLBACKS_BACKGROUND") === "false" ? { blockOnRootRunFinalization: true } : {}; - client = new Client(clientParams); - } - return client; -}; - -//#endregion - -//# sourceMappingURL=tracer.js.map -;// CONCATENATED MODULE: ./node_modules/langsmith/dist/singletons/traceable.js -class MockAsyncLocalStorage { - getStore() { - return undefined; - } - run(_, callback) { - return callback(); - } -} -const traceable_TRACING_ALS_KEY = Symbol.for("ls:tracing_async_local_storage"); -const mockAsyncLocalStorage = new MockAsyncLocalStorage(); -class AsyncLocalStorageProvider { - getInstance() { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - return globalThis[traceable_TRACING_ALS_KEY] ?? mockAsyncLocalStorage; - } - initializeGlobalInstance(instance) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - if (globalThis[traceable_TRACING_ALS_KEY] === undefined) { - // eslint-disable-next-line @typescript-eslint/no-explicit-any - globalThis[traceable_TRACING_ALS_KEY] = instance; - } - } -} -const traceable_AsyncLocalStorageProviderSingleton = new AsyncLocalStorageProvider(); -function getCurrentRunTree(permitAbsentRunTree = false) { - const runTree = traceable_AsyncLocalStorageProviderSingleton.getInstance().getStore(); - if (!permitAbsentRunTree && runTree === undefined) { - throw new Error("Could not get the current run tree.\n\nPlease make sure you are calling this method within a traceable function and that tracing is enabled."); - } - return runTree; -} -// eslint-disable-next-line @typescript-eslint/no-explicit-any -function withRunTree(runTree, fn) { - const storage = traceable_AsyncLocalStorageProviderSingleton.getInstance(); - return new Promise((resolve, reject) => { - storage.run(runTree, () => void Promise.resolve(fn()).then(resolve).catch(reject)); - }); -} -const ROOT = Symbol.for("langsmith:traceable:root"); -function isTraceableFunction(x -// eslint-disable-next-line @typescript-eslint/no-explicit-any -) { - return typeof x === "function" && "langsmith:traceable" in x; -} - -;// CONCATENATED MODULE: ./node_modules/langsmith/singletons/traceable.js - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/tracer_langchain.js - - - - - - - - - -//#region src/tracers/tracer_langchain.ts -var tracer_langchain_exports = {}; -__export(tracer_langchain_exports, { LangChainTracer: () => LangChainTracer }); -/** -* Extract usage_metadata from chat generations. -* -* Iterates through generations to find and aggregates all usage_metadata -* found in chat messages. This is typically present in chat model outputs. -*/ -function _getUsageMetadataFromGenerations(generations) { - let output = void 0; - for (const generationBatch of generations) for (const generation of generationBatch) if (AIMessage.isInstance(generation.message) && generation.message.usage_metadata !== void 0) output = mergeUsageMetadata(output, generation.message.usage_metadata); - return output; -} -var LangChainTracer = class LangChainTracer extends BaseTracer { - name = "langchain_tracer"; - projectName; - exampleId; - client; - replicas; - usesRunTreeMap = true; - constructor(fields = {}) { - super(fields); - const { exampleId, projectName, client, replicas } = fields; - this.projectName = projectName ?? getDefaultProjectName(); - this.replicas = replicas; - this.exampleId = exampleId; - this.client = client ?? getDefaultLangChainClientSingleton(); - const traceableTree = LangChainTracer.getTraceableRunTree(); - if (traceableTree) this.updateFromRunTree(traceableTree); - } - async persistRun(_run) {} - async onRunCreate(run) { - if (!run.extra?.lc_defers_inputs) { - const runTree = this.getRunTreeWithTracingConfig(run.id); - await runTree?.postRun(); - } - } - async onRunUpdate(run) { - const runTree = this.getRunTreeWithTracingConfig(run.id); - if (run.extra?.lc_defers_inputs) await runTree?.postRun(); - else await runTree?.patchRun(); - } - onLLMEnd(run) { - const outputs = run.outputs; - if (outputs?.generations) { - const usageMetadata = _getUsageMetadataFromGenerations(outputs.generations); - if (usageMetadata !== void 0) { - run.extra = run.extra ?? {}; - const metadata = run.extra.metadata ?? {}; - metadata.usage_metadata = usageMetadata; - run.extra.metadata = metadata; - } - } - } - getRun(id) { - return this.runTreeMap.get(id); - } - updateFromRunTree(runTree) { - this.runTreeMap.set(runTree.id, runTree); - let rootRun = runTree; - const visited = /* @__PURE__ */ new Set(); - while (rootRun.parent_run) { - if (visited.has(rootRun.id)) break; - visited.add(rootRun.id); - if (!rootRun.parent_run) break; - rootRun = rootRun.parent_run; - } - visited.clear(); - const queue = [rootRun]; - while (queue.length > 0) { - const current = queue.shift(); - if (!current || visited.has(current.id)) continue; - visited.add(current.id); - this.runTreeMap.set(current.id, current); - if (current.child_runs) queue.push(...current.child_runs); - } - this.client = runTree.client ?? this.client; - this.replicas = runTree.replicas ?? this.replicas; - this.projectName = runTree.project_name ?? this.projectName; - this.exampleId = runTree.reference_example_id ?? this.exampleId; - } - getRunTreeWithTracingConfig(id) { - const runTree = this.runTreeMap.get(id); - if (!runTree) return void 0; - return new run_trees_RunTree({ - ...runTree, - client: this.client, - project_name: this.projectName, - replicas: this.replicas, - reference_example_id: this.exampleId, - tracingEnabled: true - }); - } - static getTraceableRunTree() { - try { - return getCurrentRunTree(true); - } catch { - return void 0; - } - } -}; - -//#endregion - -//# sourceMappingURL=tracer_langchain.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/callbacks.js - - - - -//#region src/singletons/callbacks.ts -let queue; -/** -* Creates a queue using the p-queue library. The queue is configured to -* auto-start and has a concurrency of 1, meaning it will process tasks -* one at a time. -*/ -function createQueue() { - const PQueue = true ? p_queue_dist["default"] : p_queue_dist; - return new PQueue({ - autoStart: true, - concurrency: 1 - }); -} -function getQueue() { - if (typeof queue === "undefined") queue = createQueue(); - return queue; -} -/** -* Consume a promise, either adding it to the queue or waiting for it to resolve -* @param promiseFn Promise to consume -* @param wait Whether to wait for the promise to resolve or resolve immediately -*/ -async function consumeCallback(promiseFn, wait) { - if (wait === true) { - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance !== void 0) await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); - else await promiseFn(); - } else { - queue = getQueue(); - queue.add(async () => { - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance !== void 0) await asyncLocalStorageInstance.run(void 0, async () => promiseFn()); - else await promiseFn(); - }); - } -} -/** -* Waits for all promises in the queue to resolve. If the queue is -* undefined, it immediately resolves a promise. -*/ -async function awaitAllCallbacks() { - const defaultClient = getDefaultLangChainClientSingleton(); - await Promise.allSettled([typeof queue !== "undefined" ? queue.onIdle() : Promise.resolve(), defaultClient.awaitPendingTraceBatches()]); -} - -//#endregion - -//# sourceMappingURL=callbacks.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/promises.js - - - -//#region src/callbacks/promises.ts -var promises_exports = {}; -__export(promises_exports, { - awaitAllCallbacks: () => awaitAllCallbacks, - consumeCallback: () => consumeCallback -}); - -//#endregion - -//# sourceMappingURL=promises.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/callbacks.js - - -//#region src/utils/callbacks.ts -const callbacks_isTracingEnabled = (tracingEnabled) => { - if (tracingEnabled !== void 0) return tracingEnabled; - const envVars = [ - "LANGSMITH_TRACING_V2", - "LANGCHAIN_TRACING_V2", - "LANGSMITH_TRACING", - "LANGCHAIN_TRACING" - ]; - return !!envVars.find((envVar) => getEnvironmentVariable(envVar) === "true"); -}; - -//#endregion - -//# sourceMappingURL=callbacks.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/context.js - - - -//#region src/singletons/async_local_storage/context.ts -/** -* Set a context variable. Context variables are scoped to any -* child runnables called by the current runnable, or globally if set outside -* of any runnable. -* -* @remarks -* This function is only supported in environments that support AsyncLocalStorage, -* including Node.js, Deno, and Cloudflare Workers. -* -* @example -* ```ts -* import { RunnableLambda } from "@langchain/core/runnables"; -* import { -* getContextVariable, -* setContextVariable -* } from "@langchain/core/context"; -* -* const nested = RunnableLambda.from(() => { -* // "bar" because it was set by a parent -* console.log(getContextVariable("foo")); -* -* // Override to "baz", but only for child runnables -* setContextVariable("foo", "baz"); -* -* // Now "baz", but only for child runnables -* return getContextVariable("foo"); -* }); -* -* const runnable = RunnableLambda.from(async () => { -* // Set a context variable named "foo" -* setContextVariable("foo", "bar"); -* -* const res = await nested.invoke({}); -* -* // Still "bar" since child changes do not affect parents -* console.log(getContextVariable("foo")); -* -* return res; -* }); -* -* // undefined, because context variable has not been set yet -* console.log(getContextVariable("foo")); -* -* // Final return value is "baz" -* const result = await runnable.invoke({}); -* ``` -* -* @param name The name of the context variable. -* @param value The value to set. -*/ -function setContextVariable(name, value) { - const asyncLocalStorageInstance = getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance === void 0) throw new Error(`Internal error: Global shared async local storage instance has not been initialized.`); - const runTree = asyncLocalStorageInstance.getStore(); - const contextVars = { ...runTree?.[_CONTEXT_VARIABLES_KEY] }; - contextVars[name] = value; - let newValue = {}; - if (isRunTree(runTree)) newValue = new RunTree(runTree); - newValue[_CONTEXT_VARIABLES_KEY] = contextVars; - asyncLocalStorageInstance.enterWith(newValue); -} -/** -* Get the value of a previously set context variable. Context variables -* are scoped to any child runnables called by the current runnable, -* or globally if set outside of any runnable. -* -* @remarks -* This function is only supported in environments that support AsyncLocalStorage, -* including Node.js, Deno, and Cloudflare Workers. -* -* @example -* ```ts -* import { RunnableLambda } from "@langchain/core/runnables"; -* import { -* getContextVariable, -* setContextVariable -* } from "@langchain/core/context"; -* -* const nested = RunnableLambda.from(() => { -* // "bar" because it was set by a parent -* console.log(getContextVariable("foo")); -* -* // Override to "baz", but only for child runnables -* setContextVariable("foo", "baz"); -* -* // Now "baz", but only for child runnables -* return getContextVariable("foo"); -* }); -* -* const runnable = RunnableLambda.from(async () => { -* // Set a context variable named "foo" -* setContextVariable("foo", "bar"); -* -* const res = await nested.invoke({}); -* -* // Still "bar" since child changes do not affect parents -* console.log(getContextVariable("foo")); -* -* return res; -* }); -* -* // undefined, because context variable has not been set yet -* console.log(getContextVariable("foo")); -* -* // Final return value is "baz" -* const result = await runnable.invoke({}); -* ``` -* -* @param name The name of the context variable. -*/ -function getContextVariable(name) { - const asyncLocalStorageInstance = globals_getGlobalAsyncLocalStorageInstance(); - if (asyncLocalStorageInstance === void 0) return void 0; - const runTree = asyncLocalStorageInstance.getStore(); - return runTree?.[globals_CONTEXT_VARIABLES_KEY]?.[name]; -} -const LC_CONFIGURE_HOOKS_KEY = Symbol("lc:configure_hooks"); -const _getConfigureHooks = () => getContextVariable(LC_CONFIGURE_HOOKS_KEY) || []; -/** -* Register a callback configure hook to automatically add callback handlers to all runs. -* -* There are two ways to use this: -* -* 1. Using a context variable: -* - Set `contextVar` to specify the variable name -* - Use `setContextVariable()` to store your handler instance -* -* 2. Using an environment variable: -* - Set both `envVar` and `handlerClass` -* - The handler will be instantiated when the env var is set to "true". -* -* @example -* ```typescript -* // Method 1: Using context variable -* import { -* registerConfigureHook, -* setContextVariable -* } from "@langchain/core/context"; -* -* const tracer = new MyCallbackHandler(); -* registerConfigureHook({ -* contextVar: "my_tracer", -* }); -* setContextVariable("my_tracer", tracer); -* -* // ...run code here -* -* // Method 2: Using environment variable -* registerConfigureHook({ -* handlerClass: MyCallbackHandler, -* envVar: "MY_TRACER_ENABLED", -* }); -* process.env.MY_TRACER_ENABLED = "true"; -* -* // ...run code here -* ``` -* -* @param config Configuration object for the hook -* @param config.contextVar Name of the context variable containing the handler instance -* @param config.inheritable Whether child runs should inherit this handler -* @param config.handlerClass Optional callback handler class (required if using envVar) -* @param config.envVar Optional environment variable name to control handler activation -*/ -const registerConfigureHook = (config) => { - if (config.envVar && !config.handlerClass) throw new Error("If envVar is set, handlerClass must also be set to a non-None value."); - setContextVariable(LC_CONFIGURE_HOOKS_KEY, [..._getConfigureHooks(), config]); -}; - -//#endregion - -//# sourceMappingURL=context.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/callbacks/manager.js - - - - - - - - - - - - - -//#region src/callbacks/manager.ts -var manager_exports = {}; -__export(manager_exports, { - BaseCallbackManager: () => BaseCallbackManager, - BaseRunManager: () => BaseRunManager, - CallbackManager: () => CallbackManager, - CallbackManagerForChainRun: () => CallbackManagerForChainRun, - CallbackManagerForLLMRun: () => CallbackManagerForLLMRun, - CallbackManagerForRetrieverRun: () => CallbackManagerForRetrieverRun, - CallbackManagerForToolRun: () => CallbackManagerForToolRun, - ensureHandler: () => ensureHandler, - parseCallbackConfigArg: () => parseCallbackConfigArg -}); -function parseCallbackConfigArg(arg) { - if (!arg) return {}; - else if (Array.isArray(arg) || "name" in arg) return { callbacks: arg }; - else return arg; -} -/** -* Manage callbacks from different components of LangChain. -*/ -var BaseCallbackManager = class { - setHandler(handler) { - return this.setHandlers([handler]); - } -}; -/** -* Base class for run manager in LangChain. -*/ -var BaseRunManager = class { - constructor(runId, handlers, inheritableHandlers, tags, inheritableTags, metadata, inheritableMetadata, _parentRunId) { - this.runId = runId; - this.handlers = handlers; - this.inheritableHandlers = inheritableHandlers; - this.tags = tags; - this.inheritableTags = inheritableTags; - this.metadata = metadata; - this.inheritableMetadata = inheritableMetadata; - this._parentRunId = _parentRunId; - } - get parentRunId() { - return this._parentRunId; - } - async handleText(text) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - try { - await handler.handleText?.(text, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleText: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - async handleCustomEvent(eventName, data, _runId, _tags, _metadata) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - try { - await handler.handleCustomEvent?.(eventName, data, this.runId, this.tags, this.metadata); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } -}; -/** -* Manages callbacks for retriever runs. -*/ -var CallbackManagerForRetrieverRun = class extends BaseRunManager { - getChild(tag) { - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) manager.addTags([tag], false); - return manager; - } - async handleRetrieverEnd(documents) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) try { - await handler.handleRetrieverEnd?.(documents, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetriever`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - async handleRetrieverError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreRetriever) try { - await handler.handleRetrieverError?.(err, this.runId, this._parentRunId, this.tags); - } catch (error) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverError: ${error}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } -}; -var CallbackManagerForLLMRun = class extends BaseRunManager { - async handleLLMNewToken(token, idx, _runId, _parentRunId, _tags, fields) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) try { - await handler.handleLLMNewToken?.(token, idx ?? { - prompt: 0, - completion: 0 - }, this.runId, this._parentRunId, this.tags, fields); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMNewToken: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - async handleLLMError(err, _runId, _parentRunId, _tags, extraParams) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) try { - await handler.handleLLMError?.(err, this.runId, this._parentRunId, this.tags, extraParams); - } catch (err$1) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMError: ${err$1}`); - if (handler.raiseError) throw err$1; - } - }, handler.awaitHandlers))); - } - async handleLLMEnd(output, _runId, _parentRunId, _tags, extraParams) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreLLM) try { - await handler.handleLLMEnd?.(output, this.runId, this._parentRunId, this.tags, extraParams); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMEnd: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } -}; -var CallbackManagerForChainRun = class extends BaseRunManager { - getChild(tag) { - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) manager.addTags([tag], false); - return manager; - } - async handleChainError(err, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) try { - await handler.handleChainError?.(err, this.runId, this._parentRunId, this.tags, kwargs); - } catch (err$1) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainError: ${err$1}`); - if (handler.raiseError) throw err$1; - } - }, handler.awaitHandlers))); - } - async handleChainEnd(output, _runId, _parentRunId, _tags, kwargs) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreChain) try { - await handler.handleChainEnd?.(output, this.runId, this._parentRunId, this.tags, kwargs); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainEnd: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - async handleAgentAction(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) try { - await handler.handleAgentAction?.(action, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleAgentAction: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - async handleAgentEnd(action) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) try { - await handler.handleAgentEnd?.(action, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleAgentEnd: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } -}; -var CallbackManagerForToolRun = class extends BaseRunManager { - getChild(tag) { - const manager = new CallbackManager(this.runId); - manager.setHandlers(this.inheritableHandlers); - manager.addTags(this.inheritableTags); - manager.addMetadata(this.inheritableMetadata); - if (tag) manager.addTags([tag], false); - return manager; - } - async handleToolError(err) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) try { - await handler.handleToolError?.(err, this.runId, this._parentRunId, this.tags); - } catch (err$1) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolError: ${err$1}`); - if (handler.raiseError) throw err$1; - } - }, handler.awaitHandlers))); - } - async handleToolEnd(output) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreAgent) try { - await handler.handleToolEnd?.(output, this.runId, this._parentRunId, this.tags); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolEnd: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } -}; -/** -* @example -* ```typescript -* const prompt = PromptTemplate.fromTemplate("What is the answer to {question}?"); -* -* // Example of using LLMChain with OpenAI and a simple prompt -* const chain = new LLMChain({ -* llm: new ChatOpenAI({ model: "gpt-4o-mini", temperature: 0.9 }), -* prompt, -* }); -* -* // Running the chain with a single question -* const result = await chain.call({ -* question: "What is the airspeed velocity of an unladen swallow?", -* }); -* console.log("The answer is:", result); -* ``` -*/ -var CallbackManager = class CallbackManager extends BaseCallbackManager { - handlers = []; - inheritableHandlers = []; - tags = []; - inheritableTags = []; - metadata = {}; - inheritableMetadata = {}; - name = "callback_manager"; - _parentRunId; - constructor(parentRunId, options) { - super(); - this.handlers = options?.handlers ?? this.handlers; - this.inheritableHandlers = options?.inheritableHandlers ?? this.inheritableHandlers; - this.tags = options?.tags ?? this.tags; - this.inheritableTags = options?.inheritableTags ?? this.inheritableTags; - this.metadata = options?.metadata ?? this.metadata; - this.inheritableMetadata = options?.inheritableMetadata ?? this.inheritableMetadata; - this._parentRunId = parentRunId; - } - /** - * Gets the parent run ID, if any. - * - * @returns The parent run ID. - */ - getParentRunId() { - return this._parentRunId; - } - async handleLLMStart(llm, prompts, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - return Promise.all(prompts.map(async (prompt, idx) => { - const runId_ = idx === 0 && runId ? runId : v7(); - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreLLM) return; - if (isBaseTracer(handler)) handler._createRunForLLMStart(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - return consumeCallback(async () => { - try { - await handler.handleLLMStart?.(llm, [prompt], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); - } - async handleChatModelStart(llm, messages, runId = void 0, _parentRunId = void 0, extraParams = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - return Promise.all(messages.map(async (messageGroup, idx) => { - const runId_ = idx === 0 && runId ? runId : v7(); - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreLLM) return; - if (isBaseTracer(handler)) handler._createRunForChatModelStart(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - return consumeCallback(async () => { - try { - if (handler.handleChatModelStart) await handler.handleChatModelStart?.(llm, [messageGroup], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - else if (handler.handleLLMStart) { - const messageString = getBufferString(messageGroup); - await handler.handleLLMStart?.(llm, [messageString], runId_, this._parentRunId, extraParams, this.tags, this.metadata, runName); - } - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleLLMStart: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForLLMRun(runId_, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - })); - } - async handleChainStart(chain, inputs, runId = v7(), runType = void 0, _tags = void 0, _metadata = void 0, runName = void 0, _parentRunId = void 0, extra = void 0) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreChain) return; - if (isBaseTracer(handler)) handler._createRunForChainStart(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName, extra); - return consumeCallback(async () => { - try { - await handler.handleChainStart?.(chain, inputs, runId, this._parentRunId, this.tags, this.metadata, runType, runName, extra); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleChainStart: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForChainRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleToolStart(tool, input, runId = v7(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreAgent) return; - if (isBaseTracer(handler)) handler._createRunForToolStart(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); - return consumeCallback(async () => { - try { - await handler.handleToolStart?.(tool, input, runId, this._parentRunId, this.tags, this.metadata, runName); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleToolStart: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForToolRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleRetrieverStart(retriever, query, runId = v7(), _parentRunId = void 0, _tags = void 0, _metadata = void 0, runName = void 0) { - await Promise.all(this.handlers.map((handler) => { - if (handler.ignoreRetriever) return; - if (isBaseTracer(handler)) handler._createRunForRetrieverStart(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); - return consumeCallback(async () => { - try { - await handler.handleRetrieverStart?.(retriever, query, runId, this._parentRunId, this.tags, this.metadata, runName); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleRetrieverStart: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers); - })); - return new CallbackManagerForRetrieverRun(runId, this.handlers, this.inheritableHandlers, this.tags, this.inheritableTags, this.metadata, this.inheritableMetadata, this._parentRunId); - } - async handleCustomEvent(eventName, data, runId, _tags, _metadata) { - await Promise.all(this.handlers.map((handler) => consumeCallback(async () => { - if (!handler.ignoreCustomEvent) try { - await handler.handleCustomEvent?.(eventName, data, runId, this.tags, this.metadata); - } catch (err) { - const logFunction = handler.raiseError ? console.error : console.warn; - logFunction(`Error in handler ${handler.constructor.name}, handleCustomEvent: ${err}`); - if (handler.raiseError) throw err; - } - }, handler.awaitHandlers))); - } - addHandler(handler, inherit = true) { - this.handlers.push(handler); - if (inherit) this.inheritableHandlers.push(handler); - } - removeHandler(handler) { - this.handlers = this.handlers.filter((_handler) => _handler !== handler); - this.inheritableHandlers = this.inheritableHandlers.filter((_handler) => _handler !== handler); - } - setHandlers(handlers, inherit = true) { - this.handlers = []; - this.inheritableHandlers = []; - for (const handler of handlers) this.addHandler(handler, inherit); - } - addTags(tags, inherit = true) { - this.removeTags(tags); - this.tags.push(...tags); - if (inherit) this.inheritableTags.push(...tags); - } - removeTags(tags) { - this.tags = this.tags.filter((tag) => !tags.includes(tag)); - this.inheritableTags = this.inheritableTags.filter((tag) => !tags.includes(tag)); - } - addMetadata(metadata, inherit = true) { - this.metadata = { - ...this.metadata, - ...metadata - }; - if (inherit) this.inheritableMetadata = { - ...this.inheritableMetadata, - ...metadata - }; - } - removeMetadata(metadata) { - for (const key of Object.keys(metadata)) { - delete this.metadata[key]; - delete this.inheritableMetadata[key]; - } - } - copy(additionalHandlers = [], inherit = true) { - const manager = new CallbackManager(this._parentRunId); - for (const handler of this.handlers) { - const inheritable = this.inheritableHandlers.includes(handler); - manager.addHandler(handler, inheritable); - } - for (const tag of this.tags) { - const inheritable = this.inheritableTags.includes(tag); - manager.addTags([tag], inheritable); - } - for (const key of Object.keys(this.metadata)) { - const inheritable = Object.keys(this.inheritableMetadata).includes(key); - manager.addMetadata({ [key]: this.metadata[key] }, inheritable); - } - for (const handler of additionalHandlers) { - if (manager.handlers.filter((h) => h.name === "console_callback_handler").some((h) => h.name === handler.name)) continue; - manager.addHandler(handler, inherit); - } - return manager; - } - static fromHandlers(handlers) { - class Handler extends BaseCallbackHandler { - name = v7(); - constructor() { - super(); - Object.assign(this, handlers); - } - } - const manager = new this(); - manager.addHandler(new Handler()); - return manager; - } - static configure(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { - return this._configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options); - } - static _configureSync(inheritableHandlers, localHandlers, inheritableTags, localTags, inheritableMetadata, localMetadata, options) { - let callbackManager; - if (inheritableHandlers || localHandlers) { - if (Array.isArray(inheritableHandlers) || !inheritableHandlers) { - callbackManager = new CallbackManager(); - callbackManager.setHandlers(inheritableHandlers?.map(ensureHandler) ?? [], true); - } else callbackManager = inheritableHandlers; - callbackManager = callbackManager.copy(Array.isArray(localHandlers) ? localHandlers.map(ensureHandler) : localHandlers?.handlers, false); - } - const verboseEnabled = getEnvironmentVariable("LANGCHAIN_VERBOSE") === "true" || options?.verbose; - const tracingV2Enabled = LangChainTracer.getTraceableRunTree()?.tracingEnabled || callbacks_isTracingEnabled(); - const tracingEnabled = tracingV2Enabled || (getEnvironmentVariable("LANGCHAIN_TRACING") ?? false); - if (verboseEnabled || tracingEnabled) { - if (!callbackManager) callbackManager = new CallbackManager(); - if (verboseEnabled && !callbackManager.handlers.some((handler) => handler.name === ConsoleCallbackHandler.prototype.name)) { - const consoleHandler = new ConsoleCallbackHandler(); - callbackManager.addHandler(consoleHandler, true); - } - if (tracingEnabled && !callbackManager.handlers.some((handler) => handler.name === "langchain_tracer")) { - if (tracingV2Enabled) { - const tracerV2 = new LangChainTracer(); - callbackManager.addHandler(tracerV2, true); - } - } - if (tracingV2Enabled) { - const implicitRunTree = LangChainTracer.getTraceableRunTree(); - if (implicitRunTree && callbackManager._parentRunId === void 0) { - callbackManager._parentRunId = implicitRunTree.id; - const tracerV2 = callbackManager.handlers.find((handler) => handler.name === "langchain_tracer"); - tracerV2?.updateFromRunTree(implicitRunTree); - } - } - } - for (const { contextVar, inheritable = true, handlerClass, envVar } of _getConfigureHooks()) { - const createIfNotInContext = envVar && getEnvironmentVariable(envVar) === "true" && handlerClass; - let handler; - const contextVarValue = contextVar !== void 0 ? getContextVariable(contextVar) : void 0; - if (contextVarValue && isBaseCallbackHandler(contextVarValue)) handler = contextVarValue; - else if (createIfNotInContext) handler = new handlerClass({}); - if (handler !== void 0) { - if (!callbackManager) callbackManager = new CallbackManager(); - if (!callbackManager.handlers.some((h) => h.name === handler.name)) callbackManager.addHandler(handler, inheritable); - } - } - if (inheritableTags || localTags) { - if (callbackManager) { - callbackManager.addTags(inheritableTags ?? []); - callbackManager.addTags(localTags ?? [], false); - } - } - if (inheritableMetadata || localMetadata) { - if (callbackManager) { - callbackManager.addMetadata(inheritableMetadata ?? {}); - callbackManager.addMetadata(localMetadata ?? {}, false); - } - } - return callbackManager; - } -}; -function ensureHandler(handler) { - if ("name" in handler) return handler; - return BaseCallbackHandler.fromMethods(handler); -} - -//#endregion - -//# sourceMappingURL=manager.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/async_local_storage/index.js - - - - -//#region src/singletons/async_local_storage/index.ts -var async_local_storage_MockAsyncLocalStorage = class { - getStore() { - return void 0; - } - run(_store, callback) { - return callback(); - } - enterWith(_store) { - return void 0; - } -}; -const async_local_storage_mockAsyncLocalStorage = new async_local_storage_MockAsyncLocalStorage(); -const LC_CHILD_KEY = Symbol.for("lc:child_config"); -var async_local_storage_AsyncLocalStorageProvider = class { - getInstance() { - return globals_getGlobalAsyncLocalStorageInstance() ?? async_local_storage_mockAsyncLocalStorage; - } - getRunnableConfig() { - const storage = this.getInstance(); - return storage.getStore()?.extra?.[LC_CHILD_KEY]; - } - runWithConfig(config, callback, avoidCreatingRootRunTree) { - const callbackManager = CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata); - const storage = this.getInstance(); - const previousValue = storage.getStore(); - const parentRunId = callbackManager?.getParentRunId(); - const langChainTracer = callbackManager?.handlers?.find((handler) => handler?.name === "langchain_tracer"); - let runTree; - if (langChainTracer && parentRunId) runTree = langChainTracer.getRunTreeWithTracingConfig(parentRunId); - else if (!avoidCreatingRootRunTree) runTree = new run_trees_RunTree({ - name: "", - tracingEnabled: false - }); - if (runTree) runTree.extra = { - ...runTree.extra, - [LC_CHILD_KEY]: config - }; - if (previousValue !== void 0 && previousValue[globals_CONTEXT_VARIABLES_KEY] !== void 0) { - if (runTree === void 0) runTree = {}; - runTree[globals_CONTEXT_VARIABLES_KEY] = previousValue[globals_CONTEXT_VARIABLES_KEY]; - } - return storage.run(runTree, callback); - } - initializeGlobalInstance(instance) { - if (globals_getGlobalAsyncLocalStorageInstance() === void 0) setGlobalAsyncLocalStorageInstance(instance); - } -}; -const async_local_storage_AsyncLocalStorageProviderSingleton = new async_local_storage_AsyncLocalStorageProvider(); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/singletons/index.js - - - - -//#region src/singletons/index.ts -var singletons_exports = {}; -__export(singletons_exports, { - AsyncLocalStorageProviderSingleton: () => async_local_storage_AsyncLocalStorageProviderSingleton, - MockAsyncLocalStorage: () => async_local_storage_MockAsyncLocalStorage, - _CONTEXT_VARIABLES_KEY: () => globals_CONTEXT_VARIABLES_KEY -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: external "node:async_hooks" -const external_node_async_hooks_namespaceObject = __WEBPACK_EXTERNAL_createRequire(import.meta.url)("node:async_hooks"); -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/setup/async_local_storage.js - - - -//#region src/setup/async_local_storage.ts -function initializeAsyncLocalStorageSingleton() { - async_local_storage_AsyncLocalStorageProviderSingleton.initializeGlobalInstance(new external_node_async_hooks_namespaceObject.AsyncLocalStorage()); -} - -//#endregion - -//# sourceMappingURL=async_local_storage.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/errors.js -//#region src/errors.ts -/** @category Errors */ -var BaseLangGraphError = class extends Error { - lc_error_code; - constructor(message, fields) { - let finalMessage = message ?? ""; - if (fields?.lc_error_code) finalMessage = `${finalMessage}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langgraph/${fields.lc_error_code}/\n`; - super(finalMessage); - this.lc_error_code = fields?.lc_error_code; - } -}; -var GraphBubbleUp = class extends BaseLangGraphError { - get is_bubble_up() { - return true; - } -}; -var GraphRecursionError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "GraphRecursionError"; - } - static get unminifiable_name() { - return "GraphRecursionError"; - } -}; -var GraphValueError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "GraphValueError"; - } - static get unminifiable_name() { - return "GraphValueError"; - } -}; -var GraphInterrupt = class extends GraphBubbleUp { - interrupts; - constructor(interrupts, fields) { - super(JSON.stringify(interrupts, null, 2), fields); - this.name = "GraphInterrupt"; - this.interrupts = interrupts ?? []; - } - static get unminifiable_name() { - return "GraphInterrupt"; - } -}; -/** Raised by a node to interrupt execution. */ -var NodeInterrupt = class extends GraphInterrupt { - constructor(message, fields) { - super([{ value: message }], fields); - this.name = "NodeInterrupt"; - } - static get unminifiable_name() { - return "NodeInterrupt"; - } -}; -var ParentCommand = class extends GraphBubbleUp { - command; - constructor(command) { - super(); - this.name = "ParentCommand"; - this.command = command; - } - static get unminifiable_name() { - return "ParentCommand"; - } -}; -function isParentCommand(e) { - return e !== void 0 && e.name === ParentCommand.unminifiable_name; -} -function isGraphBubbleUp(e) { - return e !== void 0 && e.is_bubble_up === true; -} -function isGraphInterrupt(e) { - return e !== void 0 && [GraphInterrupt.unminifiable_name, NodeInterrupt.unminifiable_name].includes(e.name); -} -var EmptyInputError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "EmptyInputError"; - } - static get unminifiable_name() { - return "EmptyInputError"; - } -}; -var EmptyChannelError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "EmptyChannelError"; - } - static get unminifiable_name() { - return "EmptyChannelError"; - } -}; -var InvalidUpdateError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "InvalidUpdateError"; - } - static get unminifiable_name() { - return "InvalidUpdateError"; - } -}; -/** -* @deprecated This exception type is no longer thrown. -*/ -var MultipleSubgraphsError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "MultipleSubgraphError"; - } - static get unminifiable_name() { - return "MultipleSubgraphError"; - } -}; -var UnreachableNodeError = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "UnreachableNodeError"; - } - static get unminifiable_name() { - return "UnreachableNodeError"; - } -}; -/** -* Exception raised when an error occurs in the remote graph. -*/ -var RemoteException = class extends BaseLangGraphError { - constructor(message, fields) { - super(message, fields); - this.name = "RemoteException"; - } - static get unminifiable_name() { - return "RemoteException"; - } -}; -/** -* Used for subgraph detection. -*/ -const getSubgraphsSeenSet = () => { - if (globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] === void 0) globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")] = /* @__PURE__ */ new Set(); - return globalThis[Symbol.for("LG_CHECKPOINT_SEEN_NS_SET")]; -}; - -//#endregion - -//# sourceMappingURL=errors.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/id.js - - -//#region src/id.ts -function uuid6(clockseq) { - return v6({ clockseq }); -} -function uuid5(name, namespace) { - const namespaceBytes = namespace.replace(/-/g, "").match(/.{2}/g).map((byte) => parseInt(byte, 16)); - return v5(name, new Uint8Array(namespaceBytes)); -} - -//#endregion - -//# sourceMappingURL=id.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/serde/types.js -//#region src/serde/types.ts -const TASKS = "__pregel_tasks"; -const types_ERROR = "__error__"; -const SCHEDULED = "__scheduled__"; -const INTERRUPT = "__interrupt__"; -const RESUME = "__resume__"; - -//#endregion - -//# sourceMappingURL=types.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/serde/utils/fast-safe-stringify/index.js -//#region src/serde/utils/fast-safe-stringify/index.ts -var fast_safe_stringify_LIMIT_REPLACE_NODE = "[...]"; -var fast_safe_stringify_CIRCULAR_REPLACE_NODE = "[Circular]"; -var fast_safe_stringify_arr = []; -var fast_safe_stringify_replacerStack = []; -function fast_safe_stringify_defaultOptions() { - return { - depthLimit: Number.MAX_SAFE_INTEGER, - edgesLimit: Number.MAX_SAFE_INTEGER - }; -} -function fast_safe_stringify_stringify(obj, replacer, spacer, options) { - if (typeof options === "undefined") options = fast_safe_stringify_defaultOptions(); - fast_safe_stringify_decirc(obj, "", 0, [], void 0, 0, options); - var res; - try { - if (fast_safe_stringify_replacerStack.length === 0) res = JSON.stringify(obj, replacer, spacer); - else res = JSON.stringify(obj, fast_safe_stringify_replaceGetterValues(replacer), spacer); - } catch (_) { - return JSON.stringify("[unable to serialize, circular reference is too complex to analyze]"); - } finally { - while (fast_safe_stringify_arr.length !== 0) { - var part = fast_safe_stringify_arr.pop(); - if (part.length === 4) Object.defineProperty(part[0], part[1], part[3]); - else part[0][part[1]] = part[2]; - } - } - return res; -} -function fast_safe_stringify_setReplace(replace, val, k, parent) { - var propertyDescriptor = Object.getOwnPropertyDescriptor(parent, k); - if (propertyDescriptor.get !== void 0) if (propertyDescriptor.configurable) { - Object.defineProperty(parent, k, { value: replace }); - fast_safe_stringify_arr.push([ - parent, - k, - val, - propertyDescriptor - ]); - } else fast_safe_stringify_replacerStack.push([ - val, - k, - replace - ]); - else { - parent[k] = replace; - fast_safe_stringify_arr.push([ - parent, - k, - val - ]); - } -} -function fast_safe_stringify_decirc(val, k, edgeIndex, stack, parent, depth, options) { - depth += 1; - var i; - if (typeof val === "object" && val !== null) { - for (i = 0; i < stack.length; i++) if (stack[i] === val) { - fast_safe_stringify_setReplace(fast_safe_stringify_CIRCULAR_REPLACE_NODE, val, k, parent); - return; - } - if (typeof options.depthLimit !== "undefined" && depth > options.depthLimit) { - fast_safe_stringify_setReplace(fast_safe_stringify_LIMIT_REPLACE_NODE, val, k, parent); - return; - } - if (typeof options.edgesLimit !== "undefined" && edgeIndex + 1 > options.edgesLimit) { - fast_safe_stringify_setReplace(fast_safe_stringify_LIMIT_REPLACE_NODE, val, k, parent); - return; - } - stack.push(val); - if (Array.isArray(val)) for (i = 0; i < val.length; i++) fast_safe_stringify_decirc(val[i], i, i, stack, val, depth, options); - else { - var keys = Object.keys(val); - for (i = 0; i < keys.length; i++) { - var key = keys[i]; - fast_safe_stringify_decirc(val[key], key, i, stack, val, depth, options); - } - } - stack.pop(); - } -} -function fast_safe_stringify_replaceGetterValues(replacer) { - replacer = typeof replacer !== "undefined" ? replacer : function(k, v) { - return v; - }; - return function(key, val) { - if (fast_safe_stringify_replacerStack.length > 0) for (var i = 0; i < fast_safe_stringify_replacerStack.length; i++) { - var part = fast_safe_stringify_replacerStack[i]; - if (part[1] === key && part[0] === val) { - val = part[2]; - fast_safe_stringify_replacerStack.splice(i, 1); - break; - } - } - return replacer.call(this, key, val); - }; -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/import_constants.js -//#region src/load/import_constants.ts -/** Auto-generated by import-constants plugin. Do not edit manually */ -const optionalImportEntrypoints = []; - -//#endregion - -//# sourceMappingURL=import_constants.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/agents.js -//#region src/agents.ts -var agents_exports = {}; - -//#endregion - -//# sourceMappingURL=agents.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/config.js - - - - -//#region src/runnables/config.ts -const DEFAULT_RECURSION_LIMIT = 25; -async function getCallbackManagerForConfig(config) { - return CallbackManager._configureSync(config?.callbacks, void 0, config?.tags, void 0, config?.metadata); -} -function mergeConfigs(...configs) { - const copy = {}; - for (const options of configs.filter((c) => !!c)) for (const key of Object.keys(options)) if (key === "metadata") copy[key] = { - ...copy[key], - ...options[key] - }; - else if (key === "tags") { - const baseKeys = copy[key] ?? []; - copy[key] = [...new Set(baseKeys.concat(options[key] ?? []))]; - } else if (key === "configurable") copy[key] = { - ...copy[key], - ...options[key] - }; - else if (key === "timeout") { - if (copy.timeout === void 0) copy.timeout = options.timeout; - else if (options.timeout !== void 0) copy.timeout = Math.min(copy.timeout, options.timeout); - } else if (key === "signal") { - if (copy.signal === void 0) copy.signal = options.signal; - else if (options.signal !== void 0) if ("any" in AbortSignal) copy.signal = AbortSignal.any([copy.signal, options.signal]); - else copy.signal = options.signal; - } else if (key === "callbacks") { - const baseCallbacks = copy.callbacks; - const providedCallbacks = options.callbacks; - if (Array.isArray(providedCallbacks)) if (!baseCallbacks) copy.callbacks = providedCallbacks; - else if (Array.isArray(baseCallbacks)) copy.callbacks = baseCallbacks.concat(providedCallbacks); - else { - const manager = baseCallbacks.copy(); - for (const callback of providedCallbacks) manager.addHandler(ensureHandler(callback), true); - copy.callbacks = manager; - } - else if (providedCallbacks) if (!baseCallbacks) copy.callbacks = providedCallbacks; - else if (Array.isArray(baseCallbacks)) { - const manager = providedCallbacks.copy(); - for (const callback of baseCallbacks) manager.addHandler(ensureHandler(callback), true); - copy.callbacks = manager; - } else copy.callbacks = new CallbackManager(providedCallbacks._parentRunId, { - handlers: baseCallbacks.handlers.concat(providedCallbacks.handlers), - inheritableHandlers: baseCallbacks.inheritableHandlers.concat(providedCallbacks.inheritableHandlers), - tags: Array.from(new Set(baseCallbacks.tags.concat(providedCallbacks.tags))), - inheritableTags: Array.from(new Set(baseCallbacks.inheritableTags.concat(providedCallbacks.inheritableTags))), - metadata: { - ...baseCallbacks.metadata, - ...providedCallbacks.metadata - } - }); - } else { - const typedKey = key; - copy[typedKey] = options[typedKey] ?? copy[typedKey]; - } - return copy; -} -const PRIMITIVES = new Set([ - "string", - "number", - "boolean" -]); -/** -* Ensure that a passed config is an object with all required keys present. -*/ -function ensureConfig(config) { - const implicitConfig = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); - let empty = { - tags: [], - metadata: {}, - recursionLimit: 25, - runId: void 0 - }; - if (implicitConfig) { - const { runId, runName,...rest } = implicitConfig; - empty = Object.entries(rest).reduce((currentConfig, [key, value]) => { - if (value !== void 0) currentConfig[key] = value; - return currentConfig; - }, empty); - } - if (config) empty = Object.entries(config).reduce((currentConfig, [key, value]) => { - if (value !== void 0) currentConfig[key] = value; - return currentConfig; - }, empty); - if (empty?.configurable) { - for (const key of Object.keys(empty.configurable)) if (PRIMITIVES.has(typeof empty.configurable[key]) && !empty.metadata?.[key]) { - if (!empty.metadata) empty.metadata = {}; - empty.metadata[key] = empty.configurable[key]; - } - } - if (empty.timeout !== void 0) { - if (empty.timeout <= 0) throw new Error("Timeout must be a positive number"); - const originalTimeoutMs = empty.timeout; - const timeoutSignal = AbortSignal.timeout(originalTimeoutMs); - if (!empty.metadata) empty.metadata = {}; - if (empty.metadata.timeoutMs === void 0) empty.metadata.timeoutMs = originalTimeoutMs; - if (empty.signal !== void 0) { - if ("any" in AbortSignal) empty.signal = AbortSignal.any([empty.signal, timeoutSignal]); - } else empty.signal = timeoutSignal; - /** - * We are deleting the timeout key for the following reasons: - * - Idempotent normalization: ensureConfig may be called multiple times down the stack. If timeout remains, - * each call would synthesize new timeout signals and combine them, changing the effective timeout unpredictably. - * - Single enforcement path: downstream code relies on signal to enforce cancellation. Leaving timeout means two - * competing mechanisms (numeric timeout and signal) can be applied, sometimes with different semantics. - * - Propagation to children: pickRunnableConfigKeys would keep forwarding timeout to nested runnables, causing - * repeated re-normalization and stacked timeouts. - * - Backward compatibility: a lot of components and tests assume ensureConfig removes timeout post-normalization; - * changing that would be a breaking change. - */ - delete empty.timeout; - } - return empty; -} -/** -* Helper function that patches runnable configs with updated properties. -*/ -function config_patchConfig(config = {}, { callbacks, maxConcurrency, recursionLimit, runName, configurable, runId } = {}) { - const newConfig = ensureConfig(config); - if (callbacks !== void 0) { - /** - * If we're replacing callbacks we need to unset runName - * since that should apply only to the same run as the original callbacks - */ - delete newConfig.runName; - newConfig.callbacks = callbacks; - } - if (recursionLimit !== void 0) newConfig.recursionLimit = recursionLimit; - if (maxConcurrency !== void 0) newConfig.maxConcurrency = maxConcurrency; - if (runName !== void 0) newConfig.runName = runName; - if (configurable !== void 0) newConfig.configurable = { - ...newConfig.configurable, - ...configurable - }; - if (runId !== void 0) delete newConfig.runId; - return newConfig; -} -function config_pickRunnableConfigKeys(config) { - if (!config) return void 0; - return { - configurable: config.configurable, - recursionLimit: config.recursionLimit, - callbacks: config.callbacks, - tags: config.tags, - metadata: config.metadata, - maxConcurrency: config.maxConcurrency, - timeout: config.timeout, - signal: config.signal, - store: config.store - }; -} - -//#endregion - -//# sourceMappingURL=config.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/signal.js -//#region src/utils/signal.ts -/** -* Race a promise with an abort signal. If the signal is aborted, the promise will -* be rejected with the error from the signal. If the promise is rejected, the signal will be aborted. -* -* @param promise - The promise to race. -* @param signal - The abort signal. -* @returns The result of the promise. -*/ -async function raceWithSignal(promise, signal) { - if (signal === void 0) return promise; - let listener; - return Promise.race([promise.catch((err) => { - if (!signal?.aborted) throw err; - else return void 0; - }), new Promise((_, reject) => { - listener = () => { - reject(getAbortSignalError(signal)); - }; - signal.addEventListener("abort", listener); - if (signal.aborted) reject(getAbortSignalError(signal)); - })]).finally(() => signal.removeEventListener("abort", listener)); -} -/** -* Get the error from an abort signal. Since you can set the reason to anything, -* we have to do some type gymnastics to get a proper error message. -* -* @param signal - The abort signal. -* @returns The error from the abort signal. -*/ -function getAbortSignalError(signal) { - if (signal?.reason instanceof Error) return signal.reason; - if (typeof signal?.reason === "string") return new Error(signal.reason); - return /* @__PURE__ */ new Error("Aborted"); -} - -//#endregion - -//# sourceMappingURL=signal.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/stream.js - - - - - - -//#region src/utils/stream.ts -var stream_exports = {}; -__export(stream_exports, { - AsyncGeneratorWithSetup: () => AsyncGeneratorWithSetup, - IterableReadableStream: () => IterableReadableStream, - atee: () => atee, - concat: () => concat, - pipeGeneratorWithSetup: () => pipeGeneratorWithSetup -}); -var IterableReadableStream = class IterableReadableStream extends ReadableStream { - reader; - ensureReader() { - if (!this.reader) this.reader = this.getReader(); - } - async next() { - this.ensureReader(); - try { - const result = await this.reader.read(); - if (result.done) { - this.reader.releaseLock(); - return { - done: true, - value: void 0 - }; - } else return { - done: false, - value: result.value - }; - } catch (e) { - this.reader.releaseLock(); - throw e; - } - } - async return() { - this.ensureReader(); - if (this.locked) { - const cancelPromise = this.reader.cancel(); - this.reader.releaseLock(); - await cancelPromise; - } - return { - done: true, - value: void 0 - }; - } - async throw(e) { - this.ensureReader(); - if (this.locked) { - const cancelPromise = this.reader.cancel(); - this.reader.releaseLock(); - await cancelPromise; - } - throw e; - } - [Symbol.asyncIterator]() { - return this; - } - async [Symbol.asyncDispose]() { - await this.return(); - } - static fromReadableStream(stream) { - const reader = stream.getReader(); - return new IterableReadableStream({ - start(controller) { - return pump(); - function pump() { - return reader.read().then(({ done, value }) => { - if (done) { - controller.close(); - return; - } - controller.enqueue(value); - return pump(); - }); - } - }, - cancel() { - reader.releaseLock(); - } - }); - } - static fromAsyncGenerator(generator) { - return new IterableReadableStream({ - async pull(controller) { - const { value, done } = await generator.next(); - if (done) controller.close(); - controller.enqueue(value); - }, - async cancel(reason) { - await generator.return(reason); - } - }); - } -}; -function atee(iter, length = 2) { - const buffers = Array.from({ length }, () => []); - return buffers.map(async function* makeIter(buffer) { - while (true) if (buffer.length === 0) { - const result = await iter.next(); - for (const buffer$1 of buffers) buffer$1.push(result); - } else if (buffer[0].done) return; - else yield buffer.shift().value; - }); -} -function concat(first, second) { - if (Array.isArray(first) && Array.isArray(second)) return first.concat(second); - else if (typeof first === "string" && typeof second === "string") return first + second; - else if (typeof first === "number" && typeof second === "number") return first + second; - else if ("concat" in first && typeof first.concat === "function") return first.concat(second); - else if (typeof first === "object" && typeof second === "object") { - const chunk = { ...first }; - for (const [key, value] of Object.entries(second)) if (key in chunk && !Array.isArray(chunk[key])) chunk[key] = concat(chunk[key], value); - else chunk[key] = value; - return chunk; - } else throw new Error(`Cannot concat ${typeof first} and ${typeof second}`); -} -var AsyncGeneratorWithSetup = class { - generator; - setup; - config; - signal; - firstResult; - firstResultUsed = false; - constructor(params) { - this.generator = params.generator; - this.config = params.config; - this.signal = params.signal ?? this.config?.signal; - this.setup = new Promise((resolve, reject) => { - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(params.config), async () => { - this.firstResult = params.generator.next(); - if (params.startSetup) this.firstResult.then(params.startSetup).then(resolve, reject); - else this.firstResult.then((_result) => resolve(void 0), reject); - }, true); - }); - } - async next(...args) { - this.signal?.throwIfAborted(); - if (!this.firstResultUsed) { - this.firstResultUsed = true; - return this.firstResult; - } - return async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(this.config), this.signal ? async () => { - return raceWithSignal(this.generator.next(...args), this.signal); - } : async () => { - return this.generator.next(...args); - }, true); - } - async return(value) { - return this.generator.return(value); - } - async throw(e) { - return this.generator.throw(e); - } - [Symbol.asyncIterator]() { - return this; - } - async [Symbol.asyncDispose]() { - await this.return(); - } -}; -async function pipeGeneratorWithSetup(to, generator, startSetup, signal, ...args) { - const gen = new AsyncGeneratorWithSetup({ - generator, - startSetup, - signal - }); - const setup = await gen.setup; - return { - output: to(gen, setup, ...args), - setup - }; -} - -//#endregion - -//# sourceMappingURL=stream.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/helpers.js -//#region src/utils/fast-json-patch/src/helpers.ts -/*! -* https://github.com/Starcounter-Jack/JSON-Patch -* (c) 2017-2022 Joachim Wester -* MIT licensed -*/ -const _hasOwnProperty = Object.prototype.hasOwnProperty; -function helpers_hasOwnProperty(obj, key) { - return _hasOwnProperty.call(obj, key); -} -function _objectKeys(obj) { - if (Array.isArray(obj)) { - const keys$1 = new Array(obj.length); - for (let k = 0; k < keys$1.length; k++) keys$1[k] = "" + k; - return keys$1; - } - if (Object.keys) return Object.keys(obj); - let keys = []; - for (let i in obj) if (helpers_hasOwnProperty(obj, i)) keys.push(i); - return keys; -} -/** -* Deeply clone the object. -* https://jsperf.com/deep-copy-vs-json-stringify-json-parse/25 (recursiveDeepCopy) -* @param {any} obj value to clone -* @return {any} cloned obj -*/ -function _deepClone(obj) { - switch (typeof obj) { - case "object": return JSON.parse(JSON.stringify(obj)); - case "undefined": return null; - default: return obj; - } -} -function isInteger(str) { - let i = 0; - const len = str.length; - let charCode; - while (i < len) { - charCode = str.charCodeAt(i); - if (charCode >= 48 && charCode <= 57) { - i++; - continue; - } - return false; - } - return true; -} -/** -* Escapes a json pointer path -* @param path The raw pointer -* @return the Escaped path -*/ -function escapePathComponent(path) { - if (path.indexOf("/") === -1 && path.indexOf("~") === -1) return path; - return path.replace(/~/g, "~0").replace(/\//g, "~1"); -} -/** -* Unescapes a json pointer path -* @param path The escaped pointer -* @return The unescaped path -*/ -function unescapePathComponent(path) { - return path.replace(/~1/g, "/").replace(/~0/g, "~"); -} -/** -* Recursively checks whether an object has any undefined values inside. -*/ -function hasUndefined(obj) { - if (obj === void 0) return true; - if (obj) { - if (Array.isArray(obj)) { - for (let i$1 = 0, len = obj.length; i$1 < len; i$1++) if (hasUndefined(obj[i$1])) return true; - } else if (typeof obj === "object") { - const objKeys = _objectKeys(obj); - const objKeysLength = objKeys.length; - for (var i = 0; i < objKeysLength; i++) if (hasUndefined(obj[objKeys[i]])) return true; - } - } - return false; -} -function patchErrorMessageFormatter(message, args) { - const messageParts = [message]; - for (const key in args) { - const value = typeof args[key] === "object" ? JSON.stringify(args[key], null, 2) : args[key]; - if (typeof value !== "undefined") messageParts.push(`${key}: ${value}`); - } - return messageParts.join("\n"); -} -var PatchError = class extends Error { - constructor(message, name, index, operation, tree) { - super(patchErrorMessageFormatter(message, { - name, - index, - operation, - tree - })); - this.name = name; - this.index = index; - this.operation = operation; - this.tree = tree; - Object.setPrototypeOf(this, new.target.prototype); - this.message = patchErrorMessageFormatter(message, { - name, - index, - operation, - tree - }); - } -}; - -//#endregion - -//# sourceMappingURL=helpers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/core.js - - - -//#region src/utils/fast-json-patch/src/core.ts -var core_exports = {}; -__export(core_exports, { - JsonPatchError: () => JsonPatchError, - _areEquals: () => _areEquals, - applyOperation: () => applyOperation, - applyPatch: () => applyPatch, - applyReducer: () => applyReducer, - deepClone: () => deepClone, - getValueByPointer: () => getValueByPointer, - validate: () => core_validate, - validator: () => validator -}); -const JsonPatchError = PatchError; -const deepClone = _deepClone; -/** -* Check if a key is a dangerous prototype property that could lead to prototype pollution. -* This provides defense-in-depth alongside the check in applyOperation. -*/ -function isDangerousKey(key) { - return Object.getOwnPropertyNames(Object.prototype).includes(key); -} -const objOps = { - add: function(obj, key, document) { - if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons"); - obj[key] = this.value; - return { newDocument: document }; - }, - remove: function(obj, key, document) { - if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons"); - var removed = obj[key]; - delete obj[key]; - return { - newDocument: document, - removed - }; - }, - replace: function(obj, key, document) { - if (isDangerousKey(key)) throw new TypeError("JSON-Patch: modifying `__proto__`, `constructor`, or `prototype` prop is banned for security reasons"); - var removed = obj[key]; - obj[key] = this.value; - return { - newDocument: document, - removed - }; - }, - move: function(obj, key, document) { - let removed = getValueByPointer(document, this.path); - if (removed) removed = _deepClone(removed); - const originalValue = applyOperation(document, { - op: "remove", - path: this.from - }).removed; - applyOperation(document, { - op: "add", - path: this.path, - value: originalValue - }); - return { - newDocument: document, - removed - }; - }, - copy: function(obj, key, document) { - const valueToCopy = getValueByPointer(document, this.from); - applyOperation(document, { - op: "add", - path: this.path, - value: _deepClone(valueToCopy) - }); - return { newDocument: document }; - }, - test: function(obj, key, document) { - return { - newDocument: document, - test: _areEquals(obj[key], this.value) - }; - }, - _get: function(obj, key, document) { - this.value = obj[key]; - return { newDocument: document }; - } -}; -var arrOps = { - add: function(arr, i, document) { - if (isInteger(i)) arr.splice(i, 0, this.value); - else arr[i] = this.value; - return { - newDocument: document, - index: i - }; - }, - remove: function(arr, i, document) { - var removedList = arr.splice(i, 1); - return { - newDocument: document, - removed: removedList[0] - }; - }, - replace: function(arr, i, document) { - var removed = arr[i]; - arr[i] = this.value; - return { - newDocument: document, - removed - }; - }, - move: objOps.move, - copy: objOps.copy, - test: objOps.test, - _get: objOps._get -}; -/** -* Retrieves a value from a JSON document by a JSON pointer. -* Returns the value. -* -* @param document The document to get the value from -* @param pointer an escaped JSON pointer -* @return The retrieved value -*/ -function getValueByPointer(document, pointer) { - if (pointer == "") return document; - var getOriginalDestination = { - op: "_get", - path: pointer - }; - applyOperation(document, getOriginalDestination); - return getOriginalDestination.value; -} -/** -* Apply a single JSON Patch Operation on a JSON document. -* Returns the {newDocument, result} of the operation. -* It modifies the `document` and `operation` objects - it gets the values by reference. -* If you would like to avoid touching your values, clone them: -* `jsonpatch.applyOperation(document, jsonpatch._deepClone(operation))`. -* -* @param document The document to patch -* @param operation The operation to apply -* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. -* @param mutateDocument Whether to mutate the original document or clone it before applying -* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. -* @return `{newDocument, result}` after the operation -*/ -function applyOperation(document, operation, validateOperation = false, mutateDocument = true, banPrototypeModifications = true, index = 0) { - if (validateOperation) if (typeof validateOperation == "function") validateOperation(operation, 0, document, operation.path); - else validator(operation, 0); - if (operation.path === "") { - let returnValue = { newDocument: document }; - if (operation.op === "add") { - returnValue.newDocument = operation.value; - return returnValue; - } else if (operation.op === "replace") { - returnValue.newDocument = operation.value; - returnValue.removed = document; - return returnValue; - } else if (operation.op === "move" || operation.op === "copy") { - returnValue.newDocument = getValueByPointer(document, operation.from); - if (operation.op === "move") returnValue.removed = document; - return returnValue; - } else if (operation.op === "test") { - returnValue.test = _areEquals(document, operation.value); - if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - returnValue.newDocument = document; - return returnValue; - } else if (operation.op === "remove") { - returnValue.removed = document; - returnValue.newDocument = null; - return returnValue; - } else if (operation.op === "_get") { - operation.value = document; - return returnValue; - } else if (validateOperation) throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); - else return returnValue; - } else { - if (!mutateDocument) document = _deepClone(document); - const path = operation.path || ""; - const keys = path.split("/"); - let obj = document; - let t = 1; - let len = keys.length; - let existingPathFragment = void 0; - let key; - let validateFunction; - if (typeof validateOperation == "function") validateFunction = validateOperation; - else validateFunction = validator; - while (true) { - key = keys[t]; - if (key && key.indexOf("~") != -1) key = unescapePathComponent(key); - if (banPrototypeModifications && (key == "__proto__" || key == "prototype" && t > 0 && keys[t - 1] == "constructor")) throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README"); - if (validateOperation) { - if (existingPathFragment === void 0) { - if (obj[key] === void 0) existingPathFragment = keys.slice(0, t).join("/"); - else if (t == len - 1) existingPathFragment = operation.path; - if (existingPathFragment !== void 0) validateFunction(operation, 0, document, existingPathFragment); - } - } - t++; - if (Array.isArray(obj)) { - if (key === "-") key = obj.length; - else if (validateOperation && !isInteger(key)) throw new JsonPatchError("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index", "OPERATION_PATH_ILLEGAL_ARRAY_INDEX", index, operation, document); - else if (isInteger(key)) key = ~~key; - if (t >= len) { - if (validateOperation && operation.op === "add" && key > obj.length) throw new JsonPatchError("The specified index MUST NOT be greater than the number of elements in the array", "OPERATION_VALUE_OUT_OF_BOUNDS", index, operation, document); - const returnValue = arrOps[operation.op].call(operation, obj, key, document); - if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - return returnValue; - } - } else if (t >= len) { - const returnValue = objOps[operation.op].call(operation, obj, key, document); - if (returnValue.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - return returnValue; - } - obj = obj[key]; - if (validateOperation && t < len && (!obj || typeof obj !== "object")) throw new JsonPatchError("Cannot perform operation at the desired path", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); - } - } -} -/** -* Apply a full JSON Patch array on a JSON document. -* Returns the {newDocument, result} of the patch. -* It modifies the `document` object and `patch` - it gets the values by reference. -* If you would like to avoid touching your values, clone them: -* `jsonpatch.applyPatch(document, jsonpatch._deepClone(patch))`. -* -* @param document The document to patch -* @param patch The patch to apply -* @param validateOperation `false` is without validation, `true` to use default jsonpatch's validation, or you can pass a `validateOperation` callback to be used for validation. -* @param mutateDocument Whether to mutate the original document or clone it before applying -* @param banPrototypeModifications Whether to ban modifications to `__proto__`, defaults to `true`. -* @return An array of `{newDocument, result}` after the patch -*/ -function applyPatch(document, patch, validateOperation, mutateDocument = true, banPrototypeModifications = true) { - if (validateOperation) { - if (!Array.isArray(patch)) throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - } - if (!mutateDocument) document = _deepClone(document); - const results = new Array(patch.length); - for (let i = 0, length = patch.length; i < length; i++) { - results[i] = applyOperation(document, patch[i], validateOperation, true, banPrototypeModifications, i); - document = results[i].newDocument; - } - results.newDocument = document; - return results; -} -/** -* Apply a single JSON Patch Operation on a JSON document. -* Returns the updated document. -* Suitable as a reducer. -* -* @param document The document to patch -* @param operation The operation to apply -* @return The updated document -*/ -function applyReducer(document, operation, index) { - const operationResult = applyOperation(document, operation); - if (operationResult.test === false) throw new JsonPatchError("Test operation failed", "TEST_OPERATION_FAILED", index, operation, document); - return operationResult.newDocument; -} -/** -* Validates a single operation. Called from `jsonpatch.validate`. Throws `JsonPatchError` in case of an error. -* @param {object} operation - operation object (patch) -* @param {number} index - index of operation in the sequence -* @param {object} [document] - object where the operation is supposed to be applied -* @param {string} [existingPathFragment] - comes along with `document` -*/ -function validator(operation, index, document, existingPathFragment) { - if (typeof operation !== "object" || operation === null || Array.isArray(operation)) throw new JsonPatchError("Operation is not an object", "OPERATION_NOT_AN_OBJECT", index, operation, document); - else if (!objOps[operation.op]) throw new JsonPatchError("Operation `op` property is not one of operations defined in RFC-6902", "OPERATION_OP_INVALID", index, operation, document); - else if (typeof operation.path !== "string") throw new JsonPatchError("Operation `path` property is not a string", "OPERATION_PATH_INVALID", index, operation, document); - else if (operation.path.indexOf("/") !== 0 && operation.path.length > 0) throw new JsonPatchError("Operation `path` property must start with \"/\"", "OPERATION_PATH_INVALID", index, operation, document); - else if ((operation.op === "move" || operation.op === "copy") && typeof operation.from !== "string") throw new JsonPatchError("Operation `from` property is not present (applicable in `move` and `copy` operations)", "OPERATION_FROM_REQUIRED", index, operation, document); - else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && operation.value === void 0) throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_REQUIRED", index, operation, document); - else if ((operation.op === "add" || operation.op === "replace" || operation.op === "test") && hasUndefined(operation.value)) throw new JsonPatchError("Operation `value` property is not present (applicable in `add`, `replace` and `test` operations)", "OPERATION_VALUE_CANNOT_CONTAIN_UNDEFINED", index, operation, document); - else if (document) { - if (operation.op == "add") { - var pathLen = operation.path.split("/").length; - var existingPathLen = existingPathFragment.split("/").length; - if (pathLen !== existingPathLen + 1 && pathLen !== existingPathLen) throw new JsonPatchError("Cannot perform an `add` operation at the desired path", "OPERATION_PATH_CANNOT_ADD", index, operation, document); - } else if (operation.op === "replace" || operation.op === "remove" || operation.op === "_get") { - if (operation.path !== existingPathFragment) throw new JsonPatchError("Cannot perform the operation at a path that does not exist", "OPERATION_PATH_UNRESOLVABLE", index, operation, document); - } else if (operation.op === "move" || operation.op === "copy") { - var existingValue = { - op: "_get", - path: operation.from, - value: void 0 - }; - var error = core_validate([existingValue], document); - if (error && error.name === "OPERATION_PATH_UNRESOLVABLE") throw new JsonPatchError("Cannot perform the operation from a path that does not exist", "OPERATION_FROM_UNRESOLVABLE", index, operation, document); - } - } -} -/** -* Validates a sequence of operations. If `document` parameter is provided, the sequence is additionally validated against the object document. -* If error is encountered, returns a JsonPatchError object -* @param sequence -* @param document -* @returns {JsonPatchError|undefined} -*/ -function core_validate(sequence, document, externalValidator) { - try { - if (!Array.isArray(sequence)) throw new JsonPatchError("Patch sequence must be an array", "SEQUENCE_NOT_AN_ARRAY"); - if (document) applyPatch(_deepClone(document), _deepClone(sequence), externalValidator || true); - else { - externalValidator = externalValidator || validator; - for (var i = 0; i < sequence.length; i++) externalValidator(sequence[i], i, document, void 0); - } - } catch (e) { - if (e instanceof JsonPatchError) return e; - else throw e; - } -} -function _areEquals(a, b) { - if (a === b) return true; - if (a && b && typeof a == "object" && typeof b == "object") { - var arrA = Array.isArray(a), arrB = Array.isArray(b), i, length, key; - if (arrA && arrB) { - length = a.length; - if (length != b.length) return false; - for (i = length; i-- !== 0;) if (!_areEquals(a[i], b[i])) return false; - return true; - } - if (arrA != arrB) return false; - var keys = Object.keys(a); - length = keys.length; - if (length !== Object.keys(b).length) return false; - for (i = length; i-- !== 0;) if (!b.hasOwnProperty(keys[i])) return false; - for (i = length; i-- !== 0;) { - key = keys[i]; - if (!_areEquals(a[key], b[key])) return false; - } - return true; - } - return a !== a && b !== b; -} - -//#endregion - -//# sourceMappingURL=core.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/src/duplex.js - - - -//#region src/utils/fast-json-patch/src/duplex.ts -function _generate(mirror, obj, patches, path, invertible) { - if (obj === mirror) return; - if (typeof obj.toJSON === "function") obj = obj.toJSON(); - var newKeys = _objectKeys(obj); - var oldKeys = _objectKeys(mirror); - var changed = false; - var deleted = false; - for (var t = oldKeys.length - 1; t >= 0; t--) { - var key = oldKeys[t]; - var oldVal = mirror[key]; - if (helpers_hasOwnProperty(obj, key) && !(obj[key] === void 0 && oldVal !== void 0 && Array.isArray(obj) === false)) { - var newVal = obj[key]; - if (typeof oldVal == "object" && oldVal != null && typeof newVal == "object" && newVal != null && Array.isArray(oldVal) === Array.isArray(newVal)) _generate(oldVal, newVal, patches, path + "/" + escapePathComponent(key), invertible); - else if (oldVal !== newVal) { - changed = true; - if (invertible) patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: _deepClone(oldVal) - }); - patches.push({ - op: "replace", - path: path + "/" + escapePathComponent(key), - value: _deepClone(newVal) - }); - } - } else if (Array.isArray(mirror) === Array.isArray(obj)) { - if (invertible) patches.push({ - op: "test", - path: path + "/" + escapePathComponent(key), - value: _deepClone(oldVal) - }); - patches.push({ - op: "remove", - path: path + "/" + escapePathComponent(key) - }); - deleted = true; - } else { - if (invertible) patches.push({ - op: "test", - path, - value: mirror - }); - patches.push({ - op: "replace", - path, - value: obj - }); - changed = true; - } - } - if (!deleted && newKeys.length == oldKeys.length) return; - for (var t = 0; t < newKeys.length; t++) { - var key = newKeys[t]; - if (!helpers_hasOwnProperty(mirror, key) && obj[key] !== void 0) patches.push({ - op: "add", - path: path + "/" + escapePathComponent(key), - value: _deepClone(obj[key]) - }); - } -} -/** -* Create an array of patches from the differences in two objects -*/ -function compare(tree1, tree2, invertible = false) { - var patches = []; - _generate(tree1, tree2, patches, "", invertible); - return patches; -} - -//#endregion - -//# sourceMappingURL=duplex.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/fast-json-patch/index.js - - - - -//#region src/utils/fast-json-patch/index.ts -var fast_json_patch_default = { - ...core_exports, - JsonPatchError: PatchError, - deepClone: _deepClone, - escapePathComponent: escapePathComponent, - unescapePathComponent: unescapePathComponent -}; - -//#endregion -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/log_stream.js - - - - - - - -//#region src/tracers/log_stream.ts -var log_stream_exports = {}; -__export(log_stream_exports, { - LogStreamCallbackHandler: () => LogStreamCallbackHandler, - RunLog: () => RunLog, - RunLogPatch: () => RunLogPatch, - isLogStreamHandler: () => isLogStreamHandler -}); -/** -* List of jsonpatch JSONPatchOperations, which describe how to create the run state -* from an empty dict. This is the minimal representation of the log, designed to -* be serialized as JSON and sent over the wire to reconstruct the log on the other -* side. Reconstruction of the state can be done with any jsonpatch-compliant library, -* see https://jsonpatch.com for more information. -*/ -var RunLogPatch = class { - ops; - constructor(fields) { - this.ops = fields.ops ?? []; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = applyPatch({}, ops); - return new RunLog({ - ops, - state: states[states.length - 1].newDocument - }); - } -}; -var RunLog = class RunLog extends RunLogPatch { - state; - constructor(fields) { - super(fields); - this.state = fields.state; - } - concat(other) { - const ops = this.ops.concat(other.ops); - const states = applyPatch(this.state, other.ops); - return new RunLog({ - ops, - state: states[states.length - 1].newDocument - }); - } - static fromRunLogPatch(patch) { - const states = applyPatch({}, patch.ops); - return new RunLog({ - ops: patch.ops, - state: states[states.length - 1].newDocument - }); - } -}; -const isLogStreamHandler = (handler) => handler.name === "log_stream_tracer"; -/** -* Extract standardized inputs from a run. -* -* Standardizes the inputs based on the type of the runnable used. -* -* @param run - Run object -* @param schemaFormat - The schema format to use. -* -* @returns Valid inputs are only dict. By conventions, inputs always represented -* invocation using named arguments. -* A null means that the input is not yet known! -*/ -async function _getStandardizedInputs(run, schemaFormat) { - if (schemaFormat === "original") throw new Error("Do not assign inputs with original schema drop the key for now. When inputs are added to streamLog they should be added with standardized schema for streaming events."); - const { inputs } = run; - if ([ - "retriever", - "llm", - "prompt" - ].includes(run.run_type)) return inputs; - if (Object.keys(inputs).length === 1 && inputs?.input === "") return void 0; - return inputs.input; -} -async function _getStandardizedOutputs(run, schemaFormat) { - const { outputs } = run; - if (schemaFormat === "original") return outputs; - if ([ - "retriever", - "llm", - "prompt" - ].includes(run.run_type)) return outputs; - if (outputs !== void 0 && Object.keys(outputs).length === 1 && outputs?.output !== void 0) return outputs.output; - return outputs; -} -function isChatGenerationChunk(x) { - return x !== void 0 && x.message !== void 0; -} -/** -* Class that extends the `BaseTracer` class from the -* `langchain.callbacks.tracers.base` module. It represents a callback -* handler that logs the execution of runs and emits `RunLog` instances to a -* `RunLogStream`. -*/ -var LogStreamCallbackHandler = class extends BaseTracer { - autoClose = true; - includeNames; - includeTypes; - includeTags; - excludeNames; - excludeTypes; - excludeTags; - _schemaFormat = "original"; - rootId; - keyMapByRunId = {}; - counterMapByRunName = {}; - transformStream; - writer; - receiveStream; - name = "log_stream_tracer"; - lc_prefer_streaming = true; - constructor(fields) { - super({ - _awaitHandler: true, - ...fields - }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this._schemaFormat = fields?._schemaFormat ?? this._schemaFormat; - this.transformStream = new TransformStream(); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); - } - [Symbol.asyncIterator]() { - return this.receiveStream; - } - async persistRun(_run) {} - _includeRun(run) { - if (run.id === this.rootId) return false; - const runTags = run.tags ?? []; - let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0; - if (this.includeNames !== void 0) include = include || this.includeNames.includes(run.name); - if (this.includeTypes !== void 0) include = include || this.includeTypes.includes(run.run_type); - if (this.includeTags !== void 0) include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0; - if (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(run.name); - if (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(run.run_type); - if (this.excludeTags !== void 0) include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); - return include; - } - async *tapOutputIterable(runId, output) { - for await (const chunk of output) { - if (runId !== this.rootId) { - const key = this.keyMapByRunId[runId]; - if (key) await this.writer.write(new RunLogPatch({ ops: [{ - op: "add", - path: `/logs/${key}/streamed_output/-`, - value: chunk - }] })); - } - yield chunk; - } - } - async onRunCreate(run) { - if (this.rootId === void 0) { - this.rootId = run.id; - await this.writer.write(new RunLogPatch({ ops: [{ - op: "replace", - path: "", - value: { - id: run.id, - name: run.name, - type: run.run_type, - streamed_output: [], - final_output: void 0, - logs: {} - } - }] })); - } - if (!this._includeRun(run)) return; - if (this.counterMapByRunName[run.name] === void 0) this.counterMapByRunName[run.name] = 0; - this.counterMapByRunName[run.name] += 1; - const count = this.counterMapByRunName[run.name]; - this.keyMapByRunId[run.id] = count === 1 ? run.name : `${run.name}:${count}`; - const logEntry = { - id: run.id, - name: run.name, - type: run.run_type, - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - start_time: new Date(run.start_time).toISOString(), - streamed_output: [], - streamed_output_str: [], - final_output: void 0, - end_time: void 0 - }; - if (this._schemaFormat === "streaming_events") logEntry.inputs = await _getStandardizedInputs(run, this._schemaFormat); - await this.writer.write(new RunLogPatch({ ops: [{ - op: "add", - path: `/logs/${this.keyMapByRunId[run.id]}`, - value: logEntry - }] })); - } - async onRunUpdate(run) { - try { - const runName = this.keyMapByRunId[run.id]; - if (runName === void 0) return; - const ops = []; - if (this._schemaFormat === "streaming_events") ops.push({ - op: "replace", - path: `/logs/${runName}/inputs`, - value: await _getStandardizedInputs(run, this._schemaFormat) - }); - ops.push({ - op: "add", - path: `/logs/${runName}/final_output`, - value: await _getStandardizedOutputs(run, this._schemaFormat) - }); - if (run.end_time !== void 0) ops.push({ - op: "add", - path: `/logs/${runName}/end_time`, - value: new Date(run.end_time).toISOString() - }); - const patch = new RunLogPatch({ ops }); - await this.writer.write(patch); - } finally { - if (run.id === this.rootId) { - const patch = new RunLogPatch({ ops: [{ - op: "replace", - path: "/final_output", - value: await _getStandardizedOutputs(run, this._schemaFormat) - }] }); - await this.writer.write(patch); - if (this.autoClose) await this.writer.close(); - } - } - } - async onLLMNewToken(run, token, kwargs) { - const runName = this.keyMapByRunId[run.id]; - if (runName === void 0) return; - const isChatModel = run.inputs.messages !== void 0; - let streamedOutputValue; - if (isChatModel) if (isChatGenerationChunk(kwargs?.chunk)) streamedOutputValue = kwargs?.chunk; - else streamedOutputValue = new AIMessageChunk({ - id: `run-${run.id}`, - content: token - }); - else streamedOutputValue = token; - const patch = new RunLogPatch({ ops: [{ - op: "add", - path: `/logs/${runName}/streamed_output_str/-`, - value: token - }, { - op: "add", - path: `/logs/${runName}/streamed_output/-`, - value: streamedOutputValue - }] }); - await this.writer.write(patch); - } -}; - -//#endregion - -//# sourceMappingURL=log_stream.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/outputs.js - - -//#region src/outputs.ts -var outputs_exports = {}; -__export(outputs_exports, { - ChatGenerationChunk: () => ChatGenerationChunk, - GenerationChunk: () => GenerationChunk, - RUN_KEY: () => RUN_KEY -}); -const RUN_KEY = "__run"; -/** -* Chunk of a single generation. Used for streaming. -*/ -var GenerationChunk = class GenerationChunk { - text; - generationInfo; - constructor(fields) { - this.text = fields.text; - this.generationInfo = fields.generationInfo; - } - concat(chunk) { - return new GenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo - } - }); - } -}; -var ChatGenerationChunk = class ChatGenerationChunk extends GenerationChunk { - message; - constructor(fields) { - super(fields); - this.message = fields.message; - } - concat(chunk) { - return new ChatGenerationChunk({ - text: this.text + chunk.text, - generationInfo: { - ...this.generationInfo, - ...chunk.generationInfo - }, - message: this.message.concat(chunk.message) - }); - } -}; - -//#endregion - -//# sourceMappingURL=outputs.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/is-network-error/index.js -//#region src/utils/is-network-error/index.js -const is_network_error_objectToString = Object.prototype.toString; -const is_network_error_isError = (value) => is_network_error_objectToString.call(value) === "[object Error]"; -const is_network_error_errorMessages = new Set([ - "network error", - "Failed to fetch", - "NetworkError when attempting to fetch resource.", - "The Internet connection appears to be offline.", - "Network request failed", - "fetch failed", - "terminated", - " A network error occurred.", - "Network connection lost" -]); -function is_network_error_isNetworkError(error) { - const isValid = error && is_network_error_isError(error) && error.name === "TypeError" && typeof error.message === "string"; - if (!isValid) return false; - const { message, stack } = error; - if (message === "Load failed") return stack === void 0 || "__sentry_captured__" in error; - if (message.startsWith("error sending request for url")) return true; - return is_network_error_errorMessages.has(message); -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/p-retry/index.js - - -//#region src/utils/p-retry/index.js -function p_retry_validateRetries(retries) { - if (typeof retries === "number") { - if (retries < 0) throw new TypeError("Expected `retries` to be a non-negative number."); - if (Number.isNaN(retries)) throw new TypeError("Expected `retries` to be a valid number or Infinity, got NaN."); - } else if (retries !== void 0) throw new TypeError("Expected `retries` to be a number or Infinity."); -} -function p_retry_validateNumberOption(name, value, { min = 0, allowInfinity = false } = {}) { - if (value === void 0) return; - if (typeof value !== "number" || Number.isNaN(value)) throw new TypeError(`Expected \`${name}\` to be a number${allowInfinity ? " or Infinity" : ""}.`); - if (!allowInfinity && !Number.isFinite(value)) throw new TypeError(`Expected \`${name}\` to be a finite number.`); - if (value < min) throw new TypeError(`Expected \`${name}\` to be \u2265 ${min}.`); -} -var p_retry_AbortError = class extends Error { - constructor(message) { - super(); - if (message instanceof Error) { - this.originalError = message; - ({message} = message); - } else { - this.originalError = new Error(message); - this.originalError.stack = this.stack; - } - this.name = "AbortError"; - this.message = message; - } -}; -function p_retry_calculateDelay(retriesConsumed, options) { - const attempt = Math.max(1, retriesConsumed + 1); - const random = options.randomize ? Math.random() + 1 : 1; - let timeout = Math.round(random * options.minTimeout * options.factor ** (attempt - 1)); - timeout = Math.min(timeout, options.maxTimeout); - return timeout; -} -function p_retry_calculateRemainingTime(start, max) { - if (!Number.isFinite(max)) return max; - return max - (performance.now() - start); -} -async function p_retry_onAttemptFailure({ error, attemptNumber, retriesConsumed, startTime, options }) { - const normalizedError = error instanceof Error ? error : /* @__PURE__ */ new TypeError(`Non-error was thrown: "${error}". You should only throw errors.`); - if (normalizedError instanceof p_retry_AbortError) throw normalizedError.originalError; - const retriesLeft = Number.isFinite(options.retries) ? Math.max(0, options.retries - retriesConsumed) : options.retries; - const maxRetryTime = options.maxRetryTime ?? Number.POSITIVE_INFINITY; - const context = Object.freeze({ - error: normalizedError, - attemptNumber, - retriesLeft, - retriesConsumed - }); - await options.onFailedAttempt(context); - if (p_retry_calculateRemainingTime(startTime, maxRetryTime) <= 0) throw normalizedError; - const consumeRetry = await options.shouldConsumeRetry(context); - const remainingTime = p_retry_calculateRemainingTime(startTime, maxRetryTime); - if (remainingTime <= 0 || retriesLeft <= 0) throw normalizedError; - if (normalizedError instanceof TypeError && !is_network_error_isNetworkError(normalizedError)) { - if (consumeRetry) throw normalizedError; - options.signal?.throwIfAborted(); - return false; - } - if (!await options.shouldRetry(context)) throw normalizedError; - if (!consumeRetry) { - options.signal?.throwIfAborted(); - return false; - } - const delayTime = p_retry_calculateDelay(retriesConsumed, options); - const finalDelay = Math.min(delayTime, remainingTime); - if (finalDelay > 0) await new Promise((resolve, reject) => { - const onAbort = () => { - clearTimeout(timeoutToken); - options.signal?.removeEventListener("abort", onAbort); - reject(options.signal.reason); - }; - const timeoutToken = setTimeout(() => { - options.signal?.removeEventListener("abort", onAbort); - resolve(); - }, finalDelay); - if (options.unref) timeoutToken.unref?.(); - options.signal?.addEventListener("abort", onAbort, { once: true }); - }); - options.signal?.throwIfAborted(); - return true; -} -async function p_retry_pRetry(input, options = {}) { - options = { ...options }; - p_retry_validateRetries(options.retries); - if (Object.hasOwn(options, "forever")) throw new Error("The `forever` option is no longer supported. For many use-cases, you can set `retries: Infinity` instead."); - options.retries ??= 10; - options.factor ??= 2; - options.minTimeout ??= 1e3; - options.maxTimeout ??= Number.POSITIVE_INFINITY; - options.maxRetryTime ??= Number.POSITIVE_INFINITY; - options.randomize ??= false; - options.onFailedAttempt ??= () => {}; - options.shouldRetry ??= () => true; - options.shouldConsumeRetry ??= () => true; - p_retry_validateNumberOption("factor", options.factor, { - min: 0, - allowInfinity: false - }); - p_retry_validateNumberOption("minTimeout", options.minTimeout, { - min: 0, - allowInfinity: false - }); - p_retry_validateNumberOption("maxTimeout", options.maxTimeout, { - min: 0, - allowInfinity: true - }); - p_retry_validateNumberOption("maxRetryTime", options.maxRetryTime, { - min: 0, - allowInfinity: true - }); - if (!(options.factor > 0)) options.factor = 1; - options.signal?.throwIfAborted(); - let attemptNumber = 0; - let retriesConsumed = 0; - const startTime = performance.now(); - while (Number.isFinite(options.retries) ? retriesConsumed <= options.retries : true) { - attemptNumber++; - try { - options.signal?.throwIfAborted(); - const result = await input(attemptNumber); - options.signal?.throwIfAborted(); - return result; - } catch (error) { - if (await p_retry_onAttemptFailure({ - error, - attemptNumber, - retriesConsumed, - startTime, - options - })) retriesConsumed++; - } - } - throw new Error("Retry attempts exhausted without throwing an error."); -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/async_caller.js - - - - - -//#region src/utils/async_caller.ts -var async_caller_exports = {}; -__export(async_caller_exports, { AsyncCaller: () => async_caller_AsyncCaller }); -const STATUS_NO_RETRY = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 409 -]; -const defaultFailedAttemptHandler = (error) => { - if (error.message.startsWith("Cancel") || error.message.startsWith("AbortError") || error.name === "AbortError") throw error; - if (error?.code === "ECONNABORTED") throw error; - const status = error?.response?.status ?? error?.status; - if (status && STATUS_NO_RETRY.includes(+status)) throw error; - if (error?.error?.code === "insufficient_quota") { - const err = new Error(error?.message); - err.name = "InsufficientQuotaError"; - throw err; - } -}; -/** -* A class that can be used to make async calls with concurrency and retry logic. -* -* This is useful for making calls to any kind of "expensive" external resource, -* be it because it's rate-limited, subject to network issues, etc. -* -* Concurrent calls are limited by the `maxConcurrency` parameter, which defaults -* to `Infinity`. This means that by default, all calls will be made in parallel. -* -* Retries are limited by the `maxRetries` parameter, which defaults to 6. This -* means that by default, each call will be retried up to 6 times, with an -* exponential backoff between each attempt. -*/ -var async_caller_AsyncCaller = class { - maxConcurrency; - maxRetries; - onFailedAttempt; - queue; - constructor(params) { - this.maxConcurrency = params.maxConcurrency ?? Infinity; - this.maxRetries = params.maxRetries ?? 6; - this.onFailedAttempt = params.onFailedAttempt ?? defaultFailedAttemptHandler; - const PQueue = true ? p_queue_dist["default"] : p_queue_dist; - this.queue = new PQueue({ concurrency: this.maxConcurrency }); - } - async call(callable, ...args) { - return this.queue.add(() => p_retry_pRetry(() => callable(...args).catch((error) => { - if (error instanceof Error) throw error; - else throw new Error(error); - }), { - onFailedAttempt: ({ error }) => this.onFailedAttempt?.(error), - retries: this.maxRetries, - randomize: true - }), { throwOnTimeout: true }); - } - callWithOptions(options, callable, ...args) { - if (options.signal) { - let listener; - return Promise.race([this.call(callable, ...args), new Promise((_, reject) => { - listener = () => { - reject(getAbortSignalError(options.signal)); - }; - options.signal?.addEventListener("abort", listener); - })]).finally(() => { - if (options.signal && listener) options.signal.removeEventListener("abort", listener); - }); - } - return this.call(callable, ...args); - } - fetch(...args) { - return this.call(() => fetch(...args).then((res) => res.ok ? res : Promise.reject(res))); - } -}; - -//#endregion - -//# sourceMappingURL=async_caller.js.map -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/core.js -/** A special constant with type `never` */ -const NEVER = Object.freeze({ - status: "aborted", -}); -function $constructor(name, initializer, params) { - function init(inst, def) { - if (!inst._zod) { - Object.defineProperty(inst, "_zod", { - value: { - def, - constr: _, - traits: new Set(), - }, - enumerable: false, - }); - } - if (inst._zod.traits.has(name)) { - return; - } - inst._zod.traits.add(name); - initializer(inst, def); - // support prototype modifications - const proto = _.prototype; - const keys = Object.keys(proto); - for (let i = 0; i < keys.length; i++) { - const k = keys[i]; - if (!(k in inst)) { - inst[k] = proto[k].bind(inst); - } - } - } - // doesn't work if Parent has a constructor with arguments - const Parent = params?.Parent ?? Object; - class Definition extends Parent { - } - Object.defineProperty(Definition, "name", { value: name }); - function _(def) { - var _a; - const inst = params?.Parent ? new Definition() : this; - init(inst, def); - (_a = inst._zod).deferred ?? (_a.deferred = []); - for (const fn of inst._zod.deferred) { - fn(); - } - return inst; - } - Object.defineProperty(_, "init", { value: init }); - Object.defineProperty(_, Symbol.hasInstance, { - value: (inst) => { - if (params?.Parent && inst instanceof params.Parent) - return true; - return inst?._zod?.traits?.has(name); - }, - }); - Object.defineProperty(_, "name", { value: name }); - return _; -} -////////////////////////////// UTILITIES /////////////////////////////////////// -const $brand = Symbol("zod_brand"); -class $ZodAsyncError extends Error { - constructor() { - super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`); - } -} -class $ZodEncodeError extends Error { - constructor(name) { - super(`Encountered unidirectional transform during encode: ${name}`); - this.name = "ZodEncodeError"; - } -} -const globalConfig = {}; -function config(newConfig) { - if (newConfig) - Object.assign(globalConfig, newConfig); - return globalConfig; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/util.js -// functions -function assertEqual(val) { - return val; -} -function assertNotEqual(val) { - return val; -} -function assertIs(_arg) { } -function assertNever(_x) { - throw new Error("Unexpected value in exhaustive check"); -} -function assert(_) { } -function getEnumValues(entries) { - const numericValues = Object.values(entries).filter((v) => typeof v === "number"); - const values = Object.entries(entries) - .filter(([k, _]) => numericValues.indexOf(+k) === -1) - .map(([_, v]) => v); - return values; -} -function joinValues(array, separator = "|") { - return array.map((val) => stringifyPrimitive(val)).join(separator); -} -function jsonStringifyReplacer(_, value) { - if (typeof value === "bigint") - return value.toString(); - return value; -} -function cached(getter) { - const set = false; - return { - get value() { - if (!set) { - const value = getter(); - Object.defineProperty(this, "value", { value }); - return value; - } - throw new Error("cached value already set"); - }, - }; -} -function nullish(input) { - return input === null || input === undefined; -} -function cleanRegex(source) { - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - return source.slice(start, end); -} -function floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepString = step.toString(); - let stepDecCount = (stepString.split(".")[1] || "").length; - if (stepDecCount === 0 && /\d?e-\d?/.test(stepString)) { - const match = stepString.match(/\d?e-(\d?)/); - if (match?.[1]) { - stepDecCount = Number.parseInt(match[1]); - } - } - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / 10 ** decCount; -} -const EVALUATING = Symbol("evaluating"); -function defineLazy(object, key, getter) { - let value = undefined; - Object.defineProperty(object, key, { - get() { - if (value === EVALUATING) { - // Circular reference detected, return undefined to break the cycle - return undefined; - } - if (value === undefined) { - value = EVALUATING; - value = getter(); - } - return value; - }, - set(v) { - Object.defineProperty(object, key, { - value: v, - // configurable: true, - }); - // object[key] = v; - }, - configurable: true, - }); -} -function objectClone(obj) { - return Object.create(Object.getPrototypeOf(obj), Object.getOwnPropertyDescriptors(obj)); -} -function assignProp(target, prop, value) { - Object.defineProperty(target, prop, { - value, - writable: true, - enumerable: true, - configurable: true, - }); -} -function mergeDefs(...defs) { - const mergedDescriptors = {}; - for (const def of defs) { - const descriptors = Object.getOwnPropertyDescriptors(def); - Object.assign(mergedDescriptors, descriptors); - } - return Object.defineProperties({}, mergedDescriptors); -} -function cloneDef(schema) { - return mergeDefs(schema._zod.def); -} -function getElementAtPath(obj, path) { - if (!path) - return obj; - return path.reduce((acc, key) => acc?.[key], obj); -} -function promiseAllObject(promisesObj) { - const keys = Object.keys(promisesObj); - const promises = keys.map((key) => promisesObj[key]); - return Promise.all(promises).then((results) => { - const resolvedObj = {}; - for (let i = 0; i < keys.length; i++) { - resolvedObj[keys[i]] = results[i]; - } - return resolvedObj; - }); -} -function randomString(length = 10) { - const chars = "abcdefghijklmnopqrstuvwxyz"; - let str = ""; - for (let i = 0; i < length; i++) { - str += chars[Math.floor(Math.random() * chars.length)]; - } - return str; -} -function esc(str) { - return JSON.stringify(str); -} -function slugify(input) { - return input - .toLowerCase() - .trim() - .replace(/[^\w\s-]/g, "") - .replace(/[\s_-]+/g, "-") - .replace(/^-+|-+$/g, ""); -} -const captureStackTrace = ("captureStackTrace" in Error ? Error.captureStackTrace : (..._args) => { }); -function util_isObject(data) { - return typeof data === "object" && data !== null && !Array.isArray(data); -} -const util_allowsEval = cached(() => { - // @ts-ignore - if (typeof navigator !== "undefined" && navigator?.userAgent?.includes("Cloudflare")) { - return false; - } - try { - const F = Function; - new F(""); - return true; - } - catch (_) { - return false; - } -}); -function isPlainObject(o) { - if (util_isObject(o) === false) - return false; - // modified constructor - const ctor = o.constructor; - if (ctor === undefined) - return true; - if (typeof ctor !== "function") - return true; - // modified prototype - const prot = ctor.prototype; - if (util_isObject(prot) === false) - return false; - // ctor doesn't have static `isPrototypeOf` - if (Object.prototype.hasOwnProperty.call(prot, "isPrototypeOf") === false) { - return false; - } - return true; -} -function shallowClone(o) { - if (isPlainObject(o)) - return { ...o }; - if (Array.isArray(o)) - return [...o]; - return o; -} -function numKeys(data) { - let keyCount = 0; - for (const key in data) { - if (Object.prototype.hasOwnProperty.call(data, key)) { - keyCount++; - } - } - return keyCount; -} -const getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return "undefined"; - case "string": - return "string"; - case "number": - return Number.isNaN(data) ? "nan" : "number"; - case "boolean": - return "boolean"; - case "function": - return "function"; - case "bigint": - return "bigint"; - case "symbol": - return "symbol"; - case "object": - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return "promise"; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return "map"; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return "set"; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return "date"; - } - // @ts-ignore - if (typeof File !== "undefined" && data instanceof File) { - return "file"; - } - return "object"; - default: - throw new Error(`Unknown data type: ${t}`); - } -}; -const propertyKeyTypes = new Set(["string", "number", "symbol"]); -const primitiveTypes = new Set(["string", "number", "bigint", "boolean", "symbol", "undefined"]); -function escapeRegex(str) { - return str.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); -} -// zod-specific utils -function clone(inst, def, params) { - const cl = new inst._zod.constr(def ?? inst._zod.def); - if (!def || params?.parent) - cl._zod.parent = inst; - return cl; -} -function normalizeParams(_params) { - const params = _params; - if (!params) - return {}; - if (typeof params === "string") - return { error: () => params }; - if (params?.message !== undefined) { - if (params?.error !== undefined) - throw new Error("Cannot specify both `message` and `error` params"); - params.error = params.message; - } - delete params.message; - if (typeof params.error === "string") - return { ...params, error: () => params.error }; - return params; -} -function createTransparentProxy(getter) { - let target; - return new Proxy({}, { - get(_, prop, receiver) { - target ?? (target = getter()); - return Reflect.get(target, prop, receiver); - }, - set(_, prop, value, receiver) { - target ?? (target = getter()); - return Reflect.set(target, prop, value, receiver); - }, - has(_, prop) { - target ?? (target = getter()); - return Reflect.has(target, prop); - }, - deleteProperty(_, prop) { - target ?? (target = getter()); - return Reflect.deleteProperty(target, prop); - }, - ownKeys(_) { - target ?? (target = getter()); - return Reflect.ownKeys(target); - }, - getOwnPropertyDescriptor(_, prop) { - target ?? (target = getter()); - return Reflect.getOwnPropertyDescriptor(target, prop); - }, - defineProperty(_, prop, descriptor) { - target ?? (target = getter()); - return Reflect.defineProperty(target, prop, descriptor); - }, - }); -} -function stringifyPrimitive(value) { - if (typeof value === "bigint") - return value.toString() + "n"; - if (typeof value === "string") - return `"${value}"`; - return `${value}`; -} -function optionalKeys(shape) { - return Object.keys(shape).filter((k) => { - return shape[k]._zod.optin === "optional" && shape[k]._zod.optout === "optional"; - }); -} -const NUMBER_FORMAT_RANGES = { - safeint: [Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER], - int32: [-2147483648, 2147483647], - uint32: [0, 4294967295], - float32: [-3.4028234663852886e38, 3.4028234663852886e38], - float64: [-Number.MAX_VALUE, Number.MAX_VALUE], -}; -const BIGINT_FORMAT_RANGES = { - int64: [/* @__PURE__*/ BigInt("-9223372036854775808"), /* @__PURE__*/ BigInt("9223372036854775807")], - uint64: [/* @__PURE__*/ BigInt(0), /* @__PURE__*/ BigInt("18446744073709551615")], -}; -function pick(schema, mask) { - const currDef = schema._zod.def; - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = {}; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - newShape[key] = currDef.shape[key]; - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function omit(schema, mask) { - const currDef = schema._zod.def; - const def = mergeDefs(schema._zod.def, { - get shape() { - const newShape = { ...schema._zod.def.shape }; - for (const key in mask) { - if (!(key in currDef.shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - delete newShape[key]; - } - assignProp(this, "shape", newShape); // self-caching - return newShape; - }, - checks: [], - }); - return clone(schema, def); -} -function extend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to extend: expected a plain object"); - } - const checks = schema._zod.def.checks; - const hasChecks = checks && checks.length > 0; - if (hasChecks) { - throw new Error("Object schemas containing refinements cannot be extended. Use `.safeExtend()` instead."); - } - const def = mergeDefs(schema._zod.def, { - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - checks: [], - }); - return clone(schema, def); -} -function safeExtend(schema, shape) { - if (!isPlainObject(shape)) { - throw new Error("Invalid input to safeExtend: expected a plain object"); - } - const def = { - ...schema._zod.def, - get shape() { - const _shape = { ...schema._zod.def.shape, ...shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - checks: schema._zod.def.checks, - }; - return clone(schema, def); -} -function merge(a, b) { - const def = mergeDefs(a._zod.def, { - get shape() { - const _shape = { ...a._zod.def.shape, ...b._zod.def.shape }; - assignProp(this, "shape", _shape); // self-caching - return _shape; - }, - get catchall() { - return b._zod.def.catchall; - }, - checks: [], // delete existing checks - }); - return clone(a, def); -} -function partial(Class, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in oldShape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - else { - for (const key in oldShape) { - // if (oldShape[key]!._zod.optin === "optional") continue; - shape[key] = Class - ? new Class({ - type: "optional", - innerType: oldShape[key], - }) - : oldShape[key]; - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - checks: [], - }); - return clone(schema, def); -} -function required(Class, schema, mask) { - const def = mergeDefs(schema._zod.def, { - get shape() { - const oldShape = schema._zod.def.shape; - const shape = { ...oldShape }; - if (mask) { - for (const key in mask) { - if (!(key in shape)) { - throw new Error(`Unrecognized key: "${key}"`); - } - if (!mask[key]) - continue; - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - else { - for (const key in oldShape) { - // overwrite with non-optional - shape[key] = new Class({ - type: "nonoptional", - innerType: oldShape[key], - }); - } - } - assignProp(this, "shape", shape); // self-caching - return shape; - }, - checks: [], - }); - return clone(schema, def); -} -// invalid_type | too_big | too_small | invalid_format | not_multiple_of | unrecognized_keys | invalid_union | invalid_key | invalid_element | invalid_value | custom -function aborted(x, startIndex = 0) { - if (x.aborted === true) - return true; - for (let i = startIndex; i < x.issues.length; i++) { - if (x.issues[i]?.continue !== true) { - return true; - } - } - return false; -} -function prefixIssues(path, issues) { - return issues.map((iss) => { - var _a; - (_a = iss).path ?? (_a.path = []); - iss.path.unshift(path); - return iss; - }); -} -function unwrapMessage(message) { - return typeof message === "string" ? message : message?.message; -} -function finalizeIssue(iss, ctx, config) { - const full = { ...iss, path: iss.path ?? [] }; - // for backwards compatibility - if (!iss.message) { - const message = unwrapMessage(iss.inst?._zod.def?.error?.(iss)) ?? - unwrapMessage(ctx?.error?.(iss)) ?? - unwrapMessage(config.customError?.(iss)) ?? - unwrapMessage(config.localeError?.(iss)) ?? - "Invalid input"; - full.message = message; - } - // delete (full as any).def; - delete full.inst; - delete full.continue; - if (!ctx?.reportInput) { - delete full.input; - } - return full; -} -function getSizableOrigin(input) { - if (input instanceof Set) - return "set"; - if (input instanceof Map) - return "map"; - // @ts-ignore - if (input instanceof File) - return "file"; - return "unknown"; -} -function getLengthableOrigin(input) { - if (Array.isArray(input)) - return "array"; - if (typeof input === "string") - return "string"; - return "unknown"; -} -function util_issue(...args) { - const [iss, input, inst] = args; - if (typeof iss === "string") { - return { - message: iss, - code: "custom", - input, - inst, - }; - } - return { ...iss }; -} -function cleanEnum(obj) { - return Object.entries(obj) - .filter(([k, _]) => { - // return true if NaN, meaning it's not a number, thus a string key - return Number.isNaN(Number.parseInt(k, 10)); - }) - .map((el) => el[1]); -} -// Codec utility functions -function base64ToUint8Array(base64) { - const binaryString = atob(base64); - const bytes = new Uint8Array(binaryString.length); - for (let i = 0; i < binaryString.length; i++) { - bytes[i] = binaryString.charCodeAt(i); - } - return bytes; -} -function uint8ArrayToBase64(bytes) { - let binaryString = ""; - for (let i = 0; i < bytes.length; i++) { - binaryString += String.fromCharCode(bytes[i]); - } - return btoa(binaryString); -} -function base64urlToUint8Array(base64url) { - const base64 = base64url.replace(/-/g, "+").replace(/_/g, "/"); - const padding = "=".repeat((4 - (base64.length % 4)) % 4); - return base64ToUint8Array(base64 + padding); -} -function uint8ArrayToBase64url(bytes) { - return uint8ArrayToBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); -} -function hexToUint8Array(hex) { - const cleanHex = hex.replace(/^0x/, ""); - if (cleanHex.length % 2 !== 0) { - throw new Error("Invalid hex string length"); - } - const bytes = new Uint8Array(cleanHex.length / 2); - for (let i = 0; i < cleanHex.length; i += 2) { - bytes[i / 2] = Number.parseInt(cleanHex.slice(i, i + 2), 16); - } - return bytes; -} -function uint8ArrayToHex(bytes) { - return Array.from(bytes) - .map((b) => b.toString(16).padStart(2, "0")) - .join(""); -} -// instanceof -class Class { - constructor(..._args) { } -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/errors.js - - -const initializer = (inst, def) => { - inst.name = "$ZodError"; - Object.defineProperty(inst, "_zod", { - value: inst._zod, - enumerable: false, - }); - Object.defineProperty(inst, "issues", { - value: def, - enumerable: false, - }); - inst.message = JSON.stringify(def, jsonStringifyReplacer, 2); - Object.defineProperty(inst, "toString", { - value: () => inst.message, - enumerable: false, - }); -}; -const $ZodError = $constructor("$ZodError", initializer); -const $ZodRealError = $constructor("$ZodError", initializer, { Parent: Error }); -function flattenError(error, mapper = (issue) => issue.message) { - const fieldErrors = {}; - const formErrors = []; - for (const sub of error.issues) { - if (sub.path.length > 0) { - fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || []; - fieldErrors[sub.path[0]].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; -} -function formatError(error, mapper = (issue) => issue.message) { - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - issue.errors.map((issues) => processError({ issues })); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(error); - return fieldErrors; -} -function treeifyError(error, mapper = (issue) => issue.message) { - const result = { errors: [] }; - const processError = (error, path = []) => { - var _a, _b; - for (const issue of error.issues) { - if (issue.code === "invalid_union" && issue.errors.length) { - // regular union error - issue.errors.map((issues) => processError({ issues }, issue.path)); - } - else if (issue.code === "invalid_key") { - processError({ issues: issue.issues }, issue.path); - } - else if (issue.code === "invalid_element") { - processError({ issues: issue.issues }, issue.path); - } - else { - const fullpath = [...path, ...issue.path]; - if (fullpath.length === 0) { - result.errors.push(mapper(issue)); - continue; - } - let curr = result; - let i = 0; - while (i < fullpath.length) { - const el = fullpath[i]; - const terminal = i === fullpath.length - 1; - if (typeof el === "string") { - curr.properties ?? (curr.properties = {}); - (_a = curr.properties)[el] ?? (_a[el] = { errors: [] }); - curr = curr.properties[el]; - } - else { - curr.items ?? (curr.items = []); - (_b = curr.items)[el] ?? (_b[el] = { errors: [] }); - curr = curr.items[el]; - } - if (terminal) { - curr.errors.push(mapper(issue)); - } - i++; - } - } - } - }; - processError(error); - return result; -} -/** Format a ZodError as a human-readable string in the following form. - * - * From - * - * ```ts - * ZodError { - * issues: [ - * { - * expected: 'string', - * code: 'invalid_type', - * path: [ 'username' ], - * message: 'Invalid input: expected string' - * }, - * { - * expected: 'number', - * code: 'invalid_type', - * path: [ 'favoriteNumbers', 1 ], - * message: 'Invalid input: expected number' - * } - * ]; - * } - * ``` - * - * to - * - * ``` - * username - * ✖ Expected number, received string at "username - * favoriteNumbers[0] - * ✖ Invalid input: expected number - * ``` - */ -function toDotPath(_path) { - const segs = []; - const path = _path.map((seg) => (typeof seg === "object" ? seg.key : seg)); - for (const seg of path) { - if (typeof seg === "number") - segs.push(`[${seg}]`); - else if (typeof seg === "symbol") - segs.push(`[${JSON.stringify(String(seg))}]`); - else if (/[^\w$]/.test(seg)) - segs.push(`[${JSON.stringify(seg)}]`); - else { - if (segs.length) - segs.push("."); - segs.push(seg); - } - } - return segs.join(""); -} -function prettifyError(error) { - const lines = []; - // sort by path length - const issues = [...error.issues].sort((a, b) => (a.path ?? []).length - (b.path ?? []).length); - // Process each issue - for (const issue of issues) { - lines.push(`✖ ${issue.message}`); - if (issue.path?.length) - lines.push(` → at ${toDotPath(issue.path)}`); - } - // Convert Map to formatted string - return lines.join("\n"); -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/parse.js - - - -const _parse = (_Err) => (schema, value, _ctx, _params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: false }) : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - if (result.issues.length) { - const e = new (_params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, _params?.callee); - throw e; - } - return result.value; -}; -const parse_parse = /* @__PURE__*/ _parse($ZodRealError); -const _parseAsync = (_Err) => async (schema, value, _ctx, params) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - if (result.issues.length) { - const e = new (params?.Err ?? _Err)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))); - captureStackTrace(e, params?.callee); - throw e; - } - return result.value; -}; -const parseAsync = /* @__PURE__*/ _parseAsync($ZodRealError); -const _safeParse = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? { ..._ctx, async: false } : { async: false }; - const result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) { - throw new $ZodAsyncError(); - } - return result.issues.length - ? { - success: false, - error: new (_Err ?? $ZodError)(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), - } - : { success: true, data: result.value }; -}; -const safeParse = /* @__PURE__*/ _safeParse($ZodRealError); -const _safeParseAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { async: true }) : { async: true }; - let result = schema._zod.run({ value, issues: [] }, ctx); - if (result instanceof Promise) - result = await result; - return result.issues.length - ? { - success: false, - error: new _Err(result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), - } - : { success: true, data: result.value }; -}; -const safeParseAsync = /* @__PURE__*/ _safeParseAsync($ZodRealError); -const _encode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _parse(_Err)(schema, value, ctx); -}; -const encode = /* @__PURE__*/ _encode($ZodRealError); -const _decode = (_Err) => (schema, value, _ctx) => { - return _parse(_Err)(schema, value, _ctx); -}; -const decode = /* @__PURE__*/ _decode($ZodRealError); -const _encodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _parseAsync(_Err)(schema, value, ctx); -}; -const encodeAsync = /* @__PURE__*/ _encodeAsync($ZodRealError); -const _decodeAsync = (_Err) => async (schema, value, _ctx) => { - return _parseAsync(_Err)(schema, value, _ctx); -}; -const decodeAsync = /* @__PURE__*/ _decodeAsync($ZodRealError); -const _safeEncode = (_Err) => (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _safeParse(_Err)(schema, value, ctx); -}; -const safeEncode = /* @__PURE__*/ _safeEncode($ZodRealError); -const _safeDecode = (_Err) => (schema, value, _ctx) => { - return _safeParse(_Err)(schema, value, _ctx); -}; -const safeDecode = /* @__PURE__*/ _safeDecode($ZodRealError); -const _safeEncodeAsync = (_Err) => async (schema, value, _ctx) => { - const ctx = _ctx ? Object.assign(_ctx, { direction: "backward" }) : { direction: "backward" }; - return _safeParseAsync(_Err)(schema, value, ctx); -}; -const safeEncodeAsync = /* @__PURE__*/ _safeEncodeAsync($ZodRealError); -const _safeDecodeAsync = (_Err) => async (schema, value, _ctx) => { - return _safeParseAsync(_Err)(schema, value, _ctx); -}; -const safeDecodeAsync = /* @__PURE__*/ _safeDecodeAsync($ZodRealError); - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/regexes.js - -const cuid = /^[cC][^\s-]{8,}$/; -const cuid2 = /^[0-9a-z]+$/; -const ulid = /^[0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{26}$/; -const xid = /^[0-9a-vA-V]{20}$/; -const ksuid = /^[A-Za-z0-9]{27}$/; -const nanoid = /^[a-zA-Z0-9_-]{21}$/; -/** ISO 8601-1 duration regex. Does not support the 8601-2 extensions like negative durations or fractional/negative components. */ -const duration = /^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/; -/** Implements ISO 8601-2 extensions like explicit +- prefixes, mixing weeks with other units, and fractional/negative components. */ -const extendedDuration = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -/** A regex for any UUID-like identifier: 8-4-4-4-12 hex pattern */ -const guid = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/; -/** Returns a regex for validating an RFC 9562/4122 UUID. - * - * @param version Optionally specify a version 1-8. If no version is specified, all versions are supported. */ -const uuid = (version) => { - if (!version) - return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/; - return new RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`); -}; -const uuid4 = /*@__PURE__*/ uuid(4); -const regexes_uuid6 = /*@__PURE__*/ uuid(6); -const regexes_uuid7 = /*@__PURE__*/ uuid(7); -/** Practical email validation */ -const email = /^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/; -/** Equivalent to the HTML5 input[type=email] validation implemented by browsers. Source: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/email */ -const html5Email = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -/** The classic emailregex.com regex for RFC 5322-compliant emails */ -const rfc5322Email = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; -/** A loose regex that allows Unicode characters, enforces length limits, and that's about it. */ -const unicodeEmail = /^[^\s@"]{1,64}@[^\s@]{1,255}$/u; -const idnEmail = unicodeEmail; -const browserEmail = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -const _emoji = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -function emoji() { - return new RegExp(_emoji, "u"); -} -const ipv4 = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -const ipv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/; -const mac = (delimiter) => { - const escapedDelim = escapeRegex(delimiter ?? ":"); - return new RegExp(`^(?:[0-9A-F]{2}${escapedDelim}){5}[0-9A-F]{2}$|^(?:[0-9a-f]{2}${escapedDelim}){5}[0-9a-f]{2}$`); -}; -const cidrv4 = /^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/; -const cidrv6 = /^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|::|([0-9a-fA-F]{1,4})?::([0-9a-fA-F]{1,4}:?){0,6})\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const base64 = /^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/; -const base64url = /^[A-Za-z0-9_-]*$/; -// based on https://stackoverflow.com/questions/106179/regular-expression-to-match-dns-hostname-or-ip-address -// export const hostname: RegExp = /^([a-zA-Z0-9-]+\.)*[a-zA-Z0-9-]+$/; -const hostname = /^(?=.{1,253}\.?$)[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[-0-9a-zA-Z]{0,61}[0-9a-zA-Z])?)*\.?$/; -const domain = /^([a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,}$/; -// https://blog.stevenlevithan.com/archives/validate-phone-number#r4-3 (regex sans spaces) -const e164 = /^\+(?:[0-9]){6,14}[0-9]$/; -// const dateSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -const dateSource = `(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`; -const date = /*@__PURE__*/ new RegExp(`^${dateSource}$`); -function timeSource(args) { - const hhmm = `(?:[01]\\d|2[0-3]):[0-5]\\d`; - const regex = typeof args.precision === "number" - ? args.precision === -1 - ? `${hhmm}` - : args.precision === 0 - ? `${hhmm}:[0-5]\\d` - : `${hhmm}:[0-5]\\d\\.\\d{${args.precision}}` - : `${hhmm}(?::[0-5]\\d(?:\\.\\d+)?)?`; - return regex; -} -function time(args) { - return new RegExp(`^${timeSource(args)}$`); -} -// Adapted from https://stackoverflow.com/a/3143231 -function datetime(args) { - const time = timeSource({ precision: args.precision }); - const opts = ["Z"]; - if (args.local) - opts.push(""); - // if (args.offset) opts.push(`([+-]\\d{2}:\\d{2})`); - if (args.offset) - opts.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`); - const timeRegex = `${time}(?:${opts.join("|")})`; - return new RegExp(`^${dateSource}T(?:${timeRegex})$`); -} -const string = (params) => { - const regex = params ? `[\\s\\S]{${params?.minimum ?? 0},${params?.maximum ?? ""}}` : `[\\s\\S]*`; - return new RegExp(`^${regex}$`); -}; -const bigint = /^-?\d+n?$/; -const integer = /^-?\d+$/; -const number = /^-?\d+(?:\.\d+)?/; -const regexes_boolean = /^(?:true|false)$/i; -const _null = /^null$/i; - -const _undefined = /^undefined$/i; - -// regex for string with no uppercase letters -const lowercase = /^[^A-Z]*$/; -// regex for string with no lowercase letters -const uppercase = /^[^a-z]*$/; -// regex for hexadecimal strings (any length) -const hex = /^[0-9a-fA-F]*$/; -// Hash regexes for different algorithms and encodings -// Helper function to create base64 regex with exact length and padding -function fixedBase64(bodyLength, padding) { - return new RegExp(`^[A-Za-z0-9+/]{${bodyLength}}${padding}$`); -} -// Helper function to create base64url regex with exact length (no padding) -function fixedBase64url(length) { - return new RegExp(`^[A-Za-z0-9_-]{${length}}$`); -} -// MD5 (16 bytes): base64 = 24 chars total (22 + "==") -const md5_hex = /^[0-9a-fA-F]{32}$/; -const md5_base64 = /*@__PURE__*/ fixedBase64(22, "=="); -const md5_base64url = /*@__PURE__*/ fixedBase64url(22); -// SHA1 (20 bytes): base64 = 28 chars total (27 + "=") -const sha1_hex = /^[0-9a-fA-F]{40}$/; -const sha1_base64 = /*@__PURE__*/ fixedBase64(27, "="); -const sha1_base64url = /*@__PURE__*/ fixedBase64url(27); -// SHA256 (32 bytes): base64 = 44 chars total (43 + "=") -const sha256_hex = /^[0-9a-fA-F]{64}$/; -const sha256_base64 = /*@__PURE__*/ fixedBase64(43, "="); -const sha256_base64url = /*@__PURE__*/ fixedBase64url(43); -// SHA384 (48 bytes): base64 = 64 chars total (no padding) -const sha384_hex = /^[0-9a-fA-F]{96}$/; -const sha384_base64 = /*@__PURE__*/ fixedBase64(64, ""); -const sha384_base64url = /*@__PURE__*/ fixedBase64url(64); -// SHA512 (64 bytes): base64 = 88 chars total (86 + "==") -const sha512_hex = /^[0-9a-fA-F]{128}$/; -const sha512_base64 = /*@__PURE__*/ fixedBase64(86, "=="); -const sha512_base64url = /*@__PURE__*/ fixedBase64url(86); - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/checks.js -// import { $ZodType } from "./schemas.js"; - - - -const $ZodCheck = /*@__PURE__*/ $constructor("$ZodCheck", (inst, def) => { - var _a; - inst._zod ?? (inst._zod = {}); - inst._zod.def = def; - (_a = inst._zod).onattach ?? (_a.onattach = []); -}); -const numericOriginMap = { - number: "number", - bigint: "bigint", - object: "date", -}; -const $ZodCheckLessThan = /*@__PURE__*/ $constructor("$ZodCheckLessThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.maximum : bag.exclusiveMaximum) ?? Number.POSITIVE_INFINITY; - if (def.value < curr) { - if (def.inclusive) - bag.maximum = def.value; - else - bag.exclusiveMaximum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value <= def.value : payload.value < def.value) { - return; - } - payload.issues.push({ - origin, - code: "too_big", - maximum: def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckGreaterThan = /*@__PURE__*/ $constructor("$ZodCheckGreaterThan", (inst, def) => { - $ZodCheck.init(inst, def); - const origin = numericOriginMap[typeof def.value]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - const curr = (def.inclusive ? bag.minimum : bag.exclusiveMinimum) ?? Number.NEGATIVE_INFINITY; - if (def.value > curr) { - if (def.inclusive) - bag.minimum = def.value; - else - bag.exclusiveMinimum = def.value; - } - }); - inst._zod.check = (payload) => { - if (def.inclusive ? payload.value >= def.value : payload.value > def.value) { - return; - } - payload.issues.push({ - origin, - code: "too_small", - minimum: def.value, - input: payload.value, - inclusive: def.inclusive, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMultipleOf = -/*@__PURE__*/ $constructor("$ZodCheckMultipleOf", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - var _a; - (_a = inst._zod.bag).multipleOf ?? (_a.multipleOf = def.value); - }); - inst._zod.check = (payload) => { - if (typeof payload.value !== typeof def.value) - throw new Error("Cannot mix number and bigint in multiple_of check."); - const isMultiple = typeof payload.value === "bigint" - ? payload.value % def.value === BigInt(0) - : floatSafeRemainder(payload.value, def.value) === 0; - if (isMultiple) - return; - payload.issues.push({ - origin: typeof payload.value, - code: "not_multiple_of", - divisor: def.value, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckNumberFormat = /*@__PURE__*/ $constructor("$ZodCheckNumberFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - def.format = def.format || "float64"; - const isInt = def.format?.includes("int"); - const origin = isInt ? "int" : "number"; - const [minimum, maximum] = NUMBER_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - if (isInt) - bag.pattern = integer; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (isInt) { - if (!Number.isInteger(input)) { - // invalid_format issue - // payload.issues.push({ - // expected: def.format, - // format: def.format, - // code: "invalid_format", - // input, - // inst, - // }); - // invalid_type issue - payload.issues.push({ - expected: origin, - format: def.format, - code: "invalid_type", - continue: false, - input, - inst, - }); - return; - // not_multiple_of issue - // payload.issues.push({ - // code: "not_multiple_of", - // origin: "number", - // input, - // inst, - // divisor: 1, - // }); - } - if (!Number.isSafeInteger(input)) { - if (input > 0) { - // too_big - payload.issues.push({ - input, - code: "too_big", - maximum: Number.MAX_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - continue: !def.abort, - }); - } - else { - // too_small - payload.issues.push({ - input, - code: "too_small", - minimum: Number.MIN_SAFE_INTEGER, - note: "Integers must be within the safe integer range.", - inst, - origin, - continue: !def.abort, - }); - } - return; - } - } - if (input < minimum) { - payload.issues.push({ - origin: "number", - input, - code: "too_small", - minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "number", - input, - code: "too_big", - maximum, - inst, - }); - } - }; -}); -const $ZodCheckBigIntFormat = /*@__PURE__*/ $constructor("$ZodCheckBigIntFormat", (inst, def) => { - $ZodCheck.init(inst, def); // no format checks - const [minimum, maximum] = BIGINT_FORMAT_RANGES[def.format]; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - bag.minimum = minimum; - bag.maximum = maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - if (input < minimum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_small", - minimum: minimum, - inclusive: true, - inst, - continue: !def.abort, - }); - } - if (input > maximum) { - payload.issues.push({ - origin: "bigint", - input, - code: "too_big", - maximum, - inst, - }); - } - }; -}); -const $ZodCheckMaxSize = /*@__PURE__*/ $constructor("$ZodCheckMaxSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size <= def.maximum) - return; - payload.issues.push({ - origin: getSizableOrigin(input), - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMinSize = /*@__PURE__*/ $constructor("$ZodCheckMinSize", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size >= def.minimum) - return; - payload.issues.push({ - origin: getSizableOrigin(input), - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckSizeEquals = /*@__PURE__*/ $constructor("$ZodCheckSizeEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.size !== undefined; - }); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.size; - bag.maximum = def.size; - bag.size = def.size; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const size = input.size; - if (size === def.size) - return; - const tooBig = size > def.size; - payload.issues.push({ - origin: getSizableOrigin(input), - ...(tooBig ? { code: "too_big", maximum: def.size } : { code: "too_small", minimum: def.size }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMaxLength = /*@__PURE__*/ $constructor("$ZodCheckMaxLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.maximum ?? Number.POSITIVE_INFINITY); - if (def.maximum < curr) - inst._zod.bag.maximum = def.maximum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length <= def.maximum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_big", - maximum: def.maximum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckMinLength = /*@__PURE__*/ $constructor("$ZodCheckMinLength", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; - }); - inst._zod.onattach.push((inst) => { - const curr = (inst._zod.bag.minimum ?? Number.NEGATIVE_INFINITY); - if (def.minimum > curr) - inst._zod.bag.minimum = def.minimum; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length >= def.minimum) - return; - const origin = getLengthableOrigin(input); - payload.issues.push({ - origin, - code: "too_small", - minimum: def.minimum, - inclusive: true, - input, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLengthEquals = /*@__PURE__*/ $constructor("$ZodCheckLengthEquals", (inst, def) => { - var _a; - $ZodCheck.init(inst, def); - (_a = inst._zod.def).when ?? (_a.when = (payload) => { - const val = payload.value; - return !nullish(val) && val.length !== undefined; - }); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.minimum = def.length; - bag.maximum = def.length; - bag.length = def.length; - }); - inst._zod.check = (payload) => { - const input = payload.value; - const length = input.length; - if (length === def.length) - return; - const origin = getLengthableOrigin(input); - const tooBig = length > def.length; - payload.issues.push({ - origin, - ...(tooBig ? { code: "too_big", maximum: def.length } : { code: "too_small", minimum: def.length }), - inclusive: true, - exact: true, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStringFormat = /*@__PURE__*/ $constructor("$ZodCheckStringFormat", (inst, def) => { - var _a, _b; - $ZodCheck.init(inst, def); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.format = def.format; - if (def.pattern) { - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(def.pattern); - } - }); - if (def.pattern) - (_a = inst._zod).check ?? (_a.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: def.format, - input: payload.value, - ...(def.pattern ? { pattern: def.pattern.toString() } : {}), - inst, - continue: !def.abort, - }); - }); - else - (_b = inst._zod).check ?? (_b.check = () => { }); -}); -const $ZodCheckRegex = /*@__PURE__*/ $constructor("$ZodCheckRegex", (inst, def) => { - $ZodCheckStringFormat.init(inst, def); - inst._zod.check = (payload) => { - def.pattern.lastIndex = 0; - if (def.pattern.test(payload.value)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "regex", - input: payload.value, - pattern: def.pattern.toString(), - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckLowerCase = /*@__PURE__*/ $constructor("$ZodCheckLowerCase", (inst, def) => { - def.pattern ?? (def.pattern = lowercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckUpperCase = /*@__PURE__*/ $constructor("$ZodCheckUpperCase", (inst, def) => { - def.pattern ?? (def.pattern = uppercase); - $ZodCheckStringFormat.init(inst, def); -}); -const $ZodCheckIncludes = /*@__PURE__*/ $constructor("$ZodCheckIncludes", (inst, def) => { - $ZodCheck.init(inst, def); - const escapedRegex = escapeRegex(def.includes); - const pattern = new RegExp(typeof def.position === "number" ? `^.{${def.position}}${escapedRegex}` : escapedRegex); - def.pattern = pattern; - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.includes(def.includes, def.position)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "includes", - includes: def.includes, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckStartsWith = /*@__PURE__*/ $constructor("$ZodCheckStartsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`^${escapeRegex(def.prefix)}.*`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.startsWith(def.prefix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "starts_with", - prefix: def.prefix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckEndsWith = /*@__PURE__*/ $constructor("$ZodCheckEndsWith", (inst, def) => { - $ZodCheck.init(inst, def); - const pattern = new RegExp(`.*${escapeRegex(def.suffix)}$`); - def.pattern ?? (def.pattern = pattern); - inst._zod.onattach.push((inst) => { - const bag = inst._zod.bag; - bag.patterns ?? (bag.patterns = new Set()); - bag.patterns.add(pattern); - }); - inst._zod.check = (payload) => { - if (payload.value.endsWith(def.suffix)) - return; - payload.issues.push({ - origin: "string", - code: "invalid_format", - format: "ends_with", - suffix: def.suffix, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -/////////////////////////////////// -///// $ZodCheckProperty ///// -/////////////////////////////////// -function handleCheckPropertyResult(result, payload, property) { - if (result.issues.length) { - payload.issues.push(...prefixIssues(property, result.issues)); - } -} -const $ZodCheckProperty = /*@__PURE__*/ $constructor("$ZodCheckProperty", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - const result = def.schema._zod.run({ - value: payload.value[def.property], - issues: [], - }, {}); - if (result instanceof Promise) { - return result.then((result) => handleCheckPropertyResult(result, payload, def.property)); - } - handleCheckPropertyResult(result, payload, def.property); - return; - }; -}); -const $ZodCheckMimeType = /*@__PURE__*/ $constructor("$ZodCheckMimeType", (inst, def) => { - $ZodCheck.init(inst, def); - const mimeSet = new Set(def.mime); - inst._zod.onattach.push((inst) => { - inst._zod.bag.mime = def.mime; - }); - inst._zod.check = (payload) => { - if (mimeSet.has(payload.value.type)) - return; - payload.issues.push({ - code: "invalid_value", - values: def.mime, - input: payload.value.type, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCheckOverwrite = /*@__PURE__*/ $constructor("$ZodCheckOverwrite", (inst, def) => { - $ZodCheck.init(inst, def); - inst._zod.check = (payload) => { - payload.value = def.tx(payload.value); - }; -}); - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/doc.js -class Doc { - constructor(args = []) { - this.content = []; - this.indent = 0; - if (this) - this.args = args; - } - indented(fn) { - this.indent += 1; - fn(this); - this.indent -= 1; - } - write(arg) { - if (typeof arg === "function") { - arg(this, { execution: "sync" }); - arg(this, { execution: "async" }); - return; - } - const content = arg; - const lines = content.split("\n").filter((x) => x); - const minIndent = Math.min(...lines.map((x) => x.length - x.trimStart().length)); - const dedented = lines.map((x) => x.slice(minIndent)).map((x) => " ".repeat(this.indent * 2) + x); - for (const line of dedented) { - this.content.push(line); - } - } - compile() { - const F = Function; - const args = this?.args; - const content = this?.content ?? [``]; - const lines = [...content.map((x) => ` ${x}`)]; - // console.log(lines.join("\n")); - return new F(...args, lines.join("\n")); - } -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/versions.js -const versions_version = { - major: 4, - minor: 2, - patch: 1, -}; - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/schemas.js - - - - - - - -const $ZodType = /*@__PURE__*/ $constructor("$ZodType", (inst, def) => { - var _a; - inst ?? (inst = {}); - inst._zod.def = def; // set _def property - inst._zod.bag = inst._zod.bag || {}; // initialize _bag object - inst._zod.version = versions_version; - const checks = [...(inst._zod.def.checks ?? [])]; - // if inst is itself a checks.$ZodCheck, run it as a check - if (inst._zod.traits.has("$ZodCheck")) { - checks.unshift(inst); - } - for (const ch of checks) { - for (const fn of ch._zod.onattach) { - fn(inst); - } - } - if (checks.length === 0) { - // deferred initializer - // inst._zod.parse is not yet defined - (_a = inst._zod).deferred ?? (_a.deferred = []); - inst._zod.deferred?.push(() => { - inst._zod.run = inst._zod.parse; - }); - } - else { - const runChecks = (payload, checks, ctx) => { - let isAborted = aborted(payload); - let asyncResult; - for (const ch of checks) { - if (ch._zod.def.when) { - const shouldRun = ch._zod.def.when(payload); - if (!shouldRun) - continue; - } - else if (isAborted) { - continue; - } - const currLen = payload.issues.length; - const _ = ch._zod.check(payload); - if (_ instanceof Promise && ctx?.async === false) { - throw new $ZodAsyncError(); - } - if (asyncResult || _ instanceof Promise) { - asyncResult = (asyncResult ?? Promise.resolve()).then(async () => { - await _; - const nextLen = payload.issues.length; - if (nextLen === currLen) - return; - if (!isAborted) - isAborted = aborted(payload, currLen); - }); - } - else { - const nextLen = payload.issues.length; - if (nextLen === currLen) - continue; - if (!isAborted) - isAborted = aborted(payload, currLen); - } - } - if (asyncResult) { - return asyncResult.then(() => { - return payload; - }); - } - return payload; - }; - const handleCanaryResult = (canary, payload, ctx) => { - // abort if the canary is aborted - if (aborted(canary)) { - canary.aborted = true; - return canary; - } - // run checks first, then - const checkResult = runChecks(payload, checks, ctx); - if (checkResult instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return checkResult.then((checkResult) => inst._zod.parse(checkResult, ctx)); - } - return inst._zod.parse(checkResult, ctx); - }; - inst._zod.run = (payload, ctx) => { - if (ctx.skipChecks) { - return inst._zod.parse(payload, ctx); - } - if (ctx.direction === "backward") { - // run canary - // initial pass (no checks) - const canary = inst._zod.parse({ value: payload.value, issues: [] }, { ...ctx, skipChecks: true }); - if (canary instanceof Promise) { - return canary.then((canary) => { - return handleCanaryResult(canary, payload, ctx); - }); - } - return handleCanaryResult(canary, payload, ctx); - } - // forward - const result = inst._zod.parse(payload, ctx); - if (result instanceof Promise) { - if (ctx.async === false) - throw new $ZodAsyncError(); - return result.then((result) => runChecks(result, checks, ctx)); - } - return runChecks(result, checks, ctx); - }; - } - inst["~standard"] = { - validate: (value) => { - try { - const r = safeParse(inst, value); - return r.success ? { value: r.data } : { issues: r.error?.issues }; - } - catch (_) { - return safeParseAsync(inst, value).then((r) => (r.success ? { value: r.data } : { issues: r.error?.issues })); - } - }, - vendor: "zod", - version: 1, - }; -}); - -const $ZodString = /*@__PURE__*/ $constructor("$ZodString", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = [...(inst?._zod.bag?.patterns ?? [])].pop() ?? string(inst._zod.bag); - inst._zod.parse = (payload, _) => { - if (def.coerce) - try { - payload.value = String(payload.value); - } - catch (_) { } - if (typeof payload.value === "string") - return payload; - payload.issues.push({ - expected: "string", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodStringFormat = /*@__PURE__*/ $constructor("$ZodStringFormat", (inst, def) => { - // check initialization must come first - $ZodCheckStringFormat.init(inst, def); - $ZodString.init(inst, def); -}); -const $ZodGUID = /*@__PURE__*/ $constructor("$ZodGUID", (inst, def) => { - def.pattern ?? (def.pattern = guid); - $ZodStringFormat.init(inst, def); -}); -const $ZodUUID = /*@__PURE__*/ $constructor("$ZodUUID", (inst, def) => { - if (def.version) { - const versionMap = { - v1: 1, - v2: 2, - v3: 3, - v4: 4, - v5: 5, - v6: 6, - v7: 7, - v8: 8, - }; - const v = versionMap[def.version]; - if (v === undefined) - throw new Error(`Invalid UUID version: "${def.version}"`); - def.pattern ?? (def.pattern = uuid(v)); - } - else - def.pattern ?? (def.pattern = uuid()); - $ZodStringFormat.init(inst, def); -}); -const $ZodEmail = /*@__PURE__*/ $constructor("$ZodEmail", (inst, def) => { - def.pattern ?? (def.pattern = email); - $ZodStringFormat.init(inst, def); -}); -const $ZodURL = /*@__PURE__*/ $constructor("$ZodURL", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - try { - // Trim whitespace from input - const trimmed = payload.value.trim(); - // @ts-ignore - const url = new URL(trimmed); - if (def.hostname) { - def.hostname.lastIndex = 0; - if (!def.hostname.test(url.hostname)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid hostname", - pattern: def.hostname.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - } - if (def.protocol) { - def.protocol.lastIndex = 0; - if (!def.protocol.test(url.protocol.endsWith(":") ? url.protocol.slice(0, -1) : url.protocol)) { - payload.issues.push({ - code: "invalid_format", - format: "url", - note: "Invalid protocol", - pattern: def.protocol.source, - input: payload.value, - inst, - continue: !def.abort, - }); - } - } - // Set the output value based on normalize flag - if (def.normalize) { - // Use normalized URL - payload.value = url.href; - } - else { - // Preserve the original input (trimmed) - payload.value = trimmed; - } - return; - } - catch (_) { - payload.issues.push({ - code: "invalid_format", - format: "url", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodEmoji = /*@__PURE__*/ $constructor("$ZodEmoji", (inst, def) => { - def.pattern ?? (def.pattern = emoji()); - $ZodStringFormat.init(inst, def); -}); -const $ZodNanoID = /*@__PURE__*/ $constructor("$ZodNanoID", (inst, def) => { - def.pattern ?? (def.pattern = nanoid); - $ZodStringFormat.init(inst, def); -}); -const $ZodCUID = /*@__PURE__*/ $constructor("$ZodCUID", (inst, def) => { - def.pattern ?? (def.pattern = cuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodCUID2 = /*@__PURE__*/ $constructor("$ZodCUID2", (inst, def) => { - def.pattern ?? (def.pattern = cuid2); - $ZodStringFormat.init(inst, def); -}); -const $ZodULID = /*@__PURE__*/ $constructor("$ZodULID", (inst, def) => { - def.pattern ?? (def.pattern = ulid); - $ZodStringFormat.init(inst, def); -}); -const $ZodXID = /*@__PURE__*/ $constructor("$ZodXID", (inst, def) => { - def.pattern ?? (def.pattern = xid); - $ZodStringFormat.init(inst, def); -}); -const $ZodKSUID = /*@__PURE__*/ $constructor("$ZodKSUID", (inst, def) => { - def.pattern ?? (def.pattern = ksuid); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODateTime = /*@__PURE__*/ $constructor("$ZodISODateTime", (inst, def) => { - def.pattern ?? (def.pattern = datetime(def)); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODate = /*@__PURE__*/ $constructor("$ZodISODate", (inst, def) => { - def.pattern ?? (def.pattern = date); - $ZodStringFormat.init(inst, def); -}); -const $ZodISOTime = /*@__PURE__*/ $constructor("$ZodISOTime", (inst, def) => { - def.pattern ?? (def.pattern = time(def)); - $ZodStringFormat.init(inst, def); -}); -const $ZodISODuration = /*@__PURE__*/ $constructor("$ZodISODuration", (inst, def) => { - def.pattern ?? (def.pattern = duration); - $ZodStringFormat.init(inst, def); -}); -const $ZodIPv4 = /*@__PURE__*/ $constructor("$ZodIPv4", (inst, def) => { - def.pattern ?? (def.pattern = ipv4); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv4`; -}); -const $ZodIPv6 = /*@__PURE__*/ $constructor("$ZodIPv6", (inst, def) => { - def.pattern ?? (def.pattern = ipv6); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `ipv6`; - inst._zod.check = (payload) => { - try { - // @ts-ignore - new URL(`http://[${payload.value}]`); - // return; - } - catch { - payload.issues.push({ - code: "invalid_format", - format: "ipv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -const $ZodMAC = /*@__PURE__*/ $constructor("$ZodMAC", (inst, def) => { - def.pattern ?? (def.pattern = mac(def.delimiter)); - $ZodStringFormat.init(inst, def); - inst._zod.bag.format = `mac`; -}); -const $ZodCIDRv4 = /*@__PURE__*/ $constructor("$ZodCIDRv4", (inst, def) => { - def.pattern ?? (def.pattern = cidrv4); - $ZodStringFormat.init(inst, def); -}); -const $ZodCIDRv6 = /*@__PURE__*/ $constructor("$ZodCIDRv6", (inst, def) => { - def.pattern ?? (def.pattern = cidrv6); // not used for validation - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - const parts = payload.value.split("/"); - try { - if (parts.length !== 2) - throw new Error(); - const [address, prefix] = parts; - if (!prefix) - throw new Error(); - const prefixNum = Number(prefix); - if (`${prefixNum}` !== prefix) - throw new Error(); - if (prefixNum < 0 || prefixNum > 128) - throw new Error(); - // @ts-ignore - new URL(`http://[${address}]`); - } - catch { - payload.issues.push({ - code: "invalid_format", - format: "cidrv6", - input: payload.value, - inst, - continue: !def.abort, - }); - } - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64(data) { - if (data === "") - return true; - if (data.length % 4 !== 0) - return false; - try { - // @ts-ignore - atob(data); - return true; - } - catch { - return false; - } -} -const $ZodBase64 = /*@__PURE__*/ $constructor("$ZodBase64", (inst, def) => { - def.pattern ?? (def.pattern = base64); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64"; - inst._zod.check = (payload) => { - if (isValidBase64(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -////////////////////////////// ZodBase64 ////////////////////////////// -function isValidBase64URL(data) { - if (!base64url.test(data)) - return false; - const base64 = data.replace(/[-_]/g, (c) => (c === "-" ? "+" : "/")); - const padded = base64.padEnd(Math.ceil(base64.length / 4) * 4, "="); - return isValidBase64(padded); -} -const $ZodBase64URL = /*@__PURE__*/ $constructor("$ZodBase64URL", (inst, def) => { - def.pattern ?? (def.pattern = base64url); - $ZodStringFormat.init(inst, def); - inst._zod.bag.contentEncoding = "base64url"; - inst._zod.check = (payload) => { - if (isValidBase64URL(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: "base64url", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodE164 = /*@__PURE__*/ $constructor("$ZodE164", (inst, def) => { - def.pattern ?? (def.pattern = e164); - $ZodStringFormat.init(inst, def); -}); -////////////////////////////// ZodJWT ////////////////////////////// -function isValidJWT(token, algorithm = null) { - try { - const tokensParts = token.split("."); - if (tokensParts.length !== 3) - return false; - const [header] = tokensParts; - if (!header) - return false; - // @ts-ignore - const parsedHeader = JSON.parse(atob(header)); - if ("typ" in parsedHeader && parsedHeader?.typ !== "JWT") - return false; - if (!parsedHeader.alg) - return false; - if (algorithm && (!("alg" in parsedHeader) || parsedHeader.alg !== algorithm)) - return false; - return true; - } - catch { - return false; - } -} -const $ZodJWT = /*@__PURE__*/ $constructor("$ZodJWT", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (isValidJWT(payload.value, def.alg)) - return; - payload.issues.push({ - code: "invalid_format", - format: "jwt", - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodCustomStringFormat = /*@__PURE__*/ $constructor("$ZodCustomStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - inst._zod.check = (payload) => { - if (def.fn(payload.value)) - return; - payload.issues.push({ - code: "invalid_format", - format: def.format, - input: payload.value, - inst, - continue: !def.abort, - }); - }; -}); -const $ZodNumber = /*@__PURE__*/ $constructor("$ZodNumber", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = inst._zod.bag.pattern ?? number; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Number(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "number" && !Number.isNaN(input) && Number.isFinite(input)) { - return payload; - } - const received = typeof input === "number" - ? Number.isNaN(input) - ? "NaN" - : !Number.isFinite(input) - ? "Infinity" - : undefined - : undefined; - payload.issues.push({ - expected: "number", - code: "invalid_type", - input, - inst, - ...(received ? { received } : {}), - }); - return payload; - }; -}); -const $ZodNumberFormat = /*@__PURE__*/ $constructor("$ZodNumberFormat", (inst, def) => { - $ZodCheckNumberFormat.init(inst, def); - $ZodNumber.init(inst, def); // no format checks -}); -const $ZodBoolean = /*@__PURE__*/ $constructor("$ZodBoolean", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = regexes_boolean; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = Boolean(payload.value); - } - catch (_) { } - const input = payload.value; - if (typeof input === "boolean") - return payload; - payload.issues.push({ - expected: "boolean", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodBigInt = /*@__PURE__*/ $constructor("$ZodBigInt", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = bigint; - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) - try { - payload.value = BigInt(payload.value); - } - catch (_) { } - if (typeof payload.value === "bigint") - return payload; - payload.issues.push({ - expected: "bigint", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodBigIntFormat = /*@__PURE__*/ $constructor("$ZodBigIntFormat", (inst, def) => { - $ZodCheckBigIntFormat.init(inst, def); - $ZodBigInt.init(inst, def); // no format checks -}); -const $ZodSymbol = /*@__PURE__*/ $constructor("$ZodSymbol", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "symbol") - return payload; - payload.issues.push({ - expected: "symbol", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodUndefined = /*@__PURE__*/ $constructor("$ZodUndefined", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _undefined; - inst._zod.values = new Set([undefined]); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "undefined", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodNull = /*@__PURE__*/ $constructor("$ZodNull", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.pattern = _null; - inst._zod.values = new Set([null]); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (input === null) - return payload; - payload.issues.push({ - expected: "null", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodAny = /*@__PURE__*/ $constructor("$ZodAny", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodUnknown = /*@__PURE__*/ $constructor("$ZodUnknown", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload) => payload; -}); -const $ZodNever = /*@__PURE__*/ $constructor("$ZodNever", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - payload.issues.push({ - expected: "never", - code: "invalid_type", - input: payload.value, - inst, - }); - return payload; - }; -}); -const $ZodVoid = /*@__PURE__*/ $constructor("$ZodVoid", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (typeof input === "undefined") - return payload; - payload.issues.push({ - expected: "void", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodDate = /*@__PURE__*/ $constructor("$ZodDate", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (def.coerce) { - try { - payload.value = new Date(payload.value); - } - catch (_err) { } - } - const input = payload.value; - const isDate = input instanceof Date; - const isValidDate = isDate && !Number.isNaN(input.getTime()); - if (isValidDate) - return payload; - payload.issues.push({ - expected: "date", - code: "invalid_type", - input, - ...(isDate ? { received: "Invalid Date" } : {}), - inst, - }); - return payload; - }; -}); -function handleArrayResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodArray = /*@__PURE__*/ $constructor("$ZodArray", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - expected: "array", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = Array(input.length); - const proms = []; - for (let i = 0; i < input.length; i++) { - const item = input[i]; - const result = def.element._zod.run({ - value: item, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleArrayResult(result, payload, i))); - } - else { - handleArrayResult(result, payload, i); - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; //handleArrayResultsAsync(parseResults, final); - }; -}); -function handlePropertyResult(result, final, key, input) { - if (result.issues.length) { - final.issues.push(...prefixIssues(key, result.issues)); - } - if (result.value === undefined) { - if (key in input) { - final.value[key] = undefined; - } - } - else { - final.value[key] = result.value; - } -} -function normalizeDef(def) { - const keys = Object.keys(def.shape); - for (const k of keys) { - if (!def.shape?.[k]?._zod?.traits?.has("$ZodType")) { - throw new Error(`Invalid element at key "${k}": expected a Zod schema`); - } - } - const okeys = optionalKeys(def.shape); - return { - ...def, - keys, - keySet: new Set(keys), - numKeys: keys.length, - optionalKeys: new Set(okeys), - }; -} -function handleCatchall(proms, input, payload, ctx, def, inst) { - const unrecognized = []; - // iterate over input keys - const keySet = def.keySet; - const _catchall = def.catchall._zod; - const t = _catchall.def.type; - for (const key in input) { - if (keySet.has(key)) - continue; - if (t === "never") { - unrecognized.push(key); - continue; - } - const r = _catchall.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input))); - } - else { - handlePropertyResult(r, payload, key, input); - } - } - if (unrecognized.length) { - payload.issues.push({ - code: "unrecognized_keys", - keys: unrecognized, - input, - inst, - }); - } - if (!proms.length) - return payload; - return Promise.all(proms).then(() => { - return payload; - }); -} -const $ZodObject = /*@__PURE__*/ $constructor("$ZodObject", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodType.init(inst, def); - // const sh = def.shape; - const desc = Object.getOwnPropertyDescriptor(def, "shape"); - if (!desc?.get) { - const sh = def.shape; - Object.defineProperty(def, "shape", { - get: () => { - const newSh = { ...sh }; - Object.defineProperty(def, "shape", { - value: newSh, - }); - return newSh; - }, - }); - } - const _normalized = cached(() => normalizeDef(def)); - defineLazy(inst._zod, "propValues", () => { - const shape = def.shape; - const propValues = {}; - for (const key in shape) { - const field = shape[key]._zod; - if (field.values) { - propValues[key] ?? (propValues[key] = new Set()); - for (const v of field.values) - propValues[key].add(v); - } - } - return propValues; - }); - const isObject = util_isObject; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - payload.value = {}; - const proms = []; - const shape = value.shape; - for (const key of value.keys) { - const el = shape[key]; - const r = el._zod.run({ value: input[key], issues: [] }, ctx); - if (r instanceof Promise) { - proms.push(r.then((r) => handlePropertyResult(r, payload, key, input))); - } - else { - handlePropertyResult(r, payload, key, input); - } - } - if (!catchall) { - return proms.length ? Promise.all(proms).then(() => payload) : payload; - } - return handleCatchall(proms, input, payload, ctx, _normalized.value, inst); - }; -}); -const $ZodObjectJIT = /*@__PURE__*/ $constructor("$ZodObjectJIT", (inst, def) => { - // requires cast because technically $ZodObject doesn't extend - $ZodObject.init(inst, def); - const superParse = inst._zod.parse; - const _normalized = cached(() => normalizeDef(def)); - const generateFastpass = (shape) => { - const doc = new Doc(["shape", "payload", "ctx"]); - const normalized = _normalized.value; - const parseStr = (key) => { - const k = esc(key); - return `shape[${k}]._zod.run({ value: input[${k}], issues: [] }, ctx)`; - }; - doc.write(`const input = payload.value;`); - const ids = Object.create(null); - let counter = 0; - for (const key of normalized.keys) { - ids[key] = `key_${counter++}`; - } - // A: preserve key order { - doc.write(`const newResult = {};`); - for (const key of normalized.keys) { - const id = ids[key]; - const k = esc(key); - doc.write(`const ${id} = ${parseStr(key)};`); - doc.write(` - if (${id}.issues.length) { - payload.issues = payload.issues.concat(${id}.issues.map(iss => ({ - ...iss, - path: iss.path ? [${k}, ...iss.path] : [${k}] - }))); - } - - - if (${id}.value === undefined) { - if (${k} in input) { - newResult[${k}] = undefined; - } - } else { - newResult[${k}] = ${id}.value; - } - - `); - } - doc.write(`payload.value = newResult;`); - doc.write(`return payload;`); - const fn = doc.compile(); - return (payload, ctx) => fn(shape, payload, ctx); - }; - let fastpass; - const isObject = util_isObject; - const jit = !globalConfig.jitless; - const allowsEval = util_allowsEval; - const fastEnabled = jit && allowsEval.value; // && !def.catchall; - const catchall = def.catchall; - let value; - inst._zod.parse = (payload, ctx) => { - value ?? (value = _normalized.value); - const input = payload.value; - if (!isObject(input)) { - payload.issues.push({ - expected: "object", - code: "invalid_type", - input, - inst, - }); - return payload; - } - if (jit && fastEnabled && ctx?.async === false && ctx.jitless !== true) { - // always synchronous - if (!fastpass) - fastpass = generateFastpass(def.shape); - payload = fastpass(payload, ctx); - if (!catchall) - return payload; - return handleCatchall([], input, payload, ctx, value, inst); - } - return superParse(payload, ctx); - }; -}); -function handleUnionResults(results, final, inst, ctx) { - for (const result of results) { - if (result.issues.length === 0) { - final.value = result.value; - return final; - } - } - const nonaborted = results.filter((r) => !aborted(r)); - if (nonaborted.length === 1) { - final.value = nonaborted[0].value; - return nonaborted[0]; - } - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), - }); - return final; -} -const $ZodUnion = /*@__PURE__*/ $constructor("$ZodUnion", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.options.some((o) => o._zod.optin === "optional") ? "optional" : undefined); - defineLazy(inst._zod, "optout", () => def.options.some((o) => o._zod.optout === "optional") ? "optional" : undefined); - defineLazy(inst._zod, "values", () => { - if (def.options.every((o) => o._zod.values)) { - return new Set(def.options.flatMap((option) => Array.from(option._zod.values))); - } - return undefined; - }); - defineLazy(inst._zod, "pattern", () => { - if (def.options.every((o) => o._zod.pattern)) { - const patterns = def.options.map((o) => o._zod.pattern); - return new RegExp(`^(${patterns.map((p) => cleanRegex(p.source)).join("|")})$`); - } - return undefined; - }); - const single = def.options.length === 1; - const first = def.options[0]._zod.run; - inst._zod.parse = (payload, ctx) => { - if (single) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - if (result.issues.length === 0) - return result; - results.push(result); - } - } - if (!async) - return handleUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleUnionResults(results, payload, inst, ctx); - }); - }; -}); -function handleExclusiveUnionResults(results, final, inst, ctx) { - const successes = results.filter((r) => r.issues.length === 0); - if (successes.length === 1) { - final.value = successes[0].value; - return final; - } - if (successes.length === 0) { - // No matches - same as regular union - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: results.map((result) => result.issues.map((iss) => finalizeIssue(iss, ctx, config()))), - }); - } - else { - // Multiple matches - exclusive union failure - final.issues.push({ - code: "invalid_union", - input: final.value, - inst, - errors: [], - inclusive: false, - }); - } - return final; -} -const $ZodXor = /*@__PURE__*/ $constructor("$ZodXor", (inst, def) => { - $ZodUnion.init(inst, def); - def.inclusive = false; - const single = def.options.length === 1; - const first = def.options[0]._zod.run; - inst._zod.parse = (payload, ctx) => { - if (single) { - return first(payload, ctx); - } - let async = false; - const results = []; - for (const option of def.options) { - const result = option._zod.run({ - value: payload.value, - issues: [], - }, ctx); - if (result instanceof Promise) { - results.push(result); - async = true; - } - else { - results.push(result); - } - } - if (!async) - return handleExclusiveUnionResults(results, payload, inst, ctx); - return Promise.all(results).then((results) => { - return handleExclusiveUnionResults(results, payload, inst, ctx); - }); - }; -}); -const $ZodDiscriminatedUnion = -/*@__PURE__*/ -$constructor("$ZodDiscriminatedUnion", (inst, def) => { - def.inclusive = false; - $ZodUnion.init(inst, def); - const _super = inst._zod.parse; - defineLazy(inst._zod, "propValues", () => { - const propValues = {}; - for (const option of def.options) { - const pv = option._zod.propValues; - if (!pv || Object.keys(pv).length === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(option)}"`); - for (const [k, v] of Object.entries(pv)) { - if (!propValues[k]) - propValues[k] = new Set(); - for (const val of v) { - propValues[k].add(val); - } - } - } - return propValues; - }); - const disc = cached(() => { - const opts = def.options; - const map = new Map(); - for (const o of opts) { - const values = o._zod.propValues?.[def.discriminator]; - if (!values || values.size === 0) - throw new Error(`Invalid discriminated union option at index "${def.options.indexOf(o)}"`); - for (const v of values) { - if (map.has(v)) { - throw new Error(`Duplicate discriminator value "${String(v)}"`); - } - map.set(v, o); - } - } - return map; - }); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!util_isObject(input)) { - payload.issues.push({ - code: "invalid_type", - expected: "object", - input, - inst, - }); - return payload; - } - const opt = disc.value.get(input?.[def.discriminator]); - if (opt) { - return opt._zod.run(payload, ctx); - } - if (def.unionFallback) { - return _super(payload, ctx); - } - // no matching discriminator - payload.issues.push({ - code: "invalid_union", - errors: [], - note: "No matching discriminator", - discriminator: def.discriminator, - input, - path: [def.discriminator], - inst, - }); - return payload; - }; -}); -const $ZodIntersection = /*@__PURE__*/ $constructor("$ZodIntersection", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - const left = def.left._zod.run({ value: input, issues: [] }, ctx); - const right = def.right._zod.run({ value: input, issues: [] }, ctx); - const async = left instanceof Promise || right instanceof Promise; - if (async) { - return Promise.all([left, right]).then(([left, right]) => { - return handleIntersectionResults(payload, left, right); - }); - } - return handleIntersectionResults(payload, left, right); - }; -}); -function mergeValues(a, b) { - // const aType = parse.t(a); - // const bType = parse.t(b); - if (a === b) { - return { valid: true, data: a }; - } - if (a instanceof Date && b instanceof Date && +a === +b) { - return { valid: true, data: a }; - } - if (isPlainObject(a) && isPlainObject(b)) { - const bKeys = Object.keys(b); - const sharedKeys = Object.keys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [key, ...sharedValue.mergeErrorPath], - }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - if (Array.isArray(a) && Array.isArray(b)) { - if (a.length !== b.length) { - return { valid: false, mergeErrorPath: [] }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { - valid: false, - mergeErrorPath: [index, ...sharedValue.mergeErrorPath], - }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - return { valid: false, mergeErrorPath: [] }; -} -function handleIntersectionResults(result, left, right) { - if (left.issues.length) { - result.issues.push(...left.issues); - } - if (right.issues.length) { - result.issues.push(...right.issues); - } - if (aborted(result)) - return result; - const merged = mergeValues(left.value, right.value); - if (!merged.valid) { - throw new Error(`Unmergable intersection. Error path: ` + `${JSON.stringify(merged.mergeErrorPath)}`); - } - result.value = merged.data; - return result; -} -const $ZodTuple = /*@__PURE__*/ $constructor("$ZodTuple", (inst, def) => { - $ZodType.init(inst, def); - const items = def.items; - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!Array.isArray(input)) { - payload.issues.push({ - input, - inst, - expected: "tuple", - code: "invalid_type", - }); - return payload; - } - payload.value = []; - const proms = []; - const reversedIndex = [...items].reverse().findIndex((item) => item._zod.optin !== "optional"); - const optStart = reversedIndex === -1 ? 0 : items.length - reversedIndex; - if (!def.rest) { - const tooBig = input.length > items.length; - const tooSmall = input.length < optStart - 1; - if (tooBig || tooSmall) { - payload.issues.push({ - ...(tooBig ? { code: "too_big", maximum: items.length } : { code: "too_small", minimum: items.length }), - input, - inst, - origin: "array", - }); - return payload; - } - } - let i = -1; - for (const item of items) { - i++; - if (i >= input.length) - if (i >= optStart) - continue; - const result = item._zod.run({ - value: input[i], - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleTupleResult(result, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - if (def.rest) { - const rest = input.slice(items.length); - for (const el of rest) { - i++; - const result = def.rest._zod.run({ - value: el, - issues: [], - }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleTupleResult(result, payload, i))); - } - else { - handleTupleResult(result, payload, i); - } - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}); -function handleTupleResult(result, final, index) { - if (result.issues.length) { - final.issues.push(...prefixIssues(index, result.issues)); - } - final.value[index] = result.value; -} -const $ZodRecord = /*@__PURE__*/ $constructor("$ZodRecord", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!isPlainObject(input)) { - payload.issues.push({ - expected: "record", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - const values = def.keyType._zod.values; - if (values) { - payload.value = {}; - const recordKeys = new Set(); - for (const key of values) { - if (typeof key === "string" || typeof key === "number" || typeof key === "symbol") { - recordKeys.add(typeof key === "number" ? key.toString() : key); - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[key] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[key] = result.value; - } - } - } - let unrecognized; - for (const key in input) { - if (!recordKeys.has(key)) { - unrecognized = unrecognized ?? []; - unrecognized.push(key); - } - } - if (unrecognized && unrecognized.length > 0) { - payload.issues.push({ - code: "unrecognized_keys", - input, - inst, - keys: unrecognized, - }); - } - } - else { - payload.value = {}; - for (const key of Reflect.ownKeys(input)) { - if (key === "__proto__") - continue; - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - if (keyResult instanceof Promise) { - throw new Error("Async schemas not supported in object keys currently"); - } - if (keyResult.issues.length) { - if (def.mode === "loose") { - // Pass through unchanged - payload.value[key] = input[key]; - } - else { - // Default "strict" behavior: error on invalid key - payload.issues.push({ - code: "invalid_key", - origin: "record", - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - input: key, - path: [key], - inst, - }); - } - continue; - } - const result = def.valueType._zod.run({ value: input[key], issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[keyResult.value] = result.value; - })); - } - else { - if (result.issues.length) { - payload.issues.push(...prefixIssues(key, result.issues)); - } - payload.value[keyResult.value] = result.value; - } - } - } - if (proms.length) { - return Promise.all(proms).then(() => payload); - } - return payload; - }; -}); -const $ZodMap = /*@__PURE__*/ $constructor("$ZodMap", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Map)) { - payload.issues.push({ - expected: "map", - code: "invalid_type", - input, - inst, - }); - return payload; - } - const proms = []; - payload.value = new Map(); - for (const [key, value] of input) { - const keyResult = def.keyType._zod.run({ value: key, issues: [] }, ctx); - const valueResult = def.valueType._zod.run({ value: value, issues: [] }, ctx); - if (keyResult instanceof Promise || valueResult instanceof Promise) { - proms.push(Promise.all([keyResult, valueResult]).then(([keyResult, valueResult]) => { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - })); - } - else { - handleMapResult(keyResult, valueResult, payload, key, input, inst, ctx); - } - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}); -function handleMapResult(keyResult, valueResult, final, key, input, inst, ctx) { - if (keyResult.issues.length) { - if (propertyKeyTypes.has(typeof key)) { - final.issues.push(...prefixIssues(key, keyResult.issues)); - } - else { - final.issues.push({ - code: "invalid_key", - origin: "map", - input, - inst, - issues: keyResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - }); - } - } - if (valueResult.issues.length) { - if (propertyKeyTypes.has(typeof key)) { - final.issues.push(...prefixIssues(key, valueResult.issues)); - } - else { - final.issues.push({ - origin: "map", - code: "invalid_element", - input, - inst, - key: key, - issues: valueResult.issues.map((iss) => finalizeIssue(iss, ctx, config())), - }); - } - } - final.value.set(keyResult.value, valueResult.value); -} -const $ZodSet = /*@__PURE__*/ $constructor("$ZodSet", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - const input = payload.value; - if (!(input instanceof Set)) { - payload.issues.push({ - input, - inst, - expected: "set", - code: "invalid_type", - }); - return payload; - } - const proms = []; - payload.value = new Set(); - for (const item of input) { - const result = def.valueType._zod.run({ value: item, issues: [] }, ctx); - if (result instanceof Promise) { - proms.push(result.then((result) => handleSetResult(result, payload))); - } - else - handleSetResult(result, payload); - } - if (proms.length) - return Promise.all(proms).then(() => payload); - return payload; - }; -}); -function handleSetResult(result, final) { - if (result.issues.length) { - final.issues.push(...result.issues); - } - final.value.add(result.value); -} -const $ZodEnum = /*@__PURE__*/ $constructor("$ZodEnum", (inst, def) => { - $ZodType.init(inst, def); - const values = getEnumValues(def.entries); - const valuesSet = new Set(values); - inst._zod.values = valuesSet; - inst._zod.pattern = new RegExp(`^(${values - .filter((k) => propertyKeyTypes.has(typeof k)) - .map((o) => (typeof o === "string" ? escapeRegex(o) : o.toString())) - .join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (valuesSet.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values, - input, - inst, - }); - return payload; - }; -}); -const $ZodLiteral = /*@__PURE__*/ $constructor("$ZodLiteral", (inst, def) => { - $ZodType.init(inst, def); - if (def.values.length === 0) { - throw new Error("Cannot create literal schema with no valid values"); - } - const values = new Set(def.values); - inst._zod.values = values; - inst._zod.pattern = new RegExp(`^(${def.values - .map((o) => (typeof o === "string" ? escapeRegex(o) : o ? escapeRegex(o.toString()) : String(o))) - .join("|")})$`); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - if (values.has(input)) { - return payload; - } - payload.issues.push({ - code: "invalid_value", - values: def.values, - input, - inst, - }); - return payload; - }; -}); -const $ZodFile = /*@__PURE__*/ $constructor("$ZodFile", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - const input = payload.value; - // @ts-ignore - if (input instanceof File) - return payload; - payload.issues.push({ - expected: "file", - code: "invalid_type", - input, - inst, - }); - return payload; - }; -}); -const $ZodTransform = /*@__PURE__*/ $constructor("$ZodTransform", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - const _out = def.transform(payload.value, payload); - if (ctx.async) { - const output = _out instanceof Promise ? _out : Promise.resolve(_out); - return output.then((output) => { - payload.value = output; - return payload; - }); - } - if (_out instanceof Promise) { - throw new $ZodAsyncError(); - } - payload.value = _out; - return payload; - }; -}); -function handleOptionalResult(result, input) { - if (result.issues.length && input === undefined) { - return { issues: [], value: undefined }; - } - return result; -} -const $ZodOptional = /*@__PURE__*/ $constructor("$ZodOptional", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - inst._zod.optout = "optional"; - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? new Set([...def.innerType._zod.values, undefined]) : undefined; - }); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)})?$`) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - if (def.innerType._zod.optin === "optional") { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) - return result.then((r) => handleOptionalResult(r, payload.value)); - return handleOptionalResult(result, payload.value); - } - if (payload.value === undefined) { - return payload; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNullable = /*@__PURE__*/ $constructor("$ZodNullable", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "pattern", () => { - const pattern = def.innerType._zod.pattern; - return pattern ? new RegExp(`^(${cleanRegex(pattern.source)}|null)$`) : undefined; - }); - defineLazy(inst._zod, "values", () => { - return def.innerType._zod.values ? new Set([...def.innerType._zod.values, null]) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - // Forward direction (decode): allow null to pass through - if (payload.value === null) - return payload; - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodDefault = /*@__PURE__*/ $constructor("$ZodDefault", (inst, def) => { - $ZodType.init(inst, def); - // inst._zod.qin = "true"; - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply defaults for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - /** - * $ZodDefault returns the default value immediately in forward direction. - * It doesn't pass the default value into the validator ("prefault"). There's no reason to pass the default value through validation. The validity of the default is enforced by TypeScript statically. Otherwise, it's the responsibility of the user to ensure the default is valid. In the case of pipes with divergent in/out types, you can specify the default on the `in` schema of your ZodPipe to set a "prefault" for the pipe. */ - return payload; - } - // Forward direction: continue with default handling - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleDefaultResult(result, def)); - } - return handleDefaultResult(result, def); - }; -}); -function handleDefaultResult(payload, def) { - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return payload; -} -const $ZodPrefault = /*@__PURE__*/ $constructor("$ZodPrefault", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.optin = "optional"; - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply prefault for undefined input - if (payload.value === undefined) { - payload.value = def.defaultValue; - } - return def.innerType._zod.run(payload, ctx); - }; -}); -const $ZodNonOptional = /*@__PURE__*/ $constructor("$ZodNonOptional", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => { - const v = def.innerType._zod.values; - return v ? new Set([...v].filter((x) => x !== undefined)) : undefined; - }); - inst._zod.parse = (payload, ctx) => { - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => handleNonOptionalResult(result, inst)); - } - return handleNonOptionalResult(result, inst); - }; -}); -function handleNonOptionalResult(payload, inst) { - if (!payload.issues.length && payload.value === undefined) { - payload.issues.push({ - code: "invalid_type", - expected: "nonoptional", - input: payload.value, - inst, - }); - } - return payload; -} -const $ZodSuccess = /*@__PURE__*/ $constructor("$ZodSuccess", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - throw new $ZodEncodeError("ZodSuccess"); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.issues.length === 0; - return payload; - }); - } - payload.value = result.issues.length === 0; - return payload; - }; -}); -const $ZodCatch = /*@__PURE__*/ $constructor("$ZodCatch", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "optin", () => def.innerType._zod.optin); - defineLazy(inst._zod, "optout", () => def.innerType._zod.optout); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - // Forward direction (decode): apply catch logic - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then((result) => { - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())), - }, - input: payload.value, - }); - payload.issues = []; - } - return payload; - }); - } - payload.value = result.value; - if (result.issues.length) { - payload.value = def.catchValue({ - ...payload, - error: { - issues: result.issues.map((iss) => finalizeIssue(iss, ctx, config())), - }, - input: payload.value, - }); - payload.issues = []; - } - return payload; - }; -}); -const $ZodNaN = /*@__PURE__*/ $constructor("$ZodNaN", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "number" || !Number.isNaN(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - expected: "nan", - code: "invalid_type", - }); - return payload; - } - return payload; - }; -}); -const $ZodPipe = /*@__PURE__*/ $constructor("$ZodPipe", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handlePipeResult(right, def.in, ctx)); - } - return handlePipeResult(right, def.in, ctx); - } - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handlePipeResult(left, def.out, ctx)); - } - return handlePipeResult(left, def.out, ctx); - }; -}); -function handlePipeResult(left, next, ctx) { - if (left.issues.length) { - // prevent further checks - left.aborted = true; - return left; - } - return next._zod.run({ value: left.value, issues: left.issues }, ctx); -} -const $ZodCodec = /*@__PURE__*/ $constructor("$ZodCodec", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "values", () => def.in._zod.values); - defineLazy(inst._zod, "optin", () => def.in._zod.optin); - defineLazy(inst._zod, "optout", () => def.out._zod.optout); - defineLazy(inst._zod, "propValues", () => def.in._zod.propValues); - inst._zod.parse = (payload, ctx) => { - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const left = def.in._zod.run(payload, ctx); - if (left instanceof Promise) { - return left.then((left) => handleCodecAResult(left, def, ctx)); - } - return handleCodecAResult(left, def, ctx); - } - else { - const right = def.out._zod.run(payload, ctx); - if (right instanceof Promise) { - return right.then((right) => handleCodecAResult(right, def, ctx)); - } - return handleCodecAResult(right, def, ctx); - } - }; -}); -function handleCodecAResult(result, def, ctx) { - if (result.issues.length) { - // prevent further checks - result.aborted = true; - return result; - } - const direction = ctx.direction || "forward"; - if (direction === "forward") { - const transformed = def.transform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.out, ctx)); - } - return handleCodecTxResult(result, transformed, def.out, ctx); - } - else { - const transformed = def.reverseTransform(result.value, result); - if (transformed instanceof Promise) { - return transformed.then((value) => handleCodecTxResult(result, value, def.in, ctx)); - } - return handleCodecTxResult(result, transformed, def.in, ctx); - } -} -function handleCodecTxResult(left, value, nextSchema, ctx) { - // Check if transform added any issues - if (left.issues.length) { - left.aborted = true; - return left; - } - return nextSchema._zod.run({ value, issues: left.issues }, ctx); -} -const $ZodReadonly = /*@__PURE__*/ $constructor("$ZodReadonly", (inst, def) => { - $ZodType.init(inst, def); - defineLazy(inst._zod, "propValues", () => def.innerType._zod.propValues); - defineLazy(inst._zod, "values", () => def.innerType._zod.values); - defineLazy(inst._zod, "optin", () => def.innerType?._zod?.optin); - defineLazy(inst._zod, "optout", () => def.innerType?._zod?.optout); - inst._zod.parse = (payload, ctx) => { - if (ctx.direction === "backward") { - return def.innerType._zod.run(payload, ctx); - } - const result = def.innerType._zod.run(payload, ctx); - if (result instanceof Promise) { - return result.then(handleReadonlyResult); - } - return handleReadonlyResult(result); - }; -}); -function handleReadonlyResult(payload) { - payload.value = Object.freeze(payload.value); - return payload; -} -const $ZodTemplateLiteral = /*@__PURE__*/ $constructor("$ZodTemplateLiteral", (inst, def) => { - $ZodType.init(inst, def); - const regexParts = []; - for (const part of def.parts) { - if (typeof part === "object" && part !== null) { - // is Zod schema - if (!part._zod.pattern) { - // if (!source) - throw new Error(`Invalid template literal part, no pattern found: ${[...part._zod.traits].shift()}`); - } - const source = part._zod.pattern instanceof RegExp ? part._zod.pattern.source : part._zod.pattern; - if (!source) - throw new Error(`Invalid template literal part: ${part._zod.traits}`); - const start = source.startsWith("^") ? 1 : 0; - const end = source.endsWith("$") ? source.length - 1 : source.length; - regexParts.push(source.slice(start, end)); - } - else if (part === null || primitiveTypes.has(typeof part)) { - regexParts.push(escapeRegex(`${part}`)); - } - else { - throw new Error(`Invalid template literal part: ${part}`); - } - } - inst._zod.pattern = new RegExp(`^${regexParts.join("")}$`); - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "string") { - payload.issues.push({ - input: payload.value, - inst, - expected: "template_literal", - code: "invalid_type", - }); - return payload; - } - inst._zod.pattern.lastIndex = 0; - if (!inst._zod.pattern.test(payload.value)) { - payload.issues.push({ - input: payload.value, - inst, - code: "invalid_format", - format: def.format ?? "template_literal", - pattern: inst._zod.pattern.source, - }); - return payload; - } - return payload; - }; -}); -const $ZodFunction = /*@__PURE__*/ $constructor("$ZodFunction", (inst, def) => { - $ZodType.init(inst, def); - inst._def = def; - inst._zod.def = def; - inst.implement = (func) => { - if (typeof func !== "function") { - throw new Error("implement() must be called with a function"); - } - return function (...args) { - const parsedArgs = inst._def.input ? parse_parse(inst._def.input, args) : args; - const result = Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return parse_parse(inst._def.output, result); - } - return result; - }; - }; - inst.implementAsync = (func) => { - if (typeof func !== "function") { - throw new Error("implementAsync() must be called with a function"); - } - return async function (...args) { - const parsedArgs = inst._def.input ? await parseAsync(inst._def.input, args) : args; - const result = await Reflect.apply(func, this, parsedArgs); - if (inst._def.output) { - return await parseAsync(inst._def.output, result); - } - return result; - }; - }; - inst._zod.parse = (payload, _ctx) => { - if (typeof payload.value !== "function") { - payload.issues.push({ - code: "invalid_type", - expected: "function", - input: payload.value, - inst, - }); - return payload; - } - // Check if output is a promise type to determine if we should use async implementation - const hasPromiseOutput = inst._def.output && inst._def.output._zod.def.type === "promise"; - if (hasPromiseOutput) { - payload.value = inst.implementAsync(payload.value); - } - else { - payload.value = inst.implement(payload.value); - } - return payload; - }; - inst.input = (...args) => { - const F = inst.constructor; - if (Array.isArray(args[0])) { - return new F({ - type: "function", - input: new $ZodTuple({ - type: "tuple", - items: args[0], - rest: args[1], - }), - output: inst._def.output, - }); - } - return new F({ - type: "function", - input: args[0], - output: inst._def.output, - }); - }; - inst.output = (output) => { - const F = inst.constructor; - return new F({ - type: "function", - input: inst._def.input, - output, - }); - }; - return inst; -}); -const $ZodPromise = /*@__PURE__*/ $constructor("$ZodPromise", (inst, def) => { - $ZodType.init(inst, def); - inst._zod.parse = (payload, ctx) => { - return Promise.resolve(payload.value).then((inner) => def.innerType._zod.run({ value: inner, issues: [] }, ctx)); - }; -}); -const $ZodLazy = /*@__PURE__*/ $constructor("$ZodLazy", (inst, def) => { - $ZodType.init(inst, def); - // let _innerType!: any; - // util.defineLazy(def, "getter", () => { - // if (!_innerType) { - // _innerType = def.getter(); - // } - // return () => _innerType; - // }); - defineLazy(inst._zod, "innerType", () => def.getter()); - defineLazy(inst._zod, "pattern", () => inst._zod.innerType?._zod?.pattern); - defineLazy(inst._zod, "propValues", () => inst._zod.innerType?._zod?.propValues); - defineLazy(inst._zod, "optin", () => inst._zod.innerType?._zod?.optin ?? undefined); - defineLazy(inst._zod, "optout", () => inst._zod.innerType?._zod?.optout ?? undefined); - inst._zod.parse = (payload, ctx) => { - const inner = inst._zod.innerType; - return inner._zod.run(payload, ctx); - }; -}); -const $ZodCustom = /*@__PURE__*/ $constructor("$ZodCustom", (inst, def) => { - $ZodCheck.init(inst, def); - $ZodType.init(inst, def); - inst._zod.parse = (payload, _) => { - return payload; - }; - inst._zod.check = (payload) => { - const input = payload.value; - const r = def.fn(input); - if (r instanceof Promise) { - return r.then((r) => handleRefineResult(r, payload, input, inst)); - } - handleRefineResult(r, payload, input, inst); - return; - }; -}); -function handleRefineResult(result, payload, input, inst) { - if (!result) { - const _iss = { - code: "custom", - input, - inst, // incorporates params.error into issue reporting - path: [...(inst._zod.def.path ?? [])], // incorporates params.error into issue reporting - continue: !inst._zod.def.abort, - // params: inst._zod.def.params, - }; - if (inst._zod.def.params) - _iss.params = inst._zod.def.params; - payload.issues.push(util_issue(_iss)); - } -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ar.js - -const error = () => { - const Sizable = { - string: { unit: "حرف", verb: "أن يحوي" }, - file: { unit: "بايت", verb: "أن يحوي" }, - array: { unit: "عنصر", verb: "أن يحوي" }, - set: { unit: "عنصر", verb: "أن يحوي" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "مدخل", - email: "بريد إلكتروني", - url: "رابط", - emoji: "إيموجي", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "تاريخ ووقت بمعيار ISO", - date: "تاريخ بمعيار ISO", - time: "وقت بمعيار ISO", - duration: "مدة بمعيار ISO", - ipv4: "عنوان IPv4", - ipv6: "عنوان IPv6", - cidrv4: "مدى عناوين بصيغة IPv4", - cidrv6: "مدى عناوين بصيغة IPv6", - base64: "نَص بترميز base64-encoded", - base64url: "نَص بترميز base64url-encoded", - json_string: "نَص على هيئة JSON", - e164: "رقم هاتف بمعيار E.164", - jwt: "JWT", - template_literal: "مدخل", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `مدخلات غير مقبولة: يفترض إدخال ${issue.expected}، ولكن تم إدخال ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `مدخلات غير مقبولة: يفترض إدخال ${stringifyPrimitive(issue.values[0])}`; - return `اختيار غير مقبول: يتوقع انتقاء أحد هذه الخيارات: ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return ` أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "عنصر"}`; - return `أكبر من اللازم: يفترض أن تكون ${issue.origin ?? "القيمة"} ${adj} ${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()} ${sizing.unit}`; - } - return `أصغر من اللازم: يفترض لـ ${issue.origin} أن يكون ${adj} ${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `نَص غير مقبول: يجب أن يبدأ بـ "${issue.prefix}"`; - if (_issue.format === "ends_with") - return `نَص غير مقبول: يجب أن ينتهي بـ "${_issue.suffix}"`; - if (_issue.format === "includes") - return `نَص غير مقبول: يجب أن يتضمَّن "${_issue.includes}"`; - if (_issue.format === "regex") - return `نَص غير مقبول: يجب أن يطابق النمط ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue.format} غير مقبول`; - } - case "not_multiple_of": - return `رقم غير مقبول: يجب أن يكون من مضاعفات ${issue.divisor}`; - case "unrecognized_keys": - return `معرف${issue.keys.length > 1 ? "ات" : ""} غريب${issue.keys.length > 1 ? "ة" : ""}: ${joinValues(issue.keys, "، ")}`; - case "invalid_key": - return `معرف غير مقبول في ${issue.origin}`; - case "invalid_union": - return "مدخل غير مقبول"; - case "invalid_element": - return `مدخل غير مقبول في ${issue.origin}`; - default: - return "مدخل غير مقبول"; - } - }; -}; -/* harmony default export */ function ar() { - return { - localeError: error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/az.js - -const az_error = () => { - const Sizable = { - string: { unit: "simvol", verb: "olmalıdır" }, - file: { unit: "bayt", verb: "olmalıdır" }, - array: { unit: "element", verb: "olmalıdır" }, - set: { unit: "element", verb: "olmalıdır" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - jwt: "JWT", - template_literal: "input", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Yanlış dəyər: gözlənilən ${issue.expected}, daxil olan ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Yanlış dəyər: gözlənilən ${stringifyPrimitive(issue.values[0])}`; - return `Yanlış seçim: aşağıdakılardan biri olmalıdır: ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Çox böyük: gözlənilən ${issue.origin ?? "dəyər"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`; - return `Çox böyük: gözlənilən ${issue.origin ?? "dəyər"} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - return `Çox kiçik: gözlənilən ${issue.origin} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Yanlış mətn: "${_issue.prefix}" ilə başlamalıdır`; - if (_issue.format === "ends_with") - return `Yanlış mətn: "${_issue.suffix}" ilə bitməlidir`; - if (_issue.format === "includes") - return `Yanlış mətn: "${_issue.includes}" daxil olmalıdır`; - if (_issue.format === "regex") - return `Yanlış mətn: ${_issue.pattern} şablonuna uyğun olmalıdır`; - return `Yanlış ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Yanlış ədəd: ${issue.divisor} ilə bölünə bilən olmalıdır`; - case "unrecognized_keys": - return `Tanınmayan açar${issue.keys.length > 1 ? "lar" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `${issue.origin} daxilində yanlış açar`; - case "invalid_union": - return "Yanlış dəyər"; - case "invalid_element": - return `${issue.origin} daxilində yanlış dəyər`; - default: - return `Yanlış dəyər`; - } - }; -}; -/* harmony default export */ function az() { - return { - localeError: az_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/be.js - -function getBelarusianPlural(count, one, few, many) { - const absCount = Math.abs(count); - const lastDigit = absCount % 10; - const lastTwoDigits = absCount % 100; - if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { - return many; - } - if (lastDigit === 1) { - return one; - } - if (lastDigit >= 2 && lastDigit <= 4) { - return few; - } - return many; -} -const be_error = () => { - const Sizable = { - string: { - unit: { - one: "сімвал", - few: "сімвалы", - many: "сімвалаў", - }, - verb: "мець", - }, - array: { - unit: { - one: "элемент", - few: "элементы", - many: "элементаў", - }, - verb: "мець", - }, - set: { - unit: { - one: "элемент", - few: "элементы", - many: "элементаў", - }, - verb: "мець", - }, - file: { - unit: { - one: "байт", - few: "байты", - many: "байтаў", - }, - verb: "мець", - }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "лік"; - } - case "object": { - if (Array.isArray(data)) { - return "масіў"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "увод", - email: "email адрас", - url: "URL", - emoji: "эмодзі", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO дата і час", - date: "ISO дата", - time: "ISO час", - duration: "ISO працягласць", - ipv4: "IPv4 адрас", - ipv6: "IPv6 адрас", - cidrv4: "IPv4 дыяпазон", - cidrv6: "IPv6 дыяпазон", - base64: "радок у фармаце base64", - base64url: "радок у фармаце base64url", - json_string: "JSON радок", - e164: "нумар E.164", - jwt: "JWT", - template_literal: "увод", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Няправільны ўвод: чакаўся ${issue.expected}, атрымана ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Няправільны ўвод: чакалася ${stringifyPrimitive(issue.values[0])}`; - return `Няправільны варыянт: чакаўся адзін з ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - const maxValue = Number(issue.maximum); - const unit = getBelarusianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна ${sizing.verb} ${adj}${issue.maximum.toString()} ${unit}`; - } - return `Занадта вялікі: чакалася, што ${issue.origin ?? "значэнне"} павінна быць ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - const minValue = Number(issue.minimum); - const unit = getBelarusianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Занадта малы: чакалася, што ${issue.origin} павінна ${sizing.verb} ${adj}${issue.minimum.toString()} ${unit}`; - } - return `Занадта малы: чакалася, што ${issue.origin} павінна быць ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Няправільны радок: павінен пачынацца з "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Няправільны радок: павінен заканчвацца на "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Няправільны радок: павінен змяшчаць "${_issue.includes}"`; - if (_issue.format === "regex") - return `Няправільны радок: павінен адпавядаць шаблону ${_issue.pattern}`; - return `Няправільны ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Няправільны лік: павінен быць кратным ${issue.divisor}`; - case "unrecognized_keys": - return `Нераспазнаны ${issue.keys.length > 1 ? "ключы" : "ключ"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Няправільны ключ у ${issue.origin}`; - case "invalid_union": - return "Няправільны ўвод"; - case "invalid_element": - return `Няправільнае значэнне ў ${issue.origin}`; - default: - return `Няправільны ўвод`; - } - }; -}; -/* harmony default export */ function be() { - return { - localeError: be_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/bg.js - -const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "число"; - } - case "object": { - if (Array.isArray(data)) { - return "масив"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; -}; -const bg_error = () => { - const Sizable = { - string: { unit: "символа", verb: "да съдържа" }, - file: { unit: "байта", verb: "да съдържа" }, - array: { unit: "елемента", verb: "да съдържа" }, - set: { unit: "елемента", verb: "да съдържа" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const Nouns = { - regex: "вход", - email: "имейл адрес", - url: "URL", - emoji: "емоджи", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO време", - date: "ISO дата", - time: "ISO време", - duration: "ISO продължителност", - ipv4: "IPv4 адрес", - ipv6: "IPv6 адрес", - cidrv4: "IPv4 диапазон", - cidrv6: "IPv6 диапазон", - base64: "base64-кодиран низ", - base64url: "base64url-кодиран низ", - json_string: "JSON низ", - e164: "E.164 номер", - jwt: "JWT", - template_literal: "вход", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Невалиден вход: очакван ${issue.expected}, получен ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Невалиден вход: очакван ${stringifyPrimitive(issue.values[0])}`; - return `Невалидна опция: очаквано едно от ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Твърде голямо: очаква се ${issue.origin ?? "стойност"} да съдържа ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елемента"}`; - return `Твърде голямо: очаква се ${issue.origin ?? "стойност"} да бъде ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Твърде малко: очаква се ${issue.origin} да съдържа ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Твърде малко: очаква се ${issue.origin} да бъде ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Невалиден низ: трябва да започва с "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Невалиден низ: трябва да завършва с "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Невалиден низ: трябва да включва "${_issue.includes}"`; - if (_issue.format === "regex") - return `Невалиден низ: трябва да съвпада с ${_issue.pattern}`; - let invalid_adj = "Невалиден"; - if (_issue.format === "emoji") - invalid_adj = "Невалидно"; - if (_issue.format === "datetime") - invalid_adj = "Невалидно"; - if (_issue.format === "date") - invalid_adj = "Невалидна"; - if (_issue.format === "time") - invalid_adj = "Невалидно"; - if (_issue.format === "duration") - invalid_adj = "Невалидна"; - return `${invalid_adj} ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Невалидно число: трябва да бъде кратно на ${issue.divisor}`; - case "unrecognized_keys": - return `Неразпознат${issue.keys.length > 1 ? "и" : ""} ключ${issue.keys.length > 1 ? "ове" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Невалиден ключ в ${issue.origin}`; - case "invalid_union": - return "Невалиден вход"; - case "invalid_element": - return `Невалидна стойност в ${issue.origin}`; - default: - return `Невалиден вход`; - } - }; -}; -/* harmony default export */ function bg() { - return { - localeError: bg_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ca.js - -const ca_error = () => { - const Sizable = { - string: { unit: "caràcters", verb: "contenir" }, - file: { unit: "bytes", verb: "contenir" }, - array: { unit: "elements", verb: "contenir" }, - set: { unit: "elements", verb: "contenir" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "entrada", - email: "adreça electrònica", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data i hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "durada ISO", - ipv4: "adreça IPv4", - ipv6: "adreça IPv6", - cidrv4: "rang IPv4", - cidrv6: "rang IPv6", - base64: "cadena codificada en base64", - base64url: "cadena codificada en base64url", - json_string: "cadena JSON", - e164: "número E.164", - jwt: "JWT", - template_literal: "entrada", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${parsedType(issue.input)}`; - // return `Tipus invàlid: s'esperava ${issue.expected}, s'ha rebut ${util.getParsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Valor invàlid: s'esperava ${stringifyPrimitive(issue.values[0])}`; - return `Opció invàlida: s'esperava una de ${joinValues(issue.values, " o ")}`; - case "too_big": { - const adj = issue.inclusive ? "com a màxim" : "menys de"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} contingués ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Massa gran: s'esperava que ${issue.origin ?? "el valor"} fos ${adj} ${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? "com a mínim" : "més de"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Massa petit: s'esperava que ${issue.origin} contingués ${adj} ${issue.minimum.toString()} ${sizing.unit}`; - } - return `Massa petit: s'esperava que ${issue.origin} fos ${adj} ${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Format invàlid: ha de començar amb "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Format invàlid: ha d'acabar amb "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Format invàlid: ha d'incloure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Format invàlid: ha de coincidir amb el patró ${_issue.pattern}`; - return `Format invàlid per a ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Número invàlid: ha de ser múltiple de ${issue.divisor}`; - case "unrecognized_keys": - return `Clau${issue.keys.length > 1 ? "s" : ""} no reconeguda${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Clau invàlida a ${issue.origin}`; - case "invalid_union": - return "Entrada invàlida"; // Could also be "Tipus d'unió invàlid" but "Entrada invàlida" is more general - case "invalid_element": - return `Element invàlid a ${issue.origin}`; - default: - return `Entrada invàlida`; - } - }; -}; -/* harmony default export */ function ca() { - return { - localeError: ca_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/cs.js - -const cs_error = () => { - const Sizable = { - string: { unit: "znaků", verb: "mít" }, - file: { unit: "bajtů", verb: "mít" }, - array: { unit: "prvků", verb: "mít" }, - set: { unit: "prvků", verb: "mít" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "číslo"; - } - case "string": { - return "řetězec"; - } - case "boolean": { - return "boolean"; - } - case "bigint": { - return "bigint"; - } - case "function": { - return "funkce"; - } - case "symbol": { - return "symbol"; - } - case "undefined": { - return "undefined"; - } - case "object": { - if (Array.isArray(data)) { - return "pole"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "regulární výraz", - email: "e-mailová adresa", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "datum a čas ve formátu ISO", - date: "datum ve formátu ISO", - time: "čas ve formátu ISO", - duration: "doba trvání ISO", - ipv4: "IPv4 adresa", - ipv6: "IPv6 adresa", - cidrv4: "rozsah IPv4", - cidrv6: "rozsah IPv6", - base64: "řetězec zakódovaný ve formátu base64", - base64url: "řetězec zakódovaný ve formátu base64url", - json_string: "řetězec ve formátu JSON", - e164: "číslo E.164", - jwt: "JWT", - template_literal: "vstup", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Neplatný vstup: očekáváno ${issue.expected}, obdrženo ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Neplatný vstup: očekáváno ${stringifyPrimitive(issue.values[0])}`; - return `Neplatná možnost: očekávána jedna z hodnot ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Hodnota je příliš velká: ${issue.origin ?? "hodnota"} musí mít ${adj}${issue.maximum.toString()} ${sizing.unit ?? "prvků"}`; - } - return `Hodnota je příliš velká: ${issue.origin ?? "hodnota"} musí být ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Hodnota je příliš malá: ${issue.origin ?? "hodnota"} musí mít ${adj}${issue.minimum.toString()} ${sizing.unit ?? "prvků"}`; - } - return `Hodnota je příliš malá: ${issue.origin ?? "hodnota"} musí být ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Neplatný řetězec: musí začínat na "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Neplatný řetězec: musí končit na "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Neplatný řetězec: musí obsahovat "${_issue.includes}"`; - if (_issue.format === "regex") - return `Neplatný řetězec: musí odpovídat vzoru ${_issue.pattern}`; - return `Neplatný formát ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Neplatné číslo: musí být násobkem ${issue.divisor}`; - case "unrecognized_keys": - return `Neznámé klíče: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Neplatný klíč v ${issue.origin}`; - case "invalid_union": - return "Neplatný vstup"; - case "invalid_element": - return `Neplatná hodnota v ${issue.origin}`; - default: - return `Neplatný vstup`; - } - }; -}; -/* harmony default export */ function cs() { - return { - localeError: cs_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/da.js - -const da_error = () => { - const Sizable = { - string: { unit: "tegn", verb: "havde" }, - file: { unit: "bytes", verb: "havde" }, - array: { unit: "elementer", verb: "indeholdt" }, - set: { unit: "elementer", verb: "indeholdt" }, - }; - const TypeNames = { - string: "streng", - number: "tal", - boolean: "boolean", - array: "liste", - object: "objekt", - set: "sæt", - file: "fil", - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - function getTypeName(type) { - return TypeNames[type] ?? type; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "tal"; - } - case "object": { - if (Array.isArray(data)) { - return "liste"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - return "objekt"; - } - } - return t; - }; - const Nouns = { - regex: "input", - email: "e-mailadresse", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO dato- og klokkeslæt", - date: "ISO-dato", - time: "ISO-klokkeslæt", - duration: "ISO-varighed", - ipv4: "IPv4-område", - ipv6: "IPv6-område", - cidrv4: "IPv4-spektrum", - cidrv6: "IPv6-spektrum", - base64: "base64-kodet streng", - base64url: "base64url-kodet streng", - json_string: "JSON-streng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "input", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Ugyldigt input: forventede ${getTypeName(issue.expected)}, fik ${getTypeName(parsedType(issue.input))}`; - case "invalid_value": - if (issue.values.length === 1) - return `Ugyldig værdi: forventede ${stringifyPrimitive(issue.values[0])}`; - return `Ugyldigt valg: forventede en af følgende ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - const origin = getTypeName(issue.origin); - if (sizing) - return `For stor: forventede ${origin ?? "value"} ${sizing.verb} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "elementer"}`; - return `For stor: forventede ${origin ?? "value"} havde ${adj} ${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - const origin = getTypeName(issue.origin); - if (sizing) { - return `For lille: forventede ${origin} ${sizing.verb} ${adj} ${issue.minimum.toString()} ${sizing.unit}`; - } - return `For lille: forventede ${origin} havde ${adj} ${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Ugyldig streng: skal starte med "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Ugyldig streng: skal ende med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ugyldig streng: skal indeholde "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ugyldig streng: skal matche mønsteret ${_issue.pattern}`; - return `Ugyldig ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Ugyldigt tal: skal være deleligt med ${issue.divisor}`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Ukendte nøgler" : "Ukendt nøgle"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Ugyldig nøgle i ${issue.origin}`; - case "invalid_union": - return "Ugyldigt input: matcher ingen af de tilladte typer"; - case "invalid_element": - return `Ugyldig værdi i ${issue.origin}`; - default: - return `Ugyldigt input`; - } - }; -}; -/* harmony default export */ function da() { - return { - localeError: da_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/de.js - -const de_error = () => { - const Sizable = { - string: { unit: "Zeichen", verb: "zu haben" }, - file: { unit: "Bytes", verb: "zu haben" }, - array: { unit: "Elemente", verb: "zu haben" }, - set: { unit: "Elemente", verb: "zu haben" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "Zahl"; - } - case "object": { - if (Array.isArray(data)) { - return "Array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "Eingabe", - email: "E-Mail-Adresse", - url: "URL", - emoji: "Emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-Datum und -Uhrzeit", - date: "ISO-Datum", - time: "ISO-Uhrzeit", - duration: "ISO-Dauer", - ipv4: "IPv4-Adresse", - ipv6: "IPv6-Adresse", - cidrv4: "IPv4-Bereich", - cidrv6: "IPv6-Bereich", - base64: "Base64-codierter String", - base64url: "Base64-URL-codierter String", - json_string: "JSON-String", - e164: "E.164-Nummer", - jwt: "JWT", - template_literal: "Eingabe", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Ungültige Eingabe: erwartet ${issue.expected}, erhalten ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Ungültige Eingabe: erwartet ${stringifyPrimitive(issue.values[0])}`; - return `Ungültige Option: erwartet eine von ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "Elemente"} hat`; - return `Zu groß: erwartet, dass ${issue.origin ?? "Wert"} ${adj}${issue.maximum.toString()} ist`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} hat`; - } - return `Zu klein: erwartet, dass ${issue.origin} ${adj}${issue.minimum.toString()} ist`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Ungültiger String: muss mit "${_issue.prefix}" beginnen`; - if (_issue.format === "ends_with") - return `Ungültiger String: muss mit "${_issue.suffix}" enden`; - if (_issue.format === "includes") - return `Ungültiger String: muss "${_issue.includes}" enthalten`; - if (_issue.format === "regex") - return `Ungültiger String: muss dem Muster ${_issue.pattern} entsprechen`; - return `Ungültig: ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Ungültige Zahl: muss ein Vielfaches von ${issue.divisor} sein`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Unbekannte Schlüssel" : "Unbekannter Schlüssel"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Ungültiger Schlüssel in ${issue.origin}`; - case "invalid_union": - return "Ungültige Eingabe"; - case "invalid_element": - return `Ungültiger Wert in ${issue.origin}`; - default: - return `Ungültige Eingabe`; - } - }; -}; -/* harmony default export */ function de() { - return { - localeError: de_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/en.js - -const en_parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; -}; -const en_error = () => { - const Sizable = { - string: { unit: "characters", verb: "to have" }, - file: { unit: "bytes", verb: "to have" }, - array: { unit: "items", verb: "to have" }, - set: { unit: "items", verb: "to have" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const Nouns = { - regex: "input", - email: "email address", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datetime", - date: "ISO date", - time: "ISO time", - duration: "ISO duration", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - mac: "MAC address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded string", - base64url: "base64url-encoded string", - json_string: "JSON string", - e164: "E.164 number", - jwt: "JWT", - template_literal: "input", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Invalid input: expected ${issue.expected}, received ${en_parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; - return `Invalid option: expected one of ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Too big: expected ${issue.origin ?? "value"} to have ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"}`; - return `Too big: expected ${issue.origin ?? "value"} to be ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Too small: expected ${issue.origin} to have ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Too small: expected ${issue.origin} to be ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Invalid string: must start with "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Invalid string: must end with "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Invalid string: must include "${_issue.includes}"`; - if (_issue.format === "regex") - return `Invalid string: must match pattern ${_issue.pattern}`; - return `Invalid ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Invalid number: must be a multiple of ${issue.divisor}`; - case "unrecognized_keys": - return `Unrecognized key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Invalid key in ${issue.origin}`; - case "invalid_union": - return "Invalid input"; - case "invalid_element": - return `Invalid value in ${issue.origin}`; - default: - return `Invalid input`; - } - }; -}; -/* harmony default export */ function en() { - return { - localeError: en_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/eo.js - -const eo_parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "nombro"; - } - case "object": { - if (Array.isArray(data)) { - return "tabelo"; - } - if (data === null) { - return "senvalora"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; -}; -const eo_error = () => { - const Sizable = { - string: { unit: "karaktrojn", verb: "havi" }, - file: { unit: "bajtojn", verb: "havi" }, - array: { unit: "elementojn", verb: "havi" }, - set: { unit: "elementojn", verb: "havi" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const Nouns = { - regex: "enigo", - email: "retadreso", - url: "URL", - emoji: "emoĝio", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-datotempo", - date: "ISO-dato", - time: "ISO-tempo", - duration: "ISO-daŭro", - ipv4: "IPv4-adreso", - ipv6: "IPv6-adreso", - cidrv4: "IPv4-rango", - cidrv6: "IPv6-rango", - base64: "64-ume kodita karaktraro", - base64url: "URL-64-ume kodita karaktraro", - json_string: "JSON-karaktraro", - e164: "E.164-nombro", - jwt: "JWT", - template_literal: "enigo", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Nevalida enigo: atendiĝis ${issue.expected}, riceviĝis ${eo_parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Nevalida enigo: atendiĝis ${stringifyPrimitive(issue.values[0])}`; - return `Nevalida opcio: atendiĝis unu el ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Tro granda: atendiĝis ke ${issue.origin ?? "valoro"} havu ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementojn"}`; - return `Tro granda: atendiĝis ke ${issue.origin ?? "valoro"} havu ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Tro malgranda: atendiĝis ke ${issue.origin} havu ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Tro malgranda: atendiĝis ke ${issue.origin} estu ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Nevalida karaktraro: devas komenciĝi per "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Nevalida karaktraro: devas finiĝi per "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Nevalida karaktraro: devas inkluzivi "${_issue.includes}"`; - if (_issue.format === "regex") - return `Nevalida karaktraro: devas kongrui kun la modelo ${_issue.pattern}`; - return `Nevalida ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Nevalida nombro: devas esti oblo de ${issue.divisor}`; - case "unrecognized_keys": - return `Nekonata${issue.keys.length > 1 ? "j" : ""} ŝlosilo${issue.keys.length > 1 ? "j" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Nevalida ŝlosilo en ${issue.origin}`; - case "invalid_union": - return "Nevalida enigo"; - case "invalid_element": - return `Nevalida valoro en ${issue.origin}`; - default: - return `Nevalida enigo`; - } - }; -}; -/* harmony default export */ function eo() { - return { - localeError: eo_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/es.js - -const es_error = () => { - const Sizable = { - string: { unit: "caracteres", verb: "tener" }, - file: { unit: "bytes", verb: "tener" }, - array: { unit: "elementos", verb: "tener" }, - set: { unit: "elementos", verb: "tener" }, - }; - const TypeNames = { - string: "texto", - number: "número", - boolean: "booleano", - array: "arreglo", - object: "objeto", - set: "conjunto", - file: "archivo", - date: "fecha", - bigint: "número grande", - symbol: "símbolo", - undefined: "indefinido", - null: "nulo", - function: "función", - map: "mapa", - record: "registro", - tuple: "tupla", - enum: "enumeración", - union: "unión", - literal: "literal", - promise: "promesa", - void: "vacío", - never: "nunca", - unknown: "desconocido", - any: "cualquiera", - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - function getTypeName(type) { - return TypeNames[type] ?? type; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype) { - return data.constructor.name; - } - return "object"; - } - } - return t; - }; - const Nouns = { - regex: "entrada", - email: "dirección de correo electrónico", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "fecha y hora ISO", - date: "fecha ISO", - time: "hora ISO", - duration: "duración ISO", - ipv4: "dirección IPv4", - ipv6: "dirección IPv6", - cidrv4: "rango IPv4", - cidrv6: "rango IPv6", - base64: "cadena codificada en base64", - base64url: "URL codificada en base64", - json_string: "cadena JSON", - e164: "número E.164", - jwt: "JWT", - template_literal: "entrada", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Entrada inválida: se esperaba ${getTypeName(issue.expected)}, recibido ${getTypeName(parsedType(issue.input))}`; - // return `Entrada inválida: se esperaba ${issue.expected}, recibido ${util.getParsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Entrada inválida: se esperaba ${stringifyPrimitive(issue.values[0])}`; - return `Opción inválida: se esperaba una de ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - const origin = getTypeName(issue.origin); - if (sizing) - return `Demasiado grande: se esperaba que ${origin ?? "valor"} tuviera ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Demasiado grande: se esperaba que ${origin ?? "valor"} fuera ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - const origin = getTypeName(issue.origin); - if (sizing) { - return `Demasiado pequeño: se esperaba que ${origin} tuviera ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Demasiado pequeño: se esperaba que ${origin} fuera ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Cadena inválida: debe comenzar con "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Cadena inválida: debe terminar en "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Cadena inválida: debe incluir "${_issue.includes}"`; - if (_issue.format === "regex") - return `Cadena inválida: debe coincidir con el patrón ${_issue.pattern}`; - return `Inválido ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Número inválido: debe ser múltiplo de ${issue.divisor}`; - case "unrecognized_keys": - return `Llave${issue.keys.length > 1 ? "s" : ""} desconocida${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Llave inválida en ${getTypeName(issue.origin)}`; - case "invalid_union": - return "Entrada inválida"; - case "invalid_element": - return `Valor inválido en ${getTypeName(issue.origin)}`; - default: - return `Entrada inválida`; - } - }; -}; -/* harmony default export */ function es() { - return { - localeError: es_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/fa.js - -const fa_error = () => { - const Sizable = { - string: { unit: "کاراکتر", verb: "داشته باشد" }, - file: { unit: "بایت", verb: "داشته باشد" }, - array: { unit: "آیتم", verb: "داشته باشد" }, - set: { unit: "آیتم", verb: "داشته باشد" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "عدد"; - } - case "object": { - if (Array.isArray(data)) { - return "آرایه"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "ورودی", - email: "آدرس ایمیل", - url: "URL", - emoji: "ایموجی", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "تاریخ و زمان ایزو", - date: "تاریخ ایزو", - time: "زمان ایزو", - duration: "مدت زمان ایزو", - ipv4: "IPv4 آدرس", - ipv6: "IPv6 آدرس", - cidrv4: "IPv4 دامنه", - cidrv6: "IPv6 دامنه", - base64: "base64-encoded رشته", - base64url: "base64url-encoded رشته", - json_string: "JSON رشته", - e164: "E.164 عدد", - jwt: "JWT", - template_literal: "ورودی", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `ورودی نامعتبر: می‌بایست ${issue.expected} می‌بود، ${parsedType(issue.input)} دریافت شد`; - case "invalid_value": - if (issue.values.length === 1) { - return `ورودی نامعتبر: می‌بایست ${stringifyPrimitive(issue.values[0])} می‌بود`; - } - return `گزینه نامعتبر: می‌بایست یکی از ${joinValues(issue.values, "|")} می‌بود`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصر"} باشد`; - } - return `خیلی بزرگ: ${issue.origin ?? "مقدار"} باید ${adj}${issue.maximum.toString()} باشد`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} باشد`; - } - return `خیلی کوچک: ${issue.origin} باید ${adj}${issue.minimum.toString()} باشد`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `رشته نامعتبر: باید با "${_issue.prefix}" شروع شود`; - } - if (_issue.format === "ends_with") { - return `رشته نامعتبر: باید با "${_issue.suffix}" تمام شود`; - } - if (_issue.format === "includes") { - return `رشته نامعتبر: باید شامل "${_issue.includes}" باشد`; - } - if (_issue.format === "regex") { - return `رشته نامعتبر: باید با الگوی ${_issue.pattern} مطابقت داشته باشد`; - } - return `${Nouns[_issue.format] ?? issue.format} نامعتبر`; - } - case "not_multiple_of": - return `عدد نامعتبر: باید مضرب ${issue.divisor} باشد`; - case "unrecognized_keys": - return `کلید${issue.keys.length > 1 ? "های" : ""} ناشناس: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `کلید ناشناس در ${issue.origin}`; - case "invalid_union": - return `ورودی نامعتبر`; - case "invalid_element": - return `مقدار نامعتبر در ${issue.origin}`; - default: - return `ورودی نامعتبر`; - } - }; -}; -/* harmony default export */ function fa() { - return { - localeError: fa_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/fi.js - -const fi_error = () => { - const Sizable = { - string: { unit: "merkkiä", subject: "merkkijonon" }, - file: { unit: "tavua", subject: "tiedoston" }, - array: { unit: "alkiota", subject: "listan" }, - set: { unit: "alkiota", subject: "joukon" }, - number: { unit: "", subject: "luvun" }, - bigint: { unit: "", subject: "suuren kokonaisluvun" }, - int: { unit: "", subject: "kokonaisluvun" }, - date: { unit: "", subject: "päivämäärän" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "säännöllinen lauseke", - email: "sähköpostiosoite", - url: "URL-osoite", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-aikaleima", - date: "ISO-päivämäärä", - time: "ISO-aika", - duration: "ISO-kesto", - ipv4: "IPv4-osoite", - ipv6: "IPv6-osoite", - cidrv4: "IPv4-alue", - cidrv6: "IPv6-alue", - base64: "base64-koodattu merkkijono", - base64url: "base64url-koodattu merkkijono", - json_string: "JSON-merkkijono", - e164: "E.164-luku", - jwt: "JWT", - template_literal: "templaattimerkkijono", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Virheellinen tyyppi: odotettiin ${issue.expected}, oli ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Virheellinen syöte: täytyy olla ${stringifyPrimitive(issue.values[0])}`; - return `Virheellinen valinta: täytyy olla yksi seuraavista: ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Liian suuri: ${sizing.subject} täytyy olla ${adj}${issue.maximum.toString()} ${sizing.unit}`.trim(); - } - return `Liian suuri: arvon täytyy olla ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Liian pieni: ${sizing.subject} täytyy olla ${adj}${issue.minimum.toString()} ${sizing.unit}`.trim(); - } - return `Liian pieni: arvon täytyy olla ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Virheellinen syöte: täytyy alkaa "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Virheellinen syöte: täytyy loppua "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Virheellinen syöte: täytyy sisältää "${_issue.includes}"`; - if (_issue.format === "regex") { - return `Virheellinen syöte: täytyy vastata säännöllistä lauseketta ${_issue.pattern}`; - } - return `Virheellinen ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Virheellinen luku: täytyy olla luvun ${issue.divisor} monikerta`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Tuntemattomat avaimet" : "Tuntematon avain"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return "Virheellinen avain tietueessa"; - case "invalid_union": - return "Virheellinen unioni"; - case "invalid_element": - return "Virheellinen arvo joukossa"; - default: - return `Virheellinen syöte`; - } - }; -}; -/* harmony default export */ function fi() { - return { - localeError: fi_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/fr.js - -const fr_error = () => { - const Sizable = { - string: { unit: "caractères", verb: "avoir" }, - file: { unit: "octets", verb: "avoir" }, - array: { unit: "éléments", verb: "avoir" }, - set: { unit: "éléments", verb: "avoir" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "nombre"; - } - case "object": { - if (Array.isArray(data)) { - return "tableau"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "entrée", - email: "adresse e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "date et heure ISO", - date: "date ISO", - time: "heure ISO", - duration: "durée ISO", - ipv4: "adresse IPv4", - ipv6: "adresse IPv6", - cidrv4: "plage IPv4", - cidrv6: "plage IPv6", - base64: "chaîne encodée en base64", - base64url: "chaîne encodée en base64url", - json_string: "chaîne JSON", - e164: "numéro E.164", - jwt: "JWT", - template_literal: "entrée", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Entrée invalide : ${issue.expected} attendu, ${parsedType(issue.input)} reçu`; - case "invalid_value": - if (issue.values.length === 1) - return `Entrée invalide : ${stringifyPrimitive(issue.values[0])} attendu`; - return `Option invalide : une valeur parmi ${joinValues(issue.values, "|")} attendue`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Trop grand : ${issue.origin ?? "valeur"} doit ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "élément(s)"}`; - return `Trop grand : ${issue.origin ?? "valeur"} doit être ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Trop petit : ${issue.origin} doit ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Trop petit : ${issue.origin} doit être ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Chaîne invalide : doit inclure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Chaîne invalide : doit correspondre au modèle ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue.format} invalide`; - } - case "not_multiple_of": - return `Nombre invalide : doit être un multiple de ${issue.divisor}`; - case "unrecognized_keys": - return `Clé${issue.keys.length > 1 ? "s" : ""} non reconnue${issue.keys.length > 1 ? "s" : ""} : ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Clé invalide dans ${issue.origin}`; - case "invalid_union": - return "Entrée invalide"; - case "invalid_element": - return `Valeur invalide dans ${issue.origin}`; - default: - return `Entrée invalide`; - } - }; -}; -/* harmony default export */ function fr() { - return { - localeError: fr_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/fr-CA.js - -const fr_CA_error = () => { - const Sizable = { - string: { unit: "caractères", verb: "avoir" }, - file: { unit: "octets", verb: "avoir" }, - array: { unit: "éléments", verb: "avoir" }, - set: { unit: "éléments", verb: "avoir" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "entrée", - email: "adresse courriel", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "date-heure ISO", - date: "date ISO", - time: "heure ISO", - duration: "durée ISO", - ipv4: "adresse IPv4", - ipv6: "adresse IPv6", - cidrv4: "plage IPv4", - cidrv6: "plage IPv6", - base64: "chaîne encodée en base64", - base64url: "chaîne encodée en base64url", - json_string: "chaîne JSON", - e164: "numéro E.164", - jwt: "JWT", - template_literal: "entrée", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Entrée invalide : attendu ${issue.expected}, reçu ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Entrée invalide : attendu ${stringifyPrimitive(issue.values[0])}`; - return `Option invalide : attendu l'une des valeurs suivantes ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "≤" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Trop grand : attendu que ${issue.origin ?? "la valeur"} ait ${adj}${issue.maximum.toString()} ${sizing.unit}`; - return `Trop grand : attendu que ${issue.origin ?? "la valeur"} soit ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? "≥" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Trop petit : attendu que ${issue.origin} ait ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Trop petit : attendu que ${issue.origin} soit ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Chaîne invalide : doit commencer par "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Chaîne invalide : doit se terminer par "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Chaîne invalide : doit inclure "${_issue.includes}"`; - if (_issue.format === "regex") - return `Chaîne invalide : doit correspondre au motif ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue.format} invalide`; - } - case "not_multiple_of": - return `Nombre invalide : doit être un multiple de ${issue.divisor}`; - case "unrecognized_keys": - return `Clé${issue.keys.length > 1 ? "s" : ""} non reconnue${issue.keys.length > 1 ? "s" : ""} : ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Clé invalide dans ${issue.origin}`; - case "invalid_union": - return "Entrée invalide"; - case "invalid_element": - return `Valeur invalide dans ${issue.origin}`; - default: - return `Entrée invalide`; - } - }; -}; -/* harmony default export */ function fr_CA() { - return { - localeError: fr_CA_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/he.js - -const he_error = () => { - // Hebrew labels + grammatical gender - const TypeNames = { - string: { label: "מחרוזת", gender: "f" }, - number: { label: "מספר", gender: "m" }, - boolean: { label: "ערך בוליאני", gender: "m" }, - bigint: { label: "BigInt", gender: "m" }, - date: { label: "תאריך", gender: "m" }, - array: { label: "מערך", gender: "m" }, - object: { label: "אובייקט", gender: "m" }, - null: { label: "ערך ריק (null)", gender: "m" }, - undefined: { label: "ערך לא מוגדר (undefined)", gender: "m" }, - symbol: { label: "סימבול (Symbol)", gender: "m" }, - function: { label: "פונקציה", gender: "f" }, - map: { label: "מפה (Map)", gender: "f" }, - set: { label: "קבוצה (Set)", gender: "f" }, - file: { label: "קובץ", gender: "m" }, - promise: { label: "Promise", gender: "m" }, - NaN: { label: "NaN", gender: "m" }, - unknown: { label: "ערך לא ידוע", gender: "m" }, - value: { label: "ערך", gender: "m" }, - }; - // Sizing units for size-related messages + localized origin labels - const Sizable = { - string: { unit: "תווים", shortLabel: "קצר", longLabel: "ארוך" }, - file: { unit: "בייטים", shortLabel: "קטן", longLabel: "גדול" }, - array: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" }, - set: { unit: "פריטים", shortLabel: "קטן", longLabel: "גדול" }, - number: { unit: "", shortLabel: "קטן", longLabel: "גדול" }, // no unit - }; - // Helpers — labels, articles, and verbs - const typeEntry = (t) => (t ? TypeNames[t] : undefined); - const typeLabel = (t) => { - const e = typeEntry(t); - if (e) - return e.label; - // fallback: show raw string if unknown - return t ?? TypeNames.unknown.label; - }; - const withDefinite = (t) => `ה${typeLabel(t)}`; - const verbFor = (t) => { - const e = typeEntry(t); - const gender = e?.gender ?? "m"; - return gender === "f" ? "צריכה להיות" : "צריך להיות"; - }; - const getSizing = (origin) => { - if (!origin) - return null; - return Sizable[origin] ?? null; - }; - // Robust type parser for "received" — returns a key we understand or a constructor name - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": - return Number.isNaN(data) ? "NaN" : "number"; - case "object": { - if (Array.isArray(data)) - return "array"; - if (data === null) - return "null"; - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; // keep as-is (e.g., "Date") - } - return "object"; - } - default: - return t; - } - }; - const Nouns = { - regex: { label: "קלט", gender: "m" }, - email: { label: "כתובת אימייל", gender: "f" }, - url: { label: "כתובת רשת", gender: "f" }, - emoji: { label: "אימוג'י", gender: "m" }, - uuid: { label: "UUID", gender: "m" }, - nanoid: { label: "nanoid", gender: "m" }, - guid: { label: "GUID", gender: "m" }, - cuid: { label: "cuid", gender: "m" }, - cuid2: { label: "cuid2", gender: "m" }, - ulid: { label: "ULID", gender: "m" }, - xid: { label: "XID", gender: "m" }, - ksuid: { label: "KSUID", gender: "m" }, - datetime: { label: "תאריך וזמן ISO", gender: "m" }, - date: { label: "תאריך ISO", gender: "m" }, - time: { label: "זמן ISO", gender: "m" }, - duration: { label: "משך זמן ISO", gender: "m" }, - ipv4: { label: "כתובת IPv4", gender: "f" }, - ipv6: { label: "כתובת IPv6", gender: "f" }, - cidrv4: { label: "טווח IPv4", gender: "m" }, - cidrv6: { label: "טווח IPv6", gender: "m" }, - base64: { label: "מחרוזת בבסיס 64", gender: "f" }, - base64url: { label: "מחרוזת בבסיס 64 לכתובות רשת", gender: "f" }, - json_string: { label: "מחרוזת JSON", gender: "f" }, - e164: { label: "מספר E.164", gender: "m" }, - jwt: { label: "JWT", gender: "m" }, - ends_with: { label: "קלט", gender: "m" }, - includes: { label: "קלט", gender: "m" }, - lowercase: { label: "קלט", gender: "m" }, - starts_with: { label: "קלט", gender: "m" }, - uppercase: { label: "קלט", gender: "m" }, - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": { - // Expected type: show without definite article for clearer Hebrew - const expectedKey = issue.expected; - const expected = typeLabel(expectedKey); - // Received: show localized label if known, otherwise constructor/raw - const receivedKey = parsedType(issue.input); - const received = TypeNames[receivedKey]?.label ?? receivedKey; - return `קלט לא תקין: צריך להיות ${expected}, התקבל ${received}`; - } - case "invalid_value": { - if (issue.values.length === 1) { - return `ערך לא תקין: הערך חייב להיות ${stringifyPrimitive(issue.values[0])}`; - } - // Join values with proper Hebrew formatting - const stringified = issue.values.map((v) => stringifyPrimitive(v)); - if (issue.values.length === 2) { - return `ערך לא תקין: האפשרויות המתאימות הן ${stringified[0]} או ${stringified[1]}`; - } - // For 3+ values: "a", "b" או "c" - const lastValue = stringified[stringified.length - 1]; - const restValues = stringified.slice(0, -1).join(", "); - return `ערך לא תקין: האפשרויות המתאימות הן ${restValues} או ${lastValue}`; - } - case "too_big": { - const sizing = getSizing(issue.origin); - const subject = withDefinite(issue.origin ?? "value"); - if (issue.origin === "string") { - // Special handling for strings - more natural Hebrew - return `${sizing?.longLabel ?? "ארוך"} מדי: ${subject} צריכה להכיל ${issue.maximum.toString()} ${sizing?.unit ?? ""} ${issue.inclusive ? "או פחות" : "לכל היותר"}`.trim(); - } - if (issue.origin === "number") { - // Natural Hebrew for numbers - const comparison = issue.inclusive ? `קטן או שווה ל-${issue.maximum}` : `קטן מ-${issue.maximum}`; - return `גדול מדי: ${subject} צריך להיות ${comparison}`; - } - if (issue.origin === "array" || issue.origin === "set") { - // Natural Hebrew for arrays and sets - const verb = issue.origin === "set" ? "צריכה" : "צריך"; - const comparison = issue.inclusive - ? `${issue.maximum} ${sizing?.unit ?? ""} או פחות` - : `פחות מ-${issue.maximum} ${sizing?.unit ?? ""}`; - return `גדול מדי: ${subject} ${verb} להכיל ${comparison}`.trim(); - } - const adj = issue.inclusive ? "<=" : "<"; - const be = verbFor(issue.origin ?? "value"); - if (sizing?.unit) { - return `${sizing.longLabel} מדי: ${subject} ${be} ${adj}${issue.maximum.toString()} ${sizing.unit}`; - } - return `${sizing?.longLabel ?? "גדול"} מדי: ${subject} ${be} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const sizing = getSizing(issue.origin); - const subject = withDefinite(issue.origin ?? "value"); - if (issue.origin === "string") { - // Special handling for strings - more natural Hebrew - return `${sizing?.shortLabel ?? "קצר"} מדי: ${subject} צריכה להכיל ${issue.minimum.toString()} ${sizing?.unit ?? ""} ${issue.inclusive ? "או יותר" : "לפחות"}`.trim(); - } - if (issue.origin === "number") { - // Natural Hebrew for numbers - const comparison = issue.inclusive ? `גדול או שווה ל-${issue.minimum}` : `גדול מ-${issue.minimum}`; - return `קטן מדי: ${subject} צריך להיות ${comparison}`; - } - if (issue.origin === "array" || issue.origin === "set") { - // Natural Hebrew for arrays and sets - const verb = issue.origin === "set" ? "צריכה" : "צריך"; - // Special case for singular (minimum === 1) - if (issue.minimum === 1 && issue.inclusive) { - const singularPhrase = issue.origin === "set" ? "לפחות פריט אחד" : "לפחות פריט אחד"; - return `קטן מדי: ${subject} ${verb} להכיל ${singularPhrase}`; - } - const comparison = issue.inclusive - ? `${issue.minimum} ${sizing?.unit ?? ""} או יותר` - : `יותר מ-${issue.minimum} ${sizing?.unit ?? ""}`; - return `קטן מדי: ${subject} ${verb} להכיל ${comparison}`.trim(); - } - const adj = issue.inclusive ? ">=" : ">"; - const be = verbFor(issue.origin ?? "value"); - if (sizing?.unit) { - return `${sizing.shortLabel} מדי: ${subject} ${be} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `${sizing?.shortLabel ?? "קטן"} מדי: ${subject} ${be} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - // These apply to strings — use feminine grammar + ה׳ הידיעה - if (_issue.format === "starts_with") - return `המחרוזת חייבת להתחיל ב "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `המחרוזת חייבת להסתיים ב "${_issue.suffix}"`; - if (_issue.format === "includes") - return `המחרוזת חייבת לכלול "${_issue.includes}"`; - if (_issue.format === "regex") - return `המחרוזת חייבת להתאים לתבנית ${_issue.pattern}`; - // Handle gender agreement for formats - const nounEntry = Nouns[_issue.format]; - const noun = nounEntry?.label ?? _issue.format; - const gender = nounEntry?.gender ?? "m"; - const adjective = gender === "f" ? "תקינה" : "תקין"; - return `${noun} לא ${adjective}`; - } - case "not_multiple_of": - return `מספר לא תקין: חייב להיות מכפלה של ${issue.divisor}`; - case "unrecognized_keys": - return `מפתח${issue.keys.length > 1 ? "ות" : ""} לא מזוה${issue.keys.length > 1 ? "ים" : "ה"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": { - return `שדה לא תקין באובייקט`; - } - case "invalid_union": - return "קלט לא תקין"; - case "invalid_element": { - const place = withDefinite(issue.origin ?? "array"); - return `ערך לא תקין ב${place}`; - } - default: - return `קלט לא תקין`; - } - }; -}; -/* harmony default export */ function he() { - return { - localeError: he_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/hu.js - -const hu_error = () => { - const Sizable = { - string: { unit: "karakter", verb: "legyen" }, - file: { unit: "byte", verb: "legyen" }, - array: { unit: "elem", verb: "legyen" }, - set: { unit: "elem", verb: "legyen" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "szám"; - } - case "object": { - if (Array.isArray(data)) { - return "tömb"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "bemenet", - email: "email cím", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO időbélyeg", - date: "ISO dátum", - time: "ISO idő", - duration: "ISO időintervallum", - ipv4: "IPv4 cím", - ipv6: "IPv6 cím", - cidrv4: "IPv4 tartomány", - cidrv6: "IPv6 tartomány", - base64: "base64-kódolt string", - base64url: "base64url-kódolt string", - json_string: "JSON string", - e164: "E.164 szám", - jwt: "JWT", - template_literal: "bemenet", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Érvénytelen bemenet: a várt érték ${issue.expected}, a kapott érték ${parsedType(issue.input)}`; - // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Érvénytelen bemenet: a várt érték ${stringifyPrimitive(issue.values[0])}`; - return `Érvénytelen opció: valamelyik érték várt ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Túl nagy: ${issue.origin ?? "érték"} mérete túl nagy ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elem"}`; - return `Túl nagy: a bemeneti érték ${issue.origin ?? "érték"} túl nagy: ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Túl kicsi: a bemeneti érték ${issue.origin} mérete túl kicsi ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Túl kicsi: a bemeneti érték ${issue.origin} túl kicsi ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Érvénytelen string: "${_issue.prefix}" értékkel kell kezdődnie`; - if (_issue.format === "ends_with") - return `Érvénytelen string: "${_issue.suffix}" értékkel kell végződnie`; - if (_issue.format === "includes") - return `Érvénytelen string: "${_issue.includes}" értéket kell tartalmaznia`; - if (_issue.format === "regex") - return `Érvénytelen string: ${_issue.pattern} mintának kell megfelelnie`; - return `Érvénytelen ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Érvénytelen szám: ${issue.divisor} többszörösének kell lennie`; - case "unrecognized_keys": - return `Ismeretlen kulcs${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Érvénytelen kulcs ${issue.origin}`; - case "invalid_union": - return "Érvénytelen bemenet"; - case "invalid_element": - return `Érvénytelen érték: ${issue.origin}`; - default: - return `Érvénytelen bemenet`; - } - }; -}; -/* harmony default export */ function hu() { - return { - localeError: hu_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/id.js - -const id_error = () => { - const Sizable = { - string: { unit: "karakter", verb: "memiliki" }, - file: { unit: "byte", verb: "memiliki" }, - array: { unit: "item", verb: "memiliki" }, - set: { unit: "item", verb: "memiliki" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "input", - email: "alamat email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "tanggal dan waktu format ISO", - date: "tanggal format ISO", - time: "jam format ISO", - duration: "durasi format ISO", - ipv4: "alamat IPv4", - ipv6: "alamat IPv6", - cidrv4: "rentang alamat IPv4", - cidrv6: "rentang alamat IPv6", - base64: "string dengan enkode base64", - base64url: "string dengan enkode base64url", - json_string: "string JSON", - e164: "angka E.164", - jwt: "JWT", - template_literal: "input", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Input tidak valid: diharapkan ${issue.expected}, diterima ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Input tidak valid: diharapkan ${stringifyPrimitive(issue.values[0])}`; - return `Pilihan tidak valid: diharapkan salah satu dari ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Terlalu besar: diharapkan ${issue.origin ?? "value"} memiliki ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemen"}`; - return `Terlalu besar: diharapkan ${issue.origin ?? "value"} menjadi ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Terlalu kecil: diharapkan ${issue.origin} memiliki ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Terlalu kecil: diharapkan ${issue.origin} menjadi ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `String tidak valid: harus dimulai dengan "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `String tidak valid: harus berakhir dengan "${_issue.suffix}"`; - if (_issue.format === "includes") - return `String tidak valid: harus menyertakan "${_issue.includes}"`; - if (_issue.format === "regex") - return `String tidak valid: harus sesuai pola ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue.format} tidak valid`; - } - case "not_multiple_of": - return `Angka tidak valid: harus kelipatan dari ${issue.divisor}`; - case "unrecognized_keys": - return `Kunci tidak dikenali ${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Kunci tidak valid di ${issue.origin}`; - case "invalid_union": - return "Input tidak valid"; - case "invalid_element": - return `Nilai tidak valid di ${issue.origin}`; - default: - return `Input tidak valid`; - } - }; -}; -/* harmony default export */ function id() { - return { - localeError: id_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/is.js - -const is_parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "númer"; - } - case "object": { - if (Array.isArray(data)) { - return "fylki"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; -}; -const is_error = () => { - const Sizable = { - string: { unit: "stafi", verb: "að hafa" }, - file: { unit: "bæti", verb: "að hafa" }, - array: { unit: "hluti", verb: "að hafa" }, - set: { unit: "hluti", verb: "að hafa" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const Nouns = { - regex: "gildi", - email: "netfang", - url: "vefslóð", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO dagsetning og tími", - date: "ISO dagsetning", - time: "ISO tími", - duration: "ISO tímalengd", - ipv4: "IPv4 address", - ipv6: "IPv6 address", - cidrv4: "IPv4 range", - cidrv6: "IPv6 range", - base64: "base64-encoded strengur", - base64url: "base64url-encoded strengur", - json_string: "JSON strengur", - e164: "E.164 tölugildi", - jwt: "JWT", - template_literal: "gildi", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Rangt gildi: Þú slóst inn ${is_parsedType(issue.input)} þar sem á að vera ${issue.expected}`; - case "invalid_value": - if (issue.values.length === 1) - return `Rangt gildi: gert ráð fyrir ${stringifyPrimitive(issue.values[0])}`; - return `Ógilt val: má vera eitt af eftirfarandi ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Of stórt: gert er ráð fyrir að ${issue.origin ?? "gildi"} hafi ${adj}${issue.maximum.toString()} ${sizing.unit ?? "hluti"}`; - return `Of stórt: gert er ráð fyrir að ${issue.origin ?? "gildi"} sé ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Of lítið: gert er ráð fyrir að ${issue.origin} hafi ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Of lítið: gert er ráð fyrir að ${issue.origin} sé ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Ógildur strengur: verður að byrja á "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Ógildur strengur: verður að enda á "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ógildur strengur: verður að innihalda "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ógildur strengur: verður að fylgja mynstri ${_issue.pattern}`; - return `Rangt ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Röng tala: verður að vera margfeldi af ${issue.divisor}`; - case "unrecognized_keys": - return `Óþekkt ${issue.keys.length > 1 ? "ir lyklar" : "ur lykill"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Rangur lykill í ${issue.origin}`; - case "invalid_union": - return "Rangt gildi"; - case "invalid_element": - return `Rangt gildi í ${issue.origin}`; - default: - return `Rangt gildi`; - } - }; -}; -/* harmony default export */ function is() { - return { - localeError: is_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/it.js - -const it_error = () => { - const Sizable = { - string: { unit: "caratteri", verb: "avere" }, - file: { unit: "byte", verb: "avere" }, - array: { unit: "elementi", verb: "avere" }, - set: { unit: "elementi", verb: "avere" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "numero"; - } - case "object": { - if (Array.isArray(data)) { - return "vettore"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "input", - email: "indirizzo email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e ora ISO", - date: "data ISO", - time: "ora ISO", - duration: "durata ISO", - ipv4: "indirizzo IPv4", - ipv6: "indirizzo IPv6", - cidrv4: "intervallo IPv4", - cidrv6: "intervallo IPv6", - base64: "stringa codificata in base64", - base64url: "URL codificata in base64", - json_string: "stringa JSON", - e164: "numero E.164", - jwt: "JWT", - template_literal: "input", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Input non valido: atteso ${issue.expected}, ricevuto ${parsedType(issue.input)}`; - // return `Input non valido: atteso ${issue.expected}, ricevuto ${util.getParsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Input non valido: atteso ${stringifyPrimitive(issue.values[0])}`; - return `Opzione non valida: atteso uno tra ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Troppo grande: ${issue.origin ?? "valore"} deve avere ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementi"}`; - return `Troppo grande: ${issue.origin ?? "valore"} deve essere ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Troppo piccolo: ${issue.origin} deve avere ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Troppo piccolo: ${issue.origin} deve essere ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Stringa non valida: deve iniziare con "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Stringa non valida: deve terminare con "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Stringa non valida: deve includere "${_issue.includes}"`; - if (_issue.format === "regex") - return `Stringa non valida: deve corrispondere al pattern ${_issue.pattern}`; - return `Invalid ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Numero non valido: deve essere un multiplo di ${issue.divisor}`; - case "unrecognized_keys": - return `Chiav${issue.keys.length > 1 ? "i" : "e"} non riconosciut${issue.keys.length > 1 ? "e" : "a"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Chiave non valida in ${issue.origin}`; - case "invalid_union": - return "Input non valido"; - case "invalid_element": - return `Valore non valido in ${issue.origin}`; - default: - return `Input non valido`; - } - }; -}; -/* harmony default export */ function it() { - return { - localeError: it_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ja.js - -const ja_error = () => { - const Sizable = { - string: { unit: "文字", verb: "である" }, - file: { unit: "バイト", verb: "である" }, - array: { unit: "要素", verb: "である" }, - set: { unit: "要素", verb: "である" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "数値"; - } - case "object": { - if (Array.isArray(data)) { - return "配列"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "入力値", - email: "メールアドレス", - url: "URL", - emoji: "絵文字", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO日時", - date: "ISO日付", - time: "ISO時刻", - duration: "ISO期間", - ipv4: "IPv4アドレス", - ipv6: "IPv6アドレス", - cidrv4: "IPv4範囲", - cidrv6: "IPv6範囲", - base64: "base64エンコード文字列", - base64url: "base64urlエンコード文字列", - json_string: "JSON文字列", - e164: "E.164番号", - jwt: "JWT", - template_literal: "入力値", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `無効な入力: ${issue.expected}が期待されましたが、${parsedType(issue.input)}が入力されました`; - case "invalid_value": - if (issue.values.length === 1) - return `無効な入力: ${stringifyPrimitive(issue.values[0])}が期待されました`; - return `無効な選択: ${joinValues(issue.values, "、")}のいずれかである必要があります`; - case "too_big": { - const adj = issue.inclusive ? "以下である" : "より小さい"; - const sizing = getSizing(issue.origin); - if (sizing) - return `大きすぎる値: ${issue.origin ?? "値"}は${issue.maximum.toString()}${sizing.unit ?? "要素"}${adj}必要があります`; - return `大きすぎる値: ${issue.origin ?? "値"}は${issue.maximum.toString()}${adj}必要があります`; - } - case "too_small": { - const adj = issue.inclusive ? "以上である" : "より大きい"; - const sizing = getSizing(issue.origin); - if (sizing) - return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${sizing.unit}${adj}必要があります`; - return `小さすぎる値: ${issue.origin}は${issue.minimum.toString()}${adj}必要があります`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `無効な文字列: "${_issue.prefix}"で始まる必要があります`; - if (_issue.format === "ends_with") - return `無効な文字列: "${_issue.suffix}"で終わる必要があります`; - if (_issue.format === "includes") - return `無効な文字列: "${_issue.includes}"を含む必要があります`; - if (_issue.format === "regex") - return `無効な文字列: パターン${_issue.pattern}に一致する必要があります`; - return `無効な${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `無効な数値: ${issue.divisor}の倍数である必要があります`; - case "unrecognized_keys": - return `認識されていないキー${issue.keys.length > 1 ? "群" : ""}: ${joinValues(issue.keys, "、")}`; - case "invalid_key": - return `${issue.origin}内の無効なキー`; - case "invalid_union": - return "無効な入力"; - case "invalid_element": - return `${issue.origin}内の無効な値`; - default: - return `無効な入力`; - } - }; -}; -/* harmony default export */ function ja() { - return { - localeError: ja_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ka.js - -const ka_parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "რიცხვი"; - } - case "object": { - if (Array.isArray(data)) { - return "მასივი"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - const typeMap = { - string: "სტრინგი", - boolean: "ბულეანი", - undefined: "undefined", - bigint: "bigint", - symbol: "symbol", - function: "ფუნქცია", - }; - return typeMap[t] ?? t; -}; -const ka_error = () => { - const Sizable = { - string: { unit: "სიმბოლო", verb: "უნდა შეიცავდეს" }, - file: { unit: "ბაიტი", verb: "უნდა შეიცავდეს" }, - array: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" }, - set: { unit: "ელემენტი", verb: "უნდა შეიცავდეს" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const Nouns = { - regex: "შეყვანა", - email: "ელ-ფოსტის მისამართი", - url: "URL", - emoji: "ემოჯი", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "თარიღი-დრო", - date: "თარიღი", - time: "დრო", - duration: "ხანგრძლივობა", - ipv4: "IPv4 მისამართი", - ipv6: "IPv6 მისამართი", - cidrv4: "IPv4 დიაპაზონი", - cidrv6: "IPv6 დიაპაზონი", - base64: "base64-კოდირებული სტრინგი", - base64url: "base64url-კოდირებული სტრინგი", - json_string: "JSON სტრინგი", - e164: "E.164 ნომერი", - jwt: "JWT", - template_literal: "შეყვანა", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `არასწორი შეყვანა: მოსალოდნელი ${issue.expected}, მიღებული ${ka_parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `არასწორი შეყვანა: მოსალოდნელი ${stringifyPrimitive(issue.values[0])}`; - return `არასწორი ვარიანტი: მოსალოდნელია ერთ-ერთი ${joinValues(issue.values, "|")}-დან`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `ზედმეტად დიდი: მოსალოდნელი ${issue.origin ?? "მნიშვნელობა"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit}`; - return `ზედმეტად დიდი: მოსალოდნელი ${issue.origin ?? "მნიშვნელობა"} იყოს ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `ზედმეტად პატარა: მოსალოდნელი ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `ზედმეტად პატარა: მოსალოდნელი ${issue.origin} იყოს ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `არასწორი სტრინგი: უნდა იწყებოდეს "${_issue.prefix}"-ით`; - } - if (_issue.format === "ends_with") - return `არასწორი სტრინგი: უნდა მთავრდებოდეს "${_issue.suffix}"-ით`; - if (_issue.format === "includes") - return `არასწორი სტრინგი: უნდა შეიცავდეს "${_issue.includes}"-ს`; - if (_issue.format === "regex") - return `არასწორი სტრინგი: უნდა შეესაბამებოდეს შაბლონს ${_issue.pattern}`; - return `არასწორი ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `არასწორი რიცხვი: უნდა იყოს ${issue.divisor}-ის ჯერადი`; - case "unrecognized_keys": - return `უცნობი გასაღებ${issue.keys.length > 1 ? "ები" : "ი"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `არასწორი გასაღები ${issue.origin}-ში`; - case "invalid_union": - return "არასწორი შეყვანა"; - case "invalid_element": - return `არასწორი მნიშვნელობა ${issue.origin}-ში`; - default: - return `არასწორი შეყვანა`; - } - }; -}; -/* harmony default export */ function ka() { - return { - localeError: ka_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/km.js - -const km_error = () => { - const Sizable = { - string: { unit: "តួអក្សរ", verb: "គួរមាន" }, - file: { unit: "បៃ", verb: "គួរមាន" }, - array: { unit: "ធាតុ", verb: "គួរមាន" }, - set: { unit: "ធាតុ", verb: "គួរមាន" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "មិនមែនជាលេខ (NaN)" : "លេខ"; - } - case "object": { - if (Array.isArray(data)) { - return "អារេ (Array)"; - } - if (data === null) { - return "គ្មានតម្លៃ (null)"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "ទិន្នន័យបញ្ចូល", - email: "អាសយដ្ឋានអ៊ីមែល", - url: "URL", - emoji: "សញ្ញាអារម្មណ៍", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "កាលបរិច្ឆេទ និងម៉ោង ISO", - date: "កាលបរិច្ឆេទ ISO", - time: "ម៉ោង ISO", - duration: "រយៈពេល ISO", - ipv4: "អាសយដ្ឋាន IPv4", - ipv6: "អាសយដ្ឋាន IPv6", - cidrv4: "ដែនអាសយដ្ឋាន IPv4", - cidrv6: "ដែនអាសយដ្ឋាន IPv6", - base64: "ខ្សែអក្សរអ៊ិកូដ base64", - base64url: "ខ្សែអក្សរអ៊ិកូដ base64url", - json_string: "ខ្សែអក្សរ JSON", - e164: "លេខ E.164", - jwt: "JWT", - template_literal: "ទិន្នន័យបញ្ចូល", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${issue.expected} ប៉ុន្តែទទួលបាន ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `ទិន្នន័យបញ្ចូលមិនត្រឹមត្រូវ៖ ត្រូវការ ${stringifyPrimitive(issue.values[0])}`; - return `ជម្រើសមិនត្រឹមត្រូវ៖ ត្រូវជាមួយក្នុងចំណោម ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()} ${sizing.unit ?? "ធាតុ"}`; - return `ធំពេក៖ ត្រូវការ ${issue.origin ?? "តម្លៃ"} ${adj} ${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()} ${sizing.unit}`; - } - return `តូចពេក៖ ត្រូវការ ${issue.origin} ${adj} ${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវចាប់ផ្តើមដោយ "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវបញ្ចប់ដោយ "${_issue.suffix}"`; - if (_issue.format === "includes") - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវមាន "${_issue.includes}"`; - if (_issue.format === "regex") - return `ខ្សែអក្សរមិនត្រឹមត្រូវ៖ ត្រូវតែផ្គូផ្គងនឹងទម្រង់ដែលបានកំណត់ ${_issue.pattern}`; - return `មិនត្រឹមត្រូវ៖ ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `លេខមិនត្រឹមត្រូវ៖ ត្រូវតែជាពហុគុណនៃ ${issue.divisor}`; - case "unrecognized_keys": - return `រកឃើញសោមិនស្គាល់៖ ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `សោមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`; - case "invalid_union": - return `ទិន្នន័យមិនត្រឹមត្រូវ`; - case "invalid_element": - return `ទិន្នន័យមិនត្រឹមត្រូវនៅក្នុង ${issue.origin}`; - default: - return `ទិន្នន័យមិនត្រឹមត្រូវ`; - } - }; -}; -/* harmony default export */ function km() { - return { - localeError: km_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/kh.js - -/** @deprecated Use `km` instead. */ -/* harmony default export */ function kh() { - return km(); -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ko.js - -const ko_error = () => { - const Sizable = { - string: { unit: "문자", verb: "to have" }, - file: { unit: "바이트", verb: "to have" }, - array: { unit: "개", verb: "to have" }, - set: { unit: "개", verb: "to have" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "입력", - email: "이메일 주소", - url: "URL", - emoji: "이모지", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO 날짜시간", - date: "ISO 날짜", - time: "ISO 시간", - duration: "ISO 기간", - ipv4: "IPv4 주소", - ipv6: "IPv6 주소", - cidrv4: "IPv4 범위", - cidrv6: "IPv6 범위", - base64: "base64 인코딩 문자열", - base64url: "base64url 인코딩 문자열", - json_string: "JSON 문자열", - e164: "E.164 번호", - jwt: "JWT", - template_literal: "입력", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `잘못된 입력: 예상 타입은 ${issue.expected}, 받은 타입은 ${parsedType(issue.input)}입니다`; - case "invalid_value": - if (issue.values.length === 1) - return `잘못된 입력: 값은 ${stringifyPrimitive(issue.values[0])} 이어야 합니다`; - return `잘못된 옵션: ${joinValues(issue.values, "또는 ")} 중 하나여야 합니다`; - case "too_big": { - const adj = issue.inclusive ? "이하" : "미만"; - const suffix = adj === "미만" ? "이어야 합니다" : "여야 합니다"; - const sizing = getSizing(issue.origin); - const unit = sizing?.unit ?? "요소"; - if (sizing) - return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()}${unit} ${adj}${suffix}`; - return `${issue.origin ?? "값"}이 너무 큽니다: ${issue.maximum.toString()} ${adj}${suffix}`; - } - case "too_small": { - const adj = issue.inclusive ? "이상" : "초과"; - const suffix = adj === "이상" ? "이어야 합니다" : "여야 합니다"; - const sizing = getSizing(issue.origin); - const unit = sizing?.unit ?? "요소"; - if (sizing) { - return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()}${unit} ${adj}${suffix}`; - } - return `${issue.origin ?? "값"}이 너무 작습니다: ${issue.minimum.toString()} ${adj}${suffix}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `잘못된 문자열: "${_issue.prefix}"(으)로 시작해야 합니다`; - } - if (_issue.format === "ends_with") - return `잘못된 문자열: "${_issue.suffix}"(으)로 끝나야 합니다`; - if (_issue.format === "includes") - return `잘못된 문자열: "${_issue.includes}"을(를) 포함해야 합니다`; - if (_issue.format === "regex") - return `잘못된 문자열: 정규식 ${_issue.pattern} 패턴과 일치해야 합니다`; - return `잘못된 ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `잘못된 숫자: ${issue.divisor}의 배수여야 합니다`; - case "unrecognized_keys": - return `인식할 수 없는 키: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `잘못된 키: ${issue.origin}`; - case "invalid_union": - return `잘못된 입력`; - case "invalid_element": - return `잘못된 값: ${issue.origin}`; - default: - return `잘못된 입력`; - } - }; -}; -/* harmony default export */ function ko() { - return { - localeError: ko_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/lt.js - -const lt_parsedType = (data) => { - const t = typeof data; - return parsedTypeFromType(t, data); -}; -const parsedTypeFromType = (t, data = undefined) => { - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "skaičius"; - } - case "bigint": { - return "sveikasis skaičius"; - } - case "string": { - return "eilutė"; - } - case "boolean": { - return "loginė reikšmė"; - } - case "undefined": - case "void": { - return "neapibrėžta reikšmė"; - } - case "function": { - return "funkcija"; - } - case "symbol": { - return "simbolis"; - } - case "object": { - if (data === undefined) - return "nežinomas objektas"; - if (data === null) - return "nulinė reikšmė"; - if (Array.isArray(data)) - return "masyvas"; - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - return "objektas"; - } - //Zod types below - case "null": { - return "nulinė reikšmė"; - } - } - return t; -}; -const capitalizeFirstCharacter = (text) => { - return text.charAt(0).toUpperCase() + text.slice(1); -}; -function getUnitTypeFromNumber(number) { - const abs = Math.abs(number); - const last = abs % 10; - const last2 = abs % 100; - if ((last2 >= 11 && last2 <= 19) || last === 0) - return "many"; - if (last === 1) - return "one"; - return "few"; -} -const lt_error = () => { - const Sizable = { - string: { - unit: { - one: "simbolis", - few: "simboliai", - many: "simbolių", - }, - verb: { - smaller: { - inclusive: "turi būti ne ilgesnė kaip", - notInclusive: "turi būti trumpesnė kaip", - }, - bigger: { - inclusive: "turi būti ne trumpesnė kaip", - notInclusive: "turi būti ilgesnė kaip", - }, - }, - }, - file: { - unit: { - one: "baitas", - few: "baitai", - many: "baitų", - }, - verb: { - smaller: { - inclusive: "turi būti ne didesnis kaip", - notInclusive: "turi būti mažesnis kaip", - }, - bigger: { - inclusive: "turi būti ne mažesnis kaip", - notInclusive: "turi būti didesnis kaip", - }, - }, - }, - array: { - unit: { - one: "elementą", - few: "elementus", - many: "elementų", - }, - verb: { - smaller: { - inclusive: "turi turėti ne daugiau kaip", - notInclusive: "turi turėti mažiau kaip", - }, - bigger: { - inclusive: "turi turėti ne mažiau kaip", - notInclusive: "turi turėti daugiau kaip", - }, - }, - }, - set: { - unit: { - one: "elementą", - few: "elementus", - many: "elementų", - }, - verb: { - smaller: { - inclusive: "turi turėti ne daugiau kaip", - notInclusive: "turi turėti mažiau kaip", - }, - bigger: { - inclusive: "turi turėti ne mažiau kaip", - notInclusive: "turi turėti daugiau kaip", - }, - }, - }, - }; - function getSizing(origin, unitType, inclusive, targetShouldBe) { - const result = Sizable[origin] ?? null; - if (result === null) - return result; - return { - unit: result.unit[unitType], - verb: result.verb[targetShouldBe][inclusive ? "inclusive" : "notInclusive"], - }; - } - const Nouns = { - regex: "įvestis", - email: "el. pašto adresas", - url: "URL", - emoji: "jaustukas", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO data ir laikas", - date: "ISO data", - time: "ISO laikas", - duration: "ISO trukmė", - ipv4: "IPv4 adresas", - ipv6: "IPv6 adresas", - cidrv4: "IPv4 tinklo prefiksas (CIDR)", - cidrv6: "IPv6 tinklo prefiksas (CIDR)", - base64: "base64 užkoduota eilutė", - base64url: "base64url užkoduota eilutė", - json_string: "JSON eilutė", - e164: "E.164 numeris", - jwt: "JWT", - template_literal: "įvestis", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Gautas tipas ${lt_parsedType(issue.input)}, o tikėtasi - ${parsedTypeFromType(issue.expected)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Privalo būti ${stringifyPrimitive(issue.values[0])}`; - return `Privalo būti vienas iš ${joinValues(issue.values, "|")} pasirinkimų`; - case "too_big": { - const origin = parsedTypeFromType(issue.origin); - const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.maximum)), issue.inclusive ?? false, "smaller"); - if (sizing?.verb) - return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} ${sizing.verb} ${issue.maximum.toString()} ${sizing.unit ?? "elementų"}`; - const adj = issue.inclusive ? "ne didesnis kaip" : "mažesnis kaip"; - return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} turi būti ${adj} ${issue.maximum.toString()} ${sizing?.unit}`; - } - case "too_small": { - const origin = parsedTypeFromType(issue.origin); - const sizing = getSizing(issue.origin, getUnitTypeFromNumber(Number(issue.minimum)), issue.inclusive ?? false, "bigger"); - if (sizing?.verb) - return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} ${sizing.verb} ${issue.minimum.toString()} ${sizing.unit ?? "elementų"}`; - const adj = issue.inclusive ? "ne mažesnis kaip" : "didesnis kaip"; - return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} turi būti ${adj} ${issue.minimum.toString()} ${sizing?.unit}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Eilutė privalo prasidėti "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Eilutė privalo pasibaigti "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Eilutė privalo įtraukti "${_issue.includes}"`; - if (_issue.format === "regex") - return `Eilutė privalo atitikti ${_issue.pattern}`; - return `Neteisingas ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Skaičius privalo būti ${issue.divisor} kartotinis.`; - case "unrecognized_keys": - return `Neatpažint${issue.keys.length > 1 ? "i" : "as"} rakt${issue.keys.length > 1 ? "ai" : "as"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return "Rastas klaidingas raktas"; - case "invalid_union": - return "Klaidinga įvestis"; - case "invalid_element": { - const origin = parsedTypeFromType(issue.origin); - return `${capitalizeFirstCharacter(origin ?? issue.origin ?? "reikšmė")} turi klaidingą įvestį`; - } - default: - return "Klaidinga įvestis"; - } - }; -}; -/* harmony default export */ function lt() { - return { - localeError: lt_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/mk.js - -const mk_error = () => { - const Sizable = { - string: { unit: "знаци", verb: "да имаат" }, - file: { unit: "бајти", verb: "да имаат" }, - array: { unit: "ставки", verb: "да имаат" }, - set: { unit: "ставки", verb: "да имаат" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "број"; - } - case "object": { - if (Array.isArray(data)) { - return "низа"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "внес", - email: "адреса на е-пошта", - url: "URL", - emoji: "емоџи", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO датум и време", - date: "ISO датум", - time: "ISO време", - duration: "ISO времетраење", - ipv4: "IPv4 адреса", - ipv6: "IPv6 адреса", - cidrv4: "IPv4 опсег", - cidrv6: "IPv6 опсег", - base64: "base64-енкодирана низа", - base64url: "base64url-енкодирана низа", - json_string: "JSON низа", - e164: "E.164 број", - jwt: "JWT", - template_literal: "внес", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Грешен внес: се очекува ${issue.expected}, примено ${parsedType(issue.input)}`; - // return `Invalid input: expected ${issue.expected}, received ${util.getParsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Invalid input: expected ${stringifyPrimitive(issue.values[0])}`; - return `Грешана опција: се очекува една ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Премногу голем: се очекува ${issue.origin ?? "вредноста"} да има ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елементи"}`; - return `Премногу голем: се очекува ${issue.origin ?? "вредноста"} да биде ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Премногу мал: се очекува ${issue.origin} да има ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Премногу мал: се очекува ${issue.origin} да биде ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Неважечка низа: мора да започнува со "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Неважечка низа: мора да завршува со "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Неважечка низа: мора да вклучува "${_issue.includes}"`; - if (_issue.format === "regex") - return `Неважечка низа: мора да одгоара на патернот ${_issue.pattern}`; - return `Invalid ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Грешен број: мора да биде делив со ${issue.divisor}`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Непрепознаени клучеви" : "Непрепознаен клуч"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Грешен клуч во ${issue.origin}`; - case "invalid_union": - return "Грешен внес"; - case "invalid_element": - return `Грешна вредност во ${issue.origin}`; - default: - return `Грешен внес`; - } - }; -}; -/* harmony default export */ function mk() { - return { - localeError: mk_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ms.js - -const ms_error = () => { - const Sizable = { - string: { unit: "aksara", verb: "mempunyai" }, - file: { unit: "bait", verb: "mempunyai" }, - array: { unit: "elemen", verb: "mempunyai" }, - set: { unit: "elemen", verb: "mempunyai" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "nombor"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "input", - email: "alamat e-mel", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "tarikh masa ISO", - date: "tarikh ISO", - time: "masa ISO", - duration: "tempoh ISO", - ipv4: "alamat IPv4", - ipv6: "alamat IPv6", - cidrv4: "julat IPv4", - cidrv6: "julat IPv6", - base64: "string dikodkan base64", - base64url: "string dikodkan base64url", - json_string: "string JSON", - e164: "nombor E.164", - jwt: "JWT", - template_literal: "input", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Input tidak sah: dijangka ${issue.expected}, diterima ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Input tidak sah: dijangka ${stringifyPrimitive(issue.values[0])}`; - return `Pilihan tidak sah: dijangka salah satu daripada ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elemen"}`; - return `Terlalu besar: dijangka ${issue.origin ?? "nilai"} adalah ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Terlalu kecil: dijangka ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Terlalu kecil: dijangka ${issue.origin} adalah ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `String tidak sah: mesti bermula dengan "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `String tidak sah: mesti berakhir dengan "${_issue.suffix}"`; - if (_issue.format === "includes") - return `String tidak sah: mesti mengandungi "${_issue.includes}"`; - if (_issue.format === "regex") - return `String tidak sah: mesti sepadan dengan corak ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue.format} tidak sah`; - } - case "not_multiple_of": - return `Nombor tidak sah: perlu gandaan ${issue.divisor}`; - case "unrecognized_keys": - return `Kunci tidak dikenali: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Kunci tidak sah dalam ${issue.origin}`; - case "invalid_union": - return "Input tidak sah"; - case "invalid_element": - return `Nilai tidak sah dalam ${issue.origin}`; - default: - return `Input tidak sah`; - } - }; -}; -/* harmony default export */ function ms() { - return { - localeError: ms_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/nl.js - -const nl_error = () => { - const Sizable = { - string: { unit: "tekens", verb: "te hebben" }, - file: { unit: "bytes", verb: "te hebben" }, - array: { unit: "elementen", verb: "te hebben" }, - set: { unit: "elementen", verb: "te hebben" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "getal"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "invoer", - email: "emailadres", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datum en tijd", - date: "ISO datum", - time: "ISO tijd", - duration: "ISO duur", - ipv4: "IPv4-adres", - ipv6: "IPv6-adres", - cidrv4: "IPv4-bereik", - cidrv6: "IPv6-bereik", - base64: "base64-gecodeerde tekst", - base64url: "base64 URL-gecodeerde tekst", - json_string: "JSON string", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "invoer", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Ongeldige invoer: verwacht ${issue.expected}, ontving ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Ongeldige invoer: verwacht ${stringifyPrimitive(issue.values[0])}`; - return `Ongeldige optie: verwacht één van ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Te groot: verwacht dat ${issue.origin ?? "waarde"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementen"}`; - return `Te groot: verwacht dat ${issue.origin ?? "waarde"} ${adj}${issue.maximum.toString()} is`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Te klein: verwacht dat ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Te klein: verwacht dat ${issue.origin} ${adj}${issue.minimum.toString()} is`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Ongeldige tekst: moet met "${_issue.prefix}" beginnen`; - } - if (_issue.format === "ends_with") - return `Ongeldige tekst: moet op "${_issue.suffix}" eindigen`; - if (_issue.format === "includes") - return `Ongeldige tekst: moet "${_issue.includes}" bevatten`; - if (_issue.format === "regex") - return `Ongeldige tekst: moet overeenkomen met patroon ${_issue.pattern}`; - return `Ongeldig: ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Ongeldig getal: moet een veelvoud van ${issue.divisor} zijn`; - case "unrecognized_keys": - return `Onbekende key${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Ongeldige key in ${issue.origin}`; - case "invalid_union": - return "Ongeldige invoer"; - case "invalid_element": - return `Ongeldige waarde in ${issue.origin}`; - default: - return `Ongeldige invoer`; - } - }; -}; -/* harmony default export */ function nl() { - return { - localeError: nl_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/no.js - -const no_error = () => { - const Sizable = { - string: { unit: "tegn", verb: "å ha" }, - file: { unit: "bytes", verb: "å ha" }, - array: { unit: "elementer", verb: "å inneholde" }, - set: { unit: "elementer", verb: "å inneholde" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "tall"; - } - case "object": { - if (Array.isArray(data)) { - return "liste"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "input", - email: "e-postadresse", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO dato- og klokkeslett", - date: "ISO-dato", - time: "ISO-klokkeslett", - duration: "ISO-varighet", - ipv4: "IPv4-område", - ipv6: "IPv6-område", - cidrv4: "IPv4-spekter", - cidrv6: "IPv6-spekter", - base64: "base64-enkodet streng", - base64url: "base64url-enkodet streng", - json_string: "JSON-streng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "input", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Ugyldig input: forventet ${issue.expected}, fikk ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Ugyldig verdi: forventet ${stringifyPrimitive(issue.values[0])}`; - return `Ugyldig valg: forventet en av ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementer"}`; - return `For stor(t): forventet ${issue.origin ?? "value"} til å ha ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `For lite(n): forventet ${issue.origin} til å ha ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Ugyldig streng: må starte med "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Ugyldig streng: må ende med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ugyldig streng: må inneholde "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ugyldig streng: må matche mønsteret ${_issue.pattern}`; - return `Ugyldig ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Ugyldig tall: må være et multiplum av ${issue.divisor}`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Ukjente nøkler" : "Ukjent nøkkel"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Ugyldig nøkkel i ${issue.origin}`; - case "invalid_union": - return "Ugyldig input"; - case "invalid_element": - return `Ugyldig verdi i ${issue.origin}`; - default: - return `Ugyldig input`; - } - }; -}; -/* harmony default export */ function no() { - return { - localeError: no_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ota.js - -const ota_error = () => { - const Sizable = { - string: { unit: "harf", verb: "olmalıdır" }, - file: { unit: "bayt", verb: "olmalıdır" }, - array: { unit: "unsur", verb: "olmalıdır" }, - set: { unit: "unsur", verb: "olmalıdır" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "numara"; - } - case "object": { - if (Array.isArray(data)) { - return "saf"; - } - if (data === null) { - return "gayb"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "giren", - email: "epostagâh", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO hengâmı", - date: "ISO tarihi", - time: "ISO zamanı", - duration: "ISO müddeti", - ipv4: "IPv4 nişânı", - ipv6: "IPv6 nişânı", - cidrv4: "IPv4 menzili", - cidrv6: "IPv6 menzili", - base64: "base64-şifreli metin", - base64url: "base64url-şifreli metin", - json_string: "JSON metin", - e164: "E.164 sayısı", - jwt: "JWT", - template_literal: "giren", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Fâsit giren: umulan ${issue.expected}, alınan ${parsedType(issue.input)}`; - // return `Fâsit giren: umulan ${issue.expected}, alınan ${util.getParsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Fâsit giren: umulan ${stringifyPrimitive(issue.values[0])}`; - return `Fâsit tercih: mûteberler ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elements"} sahip olmalıydı.`; - return `Fazla büyük: ${issue.origin ?? "value"}, ${adj}${issue.maximum.toString()} olmalıydı.`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} ${sizing.unit} sahip olmalıydı.`; - } - return `Fazla küçük: ${issue.origin}, ${adj}${issue.minimum.toString()} olmalıydı.`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Fâsit metin: "${_issue.prefix}" ile başlamalı.`; - if (_issue.format === "ends_with") - return `Fâsit metin: "${_issue.suffix}" ile bitmeli.`; - if (_issue.format === "includes") - return `Fâsit metin: "${_issue.includes}" ihtivâ etmeli.`; - if (_issue.format === "regex") - return `Fâsit metin: ${_issue.pattern} nakşına uymalı.`; - return `Fâsit ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Fâsit sayı: ${issue.divisor} katı olmalıydı.`; - case "unrecognized_keys": - return `Tanınmayan anahtar ${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `${issue.origin} için tanınmayan anahtar var.`; - case "invalid_union": - return "Giren tanınamadı."; - case "invalid_element": - return `${issue.origin} için tanınmayan kıymet var.`; - default: - return `Kıymet tanınamadı.`; - } - }; -}; -/* harmony default export */ function ota() { - return { - localeError: ota_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ps.js - -const ps_error = () => { - const Sizable = { - string: { unit: "توکي", verb: "ولري" }, - file: { unit: "بایټس", verb: "ولري" }, - array: { unit: "توکي", verb: "ولري" }, - set: { unit: "توکي", verb: "ولري" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "عدد"; - } - case "object": { - if (Array.isArray(data)) { - return "ارې"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "ورودي", - email: "بریښنالیک", - url: "یو آر ال", - emoji: "ایموجي", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "نیټه او وخت", - date: "نېټه", - time: "وخت", - duration: "موده", - ipv4: "د IPv4 پته", - ipv6: "د IPv6 پته", - cidrv4: "د IPv4 ساحه", - cidrv6: "د IPv6 ساحه", - base64: "base64-encoded متن", - base64url: "base64url-encoded متن", - json_string: "JSON متن", - e164: "د E.164 شمېره", - jwt: "JWT", - template_literal: "ورودي", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `ناسم ورودي: باید ${issue.expected} وای, مګر ${parsedType(issue.input)} ترلاسه شو`; - case "invalid_value": - if (issue.values.length === 1) { - return `ناسم ورودي: باید ${stringifyPrimitive(issue.values[0])} وای`; - } - return `ناسم انتخاب: باید یو له ${joinValues(issue.values, "|")} څخه وای`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عنصرونه"} ولري`; - } - return `ډیر لوی: ${issue.origin ?? "ارزښت"} باید ${adj}${issue.maximum.toString()} وي`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} ${sizing.unit} ولري`; - } - return `ډیر کوچنی: ${issue.origin} باید ${adj}${issue.minimum.toString()} وي`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `ناسم متن: باید د "${_issue.prefix}" سره پیل شي`; - } - if (_issue.format === "ends_with") { - return `ناسم متن: باید د "${_issue.suffix}" سره پای ته ورسيږي`; - } - if (_issue.format === "includes") { - return `ناسم متن: باید "${_issue.includes}" ولري`; - } - if (_issue.format === "regex") { - return `ناسم متن: باید د ${_issue.pattern} سره مطابقت ولري`; - } - return `${Nouns[_issue.format] ?? issue.format} ناسم دی`; - } - case "not_multiple_of": - return `ناسم عدد: باید د ${issue.divisor} مضرب وي`; - case "unrecognized_keys": - return `ناسم ${issue.keys.length > 1 ? "کلیډونه" : "کلیډ"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `ناسم کلیډ په ${issue.origin} کې`; - case "invalid_union": - return `ناسمه ورودي`; - case "invalid_element": - return `ناسم عنصر په ${issue.origin} کې`; - default: - return `ناسمه ورودي`; - } - }; -}; -/* harmony default export */ function ps() { - return { - localeError: ps_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/pl.js - -const pl_error = () => { - const Sizable = { - string: { unit: "znaków", verb: "mieć" }, - file: { unit: "bajtów", verb: "mieć" }, - array: { unit: "elementów", verb: "mieć" }, - set: { unit: "elementów", verb: "mieć" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "liczba"; - } - case "object": { - if (Array.isArray(data)) { - return "tablica"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "wyrażenie", - email: "adres email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data i godzina w formacie ISO", - date: "data w formacie ISO", - time: "godzina w formacie ISO", - duration: "czas trwania ISO", - ipv4: "adres IPv4", - ipv6: "adres IPv6", - cidrv4: "zakres IPv4", - cidrv6: "zakres IPv6", - base64: "ciąg znaków zakodowany w formacie base64", - base64url: "ciąg znaków zakodowany w formacie base64url", - json_string: "ciąg znaków w formacie JSON", - e164: "liczba E.164", - jwt: "JWT", - template_literal: "wejście", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Nieprawidłowe dane wejściowe: oczekiwano ${issue.expected}, otrzymano ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Nieprawidłowe dane wejściowe: oczekiwano ${stringifyPrimitive(issue.values[0])}`; - return `Nieprawidłowa opcja: oczekiwano jednej z wartości ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Za duża wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementów"}`; - } - return `Zbyt duż(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Za mała wartość: oczekiwano, że ${issue.origin ?? "wartość"} będzie mieć ${adj}${issue.minimum.toString()} ${sizing.unit ?? "elementów"}`; - } - return `Zbyt mał(y/a/e): oczekiwano, że ${issue.origin ?? "wartość"} będzie wynosić ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Nieprawidłowy ciąg znaków: musi zaczynać się od "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Nieprawidłowy ciąg znaków: musi kończyć się na "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Nieprawidłowy ciąg znaków: musi zawierać "${_issue.includes}"`; - if (_issue.format === "regex") - return `Nieprawidłowy ciąg znaków: musi odpowiadać wzorcowi ${_issue.pattern}`; - return `Nieprawidłow(y/a/e) ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Nieprawidłowa liczba: musi być wielokrotnością ${issue.divisor}`; - case "unrecognized_keys": - return `Nierozpoznane klucze${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Nieprawidłowy klucz w ${issue.origin}`; - case "invalid_union": - return "Nieprawidłowe dane wejściowe"; - case "invalid_element": - return `Nieprawidłowa wartość w ${issue.origin}`; - default: - return `Nieprawidłowe dane wejściowe`; - } - }; -}; -/* harmony default export */ function pl() { - return { - localeError: pl_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/pt.js - -const pt_error = () => { - const Sizable = { - string: { unit: "caracteres", verb: "ter" }, - file: { unit: "bytes", verb: "ter" }, - array: { unit: "itens", verb: "ter" }, - set: { unit: "itens", verb: "ter" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "número"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "nulo"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "padrão", - email: "endereço de e-mail", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "data e hora ISO", - date: "data ISO", - time: "hora ISO", - duration: "duração ISO", - ipv4: "endereço IPv4", - ipv6: "endereço IPv6", - cidrv4: "faixa de IPv4", - cidrv6: "faixa de IPv6", - base64: "texto codificado em base64", - base64url: "URL codificada em base64", - json_string: "texto JSON", - e164: "número E.164", - jwt: "JWT", - template_literal: "entrada", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Tipo inválido: esperado ${issue.expected}, recebido ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Entrada inválida: esperado ${stringifyPrimitive(issue.values[0])}`; - return `Opção inválida: esperada uma das ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Muito grande: esperado que ${issue.origin ?? "valor"} tivesse ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementos"}`; - return `Muito grande: esperado que ${issue.origin ?? "valor"} fosse ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Muito pequeno: esperado que ${issue.origin} tivesse ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Muito pequeno: esperado que ${issue.origin} fosse ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Texto inválido: deve começar com "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Texto inválido: deve terminar com "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Texto inválido: deve incluir "${_issue.includes}"`; - if (_issue.format === "regex") - return `Texto inválido: deve corresponder ao padrão ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue.format} inválido`; - } - case "not_multiple_of": - return `Número inválido: deve ser múltiplo de ${issue.divisor}`; - case "unrecognized_keys": - return `Chave${issue.keys.length > 1 ? "s" : ""} desconhecida${issue.keys.length > 1 ? "s" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Chave inválida em ${issue.origin}`; - case "invalid_union": - return "Entrada inválida"; - case "invalid_element": - return `Valor inválido em ${issue.origin}`; - default: - return `Campo inválido`; - } - }; -}; -/* harmony default export */ function pt() { - return { - localeError: pt_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ru.js - -function getRussianPlural(count, one, few, many) { - const absCount = Math.abs(count); - const lastDigit = absCount % 10; - const lastTwoDigits = absCount % 100; - if (lastTwoDigits >= 11 && lastTwoDigits <= 19) { - return many; - } - if (lastDigit === 1) { - return one; - } - if (lastDigit >= 2 && lastDigit <= 4) { - return few; - } - return many; -} -const ru_error = () => { - const Sizable = { - string: { - unit: { - one: "символ", - few: "символа", - many: "символов", - }, - verb: "иметь", - }, - file: { - unit: { - one: "байт", - few: "байта", - many: "байт", - }, - verb: "иметь", - }, - array: { - unit: { - one: "элемент", - few: "элемента", - many: "элементов", - }, - verb: "иметь", - }, - set: { - unit: { - one: "элемент", - few: "элемента", - many: "элементов", - }, - verb: "иметь", - }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "число"; - } - case "object": { - if (Array.isArray(data)) { - return "массив"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "ввод", - email: "email адрес", - url: "URL", - emoji: "эмодзи", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO дата и время", - date: "ISO дата", - time: "ISO время", - duration: "ISO длительность", - ipv4: "IPv4 адрес", - ipv6: "IPv6 адрес", - cidrv4: "IPv4 диапазон", - cidrv6: "IPv6 диапазон", - base64: "строка в формате base64", - base64url: "строка в формате base64url", - json_string: "JSON строка", - e164: "номер E.164", - jwt: "JWT", - template_literal: "ввод", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Неверный ввод: ожидалось ${issue.expected}, получено ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Неверный ввод: ожидалось ${stringifyPrimitive(issue.values[0])}`; - return `Неверный вариант: ожидалось одно из ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - const maxValue = Number(issue.maximum); - const unit = getRussianPlural(maxValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет иметь ${adj}${issue.maximum.toString()} ${unit}`; - } - return `Слишком большое значение: ожидалось, что ${issue.origin ?? "значение"} будет ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - const minValue = Number(issue.minimum); - const unit = getRussianPlural(minValue, sizing.unit.one, sizing.unit.few, sizing.unit.many); - return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет иметь ${adj}${issue.minimum.toString()} ${unit}`; - } - return `Слишком маленькое значение: ожидалось, что ${issue.origin} будет ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Неверная строка: должна начинаться с "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Неверная строка: должна заканчиваться на "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Неверная строка: должна содержать "${_issue.includes}"`; - if (_issue.format === "regex") - return `Неверная строка: должна соответствовать шаблону ${_issue.pattern}`; - return `Неверный ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Неверное число: должно быть кратным ${issue.divisor}`; - case "unrecognized_keys": - return `Нераспознанн${issue.keys.length > 1 ? "ые" : "ый"} ключ${issue.keys.length > 1 ? "и" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Неверный ключ в ${issue.origin}`; - case "invalid_union": - return "Неверные входные данные"; - case "invalid_element": - return `Неверное значение в ${issue.origin}`; - default: - return `Неверные входные данные`; - } - }; -}; -/* harmony default export */ function ru() { - return { - localeError: ru_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/sl.js - -const sl_error = () => { - const Sizable = { - string: { unit: "znakov", verb: "imeti" }, - file: { unit: "bajtov", verb: "imeti" }, - array: { unit: "elementov", verb: "imeti" }, - set: { unit: "elementov", verb: "imeti" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "število"; - } - case "object": { - if (Array.isArray(data)) { - return "tabela"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "vnos", - email: "e-poštni naslov", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO datum in čas", - date: "ISO datum", - time: "ISO čas", - duration: "ISO trajanje", - ipv4: "IPv4 naslov", - ipv6: "IPv6 naslov", - cidrv4: "obseg IPv4", - cidrv6: "obseg IPv6", - base64: "base64 kodiran niz", - base64url: "base64url kodiran niz", - json_string: "JSON niz", - e164: "E.164 številka", - jwt: "JWT", - template_literal: "vnos", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Neveljaven vnos: pričakovano ${issue.expected}, prejeto ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Neveljaven vnos: pričakovano ${stringifyPrimitive(issue.values[0])}`; - return `Neveljavna možnost: pričakovano eno izmed ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Preveliko: pričakovano, da bo ${issue.origin ?? "vrednost"} imelo ${adj}${issue.maximum.toString()} ${sizing.unit ?? "elementov"}`; - return `Preveliko: pričakovano, da bo ${issue.origin ?? "vrednost"} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Premajhno: pričakovano, da bo ${issue.origin} imelo ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Premajhno: pričakovano, da bo ${issue.origin} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Neveljaven niz: mora se začeti z "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Neveljaven niz: mora se končati z "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Neveljaven niz: mora vsebovati "${_issue.includes}"`; - if (_issue.format === "regex") - return `Neveljaven niz: mora ustrezati vzorcu ${_issue.pattern}`; - return `Neveljaven ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Neveljavno število: mora biti večkratnik ${issue.divisor}`; - case "unrecognized_keys": - return `Neprepoznan${issue.keys.length > 1 ? "i ključi" : " ključ"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Neveljaven ključ v ${issue.origin}`; - case "invalid_union": - return "Neveljaven vnos"; - case "invalid_element": - return `Neveljavna vrednost v ${issue.origin}`; - default: - return "Neveljaven vnos"; - } - }; -}; -/* harmony default export */ function sl() { - return { - localeError: sl_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/sv.js - -const sv_error = () => { - const Sizable = { - string: { unit: "tecken", verb: "att ha" }, - file: { unit: "bytes", verb: "att ha" }, - array: { unit: "objekt", verb: "att innehålla" }, - set: { unit: "objekt", verb: "att innehålla" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "antal"; - } - case "object": { - if (Array.isArray(data)) { - return "lista"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "reguljärt uttryck", - email: "e-postadress", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO-datum och tid", - date: "ISO-datum", - time: "ISO-tid", - duration: "ISO-varaktighet", - ipv4: "IPv4-intervall", - ipv6: "IPv6-intervall", - cidrv4: "IPv4-spektrum", - cidrv6: "IPv6-spektrum", - base64: "base64-kodad sträng", - base64url: "base64url-kodad sträng", - json_string: "JSON-sträng", - e164: "E.164-nummer", - jwt: "JWT", - template_literal: "mall-literal", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Ogiltig inmatning: förväntat ${issue.expected}, fick ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Ogiltig inmatning: förväntat ${stringifyPrimitive(issue.values[0])}`; - return `Ogiltigt val: förväntade en av ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `För stor(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()} ${sizing.unit ?? "element"}`; - } - return `För stor(t): förväntat ${issue.origin ?? "värdet"} att ha ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `För lite(t): förväntade ${issue.origin ?? "värdet"} att ha ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `Ogiltig sträng: måste börja med "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `Ogiltig sträng: måste sluta med "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ogiltig sträng: måste innehålla "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ogiltig sträng: måste matcha mönstret "${_issue.pattern}"`; - return `Ogiltig(t) ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Ogiltigt tal: måste vara en multipel av ${issue.divisor}`; - case "unrecognized_keys": - return `${issue.keys.length > 1 ? "Okända nycklar" : "Okänd nyckel"}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Ogiltig nyckel i ${issue.origin ?? "värdet"}`; - case "invalid_union": - return "Ogiltig input"; - case "invalid_element": - return `Ogiltigt värde i ${issue.origin ?? "värdet"}`; - default: - return `Ogiltig input`; - } - }; -}; -/* harmony default export */ function sv() { - return { - localeError: sv_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ta.js - -const ta_error = () => { - const Sizable = { - string: { unit: "எழுத்துக்கள்", verb: "கொண்டிருக்க வேண்டும்" }, - file: { unit: "பைட்டுகள்", verb: "கொண்டிருக்க வேண்டும்" }, - array: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, - set: { unit: "உறுப்புகள்", verb: "கொண்டிருக்க வேண்டும்" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "எண் அல்லாதது" : "எண்"; - } - case "object": { - if (Array.isArray(data)) { - return "அணி"; - } - if (data === null) { - return "வெறுமை"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "உள்ளீடு", - email: "மின்னஞ்சல் முகவரி", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO தேதி நேரம்", - date: "ISO தேதி", - time: "ISO நேரம்", - duration: "ISO கால அளவு", - ipv4: "IPv4 முகவரி", - ipv6: "IPv6 முகவரி", - cidrv4: "IPv4 வரம்பு", - cidrv6: "IPv6 வரம்பு", - base64: "base64-encoded சரம்", - base64url: "base64url-encoded சரம்", - json_string: "JSON சரம்", - e164: "E.164 எண்", - jwt: "JWT", - template_literal: "input", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${issue.expected}, பெறப்பட்டது ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `தவறான உள்ளீடு: எதிர்பார்க்கப்பட்டது ${stringifyPrimitive(issue.values[0])}`; - return `தவறான விருப்பம்: எதிர்பார்க்கப்பட்டது ${joinValues(issue.values, "|")} இல் ஒன்று`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "உறுப்புகள்"} ஆக இருக்க வேண்டும்`; - } - return `மிக பெரியது: எதிர்பார்க்கப்பட்டது ${issue.origin ?? "மதிப்பு"} ${adj}${issue.maximum.toString()} ஆக இருக்க வேண்டும்`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit} ஆக இருக்க வேண்டும்`; // - } - return `மிகச் சிறியது: எதிர்பார்க்கப்பட்டது ${issue.origin} ${adj}${issue.minimum.toString()} ஆக இருக்க வேண்டும்`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `தவறான சரம்: "${_issue.prefix}" இல் தொடங்க வேண்டும்`; - if (_issue.format === "ends_with") - return `தவறான சரம்: "${_issue.suffix}" இல் முடிவடைய வேண்டும்`; - if (_issue.format === "includes") - return `தவறான சரம்: "${_issue.includes}" ஐ உள்ளடக்க வேண்டும்`; - if (_issue.format === "regex") - return `தவறான சரம்: ${_issue.pattern} முறைபாட்டுடன் பொருந்த வேண்டும்`; - return `தவறான ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `தவறான எண்: ${issue.divisor} இன் பலமாக இருக்க வேண்டும்`; - case "unrecognized_keys": - return `அடையாளம் தெரியாத விசை${issue.keys.length > 1 ? "கள்" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `${issue.origin} இல் தவறான விசை`; - case "invalid_union": - return "தவறான உள்ளீடு"; - case "invalid_element": - return `${issue.origin} இல் தவறான மதிப்பு`; - default: - return `தவறான உள்ளீடு`; - } - }; -}; -/* harmony default export */ function ta() { - return { - localeError: ta_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/th.js - -const th_error = () => { - const Sizable = { - string: { unit: "ตัวอักษร", verb: "ควรมี" }, - file: { unit: "ไบต์", verb: "ควรมี" }, - array: { unit: "รายการ", verb: "ควรมี" }, - set: { unit: "รายการ", verb: "ควรมี" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "ไม่ใช่ตัวเลข (NaN)" : "ตัวเลข"; - } - case "object": { - if (Array.isArray(data)) { - return "อาร์เรย์ (Array)"; - } - if (data === null) { - return "ไม่มีค่า (null)"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "ข้อมูลที่ป้อน", - email: "ที่อยู่อีเมล", - url: "URL", - emoji: "อิโมจิ", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "วันที่เวลาแบบ ISO", - date: "วันที่แบบ ISO", - time: "เวลาแบบ ISO", - duration: "ช่วงเวลาแบบ ISO", - ipv4: "ที่อยู่ IPv4", - ipv6: "ที่อยู่ IPv6", - cidrv4: "ช่วง IP แบบ IPv4", - cidrv6: "ช่วง IP แบบ IPv6", - base64: "ข้อความแบบ Base64", - base64url: "ข้อความแบบ Base64 สำหรับ URL", - json_string: "ข้อความแบบ JSON", - e164: "เบอร์โทรศัพท์ระหว่างประเทศ (E.164)", - jwt: "โทเคน JWT", - template_literal: "ข้อมูลที่ป้อน", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `ประเภทข้อมูลไม่ถูกต้อง: ควรเป็น ${issue.expected} แต่ได้รับ ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `ค่าไม่ถูกต้อง: ควรเป็น ${stringifyPrimitive(issue.values[0])}`; - return `ตัวเลือกไม่ถูกต้อง: ควรเป็นหนึ่งใน ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "ไม่เกิน" : "น้อยกว่า"; - const sizing = getSizing(issue.origin); - if (sizing) - return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()} ${sizing.unit ?? "รายการ"}`; - return `เกินกำหนด: ${issue.origin ?? "ค่า"} ควรมี${adj} ${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? "อย่างน้อย" : "มากกว่า"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()} ${sizing.unit}`; - } - return `น้อยกว่ากำหนด: ${issue.origin} ควรมี${adj} ${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `รูปแบบไม่ถูกต้อง: ข้อความต้องขึ้นต้นด้วย "${_issue.prefix}"`; - } - if (_issue.format === "ends_with") - return `รูปแบบไม่ถูกต้อง: ข้อความต้องลงท้ายด้วย "${_issue.suffix}"`; - if (_issue.format === "includes") - return `รูปแบบไม่ถูกต้อง: ข้อความต้องมี "${_issue.includes}" อยู่ในข้อความ`; - if (_issue.format === "regex") - return `รูปแบบไม่ถูกต้อง: ต้องตรงกับรูปแบบที่กำหนด ${_issue.pattern}`; - return `รูปแบบไม่ถูกต้อง: ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `ตัวเลขไม่ถูกต้อง: ต้องเป็นจำนวนที่หารด้วย ${issue.divisor} ได้ลงตัว`; - case "unrecognized_keys": - return `พบคีย์ที่ไม่รู้จัก: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `คีย์ไม่ถูกต้องใน ${issue.origin}`; - case "invalid_union": - return "ข้อมูลไม่ถูกต้อง: ไม่ตรงกับรูปแบบยูเนียนที่กำหนดไว้"; - case "invalid_element": - return `ข้อมูลไม่ถูกต้องใน ${issue.origin}`; - default: - return `ข้อมูลไม่ถูกต้อง`; - } - }; -}; -/* harmony default export */ function th() { - return { - localeError: th_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/tr.js - -const tr_parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; -}; -const tr_error = () => { - const Sizable = { - string: { unit: "karakter", verb: "olmalı" }, - file: { unit: "bayt", verb: "olmalı" }, - array: { unit: "öğe", verb: "olmalı" }, - set: { unit: "öğe", verb: "olmalı" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const Nouns = { - regex: "girdi", - email: "e-posta adresi", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO tarih ve saat", - date: "ISO tarih", - time: "ISO saat", - duration: "ISO süre", - ipv4: "IPv4 adresi", - ipv6: "IPv6 adresi", - cidrv4: "IPv4 aralığı", - cidrv6: "IPv6 aralığı", - base64: "base64 ile şifrelenmiş metin", - base64url: "base64url ile şifrelenmiş metin", - json_string: "JSON dizesi", - e164: "E.164 sayısı", - jwt: "JWT", - template_literal: "Şablon dizesi", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Geçersiz değer: beklenen ${issue.expected}, alınan ${tr_parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Geçersiz değer: beklenen ${stringifyPrimitive(issue.values[0])}`; - return `Geçersiz seçenek: aşağıdakilerden biri olmalı: ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Çok büyük: beklenen ${issue.origin ?? "değer"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "öğe"}`; - return `Çok büyük: beklenen ${issue.origin ?? "değer"} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - return `Çok küçük: beklenen ${issue.origin} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Geçersiz metin: "${_issue.prefix}" ile başlamalı`; - if (_issue.format === "ends_with") - return `Geçersiz metin: "${_issue.suffix}" ile bitmeli`; - if (_issue.format === "includes") - return `Geçersiz metin: "${_issue.includes}" içermeli`; - if (_issue.format === "regex") - return `Geçersiz metin: ${_issue.pattern} desenine uymalı`; - return `Geçersiz ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Geçersiz sayı: ${issue.divisor} ile tam bölünebilmeli`; - case "unrecognized_keys": - return `Tanınmayan anahtar${issue.keys.length > 1 ? "lar" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `${issue.origin} içinde geçersiz anahtar`; - case "invalid_union": - return "Geçersiz değer"; - case "invalid_element": - return `${issue.origin} içinde geçersiz değer`; - default: - return `Geçersiz değer`; - } - }; -}; -/* harmony default export */ function tr() { - return { - localeError: tr_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/uk.js - -const uk_error = () => { - const Sizable = { - string: { unit: "символів", verb: "матиме" }, - file: { unit: "байтів", verb: "матиме" }, - array: { unit: "елементів", verb: "матиме" }, - set: { unit: "елементів", verb: "матиме" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "число"; - } - case "object": { - if (Array.isArray(data)) { - return "масив"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "вхідні дані", - email: "адреса електронної пошти", - url: "URL", - emoji: "емодзі", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "дата та час ISO", - date: "дата ISO", - time: "час ISO", - duration: "тривалість ISO", - ipv4: "адреса IPv4", - ipv6: "адреса IPv6", - cidrv4: "діапазон IPv4", - cidrv6: "діапазон IPv6", - base64: "рядок у кодуванні base64", - base64url: "рядок у кодуванні base64url", - json_string: "рядок JSON", - e164: "номер E.164", - jwt: "JWT", - template_literal: "вхідні дані", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${parsedType(issue.input)}`; - // return `Неправильні вхідні дані: очікується ${issue.expected}, отримано ${util.getParsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Неправильні вхідні дані: очікується ${stringifyPrimitive(issue.values[0])}`; - return `Неправильна опція: очікується одне з ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Занадто велике: очікується, що ${issue.origin ?? "значення"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "елементів"}`; - return `Занадто велике: очікується, що ${issue.origin ?? "значення"} буде ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Занадто мале: очікується, що ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Занадто мале: очікується, що ${issue.origin} буде ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Неправильний рядок: повинен починатися з "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Неправильний рядок: повинен закінчуватися на "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Неправильний рядок: повинен містити "${_issue.includes}"`; - if (_issue.format === "regex") - return `Неправильний рядок: повинен відповідати шаблону ${_issue.pattern}`; - return `Неправильний ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Неправильне число: повинно бути кратним ${issue.divisor}`; - case "unrecognized_keys": - return `Нерозпізнаний ключ${issue.keys.length > 1 ? "і" : ""}: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Неправильний ключ у ${issue.origin}`; - case "invalid_union": - return "Неправильні вхідні дані"; - case "invalid_element": - return `Неправильне значення у ${issue.origin}`; - default: - return `Неправильні вхідні дані`; - } - }; -}; -/* harmony default export */ function uk() { - return { - localeError: uk_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ua.js - -/** @deprecated Use `uk` instead. */ -/* harmony default export */ function ua() { - return uk(); -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/ur.js - -const ur_error = () => { - const Sizable = { - string: { unit: "حروف", verb: "ہونا" }, - file: { unit: "بائٹس", verb: "ہونا" }, - array: { unit: "آئٹمز", verb: "ہونا" }, - set: { unit: "آئٹمز", verb: "ہونا" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "نمبر"; - } - case "object": { - if (Array.isArray(data)) { - return "آرے"; - } - if (data === null) { - return "نل"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "ان پٹ", - email: "ای میل ایڈریس", - url: "یو آر ایل", - emoji: "ایموجی", - uuid: "یو یو آئی ڈی", - uuidv4: "یو یو آئی ڈی وی 4", - uuidv6: "یو یو آئی ڈی وی 6", - nanoid: "نینو آئی ڈی", - guid: "جی یو آئی ڈی", - cuid: "سی یو آئی ڈی", - cuid2: "سی یو آئی ڈی 2", - ulid: "یو ایل آئی ڈی", - xid: "ایکس آئی ڈی", - ksuid: "کے ایس یو آئی ڈی", - datetime: "آئی ایس او ڈیٹ ٹائم", - date: "آئی ایس او تاریخ", - time: "آئی ایس او وقت", - duration: "آئی ایس او مدت", - ipv4: "آئی پی وی 4 ایڈریس", - ipv6: "آئی پی وی 6 ایڈریس", - cidrv4: "آئی پی وی 4 رینج", - cidrv6: "آئی پی وی 6 رینج", - base64: "بیس 64 ان کوڈڈ سٹرنگ", - base64url: "بیس 64 یو آر ایل ان کوڈڈ سٹرنگ", - json_string: "جے ایس او این سٹرنگ", - e164: "ای 164 نمبر", - jwt: "جے ڈبلیو ٹی", - template_literal: "ان پٹ", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `غلط ان پٹ: ${issue.expected} متوقع تھا، ${parsedType(issue.input)} موصول ہوا`; - case "invalid_value": - if (issue.values.length === 1) - return `غلط ان پٹ: ${stringifyPrimitive(issue.values[0])} متوقع تھا`; - return `غلط آپشن: ${joinValues(issue.values, "|")} میں سے ایک متوقع تھا`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `بہت بڑا: ${issue.origin ?? "ویلیو"} کے ${adj}${issue.maximum.toString()} ${sizing.unit ?? "عناصر"} ہونے متوقع تھے`; - return `بہت بڑا: ${issue.origin ?? "ویلیو"} کا ${adj}${issue.maximum.toString()} ہونا متوقع تھا`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `بہت چھوٹا: ${issue.origin} کے ${adj}${issue.minimum.toString()} ${sizing.unit} ہونے متوقع تھے`; - } - return `بہت چھوٹا: ${issue.origin} کا ${adj}${issue.minimum.toString()} ہونا متوقع تھا`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `غلط سٹرنگ: "${_issue.prefix}" سے شروع ہونا چاہیے`; - } - if (_issue.format === "ends_with") - return `غلط سٹرنگ: "${_issue.suffix}" پر ختم ہونا چاہیے`; - if (_issue.format === "includes") - return `غلط سٹرنگ: "${_issue.includes}" شامل ہونا چاہیے`; - if (_issue.format === "regex") - return `غلط سٹرنگ: پیٹرن ${_issue.pattern} سے میچ ہونا چاہیے`; - return `غلط ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `غلط نمبر: ${issue.divisor} کا مضاعف ہونا چاہیے`; - case "unrecognized_keys": - return `غیر تسلیم شدہ کی${issue.keys.length > 1 ? "ز" : ""}: ${joinValues(issue.keys, "، ")}`; - case "invalid_key": - return `${issue.origin} میں غلط کی`; - case "invalid_union": - return "غلط ان پٹ"; - case "invalid_element": - return `${issue.origin} میں غلط ویلیو`; - default: - return `غلط ان پٹ`; - } - }; -}; -/* harmony default export */ function ur() { - return { - localeError: ur_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/vi.js - -const vi_error = () => { - const Sizable = { - string: { unit: "ký tự", verb: "có" }, - file: { unit: "byte", verb: "có" }, - array: { unit: "phần tử", verb: "có" }, - set: { unit: "phần tử", verb: "có" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "số"; - } - case "object": { - if (Array.isArray(data)) { - return "mảng"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "đầu vào", - email: "địa chỉ email", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ngày giờ ISO", - date: "ngày ISO", - time: "giờ ISO", - duration: "khoảng thời gian ISO", - ipv4: "địa chỉ IPv4", - ipv6: "địa chỉ IPv6", - cidrv4: "dải IPv4", - cidrv6: "dải IPv6", - base64: "chuỗi mã hóa base64", - base64url: "chuỗi mã hóa base64url", - json_string: "chuỗi JSON", - e164: "số E.164", - jwt: "JWT", - template_literal: "đầu vào", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Đầu vào không hợp lệ: mong đợi ${issue.expected}, nhận được ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Đầu vào không hợp lệ: mong đợi ${stringifyPrimitive(issue.values[0])}`; - return `Tùy chọn không hợp lệ: mong đợi một trong các giá trị ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${sizing.verb} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "phần tử"}`; - return `Quá lớn: mong đợi ${issue.origin ?? "giá trị"} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `Quá nhỏ: mong đợi ${issue.origin} ${sizing.verb} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `Quá nhỏ: mong đợi ${issue.origin} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Chuỗi không hợp lệ: phải bắt đầu bằng "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Chuỗi không hợp lệ: phải kết thúc bằng "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Chuỗi không hợp lệ: phải bao gồm "${_issue.includes}"`; - if (_issue.format === "regex") - return `Chuỗi không hợp lệ: phải khớp với mẫu ${_issue.pattern}`; - return `${Nouns[_issue.format] ?? issue.format} không hợp lệ`; - } - case "not_multiple_of": - return `Số không hợp lệ: phải là bội số của ${issue.divisor}`; - case "unrecognized_keys": - return `Khóa không được nhận dạng: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Khóa không hợp lệ trong ${issue.origin}`; - case "invalid_union": - return "Đầu vào không hợp lệ"; - case "invalid_element": - return `Giá trị không hợp lệ trong ${issue.origin}`; - default: - return `Đầu vào không hợp lệ`; - } - }; -}; -/* harmony default export */ function vi() { - return { - localeError: vi_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/zh-CN.js - -const zh_CN_error = () => { - const Sizable = { - string: { unit: "字符", verb: "包含" }, - file: { unit: "字节", verb: "包含" }, - array: { unit: "项", verb: "包含" }, - set: { unit: "项", verb: "包含" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "非数字(NaN)" : "数字"; - } - case "object": { - if (Array.isArray(data)) { - return "数组"; - } - if (data === null) { - return "空值(null)"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "输入", - email: "电子邮件", - url: "URL", - emoji: "表情符号", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO日期时间", - date: "ISO日期", - time: "ISO时间", - duration: "ISO时长", - ipv4: "IPv4地址", - ipv6: "IPv6地址", - cidrv4: "IPv4网段", - cidrv6: "IPv6网段", - base64: "base64编码字符串", - base64url: "base64url编码字符串", - json_string: "JSON字符串", - e164: "E.164号码", - jwt: "JWT", - template_literal: "输入", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `无效输入:期望 ${issue.expected},实际接收 ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `无效输入:期望 ${stringifyPrimitive(issue.values[0])}`; - return `无效选项:期望以下之一 ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `数值过大:期望 ${issue.origin ?? "值"} ${adj}${issue.maximum.toString()} ${sizing.unit ?? "个元素"}`; - return `数值过大:期望 ${issue.origin ?? "值"} ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `数值过小:期望 ${issue.origin} ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `数值过小:期望 ${issue.origin} ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `无效字符串:必须以 "${_issue.prefix}" 开头`; - if (_issue.format === "ends_with") - return `无效字符串:必须以 "${_issue.suffix}" 结尾`; - if (_issue.format === "includes") - return `无效字符串:必须包含 "${_issue.includes}"`; - if (_issue.format === "regex") - return `无效字符串:必须满足正则表达式 ${_issue.pattern}`; - return `无效${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `无效数字:必须是 ${issue.divisor} 的倍数`; - case "unrecognized_keys": - return `出现未知的键(key): ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `${issue.origin} 中的键(key)无效`; - case "invalid_union": - return "无效输入"; - case "invalid_element": - return `${issue.origin} 中包含无效值(value)`; - default: - return `无效输入`; - } - }; -}; -/* harmony default export */ function zh_CN() { - return { - localeError: zh_CN_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/zh-TW.js - -const zh_TW_error = () => { - const Sizable = { - string: { unit: "字元", verb: "擁有" }, - file: { unit: "位元組", verb: "擁有" }, - array: { unit: "項目", verb: "擁有" }, - set: { unit: "項目", verb: "擁有" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "number"; - } - case "object": { - if (Array.isArray(data)) { - return "array"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "輸入", - email: "郵件地址", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "ISO 日期時間", - date: "ISO 日期", - time: "ISO 時間", - duration: "ISO 期間", - ipv4: "IPv4 位址", - ipv6: "IPv6 位址", - cidrv4: "IPv4 範圍", - cidrv6: "IPv6 範圍", - base64: "base64 編碼字串", - base64url: "base64url 編碼字串", - json_string: "JSON 字串", - e164: "E.164 數值", - jwt: "JWT", - template_literal: "輸入", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `無效的輸入值:預期為 ${issue.expected},但收到 ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `無效的輸入值:預期為 ${stringifyPrimitive(issue.values[0])}`; - return `無效的選項:預期為以下其中之一 ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `數值過大:預期 ${issue.origin ?? "值"} 應為 ${adj}${issue.maximum.toString()} ${sizing.unit ?? "個元素"}`; - return `數值過大:預期 ${issue.origin ?? "值"} 應為 ${adj}${issue.maximum.toString()}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) { - return `數值過小:預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()} ${sizing.unit}`; - } - return `數值過小:預期 ${issue.origin} 應為 ${adj}${issue.minimum.toString()}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") { - return `無效的字串:必須以 "${_issue.prefix}" 開頭`; - } - if (_issue.format === "ends_with") - return `無效的字串:必須以 "${_issue.suffix}" 結尾`; - if (_issue.format === "includes") - return `無效的字串:必須包含 "${_issue.includes}"`; - if (_issue.format === "regex") - return `無效的字串:必須符合格式 ${_issue.pattern}`; - return `無效的 ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `無效的數字:必須為 ${issue.divisor} 的倍數`; - case "unrecognized_keys": - return `無法識別的鍵值${issue.keys.length > 1 ? "們" : ""}:${joinValues(issue.keys, "、")}`; - case "invalid_key": - return `${issue.origin} 中有無效的鍵值`; - case "invalid_union": - return "無效的輸入值"; - case "invalid_element": - return `${issue.origin} 中有無效的值`; - default: - return `無效的輸入值`; - } - }; -}; -/* harmony default export */ function zh_TW() { - return { - localeError: zh_TW_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/yo.js - -const yo_error = () => { - const Sizable = { - string: { unit: "àmi", verb: "ní" }, - file: { unit: "bytes", verb: "ní" }, - array: { unit: "nkan", verb: "ní" }, - set: { unit: "nkan", verb: "ní" }, - }; - function getSizing(origin) { - return Sizable[origin] ?? null; - } - const parsedType = (data) => { - const t = typeof data; - switch (t) { - case "number": { - return Number.isNaN(data) ? "NaN" : "nọ́mbà"; - } - case "object": { - if (Array.isArray(data)) { - return "akopọ"; - } - if (data === null) { - return "null"; - } - if (Object.getPrototypeOf(data) !== Object.prototype && data.constructor) { - return data.constructor.name; - } - } - } - return t; - }; - const Nouns = { - regex: "ẹ̀rọ ìbáwọlé", - email: "àdírẹ́sì ìmẹ́lì", - url: "URL", - emoji: "emoji", - uuid: "UUID", - uuidv4: "UUIDv4", - uuidv6: "UUIDv6", - nanoid: "nanoid", - guid: "GUID", - cuid: "cuid", - cuid2: "cuid2", - ulid: "ULID", - xid: "XID", - ksuid: "KSUID", - datetime: "àkókò ISO", - date: "ọjọ́ ISO", - time: "àkókò ISO", - duration: "àkókò tó pé ISO", - ipv4: "àdírẹ́sì IPv4", - ipv6: "àdírẹ́sì IPv6", - cidrv4: "àgbègbè IPv4", - cidrv6: "àgbègbè IPv6", - base64: "ọ̀rọ̀ tí a kọ́ ní base64", - base64url: "ọ̀rọ̀ base64url", - json_string: "ọ̀rọ̀ JSON", - e164: "nọ́mbà E.164", - jwt: "JWT", - template_literal: "ẹ̀rọ ìbáwọlé", - }; - return (issue) => { - switch (issue.code) { - case "invalid_type": - return `Ìbáwọlé aṣìṣe: a ní láti fi ${issue.expected}, àmọ̀ a rí ${parsedType(issue.input)}`; - case "invalid_value": - if (issue.values.length === 1) - return `Ìbáwọlé aṣìṣe: a ní láti fi ${stringifyPrimitive(issue.values[0])}`; - return `Àṣàyàn aṣìṣe: yan ọ̀kan lára ${joinValues(issue.values, "|")}`; - case "too_big": { - const adj = issue.inclusive ? "<=" : "<"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Tó pọ̀ jù: a ní láti jẹ́ pé ${issue.origin ?? "iye"} ${sizing.verb} ${adj}${issue.maximum} ${sizing.unit}`; - return `Tó pọ̀ jù: a ní láti jẹ́ ${adj}${issue.maximum}`; - } - case "too_small": { - const adj = issue.inclusive ? ">=" : ">"; - const sizing = getSizing(issue.origin); - if (sizing) - return `Kéré ju: a ní láti jẹ́ pé ${issue.origin} ${sizing.verb} ${adj}${issue.minimum} ${sizing.unit}`; - return `Kéré ju: a ní láti jẹ́ ${adj}${issue.minimum}`; - } - case "invalid_format": { - const _issue = issue; - if (_issue.format === "starts_with") - return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bẹ̀rẹ̀ pẹ̀lú "${_issue.prefix}"`; - if (_issue.format === "ends_with") - return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ parí pẹ̀lú "${_issue.suffix}"`; - if (_issue.format === "includes") - return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ ní "${_issue.includes}"`; - if (_issue.format === "regex") - return `Ọ̀rọ̀ aṣìṣe: gbọ́dọ̀ bá àpẹẹrẹ mu ${_issue.pattern}`; - return `Aṣìṣe: ${Nouns[_issue.format] ?? issue.format}`; - } - case "not_multiple_of": - return `Nọ́mbà aṣìṣe: gbọ́dọ̀ jẹ́ èyà pípín ti ${issue.divisor}`; - case "unrecognized_keys": - return `Bọtìnì àìmọ̀: ${joinValues(issue.keys, ", ")}`; - case "invalid_key": - return `Bọtìnì aṣìṣe nínú ${issue.origin}`; - case "invalid_union": - return "Ìbáwọlé aṣìṣe"; - case "invalid_element": - return `Iye aṣìṣe nínú ${issue.origin}`; - default: - return "Ìbáwọlé aṣìṣe"; - } - }; -}; -/* harmony default export */ function yo() { - return { - localeError: yo_error(), - }; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/locales/index.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/registries.js -var _a; -const $output = Symbol("ZodOutput"); -const $input = Symbol("ZodInput"); -class $ZodRegistry { - constructor() { - this._map = new WeakMap(); - this._idmap = new Map(); - } - add(schema, ..._meta) { - const meta = _meta[0]; - this._map.set(schema, meta); - if (meta && typeof meta === "object" && "id" in meta) { - if (this._idmap.has(meta.id)) { - throw new Error(`ID ${meta.id} already exists in the registry`); - } - this._idmap.set(meta.id, schema); - } - return this; - } - clear() { - this._map = new WeakMap(); - this._idmap = new Map(); - return this; - } - remove(schema) { - const meta = this._map.get(schema); - if (meta && typeof meta === "object" && "id" in meta) { - this._idmap.delete(meta.id); - } - this._map.delete(schema); - return this; - } - get(schema) { - // return this._map.get(schema) as any; - // inherit metadata - const p = schema._zod.parent; - if (p) { - const pm = { ...(this.get(p) ?? {}) }; - delete pm.id; // do not inherit id - const f = { ...pm, ...this._map.get(schema) }; - return Object.keys(f).length ? f : undefined; - } - return this._map.get(schema); - } - has(schema) { - return this._map.has(schema); - } -} -// registries -function registry() { - return new $ZodRegistry(); -} -(_a = globalThis).__zod_globalRegistry ?? (_a.__zod_globalRegistry = registry()); -const globalRegistry = globalThis.__zod_globalRegistry; - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/api.js - - - - -function _string(Class, params) { - return new Class({ - type: "string", - ...normalizeParams(params), - }); -} -function _coercedString(Class, params) { - return new Class({ - type: "string", - coerce: true, - ...normalizeParams(params), - }); -} -function _email(Class, params) { - return new Class({ - type: "string", - format: "email", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _guid(Class, params) { - return new Class({ - type: "string", - format: "guid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _uuid(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _uuidv4(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v4", - ...normalizeParams(params), - }); -} -function _uuidv6(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v6", - ...normalizeParams(params), - }); -} -function _uuidv7(Class, params) { - return new Class({ - type: "string", - format: "uuid", - check: "string_format", - abort: false, - version: "v7", - ...normalizeParams(params), - }); -} -function _url(Class, params) { - return new Class({ - type: "string", - format: "url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function api_emoji(Class, params) { - return new Class({ - type: "string", - format: "emoji", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _nanoid(Class, params) { - return new Class({ - type: "string", - format: "nanoid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _cuid(Class, params) { - return new Class({ - type: "string", - format: "cuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _cuid2(Class, params) { - return new Class({ - type: "string", - format: "cuid2", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _ulid(Class, params) { - return new Class({ - type: "string", - format: "ulid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _xid(Class, params) { - return new Class({ - type: "string", - format: "xid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _ksuid(Class, params) { - return new Class({ - type: "string", - format: "ksuid", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _ipv4(Class, params) { - return new Class({ - type: "string", - format: "ipv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _ipv6(Class, params) { - return new Class({ - type: "string", - format: "ipv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _mac(Class, params) { - return new Class({ - type: "string", - format: "mac", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _cidrv4(Class, params) { - return new Class({ - type: "string", - format: "cidrv4", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _cidrv6(Class, params) { - return new Class({ - type: "string", - format: "cidrv6", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _base64(Class, params) { - return new Class({ - type: "string", - format: "base64", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _base64url(Class, params) { - return new Class({ - type: "string", - format: "base64url", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _e164(Class, params) { - return new Class({ - type: "string", - format: "e164", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -function _jwt(Class, params) { - return new Class({ - type: "string", - format: "jwt", - check: "string_format", - abort: false, - ...normalizeParams(params), - }); -} -const TimePrecision = { - Any: null, - Minute: -1, - Second: 0, - Millisecond: 3, - Microsecond: 6, -}; -function _isoDateTime(Class, params) { - return new Class({ - type: "string", - format: "datetime", - check: "string_format", - offset: false, - local: false, - precision: null, - ...normalizeParams(params), - }); -} -function _isoDate(Class, params) { - return new Class({ - type: "string", - format: "date", - check: "string_format", - ...normalizeParams(params), - }); -} -function _isoTime(Class, params) { - return new Class({ - type: "string", - format: "time", - check: "string_format", - precision: null, - ...normalizeParams(params), - }); -} -function _isoDuration(Class, params) { - return new Class({ - type: "string", - format: "duration", - check: "string_format", - ...normalizeParams(params), - }); -} -function _number(Class, params) { - return new Class({ - type: "number", - checks: [], - ...normalizeParams(params), - }); -} -function _coercedNumber(Class, params) { - return new Class({ - type: "number", - coerce: true, - checks: [], - ...normalizeParams(params), - }); -} -function _int(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "safeint", - ...normalizeParams(params), - }); -} -function _float32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float32", - ...normalizeParams(params), - }); -} -function _float64(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "float64", - ...normalizeParams(params), - }); -} -function _int32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "int32", - ...normalizeParams(params), - }); -} -function _uint32(Class, params) { - return new Class({ - type: "number", - check: "number_format", - abort: false, - format: "uint32", - ...normalizeParams(params), - }); -} -function _boolean(Class, params) { - return new Class({ - type: "boolean", - ...normalizeParams(params), - }); -} -function _coercedBoolean(Class, params) { - return new Class({ - type: "boolean", - coerce: true, - ...normalizeParams(params), - }); -} -function _bigint(Class, params) { - return new Class({ - type: "bigint", - ...normalizeParams(params), - }); -} -function _coercedBigint(Class, params) { - return new Class({ - type: "bigint", - coerce: true, - ...normalizeParams(params), - }); -} -function _int64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "int64", - ...normalizeParams(params), - }); -} -function _uint64(Class, params) { - return new Class({ - type: "bigint", - check: "bigint_format", - abort: false, - format: "uint64", - ...normalizeParams(params), - }); -} -function _symbol(Class, params) { - return new Class({ - type: "symbol", - ...normalizeParams(params), - }); -} -function api_undefined(Class, params) { - return new Class({ - type: "undefined", - ...normalizeParams(params), - }); -} -function api_null(Class, params) { - return new Class({ - type: "null", - ...normalizeParams(params), - }); -} -function _any(Class) { - return new Class({ - type: "any", - }); -} -function _unknown(Class) { - return new Class({ - type: "unknown", - }); -} -function _never(Class, params) { - return new Class({ - type: "never", - ...normalizeParams(params), - }); -} -function _void(Class, params) { - return new Class({ - type: "void", - ...normalizeParams(params), - }); -} -function _date(Class, params) { - return new Class({ - type: "date", - ...normalizeParams(params), - }); -} -function _coercedDate(Class, params) { - return new Class({ - type: "date", - coerce: true, - ...normalizeParams(params), - }); -} -function _nan(Class, params) { - return new Class({ - type: "nan", - ...normalizeParams(params), - }); -} -function _lt(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -function _lte(value, params) { - return new $ZodCheckLessThan({ - check: "less_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -function _gt(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: false, - }); -} -function _gte(value, params) { - return new $ZodCheckGreaterThan({ - check: "greater_than", - ...normalizeParams(params), - value, - inclusive: true, - }); -} - -function _positive(params) { - return _gt(0, params); -} -// negative -function _negative(params) { - return _lt(0, params); -} -// nonpositive -function _nonpositive(params) { - return _lte(0, params); -} -// nonnegative -function _nonnegative(params) { - return _gte(0, params); -} -function _multipleOf(value, params) { - return new $ZodCheckMultipleOf({ - check: "multiple_of", - ...normalizeParams(params), - value, - }); -} -function _maxSize(maximum, params) { - return new $ZodCheckMaxSize({ - check: "max_size", - ...normalizeParams(params), - maximum, - }); -} -function _minSize(minimum, params) { - return new $ZodCheckMinSize({ - check: "min_size", - ...normalizeParams(params), - minimum, - }); -} -function _size(size, params) { - return new $ZodCheckSizeEquals({ - check: "size_equals", - ...normalizeParams(params), - size, - }); -} -function _maxLength(maximum, params) { - const ch = new $ZodCheckMaxLength({ - check: "max_length", - ...normalizeParams(params), - maximum, - }); - return ch; -} -function _minLength(minimum, params) { - return new $ZodCheckMinLength({ - check: "min_length", - ...normalizeParams(params), - minimum, - }); -} -function _length(length, params) { - return new $ZodCheckLengthEquals({ - check: "length_equals", - ...normalizeParams(params), - length, - }); -} -function _regex(pattern, params) { - return new $ZodCheckRegex({ - check: "string_format", - format: "regex", - ...normalizeParams(params), - pattern, - }); -} -function _lowercase(params) { - return new $ZodCheckLowerCase({ - check: "string_format", - format: "lowercase", - ...normalizeParams(params), - }); -} -function _uppercase(params) { - return new $ZodCheckUpperCase({ - check: "string_format", - format: "uppercase", - ...normalizeParams(params), - }); -} -function _includes(includes, params) { - return new $ZodCheckIncludes({ - check: "string_format", - format: "includes", - ...normalizeParams(params), - includes, - }); -} -function _startsWith(prefix, params) { - return new $ZodCheckStartsWith({ - check: "string_format", - format: "starts_with", - ...normalizeParams(params), - prefix, - }); -} -function _endsWith(suffix, params) { - return new $ZodCheckEndsWith({ - check: "string_format", - format: "ends_with", - ...normalizeParams(params), - suffix, - }); -} -function _property(property, schema, params) { - return new $ZodCheckProperty({ - check: "property", - property, - schema, - ...normalizeParams(params), - }); -} -function _mime(types, params) { - return new $ZodCheckMimeType({ - check: "mime_type", - mime: types, - ...normalizeParams(params), - }); -} -function _overwrite(tx) { - return new $ZodCheckOverwrite({ - check: "overwrite", - tx, - }); -} -// normalize -function _normalize(form) { - return _overwrite((input) => input.normalize(form)); -} -// trim -function _trim() { - return _overwrite((input) => input.trim()); -} -// toLowerCase -function _toLowerCase() { - return _overwrite((input) => input.toLowerCase()); -} -// toUpperCase -function _toUpperCase() { - return _overwrite((input) => input.toUpperCase()); -} -// slugify -function _slugify() { - return _overwrite((input) => slugify(input)); -} -function _array(Class, element, params) { - return new Class({ - type: "array", - element, - // get element() { - // return element; - // }, - ...normalizeParams(params), - }); -} -function _union(Class, options, params) { - return new Class({ - type: "union", - options, - ...normalizeParams(params), - }); -} -function _xor(Class, options, params) { - return new Class({ - type: "union", - options, - inclusive: false, - ...normalizeParams(params), - }); -} -function _discriminatedUnion(Class, discriminator, options, params) { - return new Class({ - type: "union", - options, - discriminator, - ...normalizeParams(params), - }); -} -function _intersection(Class, left, right) { - return new Class({ - type: "intersection", - left, - right, - }); -} -// export function _tuple( -// Class: util.SchemaClass, -// items: [], -// params?: string | $ZodTupleParams -// ): schemas.$ZodTuple<[], null>; -function _tuple(Class, items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof $ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new Class({ - type: "tuple", - items, - rest, - ...normalizeParams(params), - }); -} -function _record(Class, keyType, valueType, params) { - return new Class({ - type: "record", - keyType, - valueType, - ...normalizeParams(params), - }); -} -function _map(Class, keyType, valueType, params) { - return new Class({ - type: "map", - keyType, - valueType, - ...normalizeParams(params), - }); -} -function _set(Class, valueType, params) { - return new Class({ - type: "set", - valueType, - ...normalizeParams(params), - }); -} -function _enum(Class, values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - // if (Array.isArray(values)) { - // for (const value of values) { - // entries[value] = value; - // } - // } else { - // Object.assign(entries, values); - // } - // const entries: util.EnumLike = {}; - // for (const val of values) { - // entries[val] = val; - // } - return new Class({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function _nativeEnum(Class, entries, params) { - return new Class({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} -function _literal(Class, value, params) { - return new Class({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params), - }); -} -function _file(Class, params) { - return new Class({ - type: "file", - ...normalizeParams(params), - }); -} -function _transform(Class, fn) { - return new Class({ - type: "transform", - transform: fn, - }); -} -function _optional(Class, innerType) { - return new Class({ - type: "optional", - innerType, - }); -} -function _nullable(Class, innerType) { - return new Class({ - type: "nullable", - innerType, - }); -} -function _default(Class, innerType, defaultValue) { - return new Class({ - type: "default", - innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -function _nonoptional(Class, innerType, params) { - return new Class({ - type: "nonoptional", - innerType, - ...normalizeParams(params), - }); -} -function _success(Class, innerType) { - return new Class({ - type: "success", - innerType, - }); -} -function _catch(Class, innerType, catchValue) { - return new Class({ - type: "catch", - innerType, - catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), - }); -} -function _pipe(Class, in_, out) { - return new Class({ - type: "pipe", - in: in_, - out, - }); -} -function _readonly(Class, innerType) { - return new Class({ - type: "readonly", - innerType, - }); -} -function _templateLiteral(Class, parts, params) { - return new Class({ - type: "template_literal", - parts, - ...normalizeParams(params), - }); -} -function _lazy(Class, getter) { - return new Class({ - type: "lazy", - getter, - }); -} -function _promise(Class, innerType) { - return new Class({ - type: "promise", - innerType, - }); -} -function _custom(Class, fn, _params) { - const norm = normalizeParams(_params); - norm.abort ?? (norm.abort = true); // default to abort:false - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...norm, - }); - return schema; -} -// same as _custom but defaults to abort:false -function _refine(Class, fn, _params) { - const schema = new Class({ - type: "custom", - check: "custom", - fn: fn, - ...normalizeParams(_params), - }); - return schema; -} -function _superRefine(fn) { - const ch = _check((payload) => { - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, ch._zod.def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = ch); - _issue.continue ?? (_issue.continue = !ch._zod.def.abort); // abort is always undefined, so this is always true... - payload.issues.push(util_issue(_issue)); - } - }; - return fn(payload.value, payload); - }); - return ch; -} -function _check(fn, params) { - const ch = new $ZodCheck({ - check: "custom", - ...normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function describe(description) { - const ch = new $ZodCheck({ check: "describe" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, description }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -function meta(metadata) { - const ch = new $ZodCheck({ check: "meta" }); - ch._zod.onattach = [ - (inst) => { - const existing = globalRegistry.get(inst) ?? {}; - globalRegistry.add(inst, { ...existing, ...metadata }); - }, - ]; - ch._zod.check = () => { }; // no-op check - return ch; -} -function _stringbool(Classes, _params) { - const params = normalizeParams(_params); - let truthyArray = params.truthy ?? ["true", "1", "yes", "on", "y", "enabled"]; - let falsyArray = params.falsy ?? ["false", "0", "no", "off", "n", "disabled"]; - if (params.case !== "sensitive") { - truthyArray = truthyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - falsyArray = falsyArray.map((v) => (typeof v === "string" ? v.toLowerCase() : v)); - } - const truthySet = new Set(truthyArray); - const falsySet = new Set(falsyArray); - const _Codec = Classes.Codec ?? $ZodCodec; - const _Boolean = Classes.Boolean ?? $ZodBoolean; - const _String = Classes.String ?? $ZodString; - const stringSchema = new _String({ type: "string", error: params.error }); - const booleanSchema = new _Boolean({ type: "boolean", error: params.error }); - const codec = new _Codec({ - type: "pipe", - in: stringSchema, - out: booleanSchema, - transform: ((input, payload) => { - let data = input; - if (params.case !== "sensitive") - data = data.toLowerCase(); - if (truthySet.has(data)) { - return true; - } - else if (falsySet.has(data)) { - return false; - } - else { - payload.issues.push({ - code: "invalid_value", - expected: "stringbool", - values: [...truthySet, ...falsySet], - input: payload.value, - inst: codec, - continue: false, - }); - return {}; - } - }), - reverseTransform: ((input, _payload) => { - if (input === true) { - return truthyArray[0] || "true"; - } - else { - return falsyArray[0] || "false"; - } - }), - error: params.error, - }); - return codec; -} -function _stringFormat(Class, format, fnOrRegex, _params = {}) { - const params = normalizeParams(_params); - const def = { - ...normalizeParams(_params), - check: "string_format", - type: "string", - format, - fn: typeof fnOrRegex === "function" ? fnOrRegex : (val) => fnOrRegex.test(val), - ...params, - }; - if (fnOrRegex instanceof RegExp) { - def.pattern = fnOrRegex; - } - const inst = new Class(def); - return inst; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/to-json-schema.js - -// function initializeContext(inputs: JSONSchemaGeneratorParams): ToJSONSchemaContext { -// return { -// processor: inputs.processor, -// metadataRegistry: inputs.metadata ?? globalRegistry, -// target: inputs.target ?? "draft-2020-12", -// unrepresentable: inputs.unrepresentable ?? "throw", -// }; -// } -function initializeContext(params) { - // Normalize target: convert old non-hyphenated versions to hyphenated versions - let target = params?.target ?? "draft-2020-12"; - if (target === "draft-4") - target = "draft-04"; - if (target === "draft-7") - target = "draft-07"; - return { - processors: params.processors ?? {}, - metadataRegistry: params?.metadata ?? globalRegistry, - target, - unrepresentable: params?.unrepresentable ?? "throw", - override: params?.override ?? (() => { }), - io: params?.io ?? "output", - counter: 0, - seen: new Map(), - cycles: params?.cycles ?? "ref", - reused: params?.reused ?? "inline", - external: params?.external ?? undefined, - }; -} -function to_json_schema_process(schema, ctx, _params = { path: [], schemaPath: [] }) { - var _a; - const def = schema._zod.def; - // check for schema in seens - const seen = ctx.seen.get(schema); - if (seen) { - seen.count++; - // check if cycle - const isCycle = _params.schemaPath.includes(schema); - if (isCycle) { - seen.cycle = _params.path; - } - return seen.schema; - } - // initialize - const result = { schema: {}, count: 1, cycle: undefined, path: _params.path }; - ctx.seen.set(schema, result); - // custom method overrides default behavior - const overrideSchema = schema._zod.toJSONSchema?.(); - if (overrideSchema) { - result.schema = overrideSchema; - } - else { - const params = { - ..._params, - schemaPath: [..._params.schemaPath, schema], - path: _params.path, - }; - const parent = schema._zod.parent; - if (parent) { - // schema was cloned from another schema - result.ref = parent; - to_json_schema_process(parent, ctx, params); - ctx.seen.get(parent).isParent = true; - } - else if (schema._zod.processJSONSchema) { - schema._zod.processJSONSchema(ctx, result.schema, params); - } - else { - const _json = result.schema; - const processor = ctx.processors[def.type]; - if (!processor) { - throw new Error(`[toJSONSchema]: Non-representable type encountered: ${def.type}`); - } - processor(schema, ctx, _json, params); - } - } - // metadata - const meta = ctx.metadataRegistry.get(schema); - if (meta) - Object.assign(result.schema, meta); - if (ctx.io === "input" && isTransforming(schema)) { - // examples/defaults only apply to output type of pipe - delete result.schema.examples; - delete result.schema.default; - } - // set prefault as default - if (ctx.io === "input" && result.schema._prefault) - (_a = result.schema).default ?? (_a.default = result.schema._prefault); - delete result.schema._prefault; - // pulling fresh from ctx.seen in case it was overwritten - const _result = ctx.seen.get(schema); - return _result.schema; -} -function extractDefs(ctx, schema -// params: EmitParams -) { - // iterate over seen map; - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // returns a ref to the schema - // defId will be empty if the ref points to an external schema (or #) - const makeURI = (entry) => { - // comparing the seen objects because sometimes - // multiple schemas map to the same seen object. - // e.g. lazy - // external is configured - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - if (ctx.external) { - const externalId = ctx.external.registry.get(entry[0])?.id; // ?? "__shared";// `__schema${ctx.counter++}`; - // check if schema is in the external registry - const uriGenerator = ctx.external.uri ?? ((id) => id); - if (externalId) { - return { ref: uriGenerator(externalId) }; - } - // otherwise, add to __shared - const id = entry[1].defId ?? entry[1].schema.id ?? `schema${ctx.counter++}`; - entry[1].defId = id; // set defId so it will be reused if needed - return { defId: id, ref: `${uriGenerator("__shared")}#/${defsSegment}/${id}` }; - } - if (entry[1] === root) { - return { ref: "#" }; - } - // self-contained schema - const uriPrefix = `#`; - const defUriPrefix = `${uriPrefix}/${defsSegment}/`; - const defId = entry[1].schema.id ?? `__schema${ctx.counter++}`; - return { defId, ref: defUriPrefix + defId }; - }; - // stored cached version in `def` property - // remove all properties, set $ref - const extractToDef = (entry) => { - // if the schema is already a reference, do not extract it - if (entry[1].schema.$ref) { - return; - } - const seen = entry[1]; - const { ref, defId } = makeURI(entry); - seen.def = { ...seen.schema }; - // defId won't be set if the schema is a reference to an external schema - // or if the schema is the root schema - if (defId) - seen.defId = defId; - // wipe away all properties except $ref - const schema = seen.schema; - for (const key in schema) { - delete schema[key]; - } - schema.$ref = ref; - }; - // throw on cycles - // break cycles - if (ctx.cycles === "throw") { - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.cycle) { - throw new Error("Cycle detected: " + - `#/${seen.cycle?.join("/")}/` + - '\n\nSet the `cycles` parameter to `"ref"` to resolve cyclical schemas with defs.'); - } - } - } - // extract schemas into $defs - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - // convert root schema to # $ref - if (schema === entry[0]) { - extractToDef(entry); // this has special handling for the root schema - continue; - } - // extract schemas that are in the external registry - if (ctx.external) { - const ext = ctx.external.registry.get(entry[0])?.id; - if (schema !== entry[0] && ext) { - extractToDef(entry); - continue; - } - } - // extract schemas with `id` meta - const id = ctx.metadataRegistry.get(entry[0])?.id; - if (id) { - extractToDef(entry); - continue; - } - // break cycles - if (seen.cycle) { - // any - extractToDef(entry); - continue; - } - // extract reused schemas - if (seen.count > 1) { - if (ctx.reused === "ref") { - extractToDef(entry); - // biome-ignore lint: - continue; - } - } - } -} -function finalize(ctx, schema) { - // - // iterate over seen map; - const root = ctx.seen.get(schema); - if (!root) - throw new Error("Unprocessed schema. This is a bug in Zod."); - // flatten _refs - const flattenRef = (zodSchema) => { - const seen = ctx.seen.get(zodSchema); - const schema = seen.def ?? seen.schema; - const _cached = { ...schema }; - // already seen - if (seen.ref === null) { - return; - } - // flatten ref if defined - const ref = seen.ref; - seen.ref = null; // prevent recursion - if (ref) { - flattenRef(ref); - // merge referenced schema into current - const refSchema = ctx.seen.get(ref).schema; - if (refSchema.$ref && (ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0")) { - schema.allOf = schema.allOf ?? []; - schema.allOf.push(refSchema); - } - else { - Object.assign(schema, refSchema); - Object.assign(schema, _cached); // prevent overwriting any fields in the original schema - } - } - // execute overrides - if (!seen.isParent) - ctx.override({ - zodSchema: zodSchema, - jsonSchema: schema, - path: seen.path ?? [], - }); - }; - for (const entry of [...ctx.seen.entries()].reverse()) { - flattenRef(entry[0]); - } - const result = {}; - if (ctx.target === "draft-2020-12") { - result.$schema = "https://json-schema.org/draft/2020-12/schema"; - } - else if (ctx.target === "draft-07") { - result.$schema = "http://json-schema.org/draft-07/schema#"; - } - else if (ctx.target === "draft-04") { - result.$schema = "http://json-schema.org/draft-04/schema#"; - } - else if (ctx.target === "openapi-3.0") { - // OpenAPI 3.0 schema objects should not include a $schema property - } - else { - // Arbitrary string values are allowed but won't have a $schema property set - } - if (ctx.external?.uri) { - const id = ctx.external.registry.get(schema)?.id; - if (!id) - throw new Error("Schema is missing an `id` property"); - result.$id = ctx.external.uri(id); - } - Object.assign(result, root.def ?? root.schema); - // build defs object - const defs = ctx.external?.defs ?? {}; - for (const entry of ctx.seen.entries()) { - const seen = entry[1]; - if (seen.def && seen.defId) { - defs[seen.defId] = seen.def; - } - } - // set definitions in result - if (ctx.external) { - } - else { - if (Object.keys(defs).length > 0) { - if (ctx.target === "draft-2020-12") { - result.$defs = defs; - } - else { - result.definitions = defs; - } - } - } - try { - // this "finalizes" this schema and ensures all cycles are removed - // each call to finalize() is functionally independent - // though the seen map is shared - const finalized = JSON.parse(JSON.stringify(result)); - Object.defineProperty(finalized, "~standard", { - value: { - ...schema["~standard"], - jsonSchema: { - input: createStandardJSONSchemaMethod(schema, "input"), - output: createStandardJSONSchemaMethod(schema, "output"), - }, - }, - enumerable: false, - writable: false, - }); - return finalized; - } - catch (_err) { - throw new Error("Error converting schema to JSON."); - } -} -function isTransforming(_schema, _ctx) { - const ctx = _ctx ?? { seen: new Set() }; - if (ctx.seen.has(_schema)) - return false; - ctx.seen.add(_schema); - const def = _schema._zod.def; - if (def.type === "transform") - return true; - if (def.type === "array") - return isTransforming(def.element, ctx); - if (def.type === "set") - return isTransforming(def.valueType, ctx); - if (def.type === "lazy") - return isTransforming(def.getter(), ctx); - if (def.type === "promise" || - def.type === "optional" || - def.type === "nonoptional" || - def.type === "nullable" || - def.type === "readonly" || - def.type === "default" || - def.type === "prefault") { - return isTransforming(def.innerType, ctx); - } - if (def.type === "intersection") { - return isTransforming(def.left, ctx) || isTransforming(def.right, ctx); - } - if (def.type === "record" || def.type === "map") { - return isTransforming(def.keyType, ctx) || isTransforming(def.valueType, ctx); - } - if (def.type === "pipe") { - return isTransforming(def.in, ctx) || isTransforming(def.out, ctx); - } - if (def.type === "object") { - for (const key in def.shape) { - if (isTransforming(def.shape[key], ctx)) - return true; - } - return false; - } - if (def.type === "union") { - for (const option of def.options) { - if (isTransforming(option, ctx)) - return true; - } - return false; - } - if (def.type === "tuple") { - for (const item of def.items) { - if (isTransforming(item, ctx)) - return true; - } - if (def.rest && isTransforming(def.rest, ctx)) - return true; - return false; - } - return false; -} -/** - * Creates a toJSONSchema method for a schema instance. - * This encapsulates the logic of initializing context, processing, extracting defs, and finalizing. - */ -const createToJSONSchemaMethod = (schema, processors = {}) => (params) => { - const ctx = initializeContext({ ...params, processors }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; -const createStandardJSONSchemaMethod = (schema, io) => (params) => { - const { libraryOptions, target } = params ?? {}; - const ctx = initializeContext({ ...(libraryOptions ?? {}), target, io, processors: {} }); - to_json_schema_process(schema, ctx); - extractDefs(ctx, schema); - return finalize(ctx, schema); -}; - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/json-schema-processors.js - - -const formatMap = { - guid: "uuid", - url: "uri", - datetime: "date-time", - json_string: "json-string", - regex: "", // do not set -}; -// ==================== SIMPLE TYPE PROCESSORS ==================== -const stringProcessor = (schema, ctx, _json, _params) => { - const json = _json; - json.type = "string"; - const { minimum, maximum, format, patterns, contentEncoding } = schema._zod - .bag; - if (typeof minimum === "number") - json.minLength = minimum; - if (typeof maximum === "number") - json.maxLength = maximum; - // custom pattern overrides format - if (format) { - json.format = formatMap[format] ?? format; - if (json.format === "") - delete json.format; // empty format is not valid - } - if (contentEncoding) - json.contentEncoding = contentEncoding; - if (patterns && patterns.size > 0) { - const regexes = [...patterns]; - if (regexes.length === 1) - json.pattern = regexes[0].source; - else if (regexes.length > 1) { - json.allOf = [ - ...regexes.map((regex) => ({ - ...(ctx.target === "draft-07" || ctx.target === "draft-04" || ctx.target === "openapi-3.0" - ? { type: "string" } - : {}), - pattern: regex.source, - })), - ]; - } - } -}; -const numberProcessor = (schema, ctx, _json, _params) => { - const json = _json; - const { minimum, maximum, format, multipleOf, exclusiveMaximum, exclusiveMinimum } = schema._zod.bag; - if (typeof format === "string" && format.includes("int")) - json.type = "integer"; - else - json.type = "number"; - if (typeof exclusiveMinimum === "number") { - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.minimum = exclusiveMinimum; - json.exclusiveMinimum = true; - } - else { - json.exclusiveMinimum = exclusiveMinimum; - } - } - if (typeof minimum === "number") { - json.minimum = minimum; - if (typeof exclusiveMinimum === "number" && ctx.target !== "draft-04") { - if (exclusiveMinimum >= minimum) - delete json.minimum; - else - delete json.exclusiveMinimum; - } - } - if (typeof exclusiveMaximum === "number") { - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.maximum = exclusiveMaximum; - json.exclusiveMaximum = true; - } - else { - json.exclusiveMaximum = exclusiveMaximum; - } - } - if (typeof maximum === "number") { - json.maximum = maximum; - if (typeof exclusiveMaximum === "number" && ctx.target !== "draft-04") { - if (exclusiveMaximum <= maximum) - delete json.maximum; - else - delete json.exclusiveMaximum; - } - } - if (typeof multipleOf === "number") - json.multipleOf = multipleOf; -}; -const booleanProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const bigintProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt cannot be represented in JSON Schema"); - } -}; -const symbolProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Symbols cannot be represented in JSON Schema"); - } -}; -const nullProcessor = (_schema, ctx, json, _params) => { - if (ctx.target === "openapi-3.0") { - json.type = "string"; - json.nullable = true; - json.enum = [null]; - } - else { - json.type = "null"; - } -}; -const undefinedProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Undefined cannot be represented in JSON Schema"); - } -}; -const voidProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Void cannot be represented in JSON Schema"); - } -}; -const neverProcessor = (_schema, _ctx, json, _params) => { - json.not = {}; -}; -const anyProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const unknownProcessor = (_schema, _ctx, _json, _params) => { - // empty schema accepts anything -}; -const dateProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Date cannot be represented in JSON Schema"); - } -}; -const enumProcessor = (schema, _ctx, json, _params) => { - const def = schema._zod.def; - const values = getEnumValues(def.entries); - // Number enums can have both string and number values - if (values.every((v) => typeof v === "number")) - json.type = "number"; - if (values.every((v) => typeof v === "string")) - json.type = "string"; - json.enum = values; -}; -const literalProcessor = (schema, ctx, json, _params) => { - const def = schema._zod.def; - const vals = []; - for (const val of def.values) { - if (val === undefined) { - if (ctx.unrepresentable === "throw") { - throw new Error("Literal `undefined` cannot be represented in JSON Schema"); - } - else { - // do not add to vals - } - } - else if (typeof val === "bigint") { - if (ctx.unrepresentable === "throw") { - throw new Error("BigInt literals cannot be represented in JSON Schema"); - } - else { - vals.push(Number(val)); - } - } - else { - vals.push(val); - } - } - if (vals.length === 0) { - // do nothing (an undefined literal was stripped) - } - else if (vals.length === 1) { - const val = vals[0]; - json.type = val === null ? "null" : typeof val; - if (ctx.target === "draft-04" || ctx.target === "openapi-3.0") { - json.enum = [val]; - } - else { - json.const = val; - } - } - else { - if (vals.every((v) => typeof v === "number")) - json.type = "number"; - if (vals.every((v) => typeof v === "string")) - json.type = "string"; - if (vals.every((v) => typeof v === "boolean")) - json.type = "boolean"; - if (vals.every((v) => v === null)) - json.type = "null"; - json.enum = vals; - } -}; -const nanProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("NaN cannot be represented in JSON Schema"); - } -}; -const templateLiteralProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const pattern = schema._zod.pattern; - if (!pattern) - throw new Error("Pattern not found in template literal"); - _json.type = "string"; - _json.pattern = pattern.source; -}; -const fileProcessor = (schema, _ctx, json, _params) => { - const _json = json; - const file = { - type: "string", - format: "binary", - contentEncoding: "binary", - }; - const { minimum, maximum, mime } = schema._zod.bag; - if (minimum !== undefined) - file.minLength = minimum; - if (maximum !== undefined) - file.maxLength = maximum; - if (mime) { - if (mime.length === 1) { - file.contentMediaType = mime[0]; - Object.assign(_json, file); - } - else { - _json.anyOf = mime.map((m) => { - const mFile = { ...file, contentMediaType: m }; - return mFile; - }); - } - } - else { - Object.assign(_json, file); - } -}; -const successProcessor = (_schema, _ctx, json, _params) => { - json.type = "boolean"; -}; -const customProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Custom types cannot be represented in JSON Schema"); - } -}; -const functionProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Function types cannot be represented in JSON Schema"); - } -}; -const transformProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Transforms cannot be represented in JSON Schema"); - } -}; -const mapProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Map cannot be represented in JSON Schema"); - } -}; -const setProcessor = (_schema, ctx, _json, _params) => { - if (ctx.unrepresentable === "throw") { - throw new Error("Set cannot be represented in JSON Schema"); - } -}; -// ==================== COMPOSITE TYPE PROCESSORS ==================== -const arrayProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; - json.type = "array"; - json.items = to_json_schema_process(def.element, ctx, { ...params, path: [...params.path, "items"] }); -}; -const objectProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - json.properties = {}; - const shape = def.shape; - for (const key in shape) { - json.properties[key] = to_json_schema_process(shape[key], ctx, { - ...params, - path: [...params.path, "properties", key], - }); - } - // required keys - const allKeys = new Set(Object.keys(shape)); - const requiredKeys = new Set([...allKeys].filter((key) => { - const v = def.shape[key]._zod; - if (ctx.io === "input") { - return v.optin === undefined; - } - else { - return v.optout === undefined; - } - })); - if (requiredKeys.size > 0) { - json.required = Array.from(requiredKeys); - } - // catchall - if (def.catchall?._zod.def.type === "never") { - // strict - json.additionalProperties = false; - } - else if (!def.catchall) { - // regular - if (ctx.io === "output") - json.additionalProperties = false; - } - else if (def.catchall) { - json.additionalProperties = to_json_schema_process(def.catchall, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); - } -}; -const unionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - // Exclusive unions (inclusive === false) use oneOf (exactly one match) instead of anyOf (one or more matches) - // This includes both z.xor() and discriminated unions - const isExclusive = def.inclusive === false; - const options = def.options.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, isExclusive ? "oneOf" : "anyOf", i], - })); - if (isExclusive) { - json.oneOf = options; - } - else { - json.anyOf = options; - } -}; -const intersectionProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const a = to_json_schema_process(def.left, ctx, { - ...params, - path: [...params.path, "allOf", 0], - }); - const b = to_json_schema_process(def.right, ctx, { - ...params, - path: [...params.path, "allOf", 1], - }); - const isSimpleIntersection = (val) => "allOf" in val && Object.keys(val).length === 1; - const allOf = [ - ...(isSimpleIntersection(a) ? a.allOf : [a]), - ...(isSimpleIntersection(b) ? b.allOf : [b]), - ]; - json.allOf = allOf; -}; -const tupleProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "array"; - const prefixPath = ctx.target === "draft-2020-12" ? "prefixItems" : "items"; - const restPath = ctx.target === "draft-2020-12" ? "items" : ctx.target === "openapi-3.0" ? "items" : "additionalItems"; - const prefixItems = def.items.map((x, i) => to_json_schema_process(x, ctx, { - ...params, - path: [...params.path, prefixPath, i], - })); - const rest = def.rest - ? to_json_schema_process(def.rest, ctx, { - ...params, - path: [...params.path, restPath, ...(ctx.target === "openapi-3.0" ? [def.items.length] : [])], - }) - : null; - if (ctx.target === "draft-2020-12") { - json.prefixItems = prefixItems; - if (rest) { - json.items = rest; - } - } - else if (ctx.target === "openapi-3.0") { - json.items = { - anyOf: prefixItems, - }; - if (rest) { - json.items.anyOf.push(rest); - } - json.minItems = prefixItems.length; - if (!rest) { - json.maxItems = prefixItems.length; - } - } - else { - json.items = prefixItems; - if (rest) { - json.additionalItems = rest; - } - } - // length - const { minimum, maximum } = schema._zod.bag; - if (typeof minimum === "number") - json.minItems = minimum; - if (typeof maximum === "number") - json.maxItems = maximum; -}; -const recordProcessor = (schema, ctx, _json, params) => { - const json = _json; - const def = schema._zod.def; - json.type = "object"; - if (ctx.target === "draft-07" || ctx.target === "draft-2020-12") { - json.propertyNames = to_json_schema_process(def.keyType, ctx, { - ...params, - path: [...params.path, "propertyNames"], - }); - } - json.additionalProperties = to_json_schema_process(def.valueType, ctx, { - ...params, - path: [...params.path, "additionalProperties"], - }); -}; -const nullableProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - const inner = to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - if (ctx.target === "openapi-3.0") { - seen.ref = def.innerType; - json.nullable = true; - } - else { - json.anyOf = [inner, { type: "null" }]; - } -}; -const nonoptionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const defaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.default = JSON.parse(JSON.stringify(def.defaultValue)); -}; -const prefaultProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - if (ctx.io === "input") - json._prefault = JSON.parse(JSON.stringify(def.defaultValue)); -}; -const catchProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - let catchValue; - try { - catchValue = def.catchValue(undefined); - } - catch { - throw new Error("Dynamic catch values are not supported in JSON Schema"); - } - json.default = catchValue; -}; -const pipeProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - const innerType = ctx.io === "input" ? (def.in._zod.def.type === "transform" ? def.out : def.in) : def.out; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -const readonlyProcessor = (schema, ctx, json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; - json.readOnly = true; -}; -const promiseProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const optionalProcessor = (schema, ctx, _json, params) => { - const def = schema._zod.def; - to_json_schema_process(def.innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = def.innerType; -}; -const lazyProcessor = (schema, ctx, _json, params) => { - const innerType = schema._zod.innerType; - to_json_schema_process(innerType, ctx, params); - const seen = ctx.seen.get(schema); - seen.ref = innerType; -}; -// ==================== ALL PROCESSORS ==================== -const allProcessors = { - string: stringProcessor, - number: numberProcessor, - boolean: booleanProcessor, - bigint: bigintProcessor, - symbol: symbolProcessor, - null: nullProcessor, - undefined: undefinedProcessor, - void: voidProcessor, - never: neverProcessor, - any: anyProcessor, - unknown: unknownProcessor, - date: dateProcessor, - enum: enumProcessor, - literal: literalProcessor, - nan: nanProcessor, - template_literal: templateLiteralProcessor, - file: fileProcessor, - success: successProcessor, - custom: customProcessor, - function: functionProcessor, - transform: transformProcessor, - map: mapProcessor, - set: setProcessor, - array: arrayProcessor, - object: objectProcessor, - union: unionProcessor, - intersection: intersectionProcessor, - tuple: tupleProcessor, - record: recordProcessor, - nullable: nullableProcessor, - nonoptional: nonoptionalProcessor, - default: defaultProcessor, - prefault: prefaultProcessor, - catch: catchProcessor, - pipe: pipeProcessor, - readonly: readonlyProcessor, - promise: promiseProcessor, - optional: optionalProcessor, - lazy: lazyProcessor, -}; -function toJSONSchema(input, params) { - if ("_idmap" in input) { - // Registry case - const registry = input; - const ctx = initializeContext({ ...params, processors: allProcessors }); - const defs = {}; - // First pass: process all schemas to build the seen map - for (const entry of registry._idmap.entries()) { - const [_, schema] = entry; - to_json_schema_process(schema, ctx); - } - const schemas = {}; - const external = { - registry, - uri: params?.uri, - defs, - }; - // Update the context with external configuration - ctx.external = external; - // Second pass: emit each schema - for (const entry of registry._idmap.entries()) { - const [key, schema] = entry; - extractDefs(ctx, schema); - schemas[key] = finalize(ctx, schema); - } - if (Object.keys(defs).length > 0) { - const defsSegment = ctx.target === "draft-2020-12" ? "$defs" : "definitions"; - schemas.__shared = { - [defsSegment]: defs, - }; - } - return { schemas }; - } - // Single schema case - const ctx = initializeContext({ ...params, processors: allProcessors }); - to_json_schema_process(input, ctx); - extractDefs(ctx, input); - return finalize(ctx, input); -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/json-schema-generator.js - - -/** - * Legacy class-based interface for JSON Schema generation. - * This class wraps the new functional implementation to provide backward compatibility. - * - * @deprecated Use the `toJSONSchema` function instead for new code. - * - * @example - * ```typescript - * // Legacy usage (still supported) - * const gen = new JSONSchemaGenerator({ target: "draft-07" }); - * gen.process(schema); - * const result = gen.emit(schema); - * - * // Preferred modern usage - * const result = toJSONSchema(schema, { target: "draft-07" }); - * ``` - */ -class JSONSchemaGenerator { - /** @deprecated Access via ctx instead */ - get metadataRegistry() { - return this.ctx.metadataRegistry; - } - /** @deprecated Access via ctx instead */ - get target() { - return this.ctx.target; - } - /** @deprecated Access via ctx instead */ - get unrepresentable() { - return this.ctx.unrepresentable; - } - /** @deprecated Access via ctx instead */ - get override() { - return this.ctx.override; - } - /** @deprecated Access via ctx instead */ - get io() { - return this.ctx.io; - } - /** @deprecated Access via ctx instead */ - get counter() { - return this.ctx.counter; - } - set counter(value) { - this.ctx.counter = value; - } - /** @deprecated Access via ctx instead */ - get seen() { - return this.ctx.seen; - } - constructor(params) { - // Normalize target for internal context - let normalizedTarget = params?.target ?? "draft-2020-12"; - if (normalizedTarget === "draft-4") - normalizedTarget = "draft-04"; - if (normalizedTarget === "draft-7") - normalizedTarget = "draft-07"; - this.ctx = initializeContext({ - processors: allProcessors, - target: normalizedTarget, - ...(params?.metadata && { metadata: params.metadata }), - ...(params?.unrepresentable && { unrepresentable: params.unrepresentable }), - ...(params?.override && { override: params.override }), - ...(params?.io && { io: params.io }), - }); - } - /** - * Process a schema to prepare it for JSON Schema generation. - * This must be called before emit(). - */ - process(schema, _params = { path: [], schemaPath: [] }) { - return to_json_schema_process(schema, this.ctx, _params); - } - /** - * Emit the final JSON Schema after processing. - * Must call process() first. - */ - emit(schema, _params) { - // Apply emit params to the context - if (_params) { - if (_params.cycles) - this.ctx.cycles = _params.cycles; - if (_params.reused) - this.ctx.reused = _params.reused; - if (_params.external) - this.ctx.external = _params.external; - } - extractDefs(this.ctx, schema); - const result = finalize(this.ctx, schema); - // Strip ~standard property to match old implementation's return type - const { "~standard": _, ...plainResult } = result; - return plainResult; - } -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/json-schema.js - - -;// CONCATENATED MODULE: ./node_modules/zod/v4/core/index.js - - - - - - - - - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/types/zod.js - - -//#region src/utils/types/zod.ts -function isZodSchemaV4(schema) { - if (typeof schema !== "object" || schema === null) return false; - const obj = schema; - if (!("_zod" in obj)) return false; - const zod = obj._zod; - return typeof zod === "object" && zod !== null && "def" in zod; -} -function isZodSchemaV3(schema) { - if (typeof schema !== "object" || schema === null) return false; - const obj = schema; - if (!("_def" in obj) || "_zod" in obj) return false; - const def = obj._def; - return typeof def === "object" && def != null && "typeName" in def; -} -/** Backward compatible isZodSchema for Zod 3 */ -function isZodSchema(schema) { - if (isZodSchemaV4(schema)) console.warn("[WARNING] Attempting to use Zod 4 schema in a context where Zod 3 schema is expected. This may cause unexpected behavior."); - return isZodSchemaV3(schema); -} -/** -* Given either a Zod schema, or plain object, determine if the input is a Zod schema. -* -* @param {unknown} input -* @returns {boolean} Whether or not the provided input is a Zod schema. -*/ -function isInteropZodSchema(input) { - if (!input) return false; - if (typeof input !== "object") return false; - if (Array.isArray(input)) return false; - if (isZodSchemaV4(input) || isZodSchemaV3(input)) return true; - return false; -} -function isZodLiteralV3(obj) { - if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodLiteral") return true; - return false; -} -function isZodLiteralV4(obj) { - if (!isZodSchemaV4(obj)) return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "literal") return true; - return false; -} -/** -* Determines if the provided value is an InteropZodLiteral (Zod v3 or v4 literal schema). -* -* @param obj The value to check. -* @returns {boolean} True if the value is a Zod v3 or v4 literal schema, false otherwise. -*/ -function isInteropZodLiteral(obj) { - if (isZodLiteralV3(obj)) return true; - if (isZodLiteralV4(obj)) return true; - return false; -} -/** -* Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns a safe parse result. -* This function handles both Zod v3 and v4 schemas, returning a result object indicating success or failure. -* -* @template T - The expected output type of the schema. -* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. -* @param {unknown} input - The input value to parse. -* @returns {Promise>} A promise that resolves to a safe parse result object. -* @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. -*/ -async function interopSafeParseAsync(schema, input) { - if (isZodSchemaV4(schema)) try { - const data = await parseAsync(schema, input); - return { - success: true, - data - }; - } catch (error) { - return { - success: false, - error - }; - } - if (isZodSchemaV3(schema)) return await schema.safeParseAsync(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); -} -/** -* Asynchronously parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. -* Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. -* -* @template T - The expected output type of the schema. -* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. -* @param {unknown} input - The input value to parse. -* @returns {Promise} A promise that resolves to the parsed value. -* @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. -*/ -async function interopParseAsync(schema, input) { - if (isZodSchemaV4(schema)) return await parseAsync(schema, input); - if (isZodSchemaV3(schema)) return await schema.parseAsync(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); -} -/** -* Safely parses the input using the provided Zod schema (v3 or v4) and returns a result object -* indicating success or failure. This function is compatible with both Zod v3 and v4 schemas. -* -* @template T - The expected output type of the schema. -* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. -* @param {unknown} input - The input value to parse. -* @returns {InteropZodSafeParseResult} An object with either the parsed data (on success) -* or the error (on failure). -* @throws {Error} If the schema is not a recognized Zod v3 or v4 schema. -*/ -function interopSafeParse(schema, input) { - if (isZodSchemaV4(schema)) try { - const data = parse_parse(schema, input); - return { - success: true, - data - }; - } catch (error) { - return { - success: false, - error - }; - } - if (isZodSchemaV3(schema)) return schema.safeParse(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); -} -/** -* Parses the input using the provided Zod schema (v3 or v4) and returns the parsed value. -* Throws an error if parsing fails or if the schema is not a recognized Zod v3 or v4 schema. -* -* @template T - The expected output type of the schema. -* @param {InteropZodType} schema - The Zod schema (v3 or v4) to use for parsing. -* @param {unknown} input - The input value to parse. -* @returns {T} The parsed value. -* @throws {Error} If parsing fails or the schema is not a recognized Zod v3 or v4 schema. -*/ -function interopParse(schema, input) { - if (isZodSchemaV4(schema)) return parse_parse(schema, input); - if (isZodSchemaV3(schema)) return schema.parse(input); - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); -} -/** -* Retrieves the description from a schema definition (v3, v4, or plain object), if available. -* -* @param {unknown} schema - The schema to extract the description from. -* @returns {string | undefined} The description of the schema, or undefined if not present. -*/ -function getSchemaDescription(schema) { - if (isZodSchemaV4(schema)) return globalRegistry.get(schema)?.description; - if (isZodSchemaV3(schema)) return schema.description; - if ("description" in schema && typeof schema.description === "string") return schema.description; - return void 0; -} -/** -* Determines if the provided Zod schema is "shapeless". -* A shapeless schema is one that does not define any object shape, -* such as ZodString, ZodNumber, ZodBoolean, ZodAny, etc. -* For ZodObject, it must have no shape keys to be considered shapeless. -* ZodRecord schemas are considered shapeless since they define dynamic -* key-value mappings without fixed keys. -* -* @param schema The Zod schema to check. -* @returns {boolean} True if the schema is shapeless, false otherwise. -*/ -function isShapelessZodSchema(schema) { - if (!isInteropZodSchema(schema)) return false; - if (isZodSchemaV3(schema)) { - const def = schema._def; - if (def.typeName === "ZodObject") { - const obj = schema; - return !obj.shape || Object.keys(obj.shape).length === 0; - } - if (def.typeName === "ZodRecord") return true; - } - if (isZodSchemaV4(schema)) { - const def = schema._zod.def; - if (def.type === "object") { - const obj = schema; - return !obj.shape || Object.keys(obj.shape).length === 0; - } - if (def.type === "record") return true; - } - if (typeof schema === "object" && schema !== null && !("shape" in schema)) return true; - return false; -} -/** -* Determines if the provided Zod schema should be treated as a simple string schema -* that maps to DynamicTool. This aligns with the type-level constraint of -* InteropZodType which only matches basic string schemas. -* If the provided schema is just z.string(), we can make the determination that -* the tool is just a generic string tool that doesn't require any input validation. -* -* This function only returns true for basic ZodString schemas, including: -* - Basic string schemas (z.string()) -* - String schemas with validations (z.string().min(1), z.string().email(), etc.) -* -* This function returns false for everything else, including: -* - String schemas with defaults (z.string().default("value")) -* - Branded string schemas (z.string().brand<"UserId">()) -* - String schemas with catch operations (z.string().catch("default")) -* - Optional/nullable string schemas (z.string().optional()) -* - Transformed schemas (z.string().transform() or z.object().transform()) -* - Object or record schemas, even if they're empty -* - Any other schema type -* -* @param schema The Zod schema to check. -* @returns {boolean} True if the schema is a basic ZodString, false otherwise. -*/ -function isSimpleStringZodSchema(schema) { - if (!isInteropZodSchema(schema)) return false; - if (isZodSchemaV3(schema)) { - const def = schema._def; - return def.typeName === "ZodString"; - } - if (isZodSchemaV4(schema)) { - const def = schema._zod.def; - return def.type === "string"; - } - return false; -} -function isZodObjectV3(obj) { - if (typeof obj === "object" && obj !== null && "_def" in obj && typeof obj._def === "object" && obj._def !== null && "typeName" in obj._def && obj._def.typeName === "ZodObject") return true; - return false; -} -function isZodObjectV4(obj) { - if (!isZodSchemaV4(obj)) return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "object") return true; - return false; -} -function isZodArrayV4(obj) { - if (!isZodSchemaV4(obj)) return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "array") return true; - return false; -} -function isZodOptionalV4(obj) { - if (!isZodSchemaV4(obj)) return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "optional") return true; - return false; -} -function isZodNullableV4(obj) { - if (!isZodSchemaV4(obj)) return false; - if (typeof obj === "object" && obj !== null && "_zod" in obj && typeof obj._zod === "object" && obj._zod !== null && "def" in obj._zod && typeof obj._zod.def === "object" && obj._zod.def !== null && "type" in obj._zod.def && obj._zod.def.type === "nullable") return true; - return false; -} -/** -* Determines if the provided value is an InteropZodObject (Zod v3 or v4 object schema). -* -* @param obj The value to check. -* @returns {boolean} True if the value is a Zod v3 or v4 object schema, false otherwise. -*/ -function isInteropZodObject(obj) { - if (isZodObjectV3(obj)) return true; - if (isZodObjectV4(obj)) return true; - return false; -} -/** -* Retrieves the shape (fields) of a Zod object schema, supporting both Zod v3 and v4. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @returns {InteropZodObjectShape} The shape of the object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function getInteropZodObjectShape(schema) { - if (isZodSchemaV3(schema)) return schema.shape; - if (isZodSchemaV4(schema)) return schema._zod.def.shape; - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} -/** -* Extends a Zod object schema with additional fields, supporting both Zod v3 and v4. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @param {InteropZodObjectShape} extension - The fields to add to the schema. -* @returns {InteropZodObject} The extended Zod object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function extendInteropZodObject(schema, extension) { - if (isZodSchemaV3(schema)) return schema.extend(extension); - if (isZodSchemaV4(schema)) return extend(schema, extension); - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} -/** -* Returns a partial version of a Zod object schema, making all fields optional. -* Supports both Zod v3 and v4. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @returns {InteropZodObject} The partial Zod object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function interopZodObjectPartial(schema) { - if (isZodSchemaV3(schema)) return schema.partial(); - if (isZodSchemaV4(schema)) return partial($ZodOptional, schema, void 0); - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} -/** -* Returns a strict version of a Zod object schema, disallowing unknown keys. -* Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies strictness -* recursively to all nested object schemas and arrays of object schemas. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @param {boolean} [recursive=false] - Whether to apply strictness recursively to nested objects/arrays. -* @returns {InteropZodObject} The strict Zod object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function interopZodObjectStrict(schema, recursive = false) { - if (isZodSchemaV3(schema)) return schema.strict(); - if (isZodObjectV4(schema)) { - const outputShape = schema._zod.def.shape; - if (recursive) for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { - if (isZodObjectV4(keySchema)) { - const outputSchema = interopZodObjectStrict(keySchema, recursive); - outputShape[key] = outputSchema; - } else if (isZodArrayV4(keySchema)) { - let elementSchema = keySchema._zod.def.element; - if (isZodObjectV4(elementSchema)) elementSchema = interopZodObjectStrict(elementSchema, recursive); - outputShape[key] = clone(keySchema, { - ...keySchema._zod.def, - element: elementSchema - }); - } else outputShape[key] = keySchema; - const meta$1 = globalRegistry.get(keySchema); - if (meta$1) globalRegistry.add(outputShape[key], meta$1); - } - const modifiedSchema = clone(schema, { - ...schema._zod.def, - shape: outputShape, - catchall: _never($ZodNever) - }); - const meta = globalRegistry.get(schema); - if (meta) globalRegistry.add(modifiedSchema, meta); - return modifiedSchema; - } - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} -/** -* Returns a passthrough version of a Zod object schema, allowing unknown keys. -* Supports both Zod v3 and v4 object schemas. If `recursive` is true, applies passthrough -* recursively to all nested object schemas and arrays of object schemas. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @param {boolean} [recursive=false] - Whether to apply passthrough recursively to nested objects/arrays. -* @returns {InteropZodObject} The passthrough Zod object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function interopZodObjectPassthrough(schema, recursive = false) { - if (isZodObjectV3(schema)) return schema.passthrough(); - if (isZodObjectV4(schema)) { - const outputShape = schema._zod.def.shape; - if (recursive) for (const [key, keySchema] of Object.entries(schema._zod.def.shape)) { - if (isZodObjectV4(keySchema)) { - const outputSchema = interopZodObjectPassthrough(keySchema, recursive); - outputShape[key] = outputSchema; - } else if (isZodArrayV4(keySchema)) { - let elementSchema = keySchema._zod.def.element; - if (isZodObjectV4(elementSchema)) elementSchema = interopZodObjectPassthrough(elementSchema, recursive); - outputShape[key] = clone(keySchema, { - ...keySchema._zod.def, - element: elementSchema - }); - } else outputShape[key] = keySchema; - const meta$1 = globalRegistry.get(keySchema); - if (meta$1) globalRegistry.add(outputShape[key], meta$1); - } - const modifiedSchema = clone(schema, { - ...schema._zod.def, - shape: outputShape, - catchall: _unknown($ZodUnknown) - }); - const meta = globalRegistry.get(schema); - if (meta) globalRegistry.add(modifiedSchema, meta); - return modifiedSchema; - } - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} -/** -* Returns a getter function for the default value of a Zod schema, if one is defined. -* Supports both Zod v3 and v4 schemas. If the schema has a default value, -* the returned function will return that value when called. If no default is defined, -* returns undefined. -* -* @template T - The type of the Zod schema. -* @param {T} schema - The Zod schema instance (either v3 or v4). -* @returns {(() => InferInteropZodOutput) | undefined} A function that returns the default value, or undefined if no default is set. -*/ -function getInteropZodDefaultGetter(schema) { - if (isZodSchemaV3(schema)) try { - const defaultValue = schema.parse(void 0); - return () => defaultValue; - } catch { - return void 0; - } - if (isZodSchemaV4(schema)) try { - const defaultValue = parse_parse(schema, void 0); - return () => defaultValue; - } catch { - return void 0; - } - return void 0; -} -function isZodTransformV3(schema) { - return isZodSchemaV3(schema) && "typeName" in schema._def && schema._def.typeName === "ZodEffects"; -} -function isZodTransformV4(schema) { - return isZodSchemaV4(schema) && schema._zod.def.type === "pipe"; -} -function interopZodTransformInputSchemaImpl(schema, recursive, cache) { - const cached = cache.get(schema); - if (cached !== void 0) return cached; - if (isZodSchemaV3(schema)) { - if (isZodTransformV3(schema)) return interopZodTransformInputSchemaImpl(schema._def.schema, recursive, cache); - return schema; - } - if (isZodSchemaV4(schema)) { - let outputSchema = schema; - if (isZodTransformV4(schema)) outputSchema = interopZodTransformInputSchemaImpl(schema._zod.def.in, recursive, cache); - if (recursive) { - if (isZodObjectV4(outputSchema)) { - const outputShape = {}; - for (const [key, keySchema] of Object.entries(outputSchema._zod.def.shape)) outputShape[key] = interopZodTransformInputSchemaImpl(keySchema, recursive, cache); - outputSchema = clone(outputSchema, { - ...outputSchema._zod.def, - shape: outputShape - }); - } else if (isZodArrayV4(outputSchema)) { - const elementSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.element, recursive, cache); - outputSchema = clone(outputSchema, { - ...outputSchema._zod.def, - element: elementSchema - }); - } else if (isZodOptionalV4(outputSchema)) { - const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache); - outputSchema = clone(outputSchema, { - ...outputSchema._zod.def, - innerType: innerSchema - }); - } else if (isZodNullableV4(outputSchema)) { - const innerSchema = interopZodTransformInputSchemaImpl(outputSchema._zod.def.innerType, recursive, cache); - outputSchema = clone(outputSchema, { - ...outputSchema._zod.def, - innerType: innerSchema - }); - } - } - const meta = globalRegistry.get(schema); - if (meta) globalRegistry.add(outputSchema, meta); - cache.set(schema, outputSchema); - return outputSchema; - } - throw new Error("Schema must be an instance of z3.ZodType or z4.$ZodType"); -} -/** -* Returns the input type of a Zod transform schema, for both v3 and v4. -* If the schema is not a transform, returns undefined. If `recursive` is true, -* recursively processes nested object schemas and arrays of object schemas. -* -* @param schema - The Zod schema instance (v3 or v4) -* @param {boolean} [recursive=false] - Whether to recursively process nested objects/arrays. -* @returns The input Zod schema of the transform, or undefined if not a transform -*/ -function interopZodTransformInputSchema(schema, recursive = false) { - const cache = /* @__PURE__ */ new WeakMap(); - return interopZodTransformInputSchemaImpl(schema, recursive, cache); -} -/** -* Creates a modified version of a Zod object schema where fields matching a predicate are made optional. -* Supports both Zod v3 and v4 schemas and preserves the original schema version. -* -* @template T - The type of the Zod object schema. -* @param {T} schema - The Zod object schema instance (either v3 or v4). -* @param {(key: string, value: InteropZodType) => boolean} predicate - Function to determine which fields should be optional. -* @returns {InteropZodObject} The modified Zod object schema. -* @throws {Error} If the schema is not a Zod v3 or v4 object. -*/ -function interopZodObjectMakeFieldsOptional(schema, predicate) { - if (isZodSchemaV3(schema)) { - const shape = getInteropZodObjectShape(schema); - const modifiedShape = {}; - for (const [key, value] of Object.entries(shape)) if (predicate(key, value)) modifiedShape[key] = value.optional(); - else modifiedShape[key] = value; - return schema.extend(modifiedShape); - } - if (isZodSchemaV4(schema)) { - const shape = getInteropZodObjectShape(schema); - const outputShape = { ...schema._zod.def.shape }; - for (const [key, value] of Object.entries(shape)) if (predicate(key, value)) outputShape[key] = new $ZodOptional({ - type: "optional", - innerType: value - }); - const modifiedSchema = clone(schema, { - ...schema._zod.def, - shape: outputShape - }); - const meta = globalRegistry.get(schema); - if (meta) globalRegistry.add(modifiedSchema, meta); - return modifiedSchema; - } - throw new Error("Schema must be an instance of z3.ZodObject or z4.$ZodObject"); -} -function isInteropZodError(e) { - return e instanceof Error && (e.constructor.name === "ZodError" || e.constructor.name === "$ZodError"); -} - -//#endregion - -//# sourceMappingURL=zod.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/Options.js -//#region src/utils/zod-to-json-schema/Options.ts -const ignoreOverride = Symbol("Let zodToJsonSchema decide on which parser to use"); -const Options_defaultOptions = { - name: void 0, - $refStrategy: "root", - basePath: ["#"], - effectStrategy: "input", - pipeStrategy: "all", - dateStrategy: "format:date-time", - mapStrategy: "entries", - removeAdditionalStrategy: "passthrough", - allowedAdditionalProperties: true, - rejectedAdditionalProperties: false, - definitionPath: "definitions", - target: "jsonSchema7", - strictUnions: false, - definitions: {}, - errorMessages: false, - markdownDescription: false, - patternStrategy: "escape", - applyRegexFlags: false, - emailStrategy: "format:email", - base64Strategy: "contentEncoding:base64", - nameStrategy: "ref", - openAiAnyTypeName: "OpenAiAnyType" -}; -const getDefaultOptions = (options) => typeof options === "string" ? { - ...Options_defaultOptions, - name: options -} : { - ...Options_defaultOptions, - ...options -}; - -//#endregion - -//# sourceMappingURL=Options.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/Refs.js - - -//#region src/utils/zod-to-json-schema/Refs.ts -const getRefs = (options) => { - const _options = getDefaultOptions(options); - const currentPath = _options.name !== void 0 ? [ - ..._options.basePath, - _options.definitionPath, - _options.name - ] : _options.basePath; - return { - ..._options, - flags: { hasReferencedOpenAiAnyType: false }, - currentPath, - propertyPath: void 0, - seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [def._def, { - def: def._def, - path: [ - ..._options.basePath, - _options.definitionPath, - name - ], - jsonSchema: void 0 - }])) - }; -}; - -//#endregion - -//# sourceMappingURL=Refs.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/getRelativePath.js -//#region src/utils/zod-to-json-schema/getRelativePath.ts -const getRelativePath = (pathA, pathB) => { - let i = 0; - for (; i < pathA.length && i < pathB.length; i++) if (pathA[i] !== pathB[i]) break; - return [(pathA.length - i).toString(), ...pathB.slice(i)].join("/"); -}; - -//#endregion - -//# sourceMappingURL=getRelativePath.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/any.js - - -//#region src/utils/zod-to-json-schema/parsers/any.ts -function parseAnyDef(refs) { - if (refs.target !== "openAi") return {}; - const anyDefinitionPath = [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName - ]; - refs.flags.hasReferencedOpenAiAnyType = true; - return { $ref: refs.$refStrategy === "relative" ? getRelativePath(anyDefinitionPath, refs.currentPath) : anyDefinitionPath.join("/") }; -} - -//#endregion - -//# sourceMappingURL=any.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/errorMessages.js -//#region src/utils/zod-to-json-schema/errorMessages.ts -function addErrorMessage(res, key, errorMessage, refs) { - if (!refs?.errorMessages) return; - if (errorMessage) res.errorMessage = { - ...res.errorMessage, - [key]: errorMessage - }; -} -function setResponseValueAndErrors(res, key, value, errorMessage, refs) { - res[key] = value; - addErrorMessage(res, key, errorMessage, refs); -} - -//#endregion - -//# sourceMappingURL=errorMessages.js.map -;// CONCATENATED MODULE: ./node_modules/zod/v3/helpers/util.js -var util; -(function (util) { - util.assertEqual = (_) => { }; - function assertIs(_arg) { } - util.assertIs = assertIs; - function assertNever(_x) { - throw new Error(); - } - util.assertNever = assertNever; - util.arrayToEnum = (items) => { - const obj = {}; - for (const item of items) { - obj[item] = item; - } - return obj; - }; - util.getValidEnumValues = (obj) => { - const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== "number"); - const filtered = {}; - for (const k of validKeys) { - filtered[k] = obj[k]; - } - return util.objectValues(filtered); - }; - util.objectValues = (obj) => { - return util.objectKeys(obj).map(function (e) { - return obj[e]; - }); - }; - util.objectKeys = typeof Object.keys === "function" // eslint-disable-line ban/ban - ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban - : (object) => { - const keys = []; - for (const key in object) { - if (Object.prototype.hasOwnProperty.call(object, key)) { - keys.push(key); - } - } - return keys; - }; - util.find = (arr, checker) => { - for (const item of arr) { - if (checker(item)) - return item; - } - return undefined; - }; - util.isInteger = typeof Number.isInteger === "function" - ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban - : (val) => typeof val === "number" && Number.isFinite(val) && Math.floor(val) === val; - function joinValues(array, separator = " | ") { - return array.map((val) => (typeof val === "string" ? `'${val}'` : val)).join(separator); - } - util.joinValues = joinValues; - util.jsonStringifyReplacer = (_, value) => { - if (typeof value === "bigint") { - return value.toString(); - } - return value; - }; -})(util || (util = {})); -var objectUtil; -(function (objectUtil) { - objectUtil.mergeShapes = (first, second) => { - return { - ...first, - ...second, // second overwrites first - }; - }; -})(objectUtil || (objectUtil = {})); -const ZodParsedType = util.arrayToEnum([ - "string", - "nan", - "number", - "integer", - "float", - "boolean", - "date", - "bigint", - "symbol", - "function", - "undefined", - "null", - "array", - "object", - "unknown", - "promise", - "void", - "never", - "map", - "set", -]); -const util_getParsedType = (data) => { - const t = typeof data; - switch (t) { - case "undefined": - return ZodParsedType.undefined; - case "string": - return ZodParsedType.string; - case "number": - return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number; - case "boolean": - return ZodParsedType.boolean; - case "function": - return ZodParsedType.function; - case "bigint": - return ZodParsedType.bigint; - case "symbol": - return ZodParsedType.symbol; - case "object": - if (Array.isArray(data)) { - return ZodParsedType.array; - } - if (data === null) { - return ZodParsedType.null; - } - if (data.then && typeof data.then === "function" && data.catch && typeof data.catch === "function") { - return ZodParsedType.promise; - } - if (typeof Map !== "undefined" && data instanceof Map) { - return ZodParsedType.map; - } - if (typeof Set !== "undefined" && data instanceof Set) { - return ZodParsedType.set; - } - if (typeof Date !== "undefined" && data instanceof Date) { - return ZodParsedType.date; - } - return ZodParsedType.object; - default: - return ZodParsedType.unknown; - } -}; - -;// CONCATENATED MODULE: ./node_modules/zod/v3/ZodError.js - -const ZodIssueCode = util.arrayToEnum([ - "invalid_type", - "invalid_literal", - "custom", - "invalid_union", - "invalid_union_discriminator", - "invalid_enum_value", - "unrecognized_keys", - "invalid_arguments", - "invalid_return_type", - "invalid_date", - "invalid_string", - "too_small", - "too_big", - "invalid_intersection_types", - "not_multiple_of", - "not_finite", -]); -const quotelessJson = (obj) => { - const json = JSON.stringify(obj, null, 2); - return json.replace(/"([^"]+)":/g, "$1:"); -}; -class ZodError extends Error { - get errors() { - return this.issues; - } - constructor(issues) { - super(); - this.issues = []; - this.addIssue = (sub) => { - this.issues = [...this.issues, sub]; - }; - this.addIssues = (subs = []) => { - this.issues = [...this.issues, ...subs]; - }; - const actualProto = new.target.prototype; - if (Object.setPrototypeOf) { - // eslint-disable-next-line ban/ban - Object.setPrototypeOf(this, actualProto); - } - else { - this.__proto__ = actualProto; - } - this.name = "ZodError"; - this.issues = issues; - } - format(_mapper) { - const mapper = _mapper || - function (issue) { - return issue.message; - }; - const fieldErrors = { _errors: [] }; - const processError = (error) => { - for (const issue of error.issues) { - if (issue.code === "invalid_union") { - issue.unionErrors.map(processError); - } - else if (issue.code === "invalid_return_type") { - processError(issue.returnTypeError); - } - else if (issue.code === "invalid_arguments") { - processError(issue.argumentsError); - } - else if (issue.path.length === 0) { - fieldErrors._errors.push(mapper(issue)); - } - else { - let curr = fieldErrors; - let i = 0; - while (i < issue.path.length) { - const el = issue.path[i]; - const terminal = i === issue.path.length - 1; - if (!terminal) { - curr[el] = curr[el] || { _errors: [] }; - // if (typeof el === "string") { - // curr[el] = curr[el] || { _errors: [] }; - // } else if (typeof el === "number") { - // const errorArray: any = []; - // errorArray._errors = []; - // curr[el] = curr[el] || errorArray; - // } - } - else { - curr[el] = curr[el] || { _errors: [] }; - curr[el]._errors.push(mapper(issue)); - } - curr = curr[el]; - i++; - } - } - } - }; - processError(this); - return fieldErrors; - } - static assert(value) { - if (!(value instanceof ZodError)) { - throw new Error(`Not a ZodError: ${value}`); - } - } - toString() { - return this.message; - } - get message() { - return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2); - } - get isEmpty() { - return this.issues.length === 0; - } - flatten(mapper = (issue) => issue.message) { - const fieldErrors = Object.create(null); - const formErrors = []; - for (const sub of this.issues) { - if (sub.path.length > 0) { - const firstEl = sub.path[0]; - fieldErrors[firstEl] = fieldErrors[firstEl] || []; - fieldErrors[firstEl].push(mapper(sub)); - } - else { - formErrors.push(mapper(sub)); - } - } - return { formErrors, fieldErrors }; - } - get formErrors() { - return this.flatten(); - } -} -ZodError.create = (issues) => { - const error = new ZodError(issues); - return error; -}; - -;// CONCATENATED MODULE: ./node_modules/zod/v3/locales/en.js - - -const errorMap = (issue, _ctx) => { - let message; - switch (issue.code) { - case ZodIssueCode.invalid_type: - if (issue.received === ZodParsedType.undefined) { - message = "Required"; - } - else { - message = `Expected ${issue.expected}, received ${issue.received}`; - } - break; - case ZodIssueCode.invalid_literal: - message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`; - break; - case ZodIssueCode.unrecognized_keys: - message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, ", ")}`; - break; - case ZodIssueCode.invalid_union: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_union_discriminator: - message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`; - break; - case ZodIssueCode.invalid_enum_value: - message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`; - break; - case ZodIssueCode.invalid_arguments: - message = `Invalid function arguments`; - break; - case ZodIssueCode.invalid_return_type: - message = `Invalid function return type`; - break; - case ZodIssueCode.invalid_date: - message = `Invalid date`; - break; - case ZodIssueCode.invalid_string: - if (typeof issue.validation === "object") { - if ("includes" in issue.validation) { - message = `Invalid input: must include "${issue.validation.includes}"`; - if (typeof issue.validation.position === "number") { - message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`; - } - } - else if ("startsWith" in issue.validation) { - message = `Invalid input: must start with "${issue.validation.startsWith}"`; - } - else if ("endsWith" in issue.validation) { - message = `Invalid input: must end with "${issue.validation.endsWith}"`; - } - else { - util.assertNever(issue.validation); - } - } - else if (issue.validation !== "regex") { - message = `Invalid ${issue.validation}`; - } - else { - message = "Invalid"; - } - break; - case ZodIssueCode.too_small: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? "exactly" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "bigint") - message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.too_big: - if (issue.type === "array") - message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`; - else if (issue.type === "string") - message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`; - else if (issue.type === "number") - message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "bigint") - message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`; - else if (issue.type === "date") - message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`; - else - message = "Invalid input"; - break; - case ZodIssueCode.custom: - message = `Invalid input`; - break; - case ZodIssueCode.invalid_intersection_types: - message = `Intersection results could not be merged`; - break; - case ZodIssueCode.not_multiple_of: - message = `Number must be a multiple of ${issue.multipleOf}`; - break; - case ZodIssueCode.not_finite: - message = "Number must be finite"; - break; - default: - message = _ctx.defaultError; - util.assertNever(issue); - } - return { message }; -}; -/* harmony default export */ const locales_en = (errorMap); - -;// CONCATENATED MODULE: ./node_modules/zod/v3/errors.js - -let overrideErrorMap = locales_en; - -function setErrorMap(map) { - overrideErrorMap = map; -} -function getErrorMap() { - return overrideErrorMap; -} - -;// CONCATENATED MODULE: ./node_modules/zod/v3/helpers/parseUtil.js - - -const makeIssue = (params) => { - const { data, path, errorMaps, issueData } = params; - const fullPath = [...path, ...(issueData.path || [])]; - const fullIssue = { - ...issueData, - path: fullPath, - }; - if (issueData.message !== undefined) { - return { - ...issueData, - path: fullPath, - message: issueData.message, - }; - } - let errorMessage = ""; - const maps = errorMaps - .filter((m) => !!m) - .slice() - .reverse(); - for (const map of maps) { - errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message; - } - return { - ...issueData, - path: fullPath, - message: errorMessage, - }; -}; -const EMPTY_PATH = []; -function addIssueToContext(ctx, issueData) { - const overrideMap = getErrorMap(); - const issue = makeIssue({ - issueData: issueData, - data: ctx.data, - path: ctx.path, - errorMaps: [ - ctx.common.contextualErrorMap, // contextual error map is first priority - ctx.schemaErrorMap, // then schema-bound map if available - overrideMap, // then global override map - overrideMap === locales_en ? undefined : locales_en, // then global default map - ].filter((x) => !!x), - }); - ctx.common.issues.push(issue); -} -class ParseStatus { - constructor() { - this.value = "valid"; - } - dirty() { - if (this.value === "valid") - this.value = "dirty"; - } - abort() { - if (this.value !== "aborted") - this.value = "aborted"; - } - static mergeArray(status, results) { - const arrayValue = []; - for (const s of results) { - if (s.status === "aborted") - return INVALID; - if (s.status === "dirty") - status.dirty(); - arrayValue.push(s.value); - } - return { status: status.value, value: arrayValue }; - } - static async mergeObjectAsync(status, pairs) { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - }); - } - return ParseStatus.mergeObjectSync(status, syncPairs); - } - static mergeObjectSync(status, pairs) { - const finalObject = {}; - for (const pair of pairs) { - const { key, value } = pair; - if (key.status === "aborted") - return INVALID; - if (value.status === "aborted") - return INVALID; - if (key.status === "dirty") - status.dirty(); - if (value.status === "dirty") - status.dirty(); - if (key.value !== "__proto__" && (typeof value.value !== "undefined" || pair.alwaysSet)) { - finalObject[key.value] = value.value; - } - } - return { status: status.value, value: finalObject }; - } -} -const INVALID = Object.freeze({ - status: "aborted", -}); -const DIRTY = (value) => ({ status: "dirty", value }); -const OK = (value) => ({ status: "valid", value }); -const isAborted = (x) => x.status === "aborted"; -const isDirty = (x) => x.status === "dirty"; -const isValid = (x) => x.status === "valid"; -const isAsync = (x) => typeof Promise !== "undefined" && x instanceof Promise; - -;// CONCATENATED MODULE: ./node_modules/zod/v3/helpers/errorUtil.js -var errorUtil; -(function (errorUtil) { - errorUtil.errToObj = (message) => typeof message === "string" ? { message } : message || {}; - // biome-ignore lint: - errorUtil.toString = (message) => typeof message === "string" ? message : message?.message; -})(errorUtil || (errorUtil = {})); - -;// CONCATENATED MODULE: ./node_modules/zod/v3/types.js - - - - - -class ParseInputLazyPath { - constructor(parent, value, path, key) { - this._cachedPath = []; - this.parent = parent; - this.data = value; - this._path = path; - this._key = key; - } - get path() { - if (!this._cachedPath.length) { - if (Array.isArray(this._key)) { - this._cachedPath.push(...this._path, ...this._key); - } - else { - this._cachedPath.push(...this._path, this._key); - } - } - return this._cachedPath; - } -} -const handleResult = (ctx, result) => { - if (isValid(result)) { - return { success: true, data: result.value }; - } - else { - if (!ctx.common.issues.length) { - throw new Error("Validation failed but no issues detected."); - } - return { - success: false, - get error() { - if (this._error) - return this._error; - const error = new ZodError(ctx.common.issues); - this._error = error; - return this._error; - }, - }; - } -}; -function processCreateParams(params) { - if (!params) - return {}; - const { errorMap, invalid_type_error, required_error, description } = params; - if (errorMap && (invalid_type_error || required_error)) { - throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`); - } - if (errorMap) - return { errorMap: errorMap, description }; - const customMap = (iss, ctx) => { - const { message } = params; - if (iss.code === "invalid_enum_value") { - return { message: message ?? ctx.defaultError }; - } - if (typeof ctx.data === "undefined") { - return { message: message ?? required_error ?? ctx.defaultError }; - } - if (iss.code !== "invalid_type") - return { message: ctx.defaultError }; - return { message: message ?? invalid_type_error ?? ctx.defaultError }; - }; - return { errorMap: customMap, description }; -} -class ZodType { - get description() { - return this._def.description; - } - _getType(input) { - return util_getParsedType(input.data); - } - _getOrReturnCtx(input, ctx) { - return (ctx || { - common: input.parent.common, - data: input.data, - parsedType: util_getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }); - } - _processInputParams(input) { - return { - status: new ParseStatus(), - ctx: { - common: input.parent.common, - data: input.data, - parsedType: util_getParsedType(input.data), - schemaErrorMap: this._def.errorMap, - path: input.path, - parent: input.parent, - }, - }; - } - _parseSync(input) { - const result = this._parse(input); - if (isAsync(result)) { - throw new Error("Synchronous parse encountered promise."); - } - return result; - } - _parseAsync(input) { - const result = this._parse(input); - return Promise.resolve(result); - } - parse(data, params) { - const result = this.safeParse(data, params); - if (result.success) - return result.data; - throw result.error; - } - safeParse(data, params) { - const ctx = { - common: { - issues: [], - async: params?.async ?? false, - contextualErrorMap: params?.errorMap, - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: util_getParsedType(data), - }; - const result = this._parseSync({ data, path: ctx.path, parent: ctx }); - return handleResult(ctx, result); - } - "~validate"(data) { - const ctx = { - common: { - issues: [], - async: !!this["~standard"].async, - }, - path: [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: util_getParsedType(data), - }; - if (!this["~standard"].async) { - try { - const result = this._parseSync({ data, path: [], parent: ctx }); - return isValid(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }; - } - catch (err) { - if (err?.message?.toLowerCase()?.includes("encountered")) { - this["~standard"].async = true; - } - ctx.common = { - issues: [], - async: true, - }; - } - } - return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result) - ? { - value: result.value, - } - : { - issues: ctx.common.issues, - }); - } - async parseAsync(data, params) { - const result = await this.safeParseAsync(data, params); - if (result.success) - return result.data; - throw result.error; - } - async safeParseAsync(data, params) { - const ctx = { - common: { - issues: [], - contextualErrorMap: params?.errorMap, - async: true, - }, - path: params?.path || [], - schemaErrorMap: this._def.errorMap, - parent: null, - data, - parsedType: util_getParsedType(data), - }; - const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx }); - const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult)); - return handleResult(ctx, result); - } - refine(check, message) { - const getIssueProperties = (val) => { - if (typeof message === "string" || typeof message === "undefined") { - return { message }; - } - else if (typeof message === "function") { - return message(val); - } - else { - return message; - } - }; - return this._refinement((val, ctx) => { - const result = check(val); - const setError = () => ctx.addIssue({ - code: ZodIssueCode.custom, - ...getIssueProperties(val), - }); - if (typeof Promise !== "undefined" && result instanceof Promise) { - return result.then((data) => { - if (!data) { - setError(); - return false; - } - else { - return true; - } - }); - } - if (!result) { - setError(); - return false; - } - else { - return true; - } - }); - } - refinement(check, refinementData) { - return this._refinement((val, ctx) => { - if (!check(val)) { - ctx.addIssue(typeof refinementData === "function" ? refinementData(val, ctx) : refinementData); - return false; - } - else { - return true; - } - }); - } - _refinement(refinement) { - return new ZodEffects({ - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "refinement", refinement }, - }); - } - superRefine(refinement) { - return this._refinement(refinement); - } - constructor(def) { - /** Alias of safeParseAsync */ - this.spa = this.safeParseAsync; - this._def = def; - this.parse = this.parse.bind(this); - this.safeParse = this.safeParse.bind(this); - this.parseAsync = this.parseAsync.bind(this); - this.safeParseAsync = this.safeParseAsync.bind(this); - this.spa = this.spa.bind(this); - this.refine = this.refine.bind(this); - this.refinement = this.refinement.bind(this); - this.superRefine = this.superRefine.bind(this); - this.optional = this.optional.bind(this); - this.nullable = this.nullable.bind(this); - this.nullish = this.nullish.bind(this); - this.array = this.array.bind(this); - this.promise = this.promise.bind(this); - this.or = this.or.bind(this); - this.and = this.and.bind(this); - this.transform = this.transform.bind(this); - this.brand = this.brand.bind(this); - this.default = this.default.bind(this); - this.catch = this.catch.bind(this); - this.describe = this.describe.bind(this); - this.pipe = this.pipe.bind(this); - this.readonly = this.readonly.bind(this); - this.isNullable = this.isNullable.bind(this); - this.isOptional = this.isOptional.bind(this); - this["~standard"] = { - version: 1, - vendor: "zod", - validate: (data) => this["~validate"](data), - }; - } - optional() { - return ZodOptional.create(this, this._def); - } - nullable() { - return ZodNullable.create(this, this._def); - } - nullish() { - return this.nullable().optional(); - } - array() { - return ZodArray.create(this); - } - promise() { - return ZodPromise.create(this, this._def); - } - or(option) { - return ZodUnion.create([this, option], this._def); - } - and(incoming) { - return ZodIntersection.create(this, incoming, this._def); - } - transform(transform) { - return new ZodEffects({ - ...processCreateParams(this._def), - schema: this, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect: { type: "transform", transform }, - }); - } - default(def) { - const defaultValueFunc = typeof def === "function" ? def : () => def; - return new ZodDefault({ - ...processCreateParams(this._def), - innerType: this, - defaultValue: defaultValueFunc, - typeName: ZodFirstPartyTypeKind.ZodDefault, - }); - } - brand() { - return new ZodBranded({ - typeName: ZodFirstPartyTypeKind.ZodBranded, - type: this, - ...processCreateParams(this._def), - }); - } - catch(def) { - const catchValueFunc = typeof def === "function" ? def : () => def; - return new ZodCatch({ - ...processCreateParams(this._def), - innerType: this, - catchValue: catchValueFunc, - typeName: ZodFirstPartyTypeKind.ZodCatch, - }); - } - describe(description) { - const This = this.constructor; - return new This({ - ...this._def, - description, - }); - } - pipe(target) { - return ZodPipeline.create(this, target); - } - readonly() { - return ZodReadonly.create(this); - } - isOptional() { - return this.safeParse(undefined).success; - } - isNullable() { - return this.safeParse(null).success; - } -} -const cuidRegex = /^c[^\s-]{8,}$/i; -const cuid2Regex = /^[0-9a-z]+$/; -const ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i; -// const uuidRegex = -// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i; -const uuidRegex = /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i; -const nanoidRegex = /^[a-z0-9_-]{21}$/i; -const jwtRegex = /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/; -const durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/; -// from https://stackoverflow.com/a/46181/1550155 -// old version: too slow, didn't support unicode -// const emailRegex = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$/i; -//old email regex -// const emailRegex = /^(([^<>()[\].,;:\s@"]+(\.[^<>()[\].,;:\s@"]+)*)|(".+"))@((?!-)([^<>()[\].,;:\s@"]+\.)+[^<>()[\].,;:\s@"]{1,})[^-<>()[\].,;:\s@"]$/i; -// eslint-disable-next-line -// const emailRegex = -// /^(([^<>()[\]\\.,;:\s@\"]+(\.[^<>()[\]\\.,;:\s@\"]+)*)|(\".+\"))@((\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\])|(\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\.[A-Za-z]{2,})+))$/; -// const emailRegex = -// /^[a-zA-Z0-9\.\!\#\$\%\&\'\*\+\/\=\?\^\_\`\{\|\}\~\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/; -// const emailRegex = -// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])$/i; -const emailRegex = /^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i; -// const emailRegex = -// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\.[a-z0-9\-]+)*$/i; -// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression -const _emojiRegex = `^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`; -let emojiRegex; -// faster, simpler, safer -const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/; -const ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/; -// const ipv6Regex = -// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/; -const ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/; -const ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/; -// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript -const base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/; -// https://base64.guru/standards/base64url -const base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/; -// simple -// const dateRegexSource = `\\d{4}-\\d{2}-\\d{2}`; -// no leap year validation -// const dateRegexSource = `\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\d|2\\d))`; -// with leap year validation -const dateRegexSource = `((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`; -const dateRegex = new RegExp(`^${dateRegexSource}$`); -function timeRegexSource(args) { - let secondsRegexSource = `[0-5]\\d`; - if (args.precision) { - secondsRegexSource = `${secondsRegexSource}\\.\\d{${args.precision}}`; - } - else if (args.precision == null) { - secondsRegexSource = `${secondsRegexSource}(\\.\\d+)?`; - } - const secondsQuantifier = args.precision ? "+" : "?"; // require seconds if precision is nonzero - return `([01]\\d|2[0-3]):[0-5]\\d(:${secondsRegexSource})${secondsQuantifier}`; -} -function timeRegex(args) { - return new RegExp(`^${timeRegexSource(args)}$`); -} -// Adapted from https://stackoverflow.com/a/3143231 -function datetimeRegex(args) { - let regex = `${dateRegexSource}T${timeRegexSource(args)}`; - const opts = []; - opts.push(args.local ? `Z?` : `Z`); - if (args.offset) - opts.push(`([+-]\\d{2}:?\\d{2})`); - regex = `${regex}(${opts.join("|")})`; - return new RegExp(`^${regex}$`); -} -function isValidIP(ip, version) { - if ((version === "v4" || !version) && ipv4Regex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6Regex.test(ip)) { - return true; - } - return false; -} -function types_isValidJWT(jwt, alg) { - if (!jwtRegex.test(jwt)) - return false; - try { - const [header] = jwt.split("."); - if (!header) - return false; - // Convert base64url to base64 - const base64 = header - .replace(/-/g, "+") - .replace(/_/g, "/") - .padEnd(header.length + ((4 - (header.length % 4)) % 4), "="); - // @ts-ignore - const decoded = JSON.parse(atob(base64)); - if (typeof decoded !== "object" || decoded === null) - return false; - if ("typ" in decoded && decoded?.typ !== "JWT") - return false; - if (!decoded.alg) - return false; - if (alg && decoded.alg !== alg) - return false; - return true; - } - catch { - return false; - } -} -function isValidCidr(ip, version) { - if ((version === "v4" || !version) && ipv4CidrRegex.test(ip)) { - return true; - } - if ((version === "v6" || !version) && ipv6CidrRegex.test(ip)) { - return true; - } - return false; -} -class ZodString extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = String(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.string) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.string, - received: ctx.parsedType, - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.length < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.length > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "length") { - const tooBig = input.data.length > check.value; - const tooSmall = input.data.length < check.value; - if (tooBig || tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - if (tooBig) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - else if (tooSmall) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "string", - inclusive: true, - exact: true, - message: check.message, - }); - } - status.dirty(); - } - } - else if (check.kind === "email") { - if (!emailRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "email", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "emoji") { - if (!emojiRegex) { - emojiRegex = new RegExp(_emojiRegex, "u"); - } - if (!emojiRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "emoji", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "uuid") { - if (!uuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "uuid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "nanoid") { - if (!nanoidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "nanoid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid") { - if (!cuidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cuid2") { - if (!cuid2Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cuid2", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ulid") { - if (!ulidRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ulid", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "url") { - try { - // @ts-ignore - new URL(input.data); - } - catch { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "url", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "regex") { - check.regex.lastIndex = 0; - const testResult = check.regex.test(input.data); - if (!testResult) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "regex", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "trim") { - input.data = input.data.trim(); - } - else if (check.kind === "includes") { - if (!input.data.includes(check.value, check.position)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { includes: check.value, position: check.position }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "toLowerCase") { - input.data = input.data.toLowerCase(); - } - else if (check.kind === "toUpperCase") { - input.data = input.data.toUpperCase(); - } - else if (check.kind === "startsWith") { - if (!input.data.startsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { startsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "endsWith") { - if (!input.data.endsWith(check.value)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: { endsWith: check.value }, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "datetime") { - const regex = datetimeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "datetime", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "date") { - const regex = dateRegex; - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "date", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "time") { - const regex = timeRegex(check); - if (!regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_string, - validation: "time", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "duration") { - if (!durationRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "duration", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "ip") { - if (!isValidIP(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "ip", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "jwt") { - if (!types_isValidJWT(input.data, check.alg)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "jwt", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "cidr") { - if (!isValidCidr(input.data, check.version)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "cidr", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "base64") { - if (!base64Regex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "base64url") { - if (!base64urlRegex.test(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - validation: "base64url", - code: ZodIssueCode.invalid_string, - message: check.message, - }); - status.dirty(); - } - } - else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _regex(regex, validation, message) { - return this.refinement((data) => regex.test(data), { - validation, - code: ZodIssueCode.invalid_string, - ...errorUtil.errToObj(message), - }); - } - _addCheck(check) { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - email(message) { - return this._addCheck({ kind: "email", ...errorUtil.errToObj(message) }); - } - url(message) { - return this._addCheck({ kind: "url", ...errorUtil.errToObj(message) }); - } - emoji(message) { - return this._addCheck({ kind: "emoji", ...errorUtil.errToObj(message) }); - } - uuid(message) { - return this._addCheck({ kind: "uuid", ...errorUtil.errToObj(message) }); - } - nanoid(message) { - return this._addCheck({ kind: "nanoid", ...errorUtil.errToObj(message) }); - } - cuid(message) { - return this._addCheck({ kind: "cuid", ...errorUtil.errToObj(message) }); - } - cuid2(message) { - return this._addCheck({ kind: "cuid2", ...errorUtil.errToObj(message) }); - } - ulid(message) { - return this._addCheck({ kind: "ulid", ...errorUtil.errToObj(message) }); - } - base64(message) { - return this._addCheck({ kind: "base64", ...errorUtil.errToObj(message) }); - } - base64url(message) { - // base64url encoding is a modification of base64 that can safely be used in URLs and filenames - return this._addCheck({ - kind: "base64url", - ...errorUtil.errToObj(message), - }); - } - jwt(options) { - return this._addCheck({ kind: "jwt", ...errorUtil.errToObj(options) }); - } - ip(options) { - return this._addCheck({ kind: "ip", ...errorUtil.errToObj(options) }); - } - cidr(options) { - return this._addCheck({ kind: "cidr", ...errorUtil.errToObj(options) }); - } - datetime(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "datetime", - precision: null, - offset: false, - local: false, - message: options, - }); - } - return this._addCheck({ - kind: "datetime", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - offset: options?.offset ?? false, - local: options?.local ?? false, - ...errorUtil.errToObj(options?.message), - }); - } - date(message) { - return this._addCheck({ kind: "date", message }); - } - time(options) { - if (typeof options === "string") { - return this._addCheck({ - kind: "time", - precision: null, - message: options, - }); - } - return this._addCheck({ - kind: "time", - precision: typeof options?.precision === "undefined" ? null : options?.precision, - ...errorUtil.errToObj(options?.message), - }); - } - duration(message) { - return this._addCheck({ kind: "duration", ...errorUtil.errToObj(message) }); - } - regex(regex, message) { - return this._addCheck({ - kind: "regex", - regex: regex, - ...errorUtil.errToObj(message), - }); - } - includes(value, options) { - return this._addCheck({ - kind: "includes", - value: value, - position: options?.position, - ...errorUtil.errToObj(options?.message), - }); - } - startsWith(value, message) { - return this._addCheck({ - kind: "startsWith", - value: value, - ...errorUtil.errToObj(message), - }); - } - endsWith(value, message) { - return this._addCheck({ - kind: "endsWith", - value: value, - ...errorUtil.errToObj(message), - }); - } - min(minLength, message) { - return this._addCheck({ - kind: "min", - value: minLength, - ...errorUtil.errToObj(message), - }); - } - max(maxLength, message) { - return this._addCheck({ - kind: "max", - value: maxLength, - ...errorUtil.errToObj(message), - }); - } - length(len, message) { - return this._addCheck({ - kind: "length", - value: len, - ...errorUtil.errToObj(message), - }); - } - /** - * Equivalent to `.min(1)` - */ - nonempty(message) { - return this.min(1, errorUtil.errToObj(message)); - } - trim() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "trim" }], - }); - } - toLowerCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toLowerCase" }], - }); - } - toUpperCase() { - return new ZodString({ - ...this._def, - checks: [...this._def.checks, { kind: "toUpperCase" }], - }); - } - get isDatetime() { - return !!this._def.checks.find((ch) => ch.kind === "datetime"); - } - get isDate() { - return !!this._def.checks.find((ch) => ch.kind === "date"); - } - get isTime() { - return !!this._def.checks.find((ch) => ch.kind === "time"); - } - get isDuration() { - return !!this._def.checks.find((ch) => ch.kind === "duration"); - } - get isEmail() { - return !!this._def.checks.find((ch) => ch.kind === "email"); - } - get isURL() { - return !!this._def.checks.find((ch) => ch.kind === "url"); - } - get isEmoji() { - return !!this._def.checks.find((ch) => ch.kind === "emoji"); - } - get isUUID() { - return !!this._def.checks.find((ch) => ch.kind === "uuid"); - } - get isNANOID() { - return !!this._def.checks.find((ch) => ch.kind === "nanoid"); - } - get isCUID() { - return !!this._def.checks.find((ch) => ch.kind === "cuid"); - } - get isCUID2() { - return !!this._def.checks.find((ch) => ch.kind === "cuid2"); - } - get isULID() { - return !!this._def.checks.find((ch) => ch.kind === "ulid"); - } - get isIP() { - return !!this._def.checks.find((ch) => ch.kind === "ip"); - } - get isCIDR() { - return !!this._def.checks.find((ch) => ch.kind === "cidr"); - } - get isBase64() { - return !!this._def.checks.find((ch) => ch.kind === "base64"); - } - get isBase64url() { - // base64url encoding is a modification of base64 that can safely be used in URLs and filenames - return !!this._def.checks.find((ch) => ch.kind === "base64url"); - } - get minLength() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxLength() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodString.create = (params) => { - return new ZodString({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodString, - coerce: params?.coerce ?? false, - ...processCreateParams(params), - }); -}; -// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034 -function types_floatSafeRemainder(val, step) { - const valDecCount = (val.toString().split(".")[1] || "").length; - const stepDecCount = (step.toString().split(".")[1] || "").length; - const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount; - const valInt = Number.parseInt(val.toFixed(decCount).replace(".", "")); - const stepInt = Number.parseInt(step.toFixed(decCount).replace(".", "")); - return (valInt % stepInt) / 10 ** decCount; -} -class ZodNumber extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - this.step = this.multipleOf; - } - _parse(input) { - if (this._def.coerce) { - input.data = Number(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.number) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.number, - received: ctx.parsedType, - }); - return INVALID; - } - let ctx = undefined; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "int") { - if (!util.isInteger(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: "integer", - received: "float", - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: check.value, - type: "number", - inclusive: check.inclusive, - exact: false, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (types_floatSafeRemainder(input.data, check.value) !== 0) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "finite") { - if (!Number.isFinite(input.data)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_finite, - message: check.message, - }); - status.dirty(); - } - } - else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodNumber({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodNumber({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - int(message) { - return this._addCheck({ - kind: "int", - message: errorUtil.toString(message), - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: false, - message: errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: 0, - inclusive: true, - message: errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value: value, - message: errorUtil.toString(message), - }); - } - finite(message) { - return this._addCheck({ - kind: "finite", - message: errorUtil.toString(message), - }); - } - safe(message) { - return this._addCheck({ - kind: "min", - inclusive: true, - value: Number.MIN_SAFE_INTEGER, - message: errorUtil.toString(message), - })._addCheck({ - kind: "max", - inclusive: true, - value: Number.MAX_SAFE_INTEGER, - message: errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } - get isInt() { - return !!this._def.checks.find((ch) => ch.kind === "int" || (ch.kind === "multipleOf" && util.isInteger(ch.value))); - } - get isFinite() { - let max = null; - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "finite" || ch.kind === "int" || ch.kind === "multipleOf") { - return true; - } - else if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - else if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return Number.isFinite(min) && Number.isFinite(max); - } -} -ZodNumber.create = (params) => { - return new ZodNumber({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodNumber, - coerce: params?.coerce || false, - ...processCreateParams(params), - }); -}; -class ZodBigInt extends ZodType { - constructor() { - super(...arguments); - this.min = this.gte; - this.max = this.lte; - } - _parse(input) { - if (this._def.coerce) { - try { - input.data = BigInt(input.data); - } - catch { - return this._getInvalidInput(input); - } - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.bigint) { - return this._getInvalidInput(input); - } - let ctx = undefined; - const status = new ParseStatus(); - for (const check of this._def.checks) { - if (check.kind === "min") { - const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value; - if (tooSmall) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - type: "bigint", - minimum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "max") { - const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value; - if (tooBig) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - type: "bigint", - maximum: check.value, - inclusive: check.inclusive, - message: check.message, - }); - status.dirty(); - } - } - else if (check.kind === "multipleOf") { - if (input.data % check.value !== BigInt(0)) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.not_multiple_of, - multipleOf: check.value, - message: check.message, - }); - status.dirty(); - } - } - else { - util.assertNever(check); - } - } - return { status: status.value, value: input.data }; - } - _getInvalidInput(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.bigint, - received: ctx.parsedType, - }); - return INVALID; - } - gte(value, message) { - return this.setLimit("min", value, true, errorUtil.toString(message)); - } - gt(value, message) { - return this.setLimit("min", value, false, errorUtil.toString(message)); - } - lte(value, message) { - return this.setLimit("max", value, true, errorUtil.toString(message)); - } - lt(value, message) { - return this.setLimit("max", value, false, errorUtil.toString(message)); - } - setLimit(kind, value, inclusive, message) { - return new ZodBigInt({ - ...this._def, - checks: [ - ...this._def.checks, - { - kind, - value, - inclusive, - message: errorUtil.toString(message), - }, - ], - }); - } - _addCheck(check) { - return new ZodBigInt({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - positive(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); - } - negative(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: false, - message: errorUtil.toString(message), - }); - } - nonpositive(message) { - return this._addCheck({ - kind: "max", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); - } - nonnegative(message) { - return this._addCheck({ - kind: "min", - value: BigInt(0), - inclusive: true, - message: errorUtil.toString(message), - }); - } - multipleOf(value, message) { - return this._addCheck({ - kind: "multipleOf", - value, - message: errorUtil.toString(message), - }); - } - get minValue() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min; - } - get maxValue() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max; - } -} -ZodBigInt.create = (params) => { - return new ZodBigInt({ - checks: [], - typeName: ZodFirstPartyTypeKind.ZodBigInt, - coerce: params?.coerce ?? false, - ...processCreateParams(params), - }); -}; -class ZodBoolean extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = Boolean(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.boolean) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.boolean, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } -} -ZodBoolean.create = (params) => { - return new ZodBoolean({ - typeName: ZodFirstPartyTypeKind.ZodBoolean, - coerce: params?.coerce || false, - ...processCreateParams(params), - }); -}; -class ZodDate extends ZodType { - _parse(input) { - if (this._def.coerce) { - input.data = new Date(input.data); - } - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.date) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.date, - received: ctx.parsedType, - }); - return INVALID; - } - if (Number.isNaN(input.data.getTime())) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_date, - }); - return INVALID; - } - const status = new ParseStatus(); - let ctx = undefined; - for (const check of this._def.checks) { - if (check.kind === "min") { - if (input.data.getTime() < check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - message: check.message, - inclusive: true, - exact: false, - minimum: check.value, - type: "date", - }); - status.dirty(); - } - } - else if (check.kind === "max") { - if (input.data.getTime() > check.value) { - ctx = this._getOrReturnCtx(input, ctx); - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - message: check.message, - inclusive: true, - exact: false, - maximum: check.value, - type: "date", - }); - status.dirty(); - } - } - else { - util.assertNever(check); - } - } - return { - status: status.value, - value: new Date(input.data.getTime()), - }; - } - _addCheck(check) { - return new ZodDate({ - ...this._def, - checks: [...this._def.checks, check], - }); - } - min(minDate, message) { - return this._addCheck({ - kind: "min", - value: minDate.getTime(), - message: errorUtil.toString(message), - }); - } - max(maxDate, message) { - return this._addCheck({ - kind: "max", - value: maxDate.getTime(), - message: errorUtil.toString(message), - }); - } - get minDate() { - let min = null; - for (const ch of this._def.checks) { - if (ch.kind === "min") { - if (min === null || ch.value > min) - min = ch.value; - } - } - return min != null ? new Date(min) : null; - } - get maxDate() { - let max = null; - for (const ch of this._def.checks) { - if (ch.kind === "max") { - if (max === null || ch.value < max) - max = ch.value; - } - } - return max != null ? new Date(max) : null; - } -} -ZodDate.create = (params) => { - return new ZodDate({ - checks: [], - coerce: params?.coerce || false, - typeName: ZodFirstPartyTypeKind.ZodDate, - ...processCreateParams(params), - }); -}; -class ZodSymbol extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.symbol) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.symbol, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } -} -ZodSymbol.create = (params) => { - return new ZodSymbol({ - typeName: ZodFirstPartyTypeKind.ZodSymbol, - ...processCreateParams(params), - }); -}; -class ZodUndefined extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.undefined, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } -} -ZodUndefined.create = (params) => { - return new ZodUndefined({ - typeName: ZodFirstPartyTypeKind.ZodUndefined, - ...processCreateParams(params), - }); -}; -class ZodNull extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.null) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.null, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } -} -ZodNull.create = (params) => { - return new ZodNull({ - typeName: ZodFirstPartyTypeKind.ZodNull, - ...processCreateParams(params), - }); -}; -class ZodAny extends ZodType { - constructor() { - super(...arguments); - // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject. - this._any = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodAny.create = (params) => { - return new ZodAny({ - typeName: ZodFirstPartyTypeKind.ZodAny, - ...processCreateParams(params), - }); -}; -class ZodUnknown extends ZodType { - constructor() { - super(...arguments); - // required - this._unknown = true; - } - _parse(input) { - return OK(input.data); - } -} -ZodUnknown.create = (params) => { - return new ZodUnknown({ - typeName: ZodFirstPartyTypeKind.ZodUnknown, - ...processCreateParams(params), - }); -}; -class ZodNever extends ZodType { - _parse(input) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.never, - received: ctx.parsedType, - }); - return INVALID; - } -} -ZodNever.create = (params) => { - return new ZodNever({ - typeName: ZodFirstPartyTypeKind.ZodNever, - ...processCreateParams(params), - }); -}; -class ZodVoid extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.undefined) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.void, - received: ctx.parsedType, - }); - return INVALID; - } - return OK(input.data); - } -} -ZodVoid.create = (params) => { - return new ZodVoid({ - typeName: ZodFirstPartyTypeKind.ZodVoid, - ...processCreateParams(params), - }); -}; -class ZodArray extends ZodType { - _parse(input) { - const { ctx, status } = this._processInputParams(input); - const def = this._def; - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return INVALID; - } - if (def.exactLength !== null) { - const tooBig = ctx.data.length > def.exactLength.value; - const tooSmall = ctx.data.length < def.exactLength.value; - if (tooBig || tooSmall) { - addIssueToContext(ctx, { - code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small, - minimum: (tooSmall ? def.exactLength.value : undefined), - maximum: (tooBig ? def.exactLength.value : undefined), - type: "array", - inclusive: true, - exact: true, - message: def.exactLength.message, - }); - status.dirty(); - } - } - if (def.minLength !== null) { - if (ctx.data.length < def.minLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.minLength.message, - }); - status.dirty(); - } - } - if (def.maxLength !== null) { - if (ctx.data.length > def.maxLength.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxLength.value, - type: "array", - inclusive: true, - exact: false, - message: def.maxLength.message, - }); - status.dirty(); - } - } - if (ctx.common.async) { - return Promise.all([...ctx.data].map((item, i) => { - return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - })).then((result) => { - return ParseStatus.mergeArray(status, result); - }); - } - const result = [...ctx.data].map((item, i) => { - return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i)); - }); - return ParseStatus.mergeArray(status, result); - } - get element() { - return this._def.type; - } - min(minLength, message) { - return new ZodArray({ - ...this._def, - minLength: { value: minLength, message: errorUtil.toString(message) }, - }); - } - max(maxLength, message) { - return new ZodArray({ - ...this._def, - maxLength: { value: maxLength, message: errorUtil.toString(message) }, - }); - } - length(len, message) { - return new ZodArray({ - ...this._def, - exactLength: { value: len, message: errorUtil.toString(message) }, - }); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodArray.create = (schema, params) => { - return new ZodArray({ - type: schema, - minLength: null, - maxLength: null, - exactLength: null, - typeName: ZodFirstPartyTypeKind.ZodArray, - ...processCreateParams(params), - }); -}; -function deepPartialify(schema) { - if (schema instanceof ZodObject) { - const newShape = {}; - for (const key in schema.shape) { - const fieldSchema = schema.shape[key]; - newShape[key] = ZodOptional.create(deepPartialify(fieldSchema)); - } - return new ZodObject({ - ...schema._def, - shape: () => newShape, - }); - } - else if (schema instanceof ZodArray) { - return new ZodArray({ - ...schema._def, - type: deepPartialify(schema.element), - }); - } - else if (schema instanceof ZodOptional) { - return ZodOptional.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodNullable) { - return ZodNullable.create(deepPartialify(schema.unwrap())); - } - else if (schema instanceof ZodTuple) { - return ZodTuple.create(schema.items.map((item) => deepPartialify(item))); - } - else { - return schema; - } -} -class ZodObject extends ZodType { - constructor() { - super(...arguments); - this._cached = null; - /** - * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped. - * If you want to pass through unknown properties, use `.passthrough()` instead. - */ - this.nonstrict = this.passthrough; - // extend< - // Augmentation extends ZodRawShape, - // NewOutput extends util.flatten<{ - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }>, - // NewInput extends util.flatten<{ - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // }> - // >( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, - // UnknownKeys, - // Catchall, - // NewOutput, - // NewInput - // > { - // return new ZodObject({ - // ...this._def, - // shape: () => ({ - // ...this._def.shape(), - // ...augmentation, - // }), - // }) as any; - // } - /** - * @deprecated Use `.extend` instead - * */ - this.augment = this.extend; - } - _getCached() { - if (this._cached !== null) - return this._cached; - const shape = this._def.shape(); - const keys = util.objectKeys(shape); - this._cached = { shape, keys }; - return this._cached; - } - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.object) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - const { status, ctx } = this._processInputParams(input); - const { shape, keys: shapeKeys } = this._getCached(); - const extraKeys = []; - if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === "strip")) { - for (const key in ctx.data) { - if (!shapeKeys.includes(key)) { - extraKeys.push(key); - } - } - } - const pairs = []; - for (const key of shapeKeys) { - const keyValidator = shape[key]; - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (this._def.catchall instanceof ZodNever) { - const unknownKeys = this._def.unknownKeys; - if (unknownKeys === "passthrough") { - for (const key of extraKeys) { - pairs.push({ - key: { status: "valid", value: key }, - value: { status: "valid", value: ctx.data[key] }, - }); - } - } - else if (unknownKeys === "strict") { - if (extraKeys.length > 0) { - addIssueToContext(ctx, { - code: ZodIssueCode.unrecognized_keys, - keys: extraKeys, - }); - status.dirty(); - } - } - else if (unknownKeys === "strip") { - } - else { - throw new Error(`Internal ZodObject error: invalid unknownKeys value.`); - } - } - else { - // run catchall validation - const catchall = this._def.catchall; - for (const key of extraKeys) { - const value = ctx.data[key]; - pairs.push({ - key: { status: "valid", value: key }, - value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value) - ), - alwaysSet: key in ctx.data, - }); - } - } - if (ctx.common.async) { - return Promise.resolve() - .then(async () => { - const syncPairs = []; - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - syncPairs.push({ - key, - value, - alwaysSet: pair.alwaysSet, - }); - } - return syncPairs; - }) - .then((syncPairs) => { - return ParseStatus.mergeObjectSync(status, syncPairs); - }); - } - else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get shape() { - return this._def.shape(); - } - strict(message) { - errorUtil.errToObj; - return new ZodObject({ - ...this._def, - unknownKeys: "strict", - ...(message !== undefined - ? { - errorMap: (issue, ctx) => { - const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError; - if (issue.code === "unrecognized_keys") - return { - message: errorUtil.errToObj(message).message ?? defaultError, - }; - return { - message: defaultError, - }; - }, - } - : {}), - }); - } - strip() { - return new ZodObject({ - ...this._def, - unknownKeys: "strip", - }); - } - passthrough() { - return new ZodObject({ - ...this._def, - unknownKeys: "passthrough", - }); - } - // const AugmentFactory = - // (def: Def) => - // ( - // augmentation: Augmentation - // ): ZodObject< - // extendShape, Augmentation>, - // Def["unknownKeys"], - // Def["catchall"] - // > => { - // return new ZodObject({ - // ...def, - // shape: () => ({ - // ...def.shape(), - // ...augmentation, - // }), - // }) as any; - // }; - extend(augmentation) { - return new ZodObject({ - ...this._def, - shape: () => ({ - ...this._def.shape(), - ...augmentation, - }), - }); - } - /** - * Prior to zod@1.0.12 there was a bug in the - * inferred type of merged objects. Please - * upgrade if you are experiencing issues. - */ - merge(merging) { - const merged = new ZodObject({ - unknownKeys: merging._def.unknownKeys, - catchall: merging._def.catchall, - shape: () => ({ - ...this._def.shape(), - ...merging._def.shape(), - }), - typeName: ZodFirstPartyTypeKind.ZodObject, - }); - return merged; - } - // merge< - // Incoming extends AnyZodObject, - // Augmentation extends Incoming["shape"], - // NewOutput extends { - // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation - // ? Augmentation[k]["_output"] - // : k extends keyof Output - // ? Output[k] - // : never; - // }, - // NewInput extends { - // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation - // ? Augmentation[k]["_input"] - // : k extends keyof Input - // ? Input[k] - // : never; - // } - // >( - // merging: Incoming - // ): ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"], - // NewOutput, - // NewInput - // > { - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - setKey(key, schema) { - return this.augment({ [key]: schema }); - } - // merge( - // merging: Incoming - // ): //ZodObject = (merging) => { - // ZodObject< - // extendShape>, - // Incoming["_def"]["unknownKeys"], - // Incoming["_def"]["catchall"] - // > { - // // const mergedShape = objectUtil.mergeShapes( - // // this._def.shape(), - // // merging._def.shape() - // // ); - // const merged: any = new ZodObject({ - // unknownKeys: merging._def.unknownKeys, - // catchall: merging._def.catchall, - // shape: () => - // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()), - // typeName: ZodFirstPartyTypeKind.ZodObject, - // }) as any; - // return merged; - // } - catchall(index) { - return new ZodObject({ - ...this._def, - catchall: index, - }); - } - pick(mask) { - const shape = {}; - for (const key of util.objectKeys(mask)) { - if (mask[key] && this.shape[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - omit(mask) { - const shape = {}; - for (const key of util.objectKeys(this.shape)) { - if (!mask[key]) { - shape[key] = this.shape[key]; - } - } - return new ZodObject({ - ...this._def, - shape: () => shape, - }); - } - /** - * @deprecated - */ - deepPartial() { - return deepPartialify(this); - } - partial(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - const fieldSchema = this.shape[key]; - if (mask && !mask[key]) { - newShape[key] = fieldSchema; - } - else { - newShape[key] = fieldSchema.optional(); - } - } - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - required(mask) { - const newShape = {}; - for (const key of util.objectKeys(this.shape)) { - if (mask && !mask[key]) { - newShape[key] = this.shape[key]; - } - else { - const fieldSchema = this.shape[key]; - let newField = fieldSchema; - while (newField instanceof ZodOptional) { - newField = newField._def.innerType; - } - newShape[key] = newField; - } - } - return new ZodObject({ - ...this._def, - shape: () => newShape, - }); - } - keyof() { - return createZodEnum(util.objectKeys(this.shape)); - } -} -ZodObject.create = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.strictCreate = (shape, params) => { - return new ZodObject({ - shape: () => shape, - unknownKeys: "strict", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -ZodObject.lazycreate = (shape, params) => { - return new ZodObject({ - shape, - unknownKeys: "strip", - catchall: ZodNever.create(), - typeName: ZodFirstPartyTypeKind.ZodObject, - ...processCreateParams(params), - }); -}; -class ZodUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const options = this._def.options; - function handleResults(results) { - // return first issue-free validation if it exists - for (const result of results) { - if (result.result.status === "valid") { - return result.result; - } - } - for (const result of results) { - if (result.result.status === "dirty") { - // add issues from dirty option - ctx.common.issues.push(...result.ctx.common.issues); - return result.result; - } - } - // return invalid - const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, - }); - return INVALID; - } - if (ctx.common.async) { - return Promise.all(options.map(async (option) => { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - return { - result: await option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }), - ctx: childCtx, - }; - })).then(handleResults); - } - else { - let dirty = undefined; - const issues = []; - for (const option of options) { - const childCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - parent: null, - }; - const result = option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: childCtx, - }); - if (result.status === "valid") { - return result; - } - else if (result.status === "dirty" && !dirty) { - dirty = { result, ctx: childCtx }; - } - if (childCtx.common.issues.length) { - issues.push(childCtx.common.issues); - } - } - if (dirty) { - ctx.common.issues.push(...dirty.ctx.common.issues); - return dirty.result; - } - const unionErrors = issues.map((issues) => new ZodError(issues)); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union, - unionErrors, - }); - return INVALID; - } - } - get options() { - return this._def.options; - } -} -ZodUnion.create = (types, params) => { - return new ZodUnion({ - options: types, - typeName: ZodFirstPartyTypeKind.ZodUnion, - ...processCreateParams(params), - }); -}; -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -////////// ////////// -////////// ZodDiscriminatedUnion ////////// -////////// ////////// -///////////////////////////////////////////////////// -///////////////////////////////////////////////////// -const getDiscriminator = (type) => { - if (type instanceof ZodLazy) { - return getDiscriminator(type.schema); - } - else if (type instanceof ZodEffects) { - return getDiscriminator(type.innerType()); - } - else if (type instanceof ZodLiteral) { - return [type.value]; - } - else if (type instanceof ZodEnum) { - return type.options; - } - else if (type instanceof ZodNativeEnum) { - // eslint-disable-next-line ban/ban - return util.objectValues(type.enum); - } - else if (type instanceof ZodDefault) { - return getDiscriminator(type._def.innerType); - } - else if (type instanceof ZodUndefined) { - return [undefined]; - } - else if (type instanceof ZodNull) { - return [null]; - } - else if (type instanceof ZodOptional) { - return [undefined, ...getDiscriminator(type.unwrap())]; - } - else if (type instanceof ZodNullable) { - return [null, ...getDiscriminator(type.unwrap())]; - } - else if (type instanceof ZodBranded) { - return getDiscriminator(type.unwrap()); - } - else if (type instanceof ZodReadonly) { - return getDiscriminator(type.unwrap()); - } - else if (type instanceof ZodCatch) { - return getDiscriminator(type._def.innerType); - } - else { - return []; - } -}; -class ZodDiscriminatedUnion extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - const discriminator = this.discriminator; - const discriminatorValue = ctx.data[discriminator]; - const option = this.optionsMap.get(discriminatorValue); - if (!option) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_union_discriminator, - options: Array.from(this.optionsMap.keys()), - path: [discriminator], - }); - return INVALID; - } - if (ctx.common.async) { - return option._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - } - else { - return option._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - } - } - get discriminator() { - return this._def.discriminator; - } - get options() { - return this._def.options; - } - get optionsMap() { - return this._def.optionsMap; - } - /** - * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor. - * However, it only allows a union of objects, all of which need to share a discriminator property. This property must - * have a different value for each object in the union. - * @param discriminator the name of the discriminator property - * @param types an array of object schemas - * @param params - */ - static create(discriminator, options, params) { - // Get all the valid discriminator values - const optionsMap = new Map(); - // try { - for (const type of options) { - const discriminatorValues = getDiscriminator(type.shape[discriminator]); - if (!discriminatorValues.length) { - throw new Error(`A discriminator value for key \`${discriminator}\` could not be extracted from all schema options`); - } - for (const value of discriminatorValues) { - if (optionsMap.has(value)) { - throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`); - } - optionsMap.set(value, type); - } - } - return new ZodDiscriminatedUnion({ - typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion, - discriminator, - options, - optionsMap, - ...processCreateParams(params), - }); - } -} -function types_mergeValues(a, b) { - const aType = util_getParsedType(a); - const bType = util_getParsedType(b); - if (a === b) { - return { valid: true, data: a }; - } - else if (aType === ZodParsedType.object && bType === ZodParsedType.object) { - const bKeys = util.objectKeys(b); - const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1); - const newObj = { ...a, ...b }; - for (const key of sharedKeys) { - const sharedValue = types_mergeValues(a[key], b[key]); - if (!sharedValue.valid) { - return { valid: false }; - } - newObj[key] = sharedValue.data; - } - return { valid: true, data: newObj }; - } - else if (aType === ZodParsedType.array && bType === ZodParsedType.array) { - if (a.length !== b.length) { - return { valid: false }; - } - const newArray = []; - for (let index = 0; index < a.length; index++) { - const itemA = a[index]; - const itemB = b[index]; - const sharedValue = types_mergeValues(itemA, itemB); - if (!sharedValue.valid) { - return { valid: false }; - } - newArray.push(sharedValue.data); - } - return { valid: true, data: newArray }; - } - else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) { - return { valid: true, data: a }; - } - else { - return { valid: false }; - } -} -class ZodIntersection extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const handleParsed = (parsedLeft, parsedRight) => { - if (isAborted(parsedLeft) || isAborted(parsedRight)) { - return INVALID; - } - const merged = types_mergeValues(parsedLeft.value, parsedRight.value); - if (!merged.valid) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_intersection_types, - }); - return INVALID; - } - if (isDirty(parsedLeft) || isDirty(parsedRight)) { - status.dirty(); - } - return { status: status.value, value: merged.data }; - }; - if (ctx.common.async) { - return Promise.all([ - this._def.left._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - this._def.right._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), - ]).then(([left, right]) => handleParsed(left, right)); - } - else { - return handleParsed(this._def.left._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }), this._def.right._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - })); - } - } -} -ZodIntersection.create = (left, right, params) => { - return new ZodIntersection({ - left: left, - right: right, - typeName: ZodFirstPartyTypeKind.ZodIntersection, - ...processCreateParams(params), - }); -}; -// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]]; -class ZodTuple extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.array) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.array, - received: ctx.parsedType, - }); - return INVALID; - } - if (ctx.data.length < this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - return INVALID; - } - const rest = this._def.rest; - if (!rest && ctx.data.length > this._def.items.length) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: this._def.items.length, - inclusive: true, - exact: false, - type: "array", - }); - status.dirty(); - } - const items = [...ctx.data] - .map((item, itemIndex) => { - const schema = this._def.items[itemIndex] || this._def.rest; - if (!schema) - return null; - return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex)); - }) - .filter((x) => !!x); // filter nulls - if (ctx.common.async) { - return Promise.all(items).then((results) => { - return ParseStatus.mergeArray(status, results); - }); - } - else { - return ParseStatus.mergeArray(status, items); - } - } - get items() { - return this._def.items; - } - rest(rest) { - return new ZodTuple({ - ...this._def, - rest, - }); - } -} -ZodTuple.create = (schemas, params) => { - if (!Array.isArray(schemas)) { - throw new Error("You must pass an array of schemas to z.tuple([ ... ])"); - } - return new ZodTuple({ - items: schemas, - typeName: ZodFirstPartyTypeKind.ZodTuple, - rest: null, - ...processCreateParams(params), - }); -}; -class ZodRecord extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.object) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.object, - received: ctx.parsedType, - }); - return INVALID; - } - const pairs = []; - const keyType = this._def.keyType; - const valueType = this._def.valueType; - for (const key in ctx.data) { - pairs.push({ - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)), - value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)), - alwaysSet: key in ctx.data, - }); - } - if (ctx.common.async) { - return ParseStatus.mergeObjectAsync(status, pairs); - } - else { - return ParseStatus.mergeObjectSync(status, pairs); - } - } - get element() { - return this._def.valueType; - } - static create(first, second, third) { - if (second instanceof ZodType) { - return new ZodRecord({ - keyType: first, - valueType: second, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(third), - }); - } - return new ZodRecord({ - keyType: ZodString.create(), - valueType: first, - typeName: ZodFirstPartyTypeKind.ZodRecord, - ...processCreateParams(second), - }); - } -} -class ZodMap extends ZodType { - get keySchema() { - return this._def.keyType; - } - get valueSchema() { - return this._def.valueType; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.map) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.map, - received: ctx.parsedType, - }); - return INVALID; - } - const keyType = this._def.keyType; - const valueType = this._def.valueType; - const pairs = [...ctx.data.entries()].map(([key, value], index) => { - return { - key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, "key"])), - value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, "value"])), - }; - }); - if (ctx.common.async) { - const finalMap = new Map(); - return Promise.resolve().then(async () => { - for (const pair of pairs) { - const key = await pair.key; - const value = await pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - }); - } - else { - const finalMap = new Map(); - for (const pair of pairs) { - const key = pair.key; - const value = pair.value; - if (key.status === "aborted" || value.status === "aborted") { - return INVALID; - } - if (key.status === "dirty" || value.status === "dirty") { - status.dirty(); - } - finalMap.set(key.value, value.value); - } - return { status: status.value, value: finalMap }; - } - } -} -ZodMap.create = (keyType, valueType, params) => { - return new ZodMap({ - valueType, - keyType, - typeName: ZodFirstPartyTypeKind.ZodMap, - ...processCreateParams(params), - }); -}; -class ZodSet extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.set) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.set, - received: ctx.parsedType, - }); - return INVALID; - } - const def = this._def; - if (def.minSize !== null) { - if (ctx.data.size < def.minSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_small, - minimum: def.minSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.minSize.message, - }); - status.dirty(); - } - } - if (def.maxSize !== null) { - if (ctx.data.size > def.maxSize.value) { - addIssueToContext(ctx, { - code: ZodIssueCode.too_big, - maximum: def.maxSize.value, - type: "set", - inclusive: true, - exact: false, - message: def.maxSize.message, - }); - status.dirty(); - } - } - const valueType = this._def.valueType; - function finalizeSet(elements) { - const parsedSet = new Set(); - for (const element of elements) { - if (element.status === "aborted") - return INVALID; - if (element.status === "dirty") - status.dirty(); - parsedSet.add(element.value); - } - return { status: status.value, value: parsedSet }; - } - const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i))); - if (ctx.common.async) { - return Promise.all(elements).then((elements) => finalizeSet(elements)); - } - else { - return finalizeSet(elements); - } - } - min(minSize, message) { - return new ZodSet({ - ...this._def, - minSize: { value: minSize, message: errorUtil.toString(message) }, - }); - } - max(maxSize, message) { - return new ZodSet({ - ...this._def, - maxSize: { value: maxSize, message: errorUtil.toString(message) }, - }); - } - size(size, message) { - return this.min(size, message).max(size, message); - } - nonempty(message) { - return this.min(1, message); - } -} -ZodSet.create = (valueType, params) => { - return new ZodSet({ - valueType, - minSize: null, - maxSize: null, - typeName: ZodFirstPartyTypeKind.ZodSet, - ...processCreateParams(params), - }); -}; -class ZodFunction extends ZodType { - constructor() { - super(...arguments); - this.validate = this.implement; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.function) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.function, - received: ctx.parsedType, - }); - return INVALID; - } - function makeArgsIssue(args, error) { - return makeIssue({ - data: args, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), locales_en].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_arguments, - argumentsError: error, - }, - }); - } - function makeReturnsIssue(returns, error) { - return makeIssue({ - data: returns, - path: ctx.path, - errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), locales_en].filter((x) => !!x), - issueData: { - code: ZodIssueCode.invalid_return_type, - returnTypeError: error, - }, - }); - } - const params = { errorMap: ctx.common.contextualErrorMap }; - const fn = ctx.data; - if (this._def.returns instanceof ZodPromise) { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(async function (...args) { - const error = new ZodError([]); - const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => { - error.addIssue(makeArgsIssue(args, e)); - throw error; - }); - const result = await Reflect.apply(fn, this, parsedArgs); - const parsedReturns = await me._def.returns._def.type - .parseAsync(result, params) - .catch((e) => { - error.addIssue(makeReturnsIssue(result, e)); - throw error; - }); - return parsedReturns; - }); - } - else { - // Would love a way to avoid disabling this rule, but we need - // an alias (using an arrow function was what caused 2651). - // eslint-disable-next-line @typescript-eslint/no-this-alias - const me = this; - return OK(function (...args) { - const parsedArgs = me._def.args.safeParse(args, params); - if (!parsedArgs.success) { - throw new ZodError([makeArgsIssue(args, parsedArgs.error)]); - } - const result = Reflect.apply(fn, this, parsedArgs.data); - const parsedReturns = me._def.returns.safeParse(result, params); - if (!parsedReturns.success) { - throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]); - } - return parsedReturns.data; - }); - } - } - parameters() { - return this._def.args; - } - returnType() { - return this._def.returns; - } - args(...items) { - return new ZodFunction({ - ...this._def, - args: ZodTuple.create(items).rest(ZodUnknown.create()), - }); - } - returns(returnType) { - return new ZodFunction({ - ...this._def, - returns: returnType, - }); - } - implement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - strictImplement(func) { - const validatedFunc = this.parse(func); - return validatedFunc; - } - static create(args, returns, params) { - return new ZodFunction({ - args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())), - returns: returns || ZodUnknown.create(), - typeName: ZodFirstPartyTypeKind.ZodFunction, - ...processCreateParams(params), - }); - } -} -class ZodLazy extends ZodType { - get schema() { - return this._def.getter(); - } - _parse(input) { - const { ctx } = this._processInputParams(input); - const lazySchema = this._def.getter(); - return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx }); - } -} -ZodLazy.create = (getter, params) => { - return new ZodLazy({ - getter: getter, - typeName: ZodFirstPartyTypeKind.ZodLazy, - ...processCreateParams(params), - }); -}; -class ZodLiteral extends ZodType { - _parse(input) { - if (input.data !== this._def.value) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_literal, - expected: this._def.value, - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } - get value() { - return this._def.value; - } -} -ZodLiteral.create = (value, params) => { - return new ZodLiteral({ - value: value, - typeName: ZodFirstPartyTypeKind.ZodLiteral, - ...processCreateParams(params), - }); -}; -function createZodEnum(values, params) { - return new ZodEnum({ - values, - typeName: ZodFirstPartyTypeKind.ZodEnum, - ...processCreateParams(params), - }); -} -class ZodEnum extends ZodType { - _parse(input) { - if (typeof input.data !== "string") { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(this._def.values); - } - if (!this._cache.has(input.data)) { - const ctx = this._getOrReturnCtx(input); - const expectedValues = this._def.values; - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return INVALID; - } - return OK(input.data); - } - get options() { - return this._def.values; - } - get enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Values() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - get Enum() { - const enumValues = {}; - for (const val of this._def.values) { - enumValues[val] = val; - } - return enumValues; - } - extract(values, newDef = this._def) { - return ZodEnum.create(values, { - ...this._def, - ...newDef, - }); - } - exclude(values, newDef = this._def) { - return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), { - ...this._def, - ...newDef, - }); - } -} -ZodEnum.create = createZodEnum; -class ZodNativeEnum extends ZodType { - _parse(input) { - const nativeEnumValues = util.getValidEnumValues(this._def.values); - const ctx = this._getOrReturnCtx(input); - if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - expected: util.joinValues(expectedValues), - received: ctx.parsedType, - code: ZodIssueCode.invalid_type, - }); - return INVALID; - } - if (!this._cache) { - this._cache = new Set(util.getValidEnumValues(this._def.values)); - } - if (!this._cache.has(input.data)) { - const expectedValues = util.objectValues(nativeEnumValues); - addIssueToContext(ctx, { - received: ctx.data, - code: ZodIssueCode.invalid_enum_value, - options: expectedValues, - }); - return INVALID; - } - return OK(input.data); - } - get enum() { - return this._def.values; - } -} -ZodNativeEnum.create = (values, params) => { - return new ZodNativeEnum({ - values: values, - typeName: ZodFirstPartyTypeKind.ZodNativeEnum, - ...processCreateParams(params), - }); -}; -class ZodPromise extends ZodType { - unwrap() { - return this._def.type; - } - _parse(input) { - const { ctx } = this._processInputParams(input); - if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) { - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.promise, - received: ctx.parsedType, - }); - return INVALID; - } - const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data); - return OK(promisified.then((data) => { - return this._def.type.parseAsync(data, { - path: ctx.path, - errorMap: ctx.common.contextualErrorMap, - }); - })); - } -} -ZodPromise.create = (schema, params) => { - return new ZodPromise({ - type: schema, - typeName: ZodFirstPartyTypeKind.ZodPromise, - ...processCreateParams(params), - }); -}; -class ZodEffects extends ZodType { - innerType() { - return this._def.schema; - } - sourceType() { - return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects - ? this._def.schema.sourceType() - : this._def.schema; - } - _parse(input) { - const { status, ctx } = this._processInputParams(input); - const effect = this._def.effect || null; - const checkCtx = { - addIssue: (arg) => { - addIssueToContext(ctx, arg); - if (arg.fatal) { - status.abort(); - } - else { - status.dirty(); - } - }, - get path() { - return ctx.path; - }, - }; - checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx); - if (effect.type === "preprocess") { - const processed = effect.transform(ctx.data, checkCtx); - if (ctx.common.async) { - return Promise.resolve(processed).then(async (processed) => { - if (status.value === "aborted") - return INVALID; - const result = await this._def.schema._parseAsync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - }); - } - else { - if (status.value === "aborted") - return INVALID; - const result = this._def.schema._parseSync({ - data: processed, - path: ctx.path, - parent: ctx, - }); - if (result.status === "aborted") - return INVALID; - if (result.status === "dirty") - return DIRTY(result.value); - if (status.value === "dirty") - return DIRTY(result.value); - return result; - } - } - if (effect.type === "refinement") { - const executeRefinement = (acc) => { - const result = effect.refinement(acc, checkCtx); - if (ctx.common.async) { - return Promise.resolve(result); - } - if (result instanceof Promise) { - throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead."); - } - return acc; - }; - if (ctx.common.async === false) { - const inner = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - // return value is ignored - executeRefinement(inner.value); - return { status: status.value, value: inner.value }; - } - else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => { - if (inner.status === "aborted") - return INVALID; - if (inner.status === "dirty") - status.dirty(); - return executeRefinement(inner.value).then(() => { - return { status: status.value, value: inner.value }; - }); - }); - } - } - if (effect.type === "transform") { - if (ctx.common.async === false) { - const base = this._def.schema._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (!isValid(base)) - return INVALID; - const result = effect.transform(base.value, checkCtx); - if (result instanceof Promise) { - throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`); - } - return { status: status.value, value: result }; - } - else { - return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => { - if (!isValid(base)) - return INVALID; - return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({ - status: status.value, - value: result, - })); - }); - } - } - util.assertNever(effect); - } -} -ZodEffects.create = (schema, effect, params) => { - return new ZodEffects({ - schema, - typeName: ZodFirstPartyTypeKind.ZodEffects, - effect, - ...processCreateParams(params), - }); -}; -ZodEffects.createWithPreprocess = (preprocess, schema, params) => { - return new ZodEffects({ - schema, - effect: { type: "preprocess", transform: preprocess }, - typeName: ZodFirstPartyTypeKind.ZodEffects, - ...processCreateParams(params), - }); -}; - -class ZodOptional extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.undefined) { - return OK(undefined); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodOptional.create = (type, params) => { - return new ZodOptional({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodOptional, - ...processCreateParams(params), - }); -}; -class ZodNullable extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType === ZodParsedType.null) { - return OK(null); - } - return this._def.innerType._parse(input); - } - unwrap() { - return this._def.innerType; - } -} -ZodNullable.create = (type, params) => { - return new ZodNullable({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodNullable, - ...processCreateParams(params), - }); -}; -class ZodDefault extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - let data = ctx.data; - if (ctx.parsedType === ZodParsedType.undefined) { - data = this._def.defaultValue(); - } - return this._def.innerType._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - removeDefault() { - return this._def.innerType; - } -} -ZodDefault.create = (type, params) => { - return new ZodDefault({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodDefault, - defaultValue: typeof params.default === "function" ? params.default : () => params.default, - ...processCreateParams(params), - }); -}; -class ZodCatch extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - // newCtx is used to not collect issues from inner types in ctx - const newCtx = { - ...ctx, - common: { - ...ctx.common, - issues: [], - }, - }; - const result = this._def.innerType._parse({ - data: newCtx.data, - path: newCtx.path, - parent: { - ...newCtx, - }, - }); - if (isAsync(result)) { - return result.then((result) => { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - }); - } - else { - return { - status: "valid", - value: result.status === "valid" - ? result.value - : this._def.catchValue({ - get error() { - return new ZodError(newCtx.common.issues); - }, - input: newCtx.data, - }), - }; - } - } - removeCatch() { - return this._def.innerType; - } -} -ZodCatch.create = (type, params) => { - return new ZodCatch({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodCatch, - catchValue: typeof params.catch === "function" ? params.catch : () => params.catch, - ...processCreateParams(params), - }); -}; -class ZodNaN extends ZodType { - _parse(input) { - const parsedType = this._getType(input); - if (parsedType !== ZodParsedType.nan) { - const ctx = this._getOrReturnCtx(input); - addIssueToContext(ctx, { - code: ZodIssueCode.invalid_type, - expected: ZodParsedType.nan, - received: ctx.parsedType, - }); - return INVALID; - } - return { status: "valid", value: input.data }; - } -} -ZodNaN.create = (params) => { - return new ZodNaN({ - typeName: ZodFirstPartyTypeKind.ZodNaN, - ...processCreateParams(params), - }); -}; -const BRAND = Symbol("zod_brand"); -class ZodBranded extends ZodType { - _parse(input) { - const { ctx } = this._processInputParams(input); - const data = ctx.data; - return this._def.type._parse({ - data, - path: ctx.path, - parent: ctx, - }); - } - unwrap() { - return this._def.type; - } -} -class ZodPipeline extends ZodType { - _parse(input) { - const { status, ctx } = this._processInputParams(input); - if (ctx.common.async) { - const handleAsync = async () => { - const inResult = await this._def.in._parseAsync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return DIRTY(inResult.value); - } - else { - return this._def.out._parseAsync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - }; - return handleAsync(); - } - else { - const inResult = this._def.in._parseSync({ - data: ctx.data, - path: ctx.path, - parent: ctx, - }); - if (inResult.status === "aborted") - return INVALID; - if (inResult.status === "dirty") { - status.dirty(); - return { - status: "dirty", - value: inResult.value, - }; - } - else { - return this._def.out._parseSync({ - data: inResult.value, - path: ctx.path, - parent: ctx, - }); - } - } - } - static create(a, b) { - return new ZodPipeline({ - in: a, - out: b, - typeName: ZodFirstPartyTypeKind.ZodPipeline, - }); - } -} -class ZodReadonly extends ZodType { - _parse(input) { - const result = this._def.innerType._parse(input); - const freeze = (data) => { - if (isValid(data)) { - data.value = Object.freeze(data.value); - } - return data; - }; - return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result); - } - unwrap() { - return this._def.innerType; - } -} -ZodReadonly.create = (type, params) => { - return new ZodReadonly({ - innerType: type, - typeName: ZodFirstPartyTypeKind.ZodReadonly, - ...processCreateParams(params), - }); -}; -//////////////////////////////////////// -//////////////////////////////////////// -////////// ////////// -////////// z.custom ////////// -////////// ////////// -//////////////////////////////////////// -//////////////////////////////////////// -function cleanParams(params, data) { - const p = typeof params === "function" ? params(data) : typeof params === "string" ? { message: params } : params; - const p2 = typeof p === "string" ? { message: p } : p; - return p2; -} -function custom(check, _params = {}, -/** - * @deprecated - * - * Pass `fatal` into the params object instead: - * - * ```ts - * z.string().custom((val) => val.length > 5, { fatal: false }) - * ``` - * - */ -fatal) { - if (check) - return ZodAny.create().superRefine((data, ctx) => { - const r = check(data); - if (r instanceof Promise) { - return r.then((r) => { - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - }); - } - if (!r) { - const params = cleanParams(_params, data); - const _fatal = params.fatal ?? fatal ?? true; - ctx.addIssue({ code: "custom", ...params, fatal: _fatal }); - } - return; - }); - return ZodAny.create(); -} - -const late = { - object: ZodObject.lazycreate, -}; -var ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { - ZodFirstPartyTypeKind["ZodString"] = "ZodString"; - ZodFirstPartyTypeKind["ZodNumber"] = "ZodNumber"; - ZodFirstPartyTypeKind["ZodNaN"] = "ZodNaN"; - ZodFirstPartyTypeKind["ZodBigInt"] = "ZodBigInt"; - ZodFirstPartyTypeKind["ZodBoolean"] = "ZodBoolean"; - ZodFirstPartyTypeKind["ZodDate"] = "ZodDate"; - ZodFirstPartyTypeKind["ZodSymbol"] = "ZodSymbol"; - ZodFirstPartyTypeKind["ZodUndefined"] = "ZodUndefined"; - ZodFirstPartyTypeKind["ZodNull"] = "ZodNull"; - ZodFirstPartyTypeKind["ZodAny"] = "ZodAny"; - ZodFirstPartyTypeKind["ZodUnknown"] = "ZodUnknown"; - ZodFirstPartyTypeKind["ZodNever"] = "ZodNever"; - ZodFirstPartyTypeKind["ZodVoid"] = "ZodVoid"; - ZodFirstPartyTypeKind["ZodArray"] = "ZodArray"; - ZodFirstPartyTypeKind["ZodObject"] = "ZodObject"; - ZodFirstPartyTypeKind["ZodUnion"] = "ZodUnion"; - ZodFirstPartyTypeKind["ZodDiscriminatedUnion"] = "ZodDiscriminatedUnion"; - ZodFirstPartyTypeKind["ZodIntersection"] = "ZodIntersection"; - ZodFirstPartyTypeKind["ZodTuple"] = "ZodTuple"; - ZodFirstPartyTypeKind["ZodRecord"] = "ZodRecord"; - ZodFirstPartyTypeKind["ZodMap"] = "ZodMap"; - ZodFirstPartyTypeKind["ZodSet"] = "ZodSet"; - ZodFirstPartyTypeKind["ZodFunction"] = "ZodFunction"; - ZodFirstPartyTypeKind["ZodLazy"] = "ZodLazy"; - ZodFirstPartyTypeKind["ZodLiteral"] = "ZodLiteral"; - ZodFirstPartyTypeKind["ZodEnum"] = "ZodEnum"; - ZodFirstPartyTypeKind["ZodEffects"] = "ZodEffects"; - ZodFirstPartyTypeKind["ZodNativeEnum"] = "ZodNativeEnum"; - ZodFirstPartyTypeKind["ZodOptional"] = "ZodOptional"; - ZodFirstPartyTypeKind["ZodNullable"] = "ZodNullable"; - ZodFirstPartyTypeKind["ZodDefault"] = "ZodDefault"; - ZodFirstPartyTypeKind["ZodCatch"] = "ZodCatch"; - ZodFirstPartyTypeKind["ZodPromise"] = "ZodPromise"; - ZodFirstPartyTypeKind["ZodBranded"] = "ZodBranded"; - ZodFirstPartyTypeKind["ZodPipeline"] = "ZodPipeline"; - ZodFirstPartyTypeKind["ZodReadonly"] = "ZodReadonly"; -})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {})); -// requires TS 4.4+ -class types_Class { - constructor(..._) { } -} -const instanceOfType = ( -// const instanceOfType = any>( -cls, params = { - message: `Input not instance of ${cls.name}`, -}) => custom((data) => data instanceof cls, params); -const stringType = ZodString.create; -const numberType = ZodNumber.create; -const nanType = ZodNaN.create; -const bigIntType = ZodBigInt.create; -const booleanType = ZodBoolean.create; -const dateType = ZodDate.create; -const symbolType = ZodSymbol.create; -const undefinedType = ZodUndefined.create; -const nullType = ZodNull.create; -const anyType = ZodAny.create; -const unknownType = ZodUnknown.create; -const neverType = ZodNever.create; -const voidType = ZodVoid.create; -const arrayType = ZodArray.create; -const objectType = ZodObject.create; -const strictObjectType = ZodObject.strictCreate; -const unionType = ZodUnion.create; -const discriminatedUnionType = ZodDiscriminatedUnion.create; -const intersectionType = ZodIntersection.create; -const tupleType = ZodTuple.create; -const recordType = ZodRecord.create; -const mapType = ZodMap.create; -const setType = ZodSet.create; -const functionType = ZodFunction.create; -const lazyType = ZodLazy.create; -const literalType = ZodLiteral.create; -const enumType = ZodEnum.create; -const nativeEnumType = ZodNativeEnum.create; -const promiseType = ZodPromise.create; -const effectsType = ZodEffects.create; -const optionalType = ZodOptional.create; -const nullableType = ZodNullable.create; -const preprocessType = ZodEffects.createWithPreprocess; -const pipelineType = ZodPipeline.create; -const ostring = () => stringType().optional(); -const onumber = () => numberType().optional(); -const oboolean = () => booleanType().optional(); -const coerce = { - string: ((arg) => ZodString.create({ ...arg, coerce: true })), - number: ((arg) => ZodNumber.create({ ...arg, coerce: true })), - boolean: ((arg) => ZodBoolean.create({ - ...arg, - coerce: true, - })), - bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })), - date: ((arg) => ZodDate.create({ ...arg, coerce: true })), -}; - -const types_NEVER = INVALID; - -;// CONCATENATED MODULE: ./node_modules/zod/v3/external.js - - - - - - - -;// CONCATENATED MODULE: ./node_modules/zod/v3/index.js - - - -/* harmony default export */ const zod_v3 = ((/* unused pure expression or super */ null && (z))); - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/array.js - - - - -//#region src/utils/zod-to-json-schema/parsers/array.ts -function parseArrayDef(def, refs) { - const res = { type: "array" }; - if (def.type?._def && def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) res.items = parseDef(def.type._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }); - if (def.minLength) setResponseValueAndErrors(res, "minItems", def.minLength.value, def.minLength.message, refs); - if (def.maxLength) setResponseValueAndErrors(res, "maxItems", def.maxLength.value, def.maxLength.message, refs); - if (def.exactLength) { - setResponseValueAndErrors(res, "minItems", def.exactLength.value, def.exactLength.message, refs); - setResponseValueAndErrors(res, "maxItems", def.exactLength.value, def.exactLength.message, refs); - } - return res; -} - -//#endregion - -//# sourceMappingURL=array.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/bigint.js - - -//#region src/utils/zod-to-json-schema/parsers/bigint.ts -function parseBigintDef(def, refs) { - const res = { - type: "integer", - format: "int64" - }; - if (!def.checks) return res; - for (const check of def.checks) switch (check.kind) { - case "min": - if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - else setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); - else { - if (!check.inclusive) res.exclusiveMinimum = true; - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - else setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); - else { - if (!check.inclusive) res.exclusiveMaximum = true; - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); - break; - } - return res; -} - -//#endregion - -//# sourceMappingURL=bigint.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/boolean.js -//#region src/utils/zod-to-json-schema/parsers/boolean.ts -function parseBooleanDef() { - return { type: "boolean" }; -} - -//#endregion - -//# sourceMappingURL=boolean.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/branded.js - - -//#region src/utils/zod-to-json-schema/parsers/branded.ts -function parseBrandedDef(_def, refs) { - return parseDef(_def.type._def, refs); -} - -//#endregion - -//# sourceMappingURL=branded.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/catch.js - - -//#region src/utils/zod-to-json-schema/parsers/catch.ts -const parseCatchDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; - -//#endregion - -//# sourceMappingURL=catch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/date.js - - -//#region src/utils/zod-to-json-schema/parsers/date.ts -function parseDateDef(def, refs, overrideDateStrategy) { - const strategy = overrideDateStrategy ?? refs.dateStrategy; - if (Array.isArray(strategy)) return { anyOf: strategy.map((item) => parseDateDef(def, refs, item)) }; - switch (strategy) { - case "string": - case "format:date-time": return { - type: "string", - format: "date-time" - }; - case "format:date": return { - type: "string", - format: "date" - }; - case "integer": return integerDateParser(def, refs); - } -} -const integerDateParser = (def, refs) => { - const res = { - type: "integer", - format: "unix-time" - }; - if (refs.target === "openApi3") return res; - for (const check of def.checks) switch (check.kind) { - case "min": - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - break; - } - return res; -}; - -//#endregion - -//# sourceMappingURL=date.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/default.js - - -//#region src/utils/zod-to-json-schema/parsers/default.ts -function parseDefaultDef(_def, refs) { - return { - ...parseDef(_def.innerType._def, refs), - default: _def.defaultValue() - }; -} - -//#endregion - -//# sourceMappingURL=default.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/effects.js - - - -//#region src/utils/zod-to-json-schema/parsers/effects.ts -function parseEffectsDef(_def, refs) { - return refs.effectStrategy === "input" ? parseDef(_def.schema._def, refs) : parseAnyDef(refs); -} - -//#endregion - -//# sourceMappingURL=effects.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/enum.js -//#region src/utils/zod-to-json-schema/parsers/enum.ts -function parseEnumDef(def) { - return { - type: "string", - enum: Array.from(def.values) - }; -} - -//#endregion - -//# sourceMappingURL=enum.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/intersection.js - - -//#region src/utils/zod-to-json-schema/parsers/intersection.ts -const isJsonSchema7AllOfType = (type) => { - if ("type" in type && type.type === "string") return false; - return "allOf" in type; -}; -function parseIntersectionDef(def, refs) { - const allOf = [parseDef(def.left._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - "0" - ] - }), parseDef(def.right._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - "1" - ] - })].filter((x) => !!x); - let unevaluatedProperties = refs.target === "jsonSchema2019-09" ? { unevaluatedProperties: false } : void 0; - const mergedAllOf = []; - allOf.forEach((schema) => { - if (isJsonSchema7AllOfType(schema)) { - mergedAllOf.push(...schema.allOf); - if (schema.unevaluatedProperties === void 0) unevaluatedProperties = void 0; - } else { - let nestedSchema = schema; - if ("additionalProperties" in schema && schema.additionalProperties === false) { - const { additionalProperties,...rest } = schema; - nestedSchema = rest; - } else unevaluatedProperties = void 0; - mergedAllOf.push(nestedSchema); - } - }); - return mergedAllOf.length ? { - allOf: mergedAllOf, - ...unevaluatedProperties - } : void 0; -} - -//#endregion - -//# sourceMappingURL=intersection.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/literal.js -//#region src/utils/zod-to-json-schema/parsers/literal.ts -function parseLiteralDef(def, refs) { - const parsedType = typeof def.value; - if (parsedType !== "bigint" && parsedType !== "number" && parsedType !== "boolean" && parsedType !== "string") return { type: Array.isArray(def.value) ? "array" : "object" }; - if (refs.target === "openApi3") return { - type: parsedType === "bigint" ? "integer" : parsedType, - enum: [def.value] - }; - return { - type: parsedType === "bigint" ? "integer" : parsedType, - const: def.value - }; -} - -//#endregion - -//# sourceMappingURL=literal.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/string.js - - -//#region src/utils/zod-to-json-schema/parsers/string.ts -let string_emojiRegex = void 0; -/** -* Generated from the regular expressions found here as of 2024-05-22: -* https://github.com/colinhacks/zod/blob/master/src/types.ts. -* -* Expressions with /i flag have been changed accordingly. -*/ -const zodPatterns = { - cuid: /^[cC][^\s-]{8,}$/, - cuid2: /^[0-9a-z]+$/, - ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, - email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, - emoji: () => { - if (string_emojiRegex === void 0) string_emojiRegex = RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$", "u"); - return string_emojiRegex; - }, - uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, - ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, - ipv4Cidr: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/, - ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, - ipv6Cidr: /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/, - base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, - base64url: /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/, - nanoid: /^[a-zA-Z0-9_-]{21}$/, - jwt: /^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/ -}; -function parseStringDef(def, refs) { - const res = { type: "string" }; - if (def.checks) for (const check of def.checks) switch (check.kind) { - case "min": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - break; - case "max": - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case "email": - switch (refs.emailStrategy) { - case "format:email": - addFormat(res, "email", check.message, refs); - break; - case "format:idn-email": - addFormat(res, "idn-email", check.message, refs); - break; - case "pattern:zod": - addPattern(res, zodPatterns.email, check.message, refs); - break; - } - break; - case "url": - addFormat(res, "uri", check.message, refs); - break; - case "uuid": - addFormat(res, "uuid", check.message, refs); - break; - case "regex": - addPattern(res, check.regex, check.message, refs); - break; - case "cuid": - addPattern(res, zodPatterns.cuid, check.message, refs); - break; - case "cuid2": - addPattern(res, zodPatterns.cuid2, check.message, refs); - break; - case "startsWith": - addPattern(res, RegExp(`^${escapeLiteralCheckValue(check.value, refs)}`), check.message, refs); - break; - case "endsWith": - addPattern(res, RegExp(`${escapeLiteralCheckValue(check.value, refs)}$`), check.message, refs); - break; - case "datetime": - addFormat(res, "date-time", check.message, refs); - break; - case "date": - addFormat(res, "date", check.message, refs); - break; - case "time": - addFormat(res, "time", check.message, refs); - break; - case "duration": - addFormat(res, "duration", check.message, refs); - break; - case "length": - setResponseValueAndErrors(res, "minLength", typeof res.minLength === "number" ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - setResponseValueAndErrors(res, "maxLength", typeof res.maxLength === "number" ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case "includes": - addPattern(res, RegExp(escapeLiteralCheckValue(check.value, refs)), check.message, refs); - break; - case "ip": - if (check.version !== "v6") addFormat(res, "ipv4", check.message, refs); - if (check.version !== "v4") addFormat(res, "ipv6", check.message, refs); - break; - case "base64url": - addPattern(res, zodPatterns.base64url, check.message, refs); - break; - case "jwt": - addPattern(res, zodPatterns.jwt, check.message, refs); - break; - case "cidr": - if (check.version !== "v6") addPattern(res, zodPatterns.ipv4Cidr, check.message, refs); - if (check.version !== "v4") addPattern(res, zodPatterns.ipv6Cidr, check.message, refs); - break; - case "emoji": - addPattern(res, zodPatterns.emoji(), check.message, refs); - break; - case "ulid": - addPattern(res, zodPatterns.ulid, check.message, refs); - break; - case "base64": - switch (refs.base64Strategy) { - case "format:binary": - addFormat(res, "binary", check.message, refs); - break; - case "contentEncoding:base64": - setResponseValueAndErrors(res, "contentEncoding", "base64", check.message, refs); - break; - case "pattern:zod": - addPattern(res, zodPatterns.base64, check.message, refs); - break; - } - break; - case "nanoid": - addPattern(res, zodPatterns.nanoid, check.message, refs); - break; - case "toLowerCase": - case "toUpperCase": - case "trim": break; - default: - /* c8 ignore next */ - ((_) => {})(check); - } - return res; -} -function escapeLiteralCheckValue(literal, refs) { - return refs.patternStrategy === "escape" ? escapeNonAlphaNumeric(literal) : literal; -} -const ALPHA_NUMERIC = /* @__PURE__ */ new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789"); -function escapeNonAlphaNumeric(source) { - let result = ""; - for (let i = 0; i < source.length; i++) { - if (!ALPHA_NUMERIC.has(source[i])) result += "\\"; - result += source[i]; - } - return result; -} -function addFormat(schema, value, message, refs) { - if (schema.format || schema.anyOf?.some((x) => x.format)) { - if (!schema.anyOf) schema.anyOf = []; - if (schema.format) { - schema.anyOf.push({ - format: schema.format, - ...schema.errorMessage && refs.errorMessages && { errorMessage: { format: schema.errorMessage.format } } - }); - delete schema.format; - if (schema.errorMessage) { - delete schema.errorMessage.format; - if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage; - } - } - schema.anyOf.push({ - format: value, - ...message && refs.errorMessages && { errorMessage: { format: message } } - }); - } else setResponseValueAndErrors(schema, "format", value, message, refs); -} -function addPattern(schema, regex, message, refs) { - if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { - if (!schema.allOf) schema.allOf = []; - if (schema.pattern) { - schema.allOf.push({ - pattern: schema.pattern, - ...schema.errorMessage && refs.errorMessages && { errorMessage: { pattern: schema.errorMessage.pattern } } - }); - delete schema.pattern; - if (schema.errorMessage) { - delete schema.errorMessage.pattern; - if (Object.keys(schema.errorMessage).length === 0) delete schema.errorMessage; - } - } - schema.allOf.push({ - pattern: stringifyRegExpWithFlags(regex, refs), - ...message && refs.errorMessages && { errorMessage: { pattern: message } } - }); - } else setResponseValueAndErrors(schema, "pattern", stringifyRegExpWithFlags(regex, refs), message, refs); -} -function stringifyRegExpWithFlags(regex, refs) { - if (!refs.applyRegexFlags || !regex.flags) return regex.source; - const flags = { - i: regex.flags.includes("i"), - m: regex.flags.includes("m"), - s: regex.flags.includes("s") - }; - const source = flags.i ? regex.source.toLowerCase() : regex.source; - let pattern = ""; - let isEscaped = false; - let inCharGroup = false; - let inCharRange = false; - for (let i = 0; i < source.length; i++) { - if (isEscaped) { - pattern += source[i]; - isEscaped = false; - continue; - } - if (flags.i) { - if (inCharGroup) { - if (source[i].match(/[a-z]/)) { - if (inCharRange) { - pattern += source[i]; - pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); - inCharRange = false; - } else if (source[i + 1] === "-" && source[i + 2]?.match(/[a-z]/)) { - pattern += source[i]; - inCharRange = true; - } else pattern += `${source[i]}${source[i].toUpperCase()}`; - continue; - } - } else if (source[i].match(/[a-z]/)) { - pattern += `[${source[i]}${source[i].toUpperCase()}]`; - continue; - } - } - if (flags.m) { - if (source[i] === "^") { - pattern += `(^|(?<=[\r\n]))`; - continue; - } else if (source[i] === "$") { - pattern += `($|(?=[\r\n]))`; - continue; - } - } - if (flags.s && source[i] === ".") { - pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; - continue; - } - pattern += source[i]; - if (source[i] === "\\") isEscaped = true; - else if (inCharGroup && source[i] === "]") inCharGroup = false; - else if (!inCharGroup && source[i] === "[") inCharGroup = true; - } - try { - new RegExp(pattern); - } catch { - console.warn(`Could not convert regex pattern at ${refs.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`); - return regex.source; - } - return pattern; -} - -//#endregion - -//# sourceMappingURL=string.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/record.js - - - - - - -//#region src/utils/zod-to-json-schema/parsers/record.ts -function parseRecordDef(def, refs) { - if (refs.target === "openAi") console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."); - if (refs.target === "openApi3" && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return { - type: "object", - required: def.keyType._def.values, - properties: def.keyType._def.values.reduce((acc, key) => ({ - ...acc, - [key]: parseDef(def.valueType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "properties", - key - ] - }) ?? parseAnyDef(refs) - }), {}), - additionalProperties: refs.rejectedAdditionalProperties - }; - const schema = { - type: "object", - additionalProperties: parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }) ?? refs.allowedAdditionalProperties - }; - if (refs.target === "openApi3") return schema; - if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { - const { type,...keyType } = parseStringDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType - }; - } else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) return { - ...schema, - propertyNames: { enum: def.keyType._def.values } - }; - else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodBranded && def.keyType._def.type._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.type._def.checks?.length) { - const { type,...keyType } = parseBrandedDef(def.keyType._def, refs); - return { - ...schema, - propertyNames: keyType - }; - } - return schema; -} - -//#endregion - -//# sourceMappingURL=record.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/map.js - - - - -//#region src/utils/zod-to-json-schema/parsers/map.ts -function parseMapDef(def, refs) { - if (refs.mapStrategy === "record") return parseRecordDef(def, refs); - const keys = parseDef(def.keyType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - "items", - "0" - ] - }) || parseAnyDef(refs); - const values = parseDef(def.valueType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - "items", - "1" - ] - }) || parseAnyDef(refs); - return { - type: "array", - maxItems: 125, - items: { - type: "array", - items: [keys, values], - minItems: 2, - maxItems: 2 - } - }; -} - -//#endregion - -//# sourceMappingURL=map.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nativeEnum.js -//#region src/utils/zod-to-json-schema/parsers/nativeEnum.ts -function parseNativeEnumDef(def) { - const object = def.values; - const actualKeys = Object.keys(def.values).filter((key) => { - return typeof object[object[key]] !== "number"; - }); - const actualValues = actualKeys.map((key) => object[key]); - const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); - return { - type: parsedTypes.length === 1 ? parsedTypes[0] === "string" ? "string" : "number" : ["string", "number"], - enum: actualValues - }; -} - -//#endregion - -//# sourceMappingURL=nativeEnum.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/never.js - - -//#region src/utils/zod-to-json-schema/parsers/never.ts -function parseNeverDef(refs) { - return refs.target === "openAi" ? void 0 : { not: parseAnyDef({ - ...refs, - currentPath: [...refs.currentPath, "not"] - }) }; -} - -//#endregion - -//# sourceMappingURL=never.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/null.js -//#region src/utils/zod-to-json-schema/parsers/null.ts -function parseNullDef(refs) { - return refs.target === "openApi3" ? { - enum: ["null"], - nullable: true - } : { type: "null" }; -} - -//#endregion - -//# sourceMappingURL=null.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/union.js - - -//#region src/utils/zod-to-json-schema/parsers/union.ts -const primitiveMappings = { - ZodString: "string", - ZodNumber: "number", - ZodBigInt: "integer", - ZodBoolean: "boolean", - ZodNull: "null" -}; -function parseUnionDef(def, refs) { - if (refs.target === "openApi3") return asAnyOf(def, refs); - const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; - if (options.every((x) => x._def.typeName in primitiveMappings && (!x._def.checks || !x._def.checks.length))) { - const types = options.reduce((types$1, x) => { - const type = primitiveMappings[x._def.typeName]; - return type && !types$1.includes(type) ? [...types$1, type] : types$1; - }, []); - return { type: types.length > 1 ? types : types[0] }; - } else if (options.every((x) => x._def.typeName === "ZodLiteral" && !x.description)) { - const types = options.reduce((acc, x) => { - const type = typeof x._def.value; - switch (type) { - case "string": - case "number": - case "boolean": return [...acc, type]; - case "bigint": return [...acc, "integer"]; - case "object": - if (x._def.value === null) return [...acc, "null"]; - return acc; - case "symbol": - case "undefined": - case "function": - default: return acc; - } - }, []); - if (types.length === options.length) { - const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); - return { - type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], - enum: options.reduce((acc, x) => { - return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; - }, []) - }; - } - } else if (options.every((x) => x._def.typeName === "ZodEnum")) return { - type: "string", - enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x$1) => !acc.includes(x$1))], []) - }; - return asAnyOf(def, refs); -} -const asAnyOf = (def, refs) => { - const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options).map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "anyOf", - `${i}` - ] - })).filter((x) => !!x && (!refs.strictUnions || typeof x === "object" && Object.keys(x).length > 0)); - return anyOf.length ? { anyOf } : void 0; -}; - -//#endregion - -//# sourceMappingURL=union.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/nullable.js - - - -//#region src/utils/zod-to-json-schema/parsers/nullable.ts -function parseNullableDef(def, refs) { - if ([ - "ZodString", - "ZodNumber", - "ZodBigInt", - "ZodBoolean", - "ZodNull" - ].includes(def.innerType._def.typeName) && (!def.innerType._def.checks || !def.innerType._def.checks.length)) { - if (refs.target === "openApi3") return { - type: primitiveMappings[def.innerType._def.typeName], - nullable: true - }; - return { type: [primitiveMappings[def.innerType._def.typeName], "null"] }; - } - if (refs.target === "openApi3") { - const base$1 = parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath] - }); - if (base$1 && "$ref" in base$1) return { - allOf: [base$1], - nullable: true - }; - return base$1 && { - ...base$1, - nullable: true - }; - } - const base = parseDef(def.innerType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "anyOf", - "0" - ] - }); - return base && { anyOf: [base, { type: "null" }] }; -} - -//#endregion - -//# sourceMappingURL=nullable.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/number.js - - -//#region src/utils/zod-to-json-schema/parsers/number.ts -function parseNumberDef(def, refs) { - const res = { type: "number" }; - if (!def.checks) return res; - for (const check of def.checks) switch (check.kind) { - case "int": - res.type = "integer"; - addErrorMessage(res, "type", check.message, refs); - break; - case "min": - if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - else setResponseValueAndErrors(res, "exclusiveMinimum", check.value, check.message, refs); - else { - if (!check.inclusive) res.exclusiveMinimum = true; - setResponseValueAndErrors(res, "minimum", check.value, check.message, refs); - } - break; - case "max": - if (refs.target === "jsonSchema7") if (check.inclusive) setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - else setResponseValueAndErrors(res, "exclusiveMaximum", check.value, check.message, refs); - else { - if (!check.inclusive) res.exclusiveMaximum = true; - setResponseValueAndErrors(res, "maximum", check.value, check.message, refs); - } - break; - case "multipleOf": - setResponseValueAndErrors(res, "multipleOf", check.value, check.message, refs); - break; - } - return res; -} - -//#endregion - -//# sourceMappingURL=number.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/object.js - - -//#region src/utils/zod-to-json-schema/parsers/object.ts -function parseObjectDef(def, refs) { - const forceOptionalIntoNullable = refs.target === "openAi"; - const result = { - type: "object", - properties: {} - }; - const required = []; - const shape = def.shape(); - for (const propName in shape) { - let propDef = shape[propName]; - if (propDef === void 0 || propDef._def === void 0) continue; - let propOptional = safeIsOptional(propDef); - if (propOptional && forceOptionalIntoNullable) { - if (propDef._def.typeName === "ZodOptional") propDef = propDef._def.innerType; - if (!propDef.isNullable()) propDef = propDef.nullable(); - propOptional = false; - } - const parsedDef = parseDef(propDef._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "properties", - propName - ], - propertyPath: [ - ...refs.currentPath, - "properties", - propName - ] - }); - if (parsedDef === void 0) continue; - result.properties[propName] = parsedDef; - if (!propOptional) required.push(propName); - } - if (required.length) result.required = required; - const additionalProperties = decideAdditionalProperties(def, refs); - if (additionalProperties !== void 0) result.additionalProperties = additionalProperties; - return result; -} -function decideAdditionalProperties(def, refs) { - if (def.catchall._def.typeName !== "ZodNever") return parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalProperties"] - }); - switch (def.unknownKeys) { - case "passthrough": return refs.allowedAdditionalProperties; - case "strict": return refs.rejectedAdditionalProperties; - case "strip": return refs.removeAdditionalStrategy === "strict" ? refs.allowedAdditionalProperties : refs.rejectedAdditionalProperties; - } -} -function safeIsOptional(schema) { - try { - return schema.isOptional(); - } catch { - return true; - } -} - -//#endregion - -//# sourceMappingURL=object.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/optional.js - - - -//#region src/utils/zod-to-json-schema/parsers/optional.ts -const parseOptionalDef = (def, refs) => { - if (refs.currentPath.toString() === refs.propertyPath?.toString()) return parseDef(def.innerType._def, refs); - const innerSchema = parseDef(def.innerType._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "anyOf", - "1" - ] - }); - return innerSchema ? { anyOf: [{ not: parseAnyDef(refs) }, innerSchema] } : parseAnyDef(refs); -}; - -//#endregion - -//# sourceMappingURL=optional.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/pipeline.js - - -//#region src/utils/zod-to-json-schema/parsers/pipeline.ts -const parsePipelineDef = (def, refs) => { - if (refs.pipeStrategy === "input") return parseDef(def.in._def, refs); - else if (refs.pipeStrategy === "output") return parseDef(def.out._def, refs); - const a = parseDef(def.in._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - "0" - ] - }); - const b = parseDef(def.out._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "allOf", - a ? "1" : "0" - ] - }); - return { allOf: [a, b].filter((x) => x !== void 0) }; -}; - -//#endregion - -//# sourceMappingURL=pipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/promise.js - - -//#region src/utils/zod-to-json-schema/parsers/promise.ts -function parsePromiseDef(def, refs) { - return parseDef(def.type._def, refs); -} - -//#endregion - -//# sourceMappingURL=promise.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/set.js - - - -//#region src/utils/zod-to-json-schema/parsers/set.ts -function parseSetDef(def, refs) { - const items = parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, "items"] - }); - const schema = { - type: "array", - uniqueItems: true, - items - }; - if (def.minSize) setResponseValueAndErrors(schema, "minItems", def.minSize.value, def.minSize.message, refs); - if (def.maxSize) setResponseValueAndErrors(schema, "maxItems", def.maxSize.value, def.maxSize.message, refs); - return schema; -} - -//#endregion - -//# sourceMappingURL=set.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/tuple.js - - -//#region src/utils/zod-to-json-schema/parsers/tuple.ts -function parseTupleDef(def, refs) { - if (def.rest) return { - type: "array", - minItems: def.items.length, - items: def.items.map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - `${i}` - ] - })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []), - additionalItems: parseDef(def.rest._def, { - ...refs, - currentPath: [...refs.currentPath, "additionalItems"] - }) - }; - else return { - type: "array", - minItems: def.items.length, - maxItems: def.items.length, - items: def.items.map((x, i) => parseDef(x._def, { - ...refs, - currentPath: [ - ...refs.currentPath, - "items", - `${i}` - ] - })).reduce((acc, x) => x === void 0 ? acc : [...acc, x], []) - }; -} - -//#endregion - -//# sourceMappingURL=tuple.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/undefined.js - - -//#region src/utils/zod-to-json-schema/parsers/undefined.ts -function parseUndefinedDef(refs) { - return { not: parseAnyDef(refs) }; -} - -//#endregion - -//# sourceMappingURL=undefined.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/unknown.js - - -//#region src/utils/zod-to-json-schema/parsers/unknown.ts -function parseUnknownDef(refs) { - return parseAnyDef(refs); -} - -//#endregion - -//# sourceMappingURL=unknown.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parsers/readonly.js - - -//#region src/utils/zod-to-json-schema/parsers/readonly.ts -const parseReadonlyDef = (def, refs) => { - return parseDef(def.innerType._def, refs); -}; - -//#endregion - -//# sourceMappingURL=readonly.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/selectParser.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//#region src/utils/zod-to-json-schema/selectParser.ts -const selectParser = (def, typeName, refs) => { - switch (typeName) { - case ZodFirstPartyTypeKind.ZodString: return parseStringDef(def, refs); - case ZodFirstPartyTypeKind.ZodNumber: return parseNumberDef(def, refs); - case ZodFirstPartyTypeKind.ZodObject: return parseObjectDef(def, refs); - case ZodFirstPartyTypeKind.ZodBigInt: return parseBigintDef(def, refs); - case ZodFirstPartyTypeKind.ZodBoolean: return parseBooleanDef(); - case ZodFirstPartyTypeKind.ZodDate: return parseDateDef(def, refs); - case ZodFirstPartyTypeKind.ZodUndefined: return parseUndefinedDef(refs); - case ZodFirstPartyTypeKind.ZodNull: return parseNullDef(refs); - case ZodFirstPartyTypeKind.ZodArray: return parseArrayDef(def, refs); - case ZodFirstPartyTypeKind.ZodUnion: - case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: return parseUnionDef(def, refs); - case ZodFirstPartyTypeKind.ZodIntersection: return parseIntersectionDef(def, refs); - case ZodFirstPartyTypeKind.ZodTuple: return parseTupleDef(def, refs); - case ZodFirstPartyTypeKind.ZodRecord: return parseRecordDef(def, refs); - case ZodFirstPartyTypeKind.ZodLiteral: return parseLiteralDef(def, refs); - case ZodFirstPartyTypeKind.ZodEnum: return parseEnumDef(def); - case ZodFirstPartyTypeKind.ZodNativeEnum: return parseNativeEnumDef(def); - case ZodFirstPartyTypeKind.ZodNullable: return parseNullableDef(def, refs); - case ZodFirstPartyTypeKind.ZodOptional: return parseOptionalDef(def, refs); - case ZodFirstPartyTypeKind.ZodMap: return parseMapDef(def, refs); - case ZodFirstPartyTypeKind.ZodSet: return parseSetDef(def, refs); - case ZodFirstPartyTypeKind.ZodLazy: return () => def.getter()._def; - case ZodFirstPartyTypeKind.ZodPromise: return parsePromiseDef(def, refs); - case ZodFirstPartyTypeKind.ZodNaN: - case ZodFirstPartyTypeKind.ZodNever: return parseNeverDef(refs); - case ZodFirstPartyTypeKind.ZodEffects: return parseEffectsDef(def, refs); - case ZodFirstPartyTypeKind.ZodAny: return parseAnyDef(refs); - case ZodFirstPartyTypeKind.ZodUnknown: return parseUnknownDef(refs); - case ZodFirstPartyTypeKind.ZodDefault: return parseDefaultDef(def, refs); - case ZodFirstPartyTypeKind.ZodBranded: return parseBrandedDef(def, refs); - case ZodFirstPartyTypeKind.ZodReadonly: return parseReadonlyDef(def, refs); - case ZodFirstPartyTypeKind.ZodCatch: return parseCatchDef(def, refs); - case ZodFirstPartyTypeKind.ZodPipeline: return parsePipelineDef(def, refs); - case ZodFirstPartyTypeKind.ZodFunction: - case ZodFirstPartyTypeKind.ZodVoid: - case ZodFirstPartyTypeKind.ZodSymbol: return void 0; - default: - /* c8 ignore next */ - return ((_) => void 0)(typeName); - } -}; - -//#endregion - -//# sourceMappingURL=selectParser.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/parseDef.js - - - - - -//#region src/utils/zod-to-json-schema/parseDef.ts -function parseDef(def, refs, forceResolution = false) { - const seenItem = refs.seen.get(def); - if (refs.override) { - const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); - if (overrideResult !== ignoreOverride) return overrideResult; - } - if (seenItem && !forceResolution) { - const seenSchema = get$ref(seenItem, refs); - if (seenSchema !== void 0) return seenSchema; - } - const newItem = { - def, - path: refs.currentPath, - jsonSchema: void 0 - }; - refs.seen.set(def, newItem); - const jsonSchemaOrGetter = selectParser(def, def.typeName, refs); - const jsonSchema = typeof jsonSchemaOrGetter === "function" ? parseDef(jsonSchemaOrGetter(), refs) : jsonSchemaOrGetter; - if (jsonSchema) addMeta(def, refs, jsonSchema); - if (refs.postProcess) { - const postProcessResult = refs.postProcess(jsonSchema, def, refs); - newItem.jsonSchema = jsonSchema; - return postProcessResult; - } - newItem.jsonSchema = jsonSchema; - return jsonSchema; -} -const get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case "root": return { $ref: item.path.join("/") }; - case "relative": return { $ref: getRelativePath(refs.currentPath, item.path) }; - case "none": - case "seen": - if (item.path.length < refs.currentPath.length && item.path.every((value, index) => refs.currentPath[index] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join("/")}! Defaulting to any`); - return parseAnyDef(refs); - } - return refs.$refStrategy === "seen" ? parseAnyDef(refs) : void 0; - } -}; -const addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) jsonSchema.markdownDescription = def.description; - } - return jsonSchema; -}; - -//#endregion - -//# sourceMappingURL=parseDef.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/zodToJsonSchema.js - - - - -//#region src/utils/zod-to-json-schema/zodToJsonSchema.ts -const zodToJsonSchema_zodToJsonSchema = (schema, options) => { - const refs = getRefs(options); - let definitions = typeof options === "object" && options.definitions ? Object.entries(options.definitions).reduce((acc, [name$1, schema$1]) => ({ - ...acc, - [name$1]: parseDef(schema$1._def, { - ...refs, - currentPath: [ - ...refs.basePath, - refs.definitionPath, - name$1 - ] - }, true) ?? parseAnyDef(refs) - }), {}) : void 0; - const name = typeof options === "string" ? options : options?.nameStrategy === "title" ? void 0 : options?.name; - const main = parseDef(schema._def, name === void 0 ? refs : { - ...refs, - currentPath: [ - ...refs.basePath, - refs.definitionPath, - name - ] - }, false) ?? parseAnyDef(refs); - const title = typeof options === "object" && options.name !== void 0 && options.nameStrategy === "title" ? options.name : void 0; - if (title !== void 0) main.title = title; - if (refs.flags.hasReferencedOpenAiAnyType) { - if (!definitions) definitions = {}; - if (!definitions[refs.openAiAnyTypeName]) definitions[refs.openAiAnyTypeName] = { - type: [ - "string", - "number", - "integer", - "boolean", - "array", - "null" - ], - items: { $ref: refs.$refStrategy === "relative" ? "1" : [ - ...refs.basePath, - refs.definitionPath, - refs.openAiAnyTypeName - ].join("/") } - }; - } - const combined = name === void 0 ? definitions ? { - ...main, - [refs.definitionPath]: definitions - } : main : { - $ref: [ - ...refs.$refStrategy === "relative" ? [] : refs.basePath, - refs.definitionPath, - name - ].join("/"), - [refs.definitionPath]: { - ...definitions, - [name]: main - } - }; - if (refs.target === "jsonSchema7") combined.$schema = "http://json-schema.org/draft-07/schema#"; - else if (refs.target === "jsonSchema2019-09" || refs.target === "openAi") combined.$schema = "https://json-schema.org/draft/2019-09/schema#"; - if (refs.target === "openAi" && ("anyOf" in combined || "oneOf" in combined || "allOf" in combined || "type" in combined && Array.isArray(combined.type))) console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."); - return combined; -}; - -//#endregion - -//# sourceMappingURL=zodToJsonSchema.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/zod-to-json-schema/index.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/deep-compare-strict.js -function deepCompareStrict(a, b) { - const typeofa = typeof a; - if (typeofa !== typeof b) { - return false; - } - if (Array.isArray(a)) { - if (!Array.isArray(b)) { - return false; - } - const length = a.length; - if (length !== b.length) { - return false; - } - for (let i = 0; i < length; i++) { - if (!deepCompareStrict(a[i], b[i])) { - return false; - } - } - return true; - } - if (typeofa === 'object') { - if (!a || !b) { - return a === b; - } - const aKeys = Object.keys(a); - const bKeys = Object.keys(b); - const length = aKeys.length; - if (length !== bKeys.length) { - return false; - } - for (const k of aKeys) { - if (!deepCompareStrict(a[k], b[k])) { - return false; - } - } - return true; - } - return a === b; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/pointer.js -function encodePointer(p) { - return encodeURI(escapePointer(p)); -} -function escapePointer(p) { - return p.replace(/~/g, '~0').replace(/\//g, '~1'); -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/dereference.js - -const schemaKeyword = { - additionalItems: true, - unevaluatedItems: true, - items: true, - contains: true, - additionalProperties: true, - unevaluatedProperties: true, - propertyNames: true, - not: true, - if: true, - then: true, - else: true -}; -const schemaArrayKeyword = { - prefixItems: true, - items: true, - allOf: true, - anyOf: true, - oneOf: true -}; -const schemaMapKeyword = { - $defs: true, - definitions: true, - properties: true, - patternProperties: true, - dependentSchemas: true -}; -const ignoredKeyword = { - id: true, - $id: true, - $ref: true, - $schema: true, - $anchor: true, - $vocabulary: true, - $comment: true, - default: true, - enum: true, - const: true, - required: true, - type: true, - maximum: true, - minimum: true, - exclusiveMaximum: true, - exclusiveMinimum: true, - multipleOf: true, - maxLength: true, - minLength: true, - pattern: true, - format: true, - maxItems: true, - minItems: true, - uniqueItems: true, - maxProperties: true, - minProperties: true -}; -let initialBaseURI = typeof self !== 'undefined' && - self.location && - self.location.origin !== 'null' - ? - new URL(self.location.origin + self.location.pathname + location.search) - : new URL('https://github.com/cfworker'); -function dereference(schema, lookup = Object.create(null), baseURI = initialBaseURI, basePointer = '') { - if (schema && typeof schema === 'object' && !Array.isArray(schema)) { - const id = schema.$id || schema.id; - if (id) { - const url = new URL(id, baseURI.href); - if (url.hash.length > 1) { - lookup[url.href] = schema; - } - else { - url.hash = ''; - if (basePointer === '') { - baseURI = url; - } - else { - dereference(schema, lookup, baseURI); - } - } - } - } - else if (schema !== true && schema !== false) { - return lookup; - } - const schemaURI = baseURI.href + (basePointer ? '#' + basePointer : ''); - if (lookup[schemaURI] !== undefined) { - throw new Error(`Duplicate schema URI "${schemaURI}".`); - } - lookup[schemaURI] = schema; - if (schema === true || schema === false) { - return lookup; - } - if (schema.__absolute_uri__ === undefined) { - Object.defineProperty(schema, '__absolute_uri__', { - enumerable: false, - value: schemaURI - }); - } - if (schema.$ref && schema.__absolute_ref__ === undefined) { - const url = new URL(schema.$ref, baseURI.href); - url.hash = url.hash; - Object.defineProperty(schema, '__absolute_ref__', { - enumerable: false, - value: url.href - }); - } - if (schema.$recursiveRef && schema.__absolute_recursive_ref__ === undefined) { - const url = new URL(schema.$recursiveRef, baseURI.href); - url.hash = url.hash; - Object.defineProperty(schema, '__absolute_recursive_ref__', { - enumerable: false, - value: url.href - }); - } - if (schema.$anchor) { - const url = new URL('#' + schema.$anchor, baseURI.href); - lookup[url.href] = schema; - } - for (let key in schema) { - if (ignoredKeyword[key]) { - continue; - } - const keyBase = `${basePointer}/${encodePointer(key)}`; - const subSchema = schema[key]; - if (Array.isArray(subSchema)) { - if (schemaArrayKeyword[key]) { - const length = subSchema.length; - for (let i = 0; i < length; i++) { - dereference(subSchema[i], lookup, baseURI, `${keyBase}/${i}`); - } - } - } - else if (schemaMapKeyword[key]) { - for (let subKey in subSchema) { - dereference(subSchema[subKey], lookup, baseURI, `${keyBase}/${encodePointer(subKey)}`); - } - } - else { - dereference(subSchema, lookup, baseURI, keyBase); - } - } - return lookup; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/format.js -const DATE = /^(\d\d\d\d)-(\d\d)-(\d\d)$/; -const DAYS = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]; -const TIME = /^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i; -const HOSTNAME = /^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i; -const URIREF = /^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; -const URITEMPLATE = /^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i; -const URL_ = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu; -const UUID = /^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i; -const JSON_POINTER = /^(?:\/(?:[^~/]|~0|~1)*)*$/; -const JSON_POINTER_URI_FRAGMENT = /^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i; -const RELATIVE_JSON_POINTER = /^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/; -const EMAIL = (input) => { - if (input[0] === '"') - return false; - const [name, host, ...rest] = input.split('@'); - if (!name || - !host || - rest.length !== 0 || - name.length > 64 || - host.length > 253) - return false; - if (name[0] === '.' || name.endsWith('.') || name.includes('..')) - return false; - if (!/^[a-z0-9.-]+$/i.test(host) || - !/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(name)) - return false; - return host - .split('.') - .every(part => /^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(part)); -}; -const IPV4 = /^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/; -const IPV6 = /^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i; -const DURATION = (input) => input.length > 1 && - input.length < 80 && - (/^P\d+([.,]\d+)?W$/.test(input) || - (/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(input) && - /^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(input))); -function bind(r) { - return r.test.bind(r); -} -const format = { - date: format_date, - time: format_time.bind(undefined, false), - 'date-time': date_time, - duration: DURATION, - uri, - 'uri-reference': bind(URIREF), - 'uri-template': bind(URITEMPLATE), - url: bind(URL_), - email: EMAIL, - hostname: bind(HOSTNAME), - ipv4: bind(IPV4), - ipv6: bind(IPV6), - regex: regex, - uuid: bind(UUID), - 'json-pointer': bind(JSON_POINTER), - 'json-pointer-uri-fragment': bind(JSON_POINTER_URI_FRAGMENT), - 'relative-json-pointer': bind(RELATIVE_JSON_POINTER) -}; -function isLeapYear(year) { - return year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0); -} -function format_date(str) { - const matches = str.match(DATE); - if (!matches) - return false; - const year = +matches[1]; - const month = +matches[2]; - const day = +matches[3]; - return (month >= 1 && - month <= 12 && - day >= 1 && - day <= (month == 2 && isLeapYear(year) ? 29 : DAYS[month])); -} -function format_time(full, str) { - const matches = str.match(TIME); - if (!matches) - return false; - const hour = +matches[1]; - const minute = +matches[2]; - const second = +matches[3]; - const timeZone = !!matches[5]; - return (((hour <= 23 && minute <= 59 && second <= 59) || - (hour == 23 && minute == 59 && second == 60)) && - (!full || timeZone)); -} -const DATE_TIME_SEPARATOR = /t|\s/i; -function date_time(str) { - const dateTime = str.split(DATE_TIME_SEPARATOR); - return dateTime.length == 2 && format_date(dateTime[0]) && format_time(true, dateTime[1]); -} -const NOT_URI_FRAGMENT = /\/|:/; -const URI_PATTERN = /^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i; -function uri(str) { - return NOT_URI_FRAGMENT.test(str) && URI_PATTERN.test(str); -} -const Z_ANCHOR = /[^\\]\\Z/; -function regex(str) { - if (Z_ANCHOR.test(str)) - return false; - try { - new RegExp(str, 'u'); - return true; - } - catch (e) { - return false; - } -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/types.js -var OutputFormat; -(function (OutputFormat) { - OutputFormat[OutputFormat["Flag"] = 1] = "Flag"; - OutputFormat[OutputFormat["Basic"] = 2] = "Basic"; - OutputFormat[OutputFormat["Detailed"] = 4] = "Detailed"; -})(OutputFormat || (OutputFormat = {})); - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/ucs2-length.js -function ucs2length(s) { - let result = 0; - let length = s.length; - let index = 0; - let charCode; - while (index < length) { - result++; - charCode = s.charCodeAt(index++); - if (charCode >= 0xd800 && charCode <= 0xdbff && index < length) { - charCode = s.charCodeAt(index); - if ((charCode & 0xfc00) == 0xdc00) { - index++; - } - } - } - return result; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validate.js - - - - - -function validate_validate(instance, schema, draft = '2019-09', lookup = dereference(schema), shortCircuit = true, recursiveAnchor = null, instanceLocation = '#', schemaLocation = '#', evaluated = Object.create(null)) { - if (schema === true) { - return { valid: true, errors: [] }; - } - if (schema === false) { - return { - valid: false, - errors: [ - { - instanceLocation, - keyword: 'false', - keywordLocation: instanceLocation, - error: 'False boolean schema.' - } - ] - }; - } - const rawInstanceType = typeof instance; - let instanceType; - switch (rawInstanceType) { - case 'boolean': - case 'number': - case 'string': - instanceType = rawInstanceType; - break; - case 'object': - if (instance === null) { - instanceType = 'null'; - } - else if (Array.isArray(instance)) { - instanceType = 'array'; - } - else { - instanceType = 'object'; - } - break; - default: - throw new Error(`Instances of "${rawInstanceType}" type are not supported.`); - } - const { $ref, $recursiveRef, $recursiveAnchor, type: $type, const: $const, enum: $enum, required: $required, not: $not, anyOf: $anyOf, allOf: $allOf, oneOf: $oneOf, if: $if, then: $then, else: $else, format: $format, properties: $properties, patternProperties: $patternProperties, additionalProperties: $additionalProperties, unevaluatedProperties: $unevaluatedProperties, minProperties: $minProperties, maxProperties: $maxProperties, propertyNames: $propertyNames, dependentRequired: $dependentRequired, dependentSchemas: $dependentSchemas, dependencies: $dependencies, prefixItems: $prefixItems, items: $items, additionalItems: $additionalItems, unevaluatedItems: $unevaluatedItems, contains: $contains, minContains: $minContains, maxContains: $maxContains, minItems: $minItems, maxItems: $maxItems, uniqueItems: $uniqueItems, minimum: $minimum, maximum: $maximum, exclusiveMinimum: $exclusiveMinimum, exclusiveMaximum: $exclusiveMaximum, multipleOf: $multipleOf, minLength: $minLength, maxLength: $maxLength, pattern: $pattern, __absolute_ref__, __absolute_recursive_ref__ } = schema; - const errors = []; - if ($recursiveAnchor === true && recursiveAnchor === null) { - recursiveAnchor = schema; - } - if ($recursiveRef === '#') { - const refSchema = recursiveAnchor === null - ? lookup[__absolute_recursive_ref__] - : recursiveAnchor; - const keywordLocation = `${schemaLocation}/$recursiveRef`; - const result = validate_validate(instance, recursiveAnchor === null ? schema : recursiveAnchor, draft, lookup, shortCircuit, refSchema, instanceLocation, keywordLocation, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: '$recursiveRef', - keywordLocation, - error: 'A subschema had errors.' - }, ...result.errors); - } - } - if ($ref !== undefined) { - const uri = __absolute_ref__ || $ref; - const refSchema = lookup[uri]; - if (refSchema === undefined) { - let message = `Unresolved $ref "${$ref}".`; - if (__absolute_ref__ && __absolute_ref__ !== $ref) { - message += ` Absolute URI "${__absolute_ref__}".`; - } - message += `\nKnown schemas:\n- ${Object.keys(lookup).join('\n- ')}`; - throw new Error(message); - } - const keywordLocation = `${schemaLocation}/$ref`; - const result = validate_validate(instance, refSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: '$ref', - keywordLocation, - error: 'A subschema had errors.' - }, ...result.errors); - } - if (draft === '4' || draft === '7') { - return { valid: errors.length === 0, errors }; - } - } - if (Array.isArray($type)) { - let length = $type.length; - let valid = false; - for (let i = 0; i < length; i++) { - if (instanceType === $type[i] || - ($type[i] === 'integer' && - instanceType === 'number' && - instance % 1 === 0 && - instance === instance)) { - valid = true; - break; - } - } - if (!valid) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type.join('", "')}".` - }); - } - } - else if ($type === 'integer') { - if (instanceType !== 'number' || instance % 1 || instance !== instance) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` - }); - } - } - else if ($type !== undefined && instanceType !== $type) { - errors.push({ - instanceLocation, - keyword: 'type', - keywordLocation: `${schemaLocation}/type`, - error: `Instance type "${instanceType}" is invalid. Expected "${$type}".` - }); - } - if ($const !== undefined) { - if (instanceType === 'object' || instanceType === 'array') { - if (!deepCompareStrict(instance, $const)) { - errors.push({ - instanceLocation, - keyword: 'const', - keywordLocation: `${schemaLocation}/const`, - error: `Instance does not match ${JSON.stringify($const)}.` - }); - } - } - else if (instance !== $const) { - errors.push({ - instanceLocation, - keyword: 'const', - keywordLocation: `${schemaLocation}/const`, - error: `Instance does not match ${JSON.stringify($const)}.` - }); - } - } - if ($enum !== undefined) { - if (instanceType === 'object' || instanceType === 'array') { - if (!$enum.some(value => deepCompareStrict(instance, value))) { - errors.push({ - instanceLocation, - keyword: 'enum', - keywordLocation: `${schemaLocation}/enum`, - error: `Instance does not match any of ${JSON.stringify($enum)}.` - }); - } - } - else if (!$enum.some(value => instance === value)) { - errors.push({ - instanceLocation, - keyword: 'enum', - keywordLocation: `${schemaLocation}/enum`, - error: `Instance does not match any of ${JSON.stringify($enum)}.` - }); - } - } - if ($not !== undefined) { - const keywordLocation = `${schemaLocation}/not`; - const result = validate_validate(instance, $not, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation); - if (result.valid) { - errors.push({ - instanceLocation, - keyword: 'not', - keywordLocation, - error: 'Instance matched "not" schema.' - }); - } - } - let subEvaluateds = []; - if ($anyOf !== undefined) { - const keywordLocation = `${schemaLocation}/anyOf`; - const errorsLength = errors.length; - let anyValid = false; - for (let i = 0; i < $anyOf.length; i++) { - const subSchema = $anyOf[i]; - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - anyValid = anyValid || result.valid; - if (result.valid) { - subEvaluateds.push(subEvaluated); - } - } - if (anyValid) { - errors.length = errorsLength; - } - else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'anyOf', - keywordLocation, - error: 'Instance does not match any subschemas.' - }); - } - } - if ($allOf !== undefined) { - const keywordLocation = `${schemaLocation}/allOf`; - const errorsLength = errors.length; - let allValid = true; - for (let i = 0; i < $allOf.length; i++) { - const subSchema = $allOf[i]; - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - allValid = allValid && result.valid; - if (result.valid) { - subEvaluateds.push(subEvaluated); - } - } - if (allValid) { - errors.length = errorsLength; - } - else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'allOf', - keywordLocation, - error: `Instance does not match every subschema.` - }); - } - } - if ($oneOf !== undefined) { - const keywordLocation = `${schemaLocation}/oneOf`; - const errorsLength = errors.length; - const matches = $oneOf.filter((subSchema, i) => { - const subEvaluated = Object.create(evaluated); - const result = validate_validate(instance, subSchema, draft, lookup, shortCircuit, $recursiveAnchor === true ? recursiveAnchor : null, instanceLocation, `${keywordLocation}/${i}`, subEvaluated); - errors.push(...result.errors); - if (result.valid) { - subEvaluateds.push(subEvaluated); - } - return result.valid; - }).length; - if (matches === 1) { - errors.length = errorsLength; - } - else { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'oneOf', - keywordLocation, - error: `Instance does not match exactly one subschema (${matches} matches).` - }); - } - } - if (instanceType === 'object' || instanceType === 'array') { - Object.assign(evaluated, ...subEvaluateds); - } - if ($if !== undefined) { - const keywordLocation = `${schemaLocation}/if`; - const conditionResult = validate_validate(instance, $if, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, keywordLocation, evaluated).valid; - if (conditionResult) { - if ($then !== undefined) { - const thenResult = validate_validate(instance, $then, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/then`, evaluated); - if (!thenResult.valid) { - errors.push({ - instanceLocation, - keyword: 'if', - keywordLocation, - error: `Instance does not match "then" schema.` - }, ...thenResult.errors); - } - } - } - else if ($else !== undefined) { - const elseResult = validate_validate(instance, $else, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${schemaLocation}/else`, evaluated); - if (!elseResult.valid) { - errors.push({ - instanceLocation, - keyword: 'if', - keywordLocation, - error: `Instance does not match "else" schema.` - }, ...elseResult.errors); - } - } - } - if (instanceType === 'object') { - if ($required !== undefined) { - for (const key of $required) { - if (!(key in instance)) { - errors.push({ - instanceLocation, - keyword: 'required', - keywordLocation: `${schemaLocation}/required`, - error: `Instance does not have required property "${key}".` - }); - } - } - } - const keys = Object.keys(instance); - if ($minProperties !== undefined && keys.length < $minProperties) { - errors.push({ - instanceLocation, - keyword: 'minProperties', - keywordLocation: `${schemaLocation}/minProperties`, - error: `Instance does not have at least ${$minProperties} properties.` - }); - } - if ($maxProperties !== undefined && keys.length > $maxProperties) { - errors.push({ - instanceLocation, - keyword: 'maxProperties', - keywordLocation: `${schemaLocation}/maxProperties`, - error: `Instance does not have at least ${$maxProperties} properties.` - }); - } - if ($propertyNames !== undefined) { - const keywordLocation = `${schemaLocation}/propertyNames`; - for (const key in instance) { - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(key, $propertyNames, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'propertyNames', - keywordLocation, - error: `Property name "${key}" does not match schema.` - }, ...result.errors); - } - } - } - if ($dependentRequired !== undefined) { - const keywordLocation = `${schemaLocation}/dependantRequired`; - for (const key in $dependentRequired) { - if (key in instance) { - const required = $dependentRequired[key]; - for (const dependantKey of required) { - if (!(dependantKey in instance)) { - errors.push({ - instanceLocation, - keyword: 'dependentRequired', - keywordLocation, - error: `Instance has "${key}" but does not have "${dependantKey}".` - }); - } - } - } - } - } - if ($dependentSchemas !== undefined) { - for (const key in $dependentSchemas) { - const keywordLocation = `${schemaLocation}/dependentSchemas`; - if (key in instance) { - const result = validate_validate(instance, $dependentSchemas[key], draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`, evaluated); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'dependentSchemas', - keywordLocation, - error: `Instance has "${key}" but does not match dependant schema.` - }, ...result.errors); - } - } - } - } - if ($dependencies !== undefined) { - const keywordLocation = `${schemaLocation}/dependencies`; - for (const key in $dependencies) { - if (key in instance) { - const propsOrSchema = $dependencies[key]; - if (Array.isArray(propsOrSchema)) { - for (const dependantKey of propsOrSchema) { - if (!(dependantKey in instance)) { - errors.push({ - instanceLocation, - keyword: 'dependencies', - keywordLocation, - error: `Instance has "${key}" but does not have "${dependantKey}".` - }); - } - } - } - else { - const result = validate_validate(instance, propsOrSchema, draft, lookup, shortCircuit, recursiveAnchor, instanceLocation, `${keywordLocation}/${encodePointer(key)}`); - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'dependencies', - keywordLocation, - error: `Instance has "${key}" but does not match dependant schema.` - }, ...result.errors); - } - } - } - } - } - const thisEvaluated = Object.create(null); - let stop = false; - if ($properties !== undefined) { - const keywordLocation = `${schemaLocation}/properties`; - for (const key in $properties) { - if (!(key in instance)) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $properties[key], draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(key)}`); - if (result.valid) { - evaluated[key] = thisEvaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'properties', - keywordLocation, - error: `Property "${key}" does not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - if (!stop && $patternProperties !== undefined) { - const keywordLocation = `${schemaLocation}/patternProperties`; - for (const pattern in $patternProperties) { - const regex = new RegExp(pattern, 'u'); - const subSchema = $patternProperties[pattern]; - for (const key in instance) { - if (!regex.test(key)) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], subSchema, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, `${keywordLocation}/${encodePointer(pattern)}`); - if (result.valid) { - evaluated[key] = thisEvaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'patternProperties', - keywordLocation, - error: `Property "${key}" matches pattern "${pattern}" but does not match associated schema.` - }, ...result.errors); - } - } - } - } - if (!stop && $additionalProperties !== undefined) { - const keywordLocation = `${schemaLocation}/additionalProperties`; - for (const key in instance) { - if (thisEvaluated[key]) { - continue; - } - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $additionalProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (result.valid) { - evaluated[key] = true; - } - else { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'additionalProperties', - keywordLocation, - error: `Property "${key}" does not match additional properties schema.` - }, ...result.errors); - } - } - } - else if (!stop && $unevaluatedProperties !== undefined) { - const keywordLocation = `${schemaLocation}/unevaluatedProperties`; - for (const key in instance) { - if (!evaluated[key]) { - const subInstancePointer = `${instanceLocation}/${encodePointer(key)}`; - const result = validate_validate(instance[key], $unevaluatedProperties, draft, lookup, shortCircuit, recursiveAnchor, subInstancePointer, keywordLocation); - if (result.valid) { - evaluated[key] = true; - } - else { - errors.push({ - instanceLocation, - keyword: 'unevaluatedProperties', - keywordLocation, - error: `Property "${key}" does not match unevaluated properties schema.` - }, ...result.errors); - } - } - } - } - } - else if (instanceType === 'array') { - if ($maxItems !== undefined && instance.length > $maxItems) { - errors.push({ - instanceLocation, - keyword: 'maxItems', - keywordLocation: `${schemaLocation}/maxItems`, - error: `Array has too many items (${instance.length} > ${$maxItems}).` - }); - } - if ($minItems !== undefined && instance.length < $minItems) { - errors.push({ - instanceLocation, - keyword: 'minItems', - keywordLocation: `${schemaLocation}/minItems`, - error: `Array has too few items (${instance.length} < ${$minItems}).` - }); - } - const length = instance.length; - let i = 0; - let stop = false; - if ($prefixItems !== undefined) { - const keywordLocation = `${schemaLocation}/prefixItems`; - const length2 = Math.min($prefixItems.length, length); - for (; i < length2; i++) { - const result = validate_validate(instance[i], $prefixItems[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'prefixItems', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - if ($items !== undefined) { - const keywordLocation = `${schemaLocation}/items`; - if (Array.isArray($items)) { - const length2 = Math.min($items.length, length); - for (; i < length2; i++) { - const result = validate_validate(instance[i], $items[i], draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, `${keywordLocation}/${i}`); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'items', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - else { - for (; i < length; i++) { - const result = validate_validate(instance[i], $items, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'items', - keywordLocation, - error: `Items did not match schema.` - }, ...result.errors); - if (stop) - break; - } - } - } - if (!stop && $additionalItems !== undefined) { - const keywordLocation = `${schemaLocation}/additionalItems`; - for (; i < length; i++) { - const result = validate_validate(instance[i], $additionalItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - stop = shortCircuit; - errors.push({ - instanceLocation, - keyword: 'additionalItems', - keywordLocation, - error: `Items did not match additional items schema.` - }, ...result.errors); - } - } - } - } - if ($contains !== undefined) { - if (length === 0 && $minContains === undefined) { - errors.push({ - instanceLocation, - keyword: 'contains', - keywordLocation: `${schemaLocation}/contains`, - error: `Array is empty. It must contain at least one item matching the schema.` - }); - } - else if ($minContains !== undefined && length < $minContains) { - errors.push({ - instanceLocation, - keyword: 'minContains', - keywordLocation: `${schemaLocation}/minContains`, - error: `Array has less items (${length}) than minContains (${$minContains}).` - }); - } - else { - const keywordLocation = `${schemaLocation}/contains`; - const errorsLength = errors.length; - let contained = 0; - for (let j = 0; j < length; j++) { - const result = validate_validate(instance[j], $contains, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${j}`, keywordLocation); - if (result.valid) { - evaluated[j] = true; - contained++; - } - else { - errors.push(...result.errors); - } - } - if (contained >= ($minContains || 0)) { - errors.length = errorsLength; - } - if ($minContains === undefined && - $maxContains === undefined && - contained === 0) { - errors.splice(errorsLength, 0, { - instanceLocation, - keyword: 'contains', - keywordLocation, - error: `Array does not contain item matching schema.` - }); - } - else if ($minContains !== undefined && contained < $minContains) { - errors.push({ - instanceLocation, - keyword: 'minContains', - keywordLocation: `${schemaLocation}/minContains`, - error: `Array must contain at least ${$minContains} items matching schema. Only ${contained} items were found.` - }); - } - else if ($maxContains !== undefined && contained > $maxContains) { - errors.push({ - instanceLocation, - keyword: 'maxContains', - keywordLocation: `${schemaLocation}/maxContains`, - error: `Array may contain at most ${$maxContains} items matching schema. ${contained} items were found.` - }); - } - } - } - if (!stop && $unevaluatedItems !== undefined) { - const keywordLocation = `${schemaLocation}/unevaluatedItems`; - for (i; i < length; i++) { - if (evaluated[i]) { - continue; - } - const result = validate_validate(instance[i], $unevaluatedItems, draft, lookup, shortCircuit, recursiveAnchor, `${instanceLocation}/${i}`, keywordLocation); - evaluated[i] = true; - if (!result.valid) { - errors.push({ - instanceLocation, - keyword: 'unevaluatedItems', - keywordLocation, - error: `Items did not match unevaluated items schema.` - }, ...result.errors); - } - } - } - if ($uniqueItems) { - for (let j = 0; j < length; j++) { - const a = instance[j]; - const ao = typeof a === 'object' && a !== null; - for (let k = 0; k < length; k++) { - if (j === k) { - continue; - } - const b = instance[k]; - const bo = typeof b === 'object' && b !== null; - if (a === b || (ao && bo && deepCompareStrict(a, b))) { - errors.push({ - instanceLocation, - keyword: 'uniqueItems', - keywordLocation: `${schemaLocation}/uniqueItems`, - error: `Duplicate items at indexes ${j} and ${k}.` - }); - j = Number.MAX_SAFE_INTEGER; - k = Number.MAX_SAFE_INTEGER; - } - } - } - } - } - else if (instanceType === 'number') { - if (draft === '4') { - if ($minimum !== undefined && - (($exclusiveMinimum === true && instance <= $minimum) || - instance < $minimum)) { - errors.push({ - instanceLocation, - keyword: 'minimum', - keywordLocation: `${schemaLocation}/minimum`, - error: `${instance} is less than ${$exclusiveMinimum ? 'or equal to ' : ''} ${$minimum}.` - }); - } - if ($maximum !== undefined && - (($exclusiveMaximum === true && instance >= $maximum) || - instance > $maximum)) { - errors.push({ - instanceLocation, - keyword: 'maximum', - keywordLocation: `${schemaLocation}/maximum`, - error: `${instance} is greater than ${$exclusiveMaximum ? 'or equal to ' : ''} ${$maximum}.` - }); - } - } - else { - if ($minimum !== undefined && instance < $minimum) { - errors.push({ - instanceLocation, - keyword: 'minimum', - keywordLocation: `${schemaLocation}/minimum`, - error: `${instance} is less than ${$minimum}.` - }); - } - if ($maximum !== undefined && instance > $maximum) { - errors.push({ - instanceLocation, - keyword: 'maximum', - keywordLocation: `${schemaLocation}/maximum`, - error: `${instance} is greater than ${$maximum}.` - }); - } - if ($exclusiveMinimum !== undefined && instance <= $exclusiveMinimum) { - errors.push({ - instanceLocation, - keyword: 'exclusiveMinimum', - keywordLocation: `${schemaLocation}/exclusiveMinimum`, - error: `${instance} is less than ${$exclusiveMinimum}.` - }); - } - if ($exclusiveMaximum !== undefined && instance >= $exclusiveMaximum) { - errors.push({ - instanceLocation, - keyword: 'exclusiveMaximum', - keywordLocation: `${schemaLocation}/exclusiveMaximum`, - error: `${instance} is greater than or equal to ${$exclusiveMaximum}.` - }); - } - } - if ($multipleOf !== undefined) { - const remainder = instance % $multipleOf; - if (Math.abs(0 - remainder) >= 1.1920929e-7 && - Math.abs($multipleOf - remainder) >= 1.1920929e-7) { - errors.push({ - instanceLocation, - keyword: 'multipleOf', - keywordLocation: `${schemaLocation}/multipleOf`, - error: `${instance} is not a multiple of ${$multipleOf}.` - }); - } - } - } - else if (instanceType === 'string') { - const length = $minLength === undefined && $maxLength === undefined - ? 0 - : ucs2length(instance); - if ($minLength !== undefined && length < $minLength) { - errors.push({ - instanceLocation, - keyword: 'minLength', - keywordLocation: `${schemaLocation}/minLength`, - error: `String is too short (${length} < ${$minLength}).` - }); - } - if ($maxLength !== undefined && length > $maxLength) { - errors.push({ - instanceLocation, - keyword: 'maxLength', - keywordLocation: `${schemaLocation}/maxLength`, - error: `String is too long (${length} > ${$maxLength}).` - }); - } - if ($pattern !== undefined && !new RegExp($pattern, 'u').test(instance)) { - errors.push({ - instanceLocation, - keyword: 'pattern', - keywordLocation: `${schemaLocation}/pattern`, - error: `String does not match pattern.` - }); - } - if ($format !== undefined && - format[$format] && - !format[$format](instance)) { - errors.push({ - instanceLocation, - keyword: 'format', - keywordLocation: `${schemaLocation}/format`, - error: `String does not match format "${$format}".` - }); - } - } - return { valid: errors.length === 0, errors }; -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/validator.js - - -class Validator { - schema; - draft; - shortCircuit; - lookup; - constructor(schema, draft = '2019-09', shortCircuit = true) { - this.schema = schema; - this.draft = draft; - this.shortCircuit = shortCircuit; - this.lookup = dereference(schema); - } - validate(instance) { - return validate_validate(instance, this.schema, this.draft, this.lookup, this.shortCircuit); - } - addSchema(schema, id) { - if (id) { - schema = { ...schema, $id: id }; - } - dereference(schema, this.lookup); - } -} - -;// CONCATENATED MODULE: ./node_modules/@cfworker/json-schema/dist/esm/index.js - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json_schema.js - - - - - - - -//#region src/utils/json_schema.ts -var json_schema_exports = {}; -__export(json_schema_exports, { - Validator: () => Validator, - deepCompareStrict: () => deepCompareStrict, - toJsonSchema: () => toJsonSchema, - validatesOnlyStrings: () => validatesOnlyStrings -}); -/** -* Converts a Zod schema or JSON schema to a JSON schema. -* @param schema - The schema to convert. -* @param params - The parameters to pass to the toJSONSchema function. -* @returns The converted schema. -*/ -function toJsonSchema(schema, params) { - if (isZodSchemaV4(schema)) { - const inputSchema = interopZodTransformInputSchema(schema, true); - if (isZodObjectV4(inputSchema)) { - const strictSchema = interopZodObjectStrict(inputSchema, true); - return toJSONSchema(strictSchema, params); - } else return toJSONSchema(schema, params); - } - if (isZodSchemaV3(schema)) return zodToJsonSchema_zodToJsonSchema(schema); - return schema; -} -/** -* Validates if a JSON schema validates only strings. May return false negatives in some edge cases -* (like recursive or unresolvable refs). -* -* @param schema - The schema to validate. -* @returns `true` if the schema validates only strings, `false` otherwise. -*/ -function validatesOnlyStrings(schema) { - if (!schema || typeof schema !== "object" || Object.keys(schema).length === 0 || Array.isArray(schema)) return false; - if ("type" in schema) { - if (typeof schema.type === "string") return schema.type === "string"; - if (Array.isArray(schema.type)) return schema.type.every((t) => t === "string"); - return false; - } - if ("enum" in schema) return Array.isArray(schema.enum) && schema.enum.length > 0 && schema.enum.every((val) => typeof val === "string"); - if ("const" in schema) return typeof schema.const === "string"; - if ("allOf" in schema && Array.isArray(schema.allOf)) return schema.allOf.some((subschema) => validatesOnlyStrings(subschema)); - if ("anyOf" in schema && Array.isArray(schema.anyOf) || "oneOf" in schema && Array.isArray(schema.oneOf)) { - const subschemas = "anyOf" in schema ? schema.anyOf : schema.oneOf; - return subschemas.length > 0 && subschemas.every((subschema) => validatesOnlyStrings(subschema)); - } - if ("not" in schema) return false; - if ("$ref" in schema && typeof schema.$ref === "string") { - const ref = schema.$ref; - const resolved = dereference(schema); - if (resolved[ref]) return validatesOnlyStrings(resolved[ref]); - return false; - } - return false; -} - -//#endregion - -//# sourceMappingURL=json_schema.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/utils.js -//#region src/runnables/utils.ts -function isRunnableInterface(thing) { - return thing ? thing.lc_runnable : false; -} -/** -* Utility to filter the root event in the streamEvents implementation. -* This is simply binding the arguments to the namespace to make save on -* a bit of typing in the streamEvents implementation. -* -* TODO: Refactor and remove. -*/ -var _RootEventFilter = class { - includeNames; - includeTypes; - includeTags; - excludeNames; - excludeTypes; - excludeTags; - constructor(fields) { - this.includeNames = fields.includeNames; - this.includeTypes = fields.includeTypes; - this.includeTags = fields.includeTags; - this.excludeNames = fields.excludeNames; - this.excludeTypes = fields.excludeTypes; - this.excludeTags = fields.excludeTags; - } - includeEvent(event, rootType) { - let include = this.includeNames === void 0 && this.includeTypes === void 0 && this.includeTags === void 0; - const eventTags = event.tags ?? []; - if (this.includeNames !== void 0) include = include || this.includeNames.includes(event.name); - if (this.includeTypes !== void 0) include = include || this.includeTypes.includes(rootType); - if (this.includeTags !== void 0) include = include || eventTags.some((tag) => this.includeTags?.includes(tag)); - if (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(event.name); - if (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(rootType); - if (this.excludeTags !== void 0) include = include && eventTags.every((tag) => !this.excludeTags?.includes(tag)); - return include; - } -}; -const toBase64Url = (str) => { - const encoded = btoa(str); - return encoded.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); -}; - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph_mermaid.js - - -//#region src/runnables/graph_mermaid.ts -function _escapeNodeLabel(nodeLabel) { - return nodeLabel.replace(/[^a-zA-Z-_0-9]/g, "_"); -} -const MARKDOWN_SPECIAL_CHARS = [ - "*", - "_", - "`" -]; -function _generateMermaidGraphStyles(nodeColors) { - let styles = ""; - for (const [className, color] of Object.entries(nodeColors)) styles += `\tclassDef ${className} ${color};\n`; - return styles; -} -/** -* Draws a Mermaid graph using the provided graph data -*/ -function drawMermaid(nodes, edges, config) { - const { firstNode, lastNode, nodeColors, withStyles = true, curveStyle = "linear", wrapLabelNWords = 9 } = config ?? {}; - let mermaidGraph = withStyles ? `%%{init: {'flowchart': {'curve': '${curveStyle}'}}}%%\ngraph TD;\n` : "graph TD;\n"; - if (withStyles) { - const defaultClassLabel = "default"; - const formatDict = { [defaultClassLabel]: "{0}({1})" }; - if (firstNode !== void 0) formatDict[firstNode] = "{0}([{1}]):::first"; - if (lastNode !== void 0) formatDict[lastNode] = "{0}([{1}]):::last"; - for (const [key, node] of Object.entries(nodes)) { - const nodeName = node.name.split(":").pop() ?? ""; - const label = MARKDOWN_SPECIAL_CHARS.some((char) => nodeName.startsWith(char) && nodeName.endsWith(char)) ? `

${nodeName}

` : nodeName; - let finalLabel = label; - if (Object.keys(node.metadata ?? {}).length) finalLabel += `
${Object.entries(node.metadata ?? {}).map(([k, v]) => `${k} = ${v}`).join("\n")}`; - const nodeLabel = (formatDict[key] ?? formatDict[defaultClassLabel]).replace("{0}", _escapeNodeLabel(key)).replace("{1}", finalLabel); - mermaidGraph += `\t${nodeLabel}\n`; - } - } - const edgeGroups = {}; - for (const edge of edges) { - const srcParts = edge.source.split(":"); - const tgtParts = edge.target.split(":"); - const commonPrefix = srcParts.filter((src, i) => src === tgtParts[i]).join(":"); - if (!edgeGroups[commonPrefix]) edgeGroups[commonPrefix] = []; - edgeGroups[commonPrefix].push(edge); - } - const seenSubgraphs = /* @__PURE__ */ new Set(); - function sortPrefixesByDepth(prefixes) { - return [...prefixes].sort((a, b) => { - return a.split(":").length - b.split(":").length; - }); - } - function addSubgraph(edges$1, prefix) { - const selfLoop = edges$1.length === 1 && edges$1[0].source === edges$1[0].target; - if (prefix && !selfLoop) { - const subgraph = prefix.split(":").pop(); - if (seenSubgraphs.has(prefix)) throw new Error(`Found duplicate subgraph '${subgraph}' at '${prefix} -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`); - seenSubgraphs.add(prefix); - mermaidGraph += `\tsubgraph ${subgraph}\n`; - } - const nestedPrefixes = sortPrefixesByDepth(Object.keys(edgeGroups).filter((nestedPrefix) => nestedPrefix.startsWith(`${prefix}:`) && nestedPrefix !== prefix && nestedPrefix.split(":").length === prefix.split(":").length + 1)); - for (const nestedPrefix of nestedPrefixes) addSubgraph(edgeGroups[nestedPrefix], nestedPrefix); - for (const edge of edges$1) { - const { source, target, data, conditional } = edge; - let edgeLabel = ""; - if (data !== void 0) { - let edgeData = data; - const words = edgeData.split(" "); - if (words.length > wrapLabelNWords) edgeData = Array.from({ length: Math.ceil(words.length / wrapLabelNWords) }, (_, i) => words.slice(i * wrapLabelNWords, (i + 1) * wrapLabelNWords).join(" ")).join(" 
 "); - edgeLabel = conditional ? ` -.  ${edgeData}  .-> ` : ` --  ${edgeData}  --> `; - } else edgeLabel = conditional ? " -.-> " : " --> "; - mermaidGraph += `\t${_escapeNodeLabel(source)}${edgeLabel}${_escapeNodeLabel(target)};\n`; - } - if (prefix && !selfLoop) mermaidGraph += " end\n"; - } - addSubgraph(edgeGroups[""] ?? [], ""); - for (const prefix in edgeGroups) if (!prefix.includes(":") && prefix !== "") addSubgraph(edgeGroups[prefix], prefix); - if (withStyles) mermaidGraph += _generateMermaidGraphStyles(nodeColors ?? {}); - return mermaidGraph; -} -/** -* Renders Mermaid graph using the Mermaid.INK API. -* -* @example -* ```javascript -* const image = await drawMermaidImage(mermaidSyntax, { -* backgroundColor: "white", -* imageType: "png", -* }); -* fs.writeFileSync("image.png", image); -* ``` -* -* @param mermaidSyntax - The Mermaid syntax to render. -* @param config - The configuration for the image. -* @returns The image as a Blob. -*/ -async function drawMermaidImage(mermaidSyntax, config) { - let backgroundColor = config?.backgroundColor ?? "white"; - const imageType = config?.imageType ?? "png"; - const mermaidSyntaxEncoded = toBase64Url(mermaidSyntax); - if (backgroundColor !== void 0) { - const hexColorPattern = /^#(?:[0-9a-fA-F]{3}){1,2}$/; - if (!hexColorPattern.test(backgroundColor)) backgroundColor = `!${backgroundColor}`; - } - const imageUrl = `https://mermaid.ink/img/${mermaidSyntaxEncoded}?bgColor=${backgroundColor}&type=${imageType}`; - const res = await fetch(imageUrl); - if (!res.ok) throw new Error([ - `Failed to render the graph using the Mermaid.INK API.`, - `Status code: ${res.status}`, - `Status text: ${res.statusText}` - ].join("\n")); - const content = await res.blob(); - return content; -} - -//#endregion - -//# sourceMappingURL=graph_mermaid.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/graph.js - - - - - - -//#region src/runnables/graph.ts -var graph_exports = {}; -__export(graph_exports, { Graph: () => Graph }); -function nodeDataStr(id, data) { - if (id !== void 0 && !wrapper_validate(id)) return id; - else if (isRunnableInterface(data)) try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; - return dataStr; - } catch { - return data.getName(); - } - else return data.name ?? "UnknownSchema"; -} -function nodeDataJson(node) { - if (isRunnableInterface(node.data)) return { - type: "runnable", - data: { - id: node.data.lc_id, - name: node.data.getName() - } - }; - else return { - type: "schema", - data: { - ...toJsonSchema(node.data.schema), - title: node.data.name - } - }; -} -var Graph = class Graph { - nodes = {}; - edges = []; - constructor(params) { - this.nodes = params?.nodes ?? this.nodes; - this.edges = params?.edges ?? this.edges; - } - toJSON() { - const stableNodeIds = {}; - Object.values(this.nodes).forEach((node, i) => { - stableNodeIds[node.id] = wrapper_validate(node.id) ? i : node.id; - }); - return { - nodes: Object.values(this.nodes).map((node) => ({ - id: stableNodeIds[node.id], - ...nodeDataJson(node) - })), - edges: this.edges.map((edge) => { - const item = { - source: stableNodeIds[edge.source], - target: stableNodeIds[edge.target] - }; - if (typeof edge.data !== "undefined") item.data = edge.data; - if (typeof edge.conditional !== "undefined") item.conditional = edge.conditional; - return item; - }) - }; - } - addNode(data, id, metadata) { - if (id !== void 0 && this.nodes[id] !== void 0) throw new Error(`Node with id ${id} already exists`); - const nodeId = id ?? v4(); - const node = { - id: nodeId, - data, - name: nodeDataStr(id, data), - metadata - }; - this.nodes[nodeId] = node; - return node; - } - removeNode(node) { - delete this.nodes[node.id]; - this.edges = this.edges.filter((edge) => edge.source !== node.id && edge.target !== node.id); - } - addEdge(source, target, data, conditional) { - if (this.nodes[source.id] === void 0) throw new Error(`Source node ${source.id} not in graph`); - if (this.nodes[target.id] === void 0) throw new Error(`Target node ${target.id} not in graph`); - const edge = { - source: source.id, - target: target.id, - data, - conditional - }; - this.edges.push(edge); - return edge; - } - firstNode() { - return _firstNode(this); - } - lastNode() { - return _lastNode(this); - } - /** - * Add all nodes and edges from another graph. - * Note this doesn't check for duplicates, nor does it connect the graphs. - */ - extend(graph, prefix = "") { - let finalPrefix = prefix; - const nodeIds = Object.values(graph.nodes).map((node) => node.id); - if (nodeIds.every(wrapper_validate)) finalPrefix = ""; - const prefixed = (id) => { - return finalPrefix ? `${finalPrefix}:${id}` : id; - }; - Object.entries(graph.nodes).forEach(([key, value]) => { - this.nodes[prefixed(key)] = { - ...value, - id: prefixed(key) - }; - }); - const newEdges = graph.edges.map((edge) => { - return { - ...edge, - source: prefixed(edge.source), - target: prefixed(edge.target) - }; - }); - this.edges = [...this.edges, ...newEdges]; - const first = graph.firstNode(); - const last = graph.lastNode(); - return [first ? { - id: prefixed(first.id), - data: first.data - } : void 0, last ? { - id: prefixed(last.id), - data: last.data - } : void 0]; - } - trimFirstNode() { - const firstNode = this.firstNode(); - if (firstNode && _firstNode(this, [firstNode.id])) this.removeNode(firstNode); - } - trimLastNode() { - const lastNode = this.lastNode(); - if (lastNode && _lastNode(this, [lastNode.id])) this.removeNode(lastNode); - } - /** - * Return a new graph with all nodes re-identified, - * using their unique, readable names where possible. - */ - reid() { - const nodeLabels = Object.fromEntries(Object.values(this.nodes).map((node) => [node.id, node.name])); - const nodeLabelCounts = /* @__PURE__ */ new Map(); - Object.values(nodeLabels).forEach((label) => { - nodeLabelCounts.set(label, (nodeLabelCounts.get(label) || 0) + 1); - }); - const getNodeId = (nodeId) => { - const label = nodeLabels[nodeId]; - if (wrapper_validate(nodeId) && nodeLabelCounts.get(label) === 1) return label; - else return nodeId; - }; - return new Graph({ - nodes: Object.fromEntries(Object.entries(this.nodes).map(([id, node]) => [getNodeId(id), { - ...node, - id: getNodeId(id) - }])), - edges: this.edges.map((edge) => ({ - ...edge, - source: getNodeId(edge.source), - target: getNodeId(edge.target) - })) - }); - } - drawMermaid(params) { - const { withStyles, curveStyle, nodeColors = { - default: "fill:#f2f0ff,line-height:1.2", - first: "fill-opacity:0", - last: "fill:#bfb6fc" - }, wrapLabelNWords } = params ?? {}; - const graph = this.reid(); - const firstNode = graph.firstNode(); - const lastNode = graph.lastNode(); - return drawMermaid(graph.nodes, graph.edges, { - firstNode: firstNode?.id, - lastNode: lastNode?.id, - withStyles, - curveStyle, - nodeColors, - wrapLabelNWords - }); - } - async drawMermaidPng(params) { - const mermaidSyntax = this.drawMermaid(params); - return drawMermaidImage(mermaidSyntax, { backgroundColor: params?.backgroundColor }); - } -}; -/** -* Find the single node that is not a target of any edge. -* Exclude nodes/sources with ids in the exclude list. -* If there is no such node, or there are multiple, return undefined. -* When drawing the graph, this node would be the origin. -*/ -function _firstNode(graph, exclude = []) { - const targets = new Set(graph.edges.filter((edge) => !exclude.includes(edge.source)).map((edge) => edge.target)); - const found = []; - for (const node of Object.values(graph.nodes)) if (!exclude.includes(node.id) && !targets.has(node.id)) found.push(node); - return found.length === 1 ? found[0] : void 0; -} -/** -* Find the single node that is not a source of any edge. -* Exclude nodes/targets with ids in the exclude list. -* If there is no such node, or there are multiple, return undefined. -* When drawing the graph, this node would be the destination. -*/ -function _lastNode(graph, exclude = []) { - const sources = new Set(graph.edges.filter((edge) => !exclude.includes(edge.target)).map((edge) => edge.source)); - const found = []; - for (const node of Object.values(graph.nodes)) if (!exclude.includes(node.id) && !sources.has(node.id)) found.push(node); - return found.length === 1 ? found[0] : void 0; -} - -//#endregion - -//# sourceMappingURL=graph.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/event_stream.js - - - - - -//#region src/tracers/event_stream.ts -function assignName({ name, serialized }) { - if (name !== void 0) return name; - if (serialized?.name !== void 0) return serialized.name; - else if (serialized?.id !== void 0 && Array.isArray(serialized?.id)) return serialized.id[serialized.id.length - 1]; - return "Unnamed"; -} -const isStreamEventsHandler = (handler) => handler.name === "event_stream_tracer"; -/** -* Class that extends the `BaseTracer` class from the -* `langchain.callbacks.tracers.base` module. It represents a callback -* handler that logs the execution of runs and emits `RunLog` instances to a -* `RunLogStream`. -*/ -var EventStreamCallbackHandler = class extends BaseTracer { - autoClose = true; - includeNames; - includeTypes; - includeTags; - excludeNames; - excludeTypes; - excludeTags; - runInfoMap = /* @__PURE__ */ new Map(); - tappedPromises = /* @__PURE__ */ new Map(); - transformStream; - writer; - receiveStream; - readableStreamClosed = false; - name = "event_stream_tracer"; - lc_prefer_streaming = true; - constructor(fields) { - super({ - _awaitHandler: true, - ...fields - }); - this.autoClose = fields?.autoClose ?? true; - this.includeNames = fields?.includeNames; - this.includeTypes = fields?.includeTypes; - this.includeTags = fields?.includeTags; - this.excludeNames = fields?.excludeNames; - this.excludeTypes = fields?.excludeTypes; - this.excludeTags = fields?.excludeTags; - this.transformStream = new TransformStream({ flush: () => { - this.readableStreamClosed = true; - } }); - this.writer = this.transformStream.writable.getWriter(); - this.receiveStream = IterableReadableStream.fromReadableStream(this.transformStream.readable); - } - [Symbol.asyncIterator]() { - return this.receiveStream; - } - async persistRun(_run) {} - _includeRun(run) { - const runTags = run.tags ?? []; - let include = this.includeNames === void 0 && this.includeTags === void 0 && this.includeTypes === void 0; - if (this.includeNames !== void 0) include = include || this.includeNames.includes(run.name); - if (this.includeTypes !== void 0) include = include || this.includeTypes.includes(run.runType); - if (this.includeTags !== void 0) include = include || runTags.find((tag) => this.includeTags?.includes(tag)) !== void 0; - if (this.excludeNames !== void 0) include = include && !this.excludeNames.includes(run.name); - if (this.excludeTypes !== void 0) include = include && !this.excludeTypes.includes(run.runType); - if (this.excludeTags !== void 0) include = include && runTags.every((tag) => !this.excludeTags?.includes(tag)); - return include; - } - async *tapOutputIterable(runId, outputStream) { - const firstChunk = await outputStream.next(); - if (firstChunk.done) return; - const runInfo = this.runInfoMap.get(runId); - if (runInfo === void 0) { - yield firstChunk.value; - return; - } - function _formatOutputChunk(eventType, data) { - if (eventType === "llm" && typeof data === "string") return new GenerationChunk({ text: data }); - return data; - } - let tappedPromise = this.tappedPromises.get(runId); - if (tappedPromise === void 0) { - let tappedPromiseResolver; - tappedPromise = new Promise((resolve) => { - tappedPromiseResolver = resolve; - }); - this.tappedPromises.set(runId, tappedPromise); - try { - const event = { - event: `on_${runInfo.runType}_stream`, - run_id: runId, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata, - data: {} - }; - await this.send({ - ...event, - data: { chunk: _formatOutputChunk(runInfo.runType, firstChunk.value) } - }, runInfo); - yield firstChunk.value; - for await (const chunk of outputStream) { - if (runInfo.runType !== "tool" && runInfo.runType !== "retriever") await this.send({ - ...event, - data: { chunk: _formatOutputChunk(runInfo.runType, chunk) } - }, runInfo); - yield chunk; - } - } finally { - tappedPromiseResolver?.(); - } - } else { - yield firstChunk.value; - for await (const chunk of outputStream) yield chunk; - } - } - async send(payload, run) { - if (this.readableStreamClosed) return; - if (this._includeRun(run)) await this.writer.write(payload); - } - async sendEndEvent(payload, run) { - const tappedPromise = this.tappedPromises.get(payload.run_id); - if (tappedPromise !== void 0) tappedPromise.then(() => { - this.send(payload, run); - }); - else await this.send(payload, run); - } - async onLLMStart(run) { - const runName = assignName(run); - const runType = run.inputs.messages !== void 0 ? "chat_model" : "llm"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType, - inputs: run.inputs - }; - this.runInfoMap.set(run.id, runInfo); - const eventName = `on_${runType}_start`; - await this.send({ - event: eventName, - data: { input: run.inputs }, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onLLMNewToken(run, token, kwargs) { - const runInfo = this.runInfoMap.get(run.id); - let chunk; - let eventName; - if (runInfo === void 0) throw new Error(`onLLMNewToken: Run ID ${run.id} not found in run map.`); - if (this.runInfoMap.size === 1) return; - if (runInfo.runType === "chat_model") { - eventName = "on_chat_model_stream"; - if (kwargs?.chunk === void 0) chunk = new AIMessageChunk({ - content: token, - id: `run-${run.id}` - }); - else chunk = kwargs.chunk.message; - } else if (runInfo.runType === "llm") { - eventName = "on_llm_stream"; - if (kwargs?.chunk === void 0) chunk = new GenerationChunk({ text: token }); - else chunk = kwargs.chunk; - } else throw new Error(`Unexpected run type ${runInfo.runType}`); - await this.send({ - event: eventName, - data: { chunk }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onLLMEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - let eventName; - if (runInfo === void 0) throw new Error(`onLLMEnd: Run ID ${run.id} not found in run map.`); - const generations = run.outputs?.generations; - let output; - if (runInfo.runType === "chat_model") { - for (const generation of generations ?? []) { - if (output !== void 0) break; - output = generation[0]?.message; - } - eventName = "on_chat_model_end"; - } else if (runInfo.runType === "llm") { - output = { - generations: generations?.map((generation) => { - return generation.map((chunk) => { - return { - text: chunk.text, - generationInfo: chunk.generationInfo - }; - }); - }), - llmOutput: run.outputs?.llmOutput ?? {} - }; - eventName = "on_llm_end"; - } else throw new Error(`onLLMEnd: Unexpected run type: ${runInfo.runType}`); - await this.sendEndEvent({ - event: eventName, - data: { - output, - input: runInfo.inputs - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onChainStart(run) { - const runName = assignName(run); - const runType = run.run_type ?? "chain"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType: run.run_type - }; - let eventData = {}; - if (run.inputs.input === "" && Object.keys(run.inputs).length === 1) { - eventData = {}; - runInfo.inputs = {}; - } else if (run.inputs.input !== void 0) { - eventData.input = run.inputs.input; - runInfo.inputs = run.inputs.input; - } else { - eventData.input = run.inputs; - runInfo.inputs = run.inputs; - } - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: `on_${runType}_start`, - data: eventData, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onChainEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === void 0) throw new Error(`onChainEnd: Run ID ${run.id} not found in run map.`); - const eventName = `on_${run.run_type}_end`; - const inputs = run.inputs ?? runInfo.inputs ?? {}; - const outputs = run.outputs?.output ?? run.outputs; - const data = { - output: outputs, - input: inputs - }; - if (inputs.input && Object.keys(inputs).length === 1) { - data.input = inputs.input; - runInfo.inputs = inputs.input; - } - await this.sendEndEvent({ - event: eventName, - data, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata ?? {} - }, runInfo); - } - async onToolStart(run) { - const runName = assignName(run); - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType: "tool", - inputs: run.inputs ?? {} - }; - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: "on_tool_start", - data: { input: run.inputs ?? {} }, - name: runName, - run_id: run.id, - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onToolEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === void 0) throw new Error(`onToolEnd: Run ID ${run.id} not found in run map.`); - if (runInfo.inputs === void 0) throw new Error(`onToolEnd: Run ID ${run.id} is a tool call, and is expected to have traced inputs.`); - const output = run.outputs?.output === void 0 ? run.outputs : run.outputs.output; - await this.sendEndEvent({ - event: "on_tool_end", - data: { - output, - input: runInfo.inputs - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async onRetrieverStart(run) { - const runName = assignName(run); - const runType = "retriever"; - const runInfo = { - tags: run.tags ?? [], - metadata: run.extra?.metadata ?? {}, - name: runName, - runType, - inputs: { query: run.inputs.query } - }; - this.runInfoMap.set(run.id, runInfo); - await this.send({ - event: "on_retriever_start", - data: { input: { query: run.inputs.query } }, - name: runName, - tags: run.tags ?? [], - run_id: run.id, - metadata: run.extra?.metadata ?? {} - }, runInfo); - } - async onRetrieverEnd(run) { - const runInfo = this.runInfoMap.get(run.id); - this.runInfoMap.delete(run.id); - if (runInfo === void 0) throw new Error(`onRetrieverEnd: Run ID ${run.id} not found in run map.`); - await this.sendEndEvent({ - event: "on_retriever_end", - data: { - output: run.outputs?.documents ?? run.outputs, - input: runInfo.inputs - }, - run_id: run.id, - name: runInfo.name, - tags: runInfo.tags, - metadata: runInfo.metadata - }, runInfo); - } - async handleCustomEvent(eventName, data, runId) { - const runInfo = this.runInfoMap.get(runId); - if (runInfo === void 0) throw new Error(`handleCustomEvent: Run ID ${runId} not found in run map.`); - await this.send({ - event: "on_custom_event", - run_id: runId, - name: eventName, - tags: runInfo.tags, - metadata: runInfo.metadata, - data - }, runInfo); - } - async finish() { - const pendingPromises = [...this.tappedPromises.values()]; - Promise.all(pendingPromises).finally(() => { - this.writer.close(); - }); - } -}; - -//#endregion - -//# sourceMappingURL=event_stream.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/root_listener.js - - -//#region src/tracers/root_listener.ts -var RootListenersTracer = class extends BaseTracer { - name = "RootListenersTracer"; - /** The Run's ID. Type UUID */ - rootId; - config; - argOnStart; - argOnEnd; - argOnError; - constructor({ config, onStart, onEnd, onError }) { - super({ _awaitHandler: true }); - this.config = config; - this.argOnStart = onStart; - this.argOnEnd = onEnd; - this.argOnError = onError; - } - /** - * This is a legacy method only called once for an entire run tree - * therefore not useful here - * @param {Run} _ Not used - */ - persistRun(_) { - return Promise.resolve(); - } - async onRunCreate(run) { - if (this.rootId) return; - this.rootId = run.id; - if (this.argOnStart) await this.argOnStart(run, this.config); - } - async onRunUpdate(run) { - if (run.id !== this.rootId) return; - if (!run.error) { - if (this.argOnEnd) await this.argOnEnd(run, this.config); - } else if (this.argOnError) await this.argOnError(run, this.config); - } -}; - -//#endregion - -//# sourceMappingURL=root_listener.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/wrappers.js - - -//#region src/runnables/wrappers.ts -function convertToHttpEventStream(stream) { - const encoder = new TextEncoder(); - const finalStream = new ReadableStream({ async start(controller) { - for await (const chunk of stream) controller.enqueue(encoder.encode(`event: data\ndata: ${JSON.stringify(chunk)}\n\n`)); - controller.enqueue(encoder.encode("event: end\n\n")); - controller.close(); - } }); - return IterableReadableStream.fromReadableStream(finalStream); -} - -//#endregion - -//# sourceMappingURL=wrappers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/iter.js - - - - -//#region src/runnables/iter.ts -function isIterableIterator(thing) { - return typeof thing === "object" && thing !== null && typeof thing[Symbol.iterator] === "function" && typeof thing.next === "function"; -} -const isIterator = (x) => x != null && typeof x === "object" && "next" in x && typeof x.next === "function"; -function isAsyncIterable(thing) { - return typeof thing === "object" && thing !== null && typeof thing[Symbol.asyncIterator] === "function"; -} -function* consumeIteratorInContext(context, iter) { - while (true) { - const { value, done } = async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(context), iter.next.bind(iter), true); - if (done) break; - else yield value; - } -} -async function* consumeAsyncIterableInContext(context, iter) { - const iterator = iter[Symbol.asyncIterator](); - while (true) { - const { value, done } = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(context), iterator.next.bind(iter), true); - if (done) break; - else yield value; - } -} - -//#endregion - -//# sourceMappingURL=iter.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/base.js - - - - - - - - - - - - - - - - - - - - - -//#region src/runnables/base.ts -function base_coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; -} -/** -* A Runnable is a generic unit of work that can be invoked, batched, streamed, and/or -* transformed. -*/ -var Runnable = class extends Serializable { - lc_runnable = true; - name; - getName(suffix) { - const name = this.name ?? this.constructor.lc_name() ?? this.constructor.name; - return suffix ? `${name}${suffix}` : name; - } - /** - * Add retry logic to an existing runnable. - * @param fields.stopAfterAttempt The number of attempts to retry. - * @param fields.onFailedAttempt A function that is called when a retry fails. - * @returns A new RunnableRetry that, when invoked, will retry according to the parameters. - */ - withRetry(fields) { - return new RunnableRetry({ - bound: this, - kwargs: {}, - config: {}, - maxAttemptNumber: fields?.stopAfterAttempt, - ...fields - }); - } - /** - * Bind config to a Runnable, returning a new Runnable. - * @param config New configuration parameters to attach to the new runnable. - * @returns A new RunnableBinding with a config matching what's passed. - */ - withConfig(config) { - return new RunnableBinding({ - bound: this, - config, - kwargs: {} - }); - } - /** - * Create a new runnable from the current one that will try invoking - * other passed fallback runnables if the initial invocation fails. - * @param fields.fallbacks Other runnables to call if the runnable errors. - * @returns A new RunnableWithFallbacks. - */ - withFallbacks(fields) { - const fallbacks = Array.isArray(fields) ? fields : fields.fallbacks; - return new RunnableWithFallbacks({ - runnable: this, - fallbacks - }); - } - _getOptionsList(options, length = 0) { - if (Array.isArray(options) && options.length !== length) throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${options.length} options for ${length} inputs`); - if (Array.isArray(options)) return options.map(ensureConfig); - if (length > 1 && !Array.isArray(options) && options.runId) { - console.warn("Provided runId will be used only for the first element of the batch."); - const subsequent = Object.fromEntries(Object.entries(options).filter(([key]) => key !== "runId")); - return Array.from({ length }, (_, i) => ensureConfig(i === 0 ? options : subsequent)); - } - return Array.from({ length }, () => ensureConfig(options)); - } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const maxConcurrency = configList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; - const caller = new async_caller_AsyncCaller({ - maxConcurrency, - onFailedAttempt: (e) => { - throw e; - } - }); - const batchCalls = inputs.map((input, i) => caller.call(async () => { - try { - const result = await this.invoke(input, configList[i]); - return result; - } catch (e) { - if (batchOptions?.returnExceptions) return e; - throw e; - } - })); - return Promise.all(batchCalls); - } - /** - * Default streaming implementation. - * Subclasses should override this method if they support streaming output. - * @param input - * @param options - */ - async *_streamIterator(input, options) { - yield this.invoke(input, options); - } - /** - * Stream output in chunks. - * @param input - * @param options - * @returns A readable stream that is also an iterable. - */ - async stream(input, options) { - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this._streamIterator(input, config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } - _separateRunnableConfigFromCallOptions(options) { - let runnableConfig; - if (options === void 0) runnableConfig = ensureConfig(options); - else runnableConfig = ensureConfig({ - callbacks: options.callbacks, - tags: options.tags, - metadata: options.metadata, - runName: options.runName, - configurable: options.configurable, - recursionLimit: options.recursionLimit, - maxConcurrency: options.maxConcurrency, - runId: options.runId, - timeout: options.timeout, - signal: options.signal - }); - const callOptions = { ...options }; - delete callOptions.callbacks; - delete callOptions.tags; - delete callOptions.metadata; - delete callOptions.runName; - delete callOptions.configurable; - delete callOptions.recursionLimit; - delete callOptions.maxConcurrency; - delete callOptions.runId; - delete callOptions.timeout; - delete callOptions.signal; - return [runnableConfig, callOptions]; - } - async _callWithConfig(func, input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, config?.runType, void 0, void 0, config?.runName ?? this.getName()); - delete config.runId; - let output; - try { - const promise = func.call(this, input, config, runManager); - output = await raceWithSignal(promise, options?.signal); - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); - return output; - } - /** - * Internal method that handles batching and configuration for a runnable - * It takes a function, input values, and optional configuration, and - * returns a promise that resolves to the output values. - * @param func The function to be executed for each input value. - * @param input The input values to be processed. - * @param config Optional configuration for the function execution. - * @returns A promise that resolves to the output values. - */ - async _batchWithConfig(func, inputs, options, batchOptions) { - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(optionsList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), optionsList[i].runId, optionsList[i].runType, void 0, void 0, optionsList[i].runName ?? this.getName()); - delete optionsList[i].runId; - return handleStartRes; - })); - let outputs; - try { - const promise = func.call(this, inputs, optionsList, runManagers, batchOptions); - outputs = await raceWithSignal(promise, optionsList?.[0]?.signal); - } catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; - } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(outputs, "output")))); - return outputs; - } - /** @internal */ - _concatOutputChunks(first, second) { - return concat(first, second); - } - /** - * Helper method to transform an Iterator of Input values into an Iterator of - * Output values, with callbacks. - * Use this to implement `stream()` or `transform()` in Runnable subclasses. - */ - async *_transformStreamWithConfig(inputGenerator, transformer, options) { - let finalInput; - let finalInputSupported = true; - let finalOutput; - let finalOutputSupported = true; - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const outerThis = this; - async function* wrapInputForTracing() { - for await (const chunk of inputGenerator) { - if (finalInputSupported) if (finalInput === void 0) finalInput = chunk; - else try { - finalInput = outerThis._concatOutputChunks(finalInput, chunk); - } catch { - finalInput = void 0; - finalInputSupported = false; - } - yield chunk; - } - } - let runManager; - try { - const pipe = await pipeGeneratorWithSetup(transformer.bind(this), wrapInputForTracing(), async () => callbackManager_?.handleChainStart(this.toJSON(), { input: "" }, config.runId, config.runType, void 0, void 0, config.runName ?? this.getName(), void 0, { lc_defers_inputs: true }), options?.signal, config); - delete config.runId; - runManager = pipe.setup; - const streamEventsHandler = runManager?.handlers.find(isStreamEventsHandler); - let iterator = pipe.output; - if (streamEventsHandler !== void 0 && runManager !== void 0) iterator = streamEventsHandler.tapOutputIterable(runManager.runId, iterator); - const streamLogHandler = runManager?.handlers.find(isLogStreamHandler); - if (streamLogHandler !== void 0 && runManager !== void 0) iterator = streamLogHandler.tapOutputIterable(runManager.runId, iterator); - for await (const chunk of iterator) { - yield chunk; - if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = void 0; - finalOutputSupported = false; - } - } - } catch (e) { - await runManager?.handleChainError(e, void 0, void 0, void 0, { inputs: base_coerceToDict(finalInput, "input") }); - throw e; - } - await runManager?.handleChainEnd(finalOutput ?? {}, void 0, void 0, void 0, { inputs: base_coerceToDict(finalInput, "input") }); - } - getGraph(_) { - const graph = new Graph(); - const inputNode = graph.addNode({ - name: `${this.getName()}Input`, - schema: anyType() - }); - const runnableNode = graph.addNode(this); - const outputNode = graph.addNode({ - name: `${this.getName()}Output`, - schema: anyType() - }); - graph.addEdge(inputNode, runnableNode); - graph.addEdge(runnableNode, outputNode); - return graph; - } - /** - * Create a new runnable sequence that runs each individual runnable in series, - * piping the output of one runnable into another runnable or runnable-like. - * @param coerceable A runnable, function, or object whose values are functions or runnables. - * @returns A new runnable sequence. - */ - pipe(coerceable) { - return new RunnableSequence({ - first: this, - last: _coerceToRunnable(coerceable) - }); - } - /** - * Pick keys from the dict output of this runnable. Returns a new runnable. - */ - pick(keys) { - return this.pipe(new RunnablePick(keys)); - } - /** - * Assigns new fields to the dict output of this runnable. Returns a new runnable. - */ - assign(mapping) { - return this.pipe(new RunnableAssign(new RunnableMap({ steps: mapping }))); - } - /** - * Default implementation of transform, which buffers input and then calls stream. - * Subclasses should override this method if they can start producing output while - * input is still being generated. - * @param generator - * @param options - */ - async *transform(generator, options) { - let finalChunk; - for await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk; - else finalChunk = this._concatOutputChunks(finalChunk, chunk); - yield* this._streamIterator(finalChunk, ensureConfig(options)); - } - /** - * Stream all output from a runnable, as reported to the callback system. - * This includes all inner runs of LLMs, Retrievers, Tools, etc. - * Output is streamed as Log objects, which include a list of - * jsonpatch ops that describe how the state of the run has changed in each - * step, and the final state of the run. - * The jsonpatch ops can be applied in order to construct state. - * @param input - * @param options - * @param streamOptions - */ - async *streamLog(input, options, streamOptions) { - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "original" - }); - const config = ensureConfig(options); - yield* this._streamLog(input, logStreamCallbackHandler, config); - } - async *_streamLog(input, logStreamCallbackHandler, config) { - const { callbacks } = config; - if (callbacks === void 0) config.callbacks = [logStreamCallbackHandler]; - else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat([logStreamCallbackHandler]); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(logStreamCallbackHandler, true); - config.callbacks = copiedCallbacks; - } - const runnableStreamPromise = this.stream(input, config); - async function consumeRunnableStream() { - try { - const runnableStream = await runnableStreamPromise; - for await (const chunk of runnableStream) { - const patch = new RunLogPatch({ ops: [{ - op: "add", - path: "/streamed_output/-", - value: chunk - }] }); - await logStreamCallbackHandler.writer.write(patch); - } - } finally { - await logStreamCallbackHandler.writer.close(); - } - } - const runnableStreamConsumePromise = consumeRunnableStream(); - try { - for await (const log of logStreamCallbackHandler) yield log; - } finally { - await runnableStreamConsumePromise; - } - } - streamEvents(input, options, streamOptions) { - let stream; - if (options.version === "v1") stream = this._streamEventsV1(input, options, streamOptions); - else if (options.version === "v2") stream = this._streamEventsV2(input, options, streamOptions); - else throw new Error(`Only versions "v1" and "v2" of the schema are currently supported.`); - if (options.encoding === "text/event-stream") return convertToHttpEventStream(stream); - else return IterableReadableStream.fromAsyncGenerator(stream); - } - async *_streamEventsV2(input, options, streamOptions) { - const eventStreamer = new EventStreamCallbackHandler({ - ...streamOptions, - autoClose: false - }); - const config = ensureConfig(options); - const runId = config.runId ?? v4(); - config.runId = runId; - const callbacks = config.callbacks; - if (callbacks === void 0) config.callbacks = [eventStreamer]; - else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(eventStreamer); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(eventStreamer, true); - config.callbacks = copiedCallbacks; - } - const abortController = new AbortController(); - const outerThis = this; - async function consumeRunnableStream() { - let signal; - let listener = null; - try { - if (options?.signal) if ("any" in AbortSignal) signal = AbortSignal.any([abortController.signal, options.signal]); - else { - signal = options.signal; - listener = () => { - abortController.abort(); - }; - options.signal.addEventListener("abort", listener, { once: true }); - } - else signal = abortController.signal; - const runnableStream = await outerThis.stream(input, { - ...config, - signal - }); - const tappedStream = eventStreamer.tapOutputIterable(runId, runnableStream); - for await (const _ of tappedStream) if (abortController.signal.aborted) break; - } finally { - await eventStreamer.finish(); - if (signal && listener) signal.removeEventListener("abort", listener); - } - } - const runnableStreamConsumePromise = consumeRunnableStream(); - let firstEventSent = false; - let firstEventRunId; - try { - for await (const event of eventStreamer) { - if (!firstEventSent) { - event.data.input = input; - firstEventSent = true; - firstEventRunId = event.run_id; - yield event; - continue; - } - if (event.run_id === firstEventRunId && event.event.endsWith("_end")) { - if (event.data?.input) delete event.data.input; - } - yield event; - } - } finally { - abortController.abort(); - await runnableStreamConsumePromise; - } - } - async *_streamEventsV1(input, options, streamOptions) { - let runLog; - let hasEncounteredStartEvent = false; - const config = ensureConfig(options); - const rootTags = config.tags ?? []; - const rootMetadata = config.metadata ?? {}; - const rootName = config.runName ?? this.getName(); - const logStreamCallbackHandler = new LogStreamCallbackHandler({ - ...streamOptions, - autoClose: false, - _schemaFormat: "streaming_events" - }); - const rootEventFilter = new _RootEventFilter({ ...streamOptions }); - const logStream = this._streamLog(input, logStreamCallbackHandler, config); - for await (const log of logStream) { - if (!runLog) runLog = RunLog.fromRunLogPatch(log); - else runLog = runLog.concat(log); - if (runLog.state === void 0) throw new Error(`Internal error: "streamEvents" state is missing. Please open a bug report.`); - if (!hasEncounteredStartEvent) { - hasEncounteredStartEvent = true; - const state$2 = { ...runLog.state }; - const event = { - run_id: state$2.id, - event: `on_${state$2.type}_start`, - name: rootName, - tags: rootTags, - metadata: rootMetadata, - data: { input } - }; - if (rootEventFilter.includeEvent(event, state$2.type)) yield event; - } - const paths = log.ops.filter((op) => op.path.startsWith("/logs/")).map((op) => op.path.split("/")[2]); - const dedupedPaths = [...new Set(paths)]; - for (const path of dedupedPaths) { - let eventType; - let data = {}; - const logEntry = runLog.state.logs[path]; - if (logEntry.end_time === void 0) if (logEntry.streamed_output.length > 0) eventType = "stream"; - else eventType = "start"; - else eventType = "end"; - if (eventType === "start") { - if (logEntry.inputs !== void 0) data.input = logEntry.inputs; - } else if (eventType === "end") { - if (logEntry.inputs !== void 0) data.input = logEntry.inputs; - data.output = logEntry.final_output; - } else if (eventType === "stream") { - const chunkCount = logEntry.streamed_output.length; - if (chunkCount !== 1) throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${logEntry.name}"`); - data = { chunk: logEntry.streamed_output[0] }; - logEntry.streamed_output = []; - } - yield { - event: `on_${logEntry.type}_${eventType}`, - name: logEntry.name, - run_id: logEntry.id, - tags: logEntry.tags, - metadata: logEntry.metadata, - data - }; - } - const { state: state$1 } = runLog; - if (state$1.streamed_output.length > 0) { - const chunkCount = state$1.streamed_output.length; - if (chunkCount !== 1) throw new Error(`Expected exactly one chunk of streamed output, got ${chunkCount} instead. Encountered in: "${state$1.name}"`); - const data = { chunk: state$1.streamed_output[0] }; - state$1.streamed_output = []; - const event = { - event: `on_${state$1.type}_stream`, - run_id: state$1.id, - tags: rootTags, - metadata: rootMetadata, - name: rootName, - data - }; - if (rootEventFilter.includeEvent(event, state$1.type)) yield event; - } - } - const state = runLog?.state; - if (state !== void 0) { - const event = { - event: `on_${state.type}_end`, - name: rootName, - run_id: state.id, - tags: rootTags, - metadata: rootMetadata, - data: { output: state.final_output } - }; - if (rootEventFilter.includeEvent(event, state.type)) yield event; - } - } - static isRunnable(thing) { - return isRunnableInterface(thing); - } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError }) { - return new RunnableBinding({ - bound: this, - config: {}, - configFactories: [(config) => ({ callbacks: [new RootListenersTracer({ - config, - onStart, - onEnd, - onError - })] })] - }); - } - /** - * Convert a runnable to a tool. Return a new instance of `RunnableToolLike` - * which contains the runnable, name, description and schema. - * - * @template {T extends RunInput = RunInput} RunInput - The input type of the runnable. Should be the same as the `RunInput` type of the runnable. - * - * @param fields - * @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. - * @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. - * @param {z.ZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. - * @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. - */ - asTool(fields) { - return convertRunnableToTool(this, fields); - } -}; -/** -* Wraps a runnable and applies partial config upon invocation. -* -* @example -* ```typescript -* import { -* type RunnableConfig, -* RunnableLambda, -* } from "@langchain/core/runnables"; -* -* const enhanceProfile = ( -* profile: Record, -* config?: RunnableConfig -* ) => { -* if (config?.configurable?.role) { -* return { ...profile, role: config.configurable.role }; -* } -* return profile; -* }; -* -* const runnable = RunnableLambda.from(enhanceProfile); -* -* // Bind configuration to the runnable to set the user's role dynamically -* const adminRunnable = runnable.withConfig({ configurable: { role: "Admin" } }); -* const userRunnable = runnable.withConfig({ configurable: { role: "User" } }); -* -* const result1 = await adminRunnable.invoke({ -* name: "Alice", -* email: "alice@example.com" -* }); -* -* // { name: "Alice", email: "alice@example.com", role: "Admin" } -* -* const result2 = await userRunnable.invoke({ -* name: "Bob", -* email: "bob@example.com" -* }); -* -* // { name: "Bob", email: "bob@example.com", role: "User" } -* ``` -*/ -var RunnableBinding = class RunnableBinding extends Runnable { - static lc_name() { - return "RunnableBinding"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - bound; - config; - kwargs; - configFactories; - constructor(fields) { - super(fields); - this.bound = fields.bound; - this.kwargs = fields.kwargs; - this.config = fields.config; - this.configFactories = fields.configFactories; - } - getName(suffix) { - return this.bound.getName(suffix); - } - async _mergeConfig(...options) { - const config = mergeConfigs(this.config, ...options); - return mergeConfigs(config, ...this.configFactories ? await Promise.all(this.configFactories.map(async (configFactory) => await configFactory(config))) : []); - } - withConfig(config) { - return new this.constructor({ - bound: this.bound, - kwargs: this.kwargs, - config: { - ...this.config, - ...config - } - }); - } - withRetry(fields) { - return new RunnableRetry({ - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - maxAttemptNumber: fields?.stopAfterAttempt, - ...fields - }); - } - async invoke(input, options) { - return this.bound.invoke(input, await this._mergeConfig(options, this.kwargs)); - } - async batch(inputs, options, batchOptions) { - const mergedOptions = Array.isArray(options) ? await Promise.all(options.map(async (individualOption) => this._mergeConfig(ensureConfig(individualOption), this.kwargs))) : await this._mergeConfig(ensureConfig(options), this.kwargs); - return this.bound.batch(inputs, mergedOptions, batchOptions); - } - /** @internal */ - _concatOutputChunks(first, second) { - return this.bound._concatOutputChunks(first, second); - } - async *_streamIterator(input, options) { - yield* this.bound._streamIterator(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async stream(input, options) { - return this.bound.stream(input, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - async *transform(generator, options) { - yield* this.bound.transform(generator, await this._mergeConfig(ensureConfig(options), this.kwargs)); - } - streamEvents(input, options, streamOptions) { - const outerThis = this; - const generator = async function* () { - yield* outerThis.bound.streamEvents(input, { - ...await outerThis._mergeConfig(ensureConfig(options), outerThis.kwargs), - version: options.version - }, streamOptions); - }; - return IterableReadableStream.fromAsyncGenerator(generator()); - } - static isRunnableBinding(thing) { - return thing.bound && Runnable.isRunnable(thing.bound); - } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError }) { - return new RunnableBinding({ - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - configFactories: [(config) => ({ callbacks: [new RootListenersTracer({ - config, - onStart, - onEnd, - onError - })] })] - }); - } -}; -/** -* A runnable that delegates calls to another runnable -* with each element of the input sequence. -* @example -* ```typescript -* import { RunnableEach, RunnableLambda } from "@langchain/core/runnables"; -* -* const toUpperCase = (input: string): string => input.toUpperCase(); -* const addGreeting = (input: string): string => `Hello, ${input}!`; -* -* const upperCaseLambda = RunnableLambda.from(toUpperCase); -* const greetingLambda = RunnableLambda.from(addGreeting); -* -* const chain = new RunnableEach({ -* bound: upperCaseLambda.pipe(greetingLambda), -* }); -* -* const result = await chain.invoke(["alice", "bob", "carol"]) -* -* // ["Hello, ALICE!", "Hello, BOB!", "Hello, CAROL!"] -* ``` -*/ -var RunnableEach = class RunnableEach extends Runnable { - static lc_name() { - return "RunnableEach"; - } - lc_serializable = true; - lc_namespace = ["langchain_core", "runnables"]; - bound; - constructor(fields) { - super(fields); - this.bound = fields.bound; - } - /** - * Invokes the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(inputs, config) { - return this._callWithConfig(this._invoke.bind(this), inputs, config); - } - /** - * A helper method that is used to invoke the runnable with the specified input and configuration. - * @param input The input to invoke the runnable with. - * @param config The configuration to invoke the runnable with. - * @returns A promise that resolves to the output of the runnable. - */ - async _invoke(inputs, config, runManager) { - return this.bound.batch(inputs, config_patchConfig(config, { callbacks: runManager?.getChild() })); - } - /** - * Bind lifecycle listeners to a Runnable, returning a new Runnable. - * The Run object contains information about the run, including its id, - * type, input, output, error, startTime, endTime, and any tags or metadata - * added to the run. - * - * @param {Object} params - The object containing the callback functions. - * @param {(run: Run) => void} params.onStart - Called before the runnable starts running, with the Run object. - * @param {(run: Run) => void} params.onEnd - Called after the runnable finishes running, with the Run object. - * @param {(run: Run) => void} params.onError - Called if the runnable throws an error, with the Run object. - */ - withListeners({ onStart, onEnd, onError }) { - return new RunnableEach({ bound: this.bound.withListeners({ - onStart, - onEnd, - onError - }) }); - } -}; -/** -* Base class for runnables that can be retried a -* specified number of times. -* @example -* ```typescript -* import { -* RunnableLambda, -* RunnableRetry, -* } from "@langchain/core/runnables"; -* -* // Simulate an API call that fails -* const simulateApiCall = (input: string): string => { -* console.log(`Attempting API call with input: ${input}`); -* throw new Error("API call failed due to network issue"); -* }; -* -* const apiCallLambda = RunnableLambda.from(simulateApiCall); -* -* // Apply retry logic using the .withRetry() method -* const apiCallWithRetry = apiCallLambda.withRetry({ stopAfterAttempt: 3 }); -* -* // Alternatively, create a RunnableRetry instance manually -* const manualRetry = new RunnableRetry({ -* bound: apiCallLambda, -* maxAttemptNumber: 3, -* config: {}, -* }); -* -* // Example invocation using the .withRetry() method -* const res = await apiCallWithRetry -* .invoke("Request 1") -* .catch((error) => { -* console.error("Failed after multiple retries:", error.message); -* }); -* -* // Example invocation using the manual retry instance -* const res2 = await manualRetry -* .invoke("Request 2") -* .catch((error) => { -* console.error("Failed after multiple retries:", error.message); -* }); -* ``` -*/ -var RunnableRetry = class extends RunnableBinding { - static lc_name() { - return "RunnableRetry"; - } - lc_namespace = ["langchain_core", "runnables"]; - maxAttemptNumber = 3; - onFailedAttempt = () => {}; - constructor(fields) { - super(fields); - this.maxAttemptNumber = fields.maxAttemptNumber ?? this.maxAttemptNumber; - this.onFailedAttempt = fields.onFailedAttempt ?? this.onFailedAttempt; - } - _patchConfigForRetry(attempt, config, runManager) { - const tag = attempt > 1 ? `retry:attempt:${attempt}` : void 0; - return config_patchConfig(config, { callbacks: runManager?.getChild(tag) }); - } - async _invoke(input, config, runManager) { - return p_retry_pRetry((attemptNumber) => super.invoke(input, this._patchConfigForRetry(attemptNumber, config, runManager)), { - onFailedAttempt: ({ error }) => this.onFailedAttempt(error, input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true - }); - } - /** - * Method that invokes the runnable with the specified input, run manager, - * and config. It handles the retry logic by catching any errors and - * recursively invoking itself with the updated config for the next retry - * attempt. - * @param input The input for the runnable. - * @param runManager The run manager for the runnable. - * @param config The config for the runnable. - * @returns A promise that resolves to the output of the runnable. - */ - async invoke(input, config) { - return this._callWithConfig(this._invoke.bind(this), input, config); - } - async _batch(inputs, configs, runManagers, batchOptions) { - const resultsMap = {}; - try { - await p_retry_pRetry(async (attemptNumber) => { - const remainingIndexes = inputs.map((_, i) => i).filter((i) => resultsMap[i.toString()] === void 0 || resultsMap[i.toString()] instanceof Error); - const remainingInputs = remainingIndexes.map((i) => inputs[i]); - const patchedConfigs = remainingIndexes.map((i) => this._patchConfigForRetry(attemptNumber, configs?.[i], runManagers?.[i])); - const results = await super.batch(remainingInputs, patchedConfigs, { - ...batchOptions, - returnExceptions: true - }); - let firstException; - for (let i = 0; i < results.length; i += 1) { - const result = results[i]; - const resultMapIndex = remainingIndexes[i]; - if (result instanceof Error) { - if (firstException === void 0) { - firstException = result; - firstException.input = remainingInputs[i]; - } - } - resultsMap[resultMapIndex.toString()] = result; - } - if (firstException) throw firstException; - return results; - }, { - onFailedAttempt: ({ error }) => this.onFailedAttempt(error, error.input), - retries: Math.max(this.maxAttemptNumber - 1, 0), - randomize: true - }); - } catch (e) { - if (batchOptions?.returnExceptions !== true) throw e; - } - return Object.keys(resultsMap).sort((a, b) => parseInt(a, 10) - parseInt(b, 10)).map((key) => resultsMap[parseInt(key, 10)]); - } - async batch(inputs, options, batchOptions) { - return this._batchWithConfig(this._batch.bind(this), inputs, options, batchOptions); - } -}; -/** -* A sequence of runnables, where the output of each is the input of the next. -* @example -* ```typescript -* const promptTemplate = PromptTemplate.fromTemplate( -* "Tell me a joke about {topic}", -* ); -* const chain = RunnableSequence.from([promptTemplate, new ChatOpenAI({ model: "gpt-4o-mini" })]); -* const result = await chain.invoke({ topic: "bears" }); -* ``` -*/ -var RunnableSequence = class RunnableSequence extends Runnable { - static lc_name() { - return "RunnableSequence"; - } - first; - middle = []; - last; - omitSequenceTags = false; - lc_serializable = true; - lc_namespace = ["langchain_core", "runnables"]; - constructor(fields) { - super(fields); - this.first = fields.first; - this.middle = fields.middle ?? this.middle; - this.last = fields.last; - this.name = fields.name; - this.omitSequenceTags = fields.omitSequenceTags ?? this.omitSequenceTags; - } - get steps() { - return [ - this.first, - ...this.middle, - this.last - ]; - } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config.runId, void 0, void 0, void 0, config?.runName); - delete config.runId; - let nextStepInput = input; - let finalOutput; - try { - const initialSteps = [this.first, ...this.middle]; - for (let i = 0; i < initialSteps.length; i += 1) { - const step = initialSteps[i]; - const promise = step.invoke(nextStepInput, config_patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) })); - nextStepInput = await raceWithSignal(promise, options?.signal); - } - if (options?.signal?.aborted) throw getAbortSignalError(options.signal); - finalOutput = await this.last.invoke(nextStepInput, config_patchConfig(config, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${this.steps.length}`) })); - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); - return finalOutput; - } - async batch(inputs, options, batchOptions) { - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map(getCallbackManagerForConfig)); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName); - delete configList[i].runId; - return handleStartRes; - })); - let nextStepInputs = inputs; - try { - for (let i = 0; i < this.steps.length; i += 1) { - const step = this.steps[i]; - const promise = step.batch(nextStepInputs, runManagers.map((runManager, j) => { - const childRunManager = runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`); - return config_patchConfig(configList[j], { callbacks: childRunManager }); - }), batchOptions); - nextStepInputs = await raceWithSignal(promise, configList[0]?.signal); - } - } catch (e) { - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(e))); - throw e; - } - await Promise.all(runManagers.map((runManager) => runManager?.handleChainEnd(base_coerceToDict(nextStepInputs, "output")))); - return nextStepInputs; - } - /** @internal */ - _concatOutputChunks(first, second) { - return this.last._concatOutputChunks(first, second); - } - async *_streamIterator(input, options) { - const callbackManager_ = await getCallbackManagerForConfig(options); - const { runId,...otherOptions } = options ?? {}; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherOptions?.runName); - const steps = [ - this.first, - ...this.middle, - this.last - ]; - let concatSupported = true; - let finalOutput; - async function* inputGenerator() { - yield input; - } - try { - let finalGenerator = steps[0].transform(inputGenerator(), config_patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:1`) })); - for (let i = 1; i < steps.length; i += 1) { - const step = steps[i]; - finalGenerator = await step.transform(finalGenerator, config_patchConfig(otherOptions, { callbacks: runManager?.getChild(this.omitSequenceTags ? void 0 : `seq:step:${i + 1}`) })); - } - for await (const chunk of finalGenerator) { - options?.signal?.throwIfAborted(); - yield chunk; - if (concatSupported) if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = void 0; - concatSupported = false; - } - } - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(base_coerceToDict(finalOutput, "output")); - } - getGraph(config) { - const graph = new Graph(); - let currentLastNode = null; - this.steps.forEach((step, index) => { - const stepGraph = step.getGraph(config); - if (index !== 0) stepGraph.trimFirstNode(); - if (index !== this.steps.length - 1) stepGraph.trimLastNode(); - graph.extend(stepGraph); - const stepFirstNode = stepGraph.firstNode(); - if (!stepFirstNode) throw new Error(`Runnable ${step} has no first node`); - if (currentLastNode) graph.addEdge(currentLastNode, stepFirstNode); - currentLastNode = stepGraph.lastNode(); - }); - return graph; - } - pipe(coerceable) { - if (RunnableSequence.isRunnableSequence(coerceable)) return new RunnableSequence({ - first: this.first, - middle: this.middle.concat([ - this.last, - coerceable.first, - ...coerceable.middle - ]), - last: coerceable.last, - name: this.name ?? coerceable.name - }); - else return new RunnableSequence({ - first: this.first, - middle: [...this.middle, this.last], - last: _coerceToRunnable(coerceable), - name: this.name - }); - } - static isRunnableSequence(thing) { - return Array.isArray(thing.middle) && Runnable.isRunnable(thing); - } - static from([first, ...runnables], nameOrFields) { - let extra = {}; - if (typeof nameOrFields === "string") extra.name = nameOrFields; - else if (nameOrFields !== void 0) extra = nameOrFields; - return new RunnableSequence({ - ...extra, - first: _coerceToRunnable(first), - middle: runnables.slice(0, -1).map(_coerceToRunnable), - last: _coerceToRunnable(runnables[runnables.length - 1]) - }); - } -}; -/** -* A runnable that runs a mapping of runnables in parallel, -* and returns a mapping of their outputs. -* @example -* ```typescript -* const mapChain = RunnableMap.from({ -* joke: PromptTemplate.fromTemplate("Tell me a joke about {topic}").pipe( -* new ChatAnthropic({}), -* ), -* poem: PromptTemplate.fromTemplate("write a 2-line poem about {topic}").pipe( -* new ChatAnthropic({}), -* ), -* }); -* const result = await mapChain.invoke({ topic: "bear" }); -* ``` -*/ -var RunnableMap = class RunnableMap extends Runnable { - static lc_name() { - return "RunnableMap"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - steps; - getStepsKeys() { - return Object.keys(this.steps); - } - constructor(fields) { - super(fields); - this.steps = {}; - for (const [key, value] of Object.entries(fields.steps)) this.steps[key] = _coerceToRunnable(value); - } - static from(steps) { - return new RunnableMap({ steps }); - } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), { input }, config.runId, void 0, void 0, void 0, config?.runName); - delete config.runId; - const output = {}; - try { - const promises = Object.entries(this.steps).map(async ([key, runnable]) => { - output[key] = await runnable.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`map:key:${key}`) })); - }); - await raceWithSignal(Promise.all(promises), options?.signal); - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(output); - return output; - } - async *_transform(generator, runManager, options) { - const steps = { ...this.steps }; - const inputCopies = atee(generator, Object.keys(steps).length); - const tasks = new Map(Object.entries(steps).map(([key, runnable], i) => { - const gen = runnable.transform(inputCopies[i], config_patchConfig(options, { callbacks: runManager?.getChild(`map:key:${key}`) })); - return [key, gen.next().then((result) => ({ - key, - gen, - result - }))]; - })); - while (tasks.size) { - const promise = Promise.race(tasks.values()); - const { key, result, gen } = await raceWithSignal(promise, options?.signal); - tasks.delete(key); - if (!result.done) { - yield { [key]: result.value }; - tasks.set(key, gen.next().then((result$1) => ({ - key, - gen, - result: result$1 - }))); - } - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -}; -/** -* A runnable that wraps a traced LangSmith function. -*/ -var RunnableTraceable = class RunnableTraceable extends Runnable { - lc_serializable = false; - lc_namespace = ["langchain_core", "runnables"]; - func; - constructor(fields) { - super(fields); - if (!isTraceableFunction(fields.func)) throw new Error("RunnableTraceable requires a function that is wrapped in traceable higher-order function"); - this.func = fields.func; - } - async invoke(input, options) { - const [config] = this._getOptionsList(options ?? {}, 1); - const callbacks = await getCallbackManagerForConfig(config); - const promise = this.func(config_patchConfig(config, { callbacks }), input); - return raceWithSignal(promise, config?.signal); - } - async *_streamIterator(input, options) { - const [config] = this._getOptionsList(options ?? {}, 1); - const result = await this.invoke(input, options); - if (isAsyncIterable(result)) { - for await (const item of result) { - config?.signal?.throwIfAborted(); - yield item; - } - return; - } - if (isIterator(result)) { - while (true) { - config?.signal?.throwIfAborted(); - const state = result.next(); - if (state.done) break; - yield state.value; - } - return; - } - yield result; - } - static from(func) { - return new RunnableTraceable({ func }); - } -}; -function assertNonTraceableFunction(func) { - if (isTraceableFunction(func)) throw new Error("RunnableLambda requires a function that is not wrapped in traceable higher-order function. This shouldn't happen."); -} -/** -* A runnable that wraps an arbitrary function that takes a single argument. -* @example -* ```typescript -* import { RunnableLambda } from "@langchain/core/runnables"; -* -* const add = (input: { x: number; y: number }) => input.x + input.y; -* -* const multiply = (input: { value: number; multiplier: number }) => -* input.value * input.multiplier; -* -* // Create runnables for the functions -* const addLambda = RunnableLambda.from(add); -* const multiplyLambda = RunnableLambda.from(multiply); -* -* // Chain the lambdas for a mathematical operation -* const chainedLambda = addLambda.pipe((result) => -* multiplyLambda.invoke({ value: result, multiplier: 2 }) -* ); -* -* // Example invocation of the chainedLambda -* const result = await chainedLambda.invoke({ x: 2, y: 3 }); -* -* // Will log "10" (since (2 + 3) * 2 = 10) -* ``` -*/ -var RunnableLambda = class RunnableLambda extends Runnable { - static lc_name() { - return "RunnableLambda"; - } - lc_namespace = ["langchain_core", "runnables"]; - func; - constructor(fields) { - if (isTraceableFunction(fields.func)) return RunnableTraceable.from(fields.func); - super(fields); - assertNonTraceableFunction(fields.func); - this.func = fields.func; - } - static from(func) { - return new RunnableLambda({ func }); - } - async _invoke(input, config, runManager) { - return new Promise((resolve, reject) => { - const childConfig = config_patchConfig(config, { - callbacks: runManager?.getChild(), - recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 - }); - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { - try { - let output = await this.func(input, { ...childConfig }); - if (output && Runnable.isRunnable(output)) { - if (config?.recursionLimit === 0) throw new Error("Recursion limit reached."); - output = await output.invoke(input, { - ...childConfig, - recursionLimit: (childConfig.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 - }); - } else if (isAsyncIterable(output)) { - let finalOutput; - for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = chunk; - } - } - output = finalOutput; - } else if (isIterableIterator(output)) { - let finalOutput; - for (const chunk of consumeIteratorInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = this._concatOutputChunks(finalOutput, chunk); - } catch { - finalOutput = chunk; - } - } - output = finalOutput; - } - resolve(output); - } catch (e) { - reject(e); - } - }); - }); - } - async invoke(input, options) { - return this._callWithConfig(this._invoke.bind(this), input, options); - } - async *_transform(generator, runManager, config) { - let finalChunk; - for await (const chunk of generator) if (finalChunk === void 0) finalChunk = chunk; - else try { - finalChunk = this._concatOutputChunks(finalChunk, chunk); - } catch { - finalChunk = chunk; - } - const childConfig = config_patchConfig(config, { - callbacks: runManager?.getChild(), - recursionLimit: (config?.recursionLimit ?? DEFAULT_RECURSION_LIMIT) - 1 - }); - const output = await new Promise((resolve, reject) => { - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { - try { - const res = await this.func(finalChunk, { - ...childConfig, - config: childConfig - }); - resolve(res); - } catch (e) { - reject(e); - } - }); - }); - if (output && Runnable.isRunnable(output)) { - if (config?.recursionLimit === 0) throw new Error("Recursion limit reached."); - const stream = await output.stream(finalChunk, childConfig); - for await (const chunk of stream) yield chunk; - } else if (isAsyncIterable(output)) for await (const chunk of consumeAsyncIterableInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - yield chunk; - } - else if (isIterableIterator(output)) for (const chunk of consumeIteratorInContext(childConfig, output)) { - config?.signal?.throwIfAborted(); - yield chunk; - } - else yield output; - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -}; -/** -* A runnable that runs a mapping of runnables in parallel, -* and returns a mapping of their outputs. -* @example -* ```typescript -* import { -* RunnableLambda, -* RunnableParallel, -* } from "@langchain/core/runnables"; -* -* const addYears = (age: number): number => age + 5; -* const yearsToFifty = (age: number): number => 50 - age; -* const yearsToHundred = (age: number): number => 100 - age; -* -* const addYearsLambda = RunnableLambda.from(addYears); -* const milestoneFiftyLambda = RunnableLambda.from(yearsToFifty); -* const milestoneHundredLambda = RunnableLambda.from(yearsToHundred); -* -* // Pipe will coerce objects into RunnableParallel by default, but we -* // explicitly instantiate one here to demonstrate -* const sequence = addYearsLambda.pipe( -* RunnableParallel.from({ -* years_to_fifty: milestoneFiftyLambda, -* years_to_hundred: milestoneHundredLambda, -* }) -* ); -* -* // Invoke the sequence with a single age input -* const res = await sequence.invoke(25); -* -* // { years_to_fifty: 20, years_to_hundred: 70 } -* ``` -*/ -var RunnableParallel = class extends RunnableMap {}; -/** -* A Runnable that can fallback to other Runnables if it fails. -* External APIs (e.g., APIs for a language model) may at times experience -* degraded performance or even downtime. -* -* In these cases, it can be useful to have a fallback Runnable that can be -* used in place of the original Runnable (e.g., fallback to another LLM provider). -* -* Fallbacks can be defined at the level of a single Runnable, or at the level -* of a chain of Runnables. Fallbacks are tried in order until one succeeds or -* all fail. -* -* While you can instantiate a `RunnableWithFallbacks` directly, it is usually -* more convenient to use the `withFallbacks` method on an existing Runnable. -* -* When streaming, fallbacks will only be called on failures during the initial -* stream creation. Errors that occur after a stream starts will not fallback -* to the next Runnable. -* -* @example -* ```typescript -* import { -* RunnableLambda, -* RunnableWithFallbacks, -* } from "@langchain/core/runnables"; -* -* const primaryOperation = (input: string): string => { -* if (input !== "safe") { -* throw new Error("Primary operation failed due to unsafe input"); -* } -* return `Processed: ${input}`; -* }; -* -* // Define a fallback operation that processes the input differently -* const fallbackOperation = (input: string): string => -* `Fallback processed: ${input}`; -* -* const primaryRunnable = RunnableLambda.from(primaryOperation); -* const fallbackRunnable = RunnableLambda.from(fallbackOperation); -* -* // Apply the fallback logic using the .withFallbacks() method -* const runnableWithFallback = primaryRunnable.withFallbacks([fallbackRunnable]); -* -* // Alternatively, create a RunnableWithFallbacks instance manually -* const manualFallbackChain = new RunnableWithFallbacks({ -* runnable: primaryRunnable, -* fallbacks: [fallbackRunnable], -* }); -* -* // Example invocation using .withFallbacks() -* const res = await runnableWithFallback -* .invoke("unsafe input") -* .catch((error) => { -* console.error("Failed after all attempts:", error.message); -* }); -* -* // "Fallback processed: unsafe input" -* -* // Example invocation using manual instantiation -* const res = await manualFallbackChain -* .invoke("safe") -* .catch((error) => { -* console.error("Failed after all attempts:", error.message); -* }); -* -* // "Processed: safe" -* ``` -*/ -var RunnableWithFallbacks = class extends Runnable { - static lc_name() { - return "RunnableWithFallbacks"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - runnable; - fallbacks; - constructor(fields) { - super(fields); - this.runnable = fields.runnable; - this.fallbacks = fields.fallbacks; - } - *runnables() { - yield this.runnable; - for (const fallback of this.fallbacks) yield fallback; - } - async invoke(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const { runId,...otherConfigFields } = config; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); - const childConfig = config_patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); - const res = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { - let firstError; - for (const runnable of this.runnables()) { - config?.signal?.throwIfAborted(); - try { - const output = await runnable.invoke(input, childConfig); - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); - return output; - } catch (e) { - if (firstError === void 0) firstError = e; - } - } - if (firstError === void 0) throw new Error("No error stored at end of fallback."); - await runManager?.handleChainError(firstError); - throw firstError; - }); - return res; - } - async *_streamIterator(input, options) { - const config = ensureConfig(options); - const callbackManager_ = await getCallbackManagerForConfig(config); - const { runId,...otherConfigFields } = config; - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), runId, void 0, void 0, void 0, otherConfigFields?.runName); - let firstError; - let stream; - for (const runnable of this.runnables()) { - config?.signal?.throwIfAborted(); - const childConfig = config_patchConfig(otherConfigFields, { callbacks: runManager?.getChild() }); - try { - const originalStream = await runnable.stream(input, childConfig); - stream = consumeAsyncIterableInContext(childConfig, originalStream); - break; - } catch (e) { - if (firstError === void 0) firstError = e; - } - } - if (stream === void 0) { - const error = firstError ?? /* @__PURE__ */ new Error("No error stored at end of fallback."); - await runManager?.handleChainError(error); - throw error; - } - let output; - try { - for await (const chunk of stream) { - yield chunk; - try { - output = output === void 0 ? output : this._concatOutputChunks(output, chunk); - } catch { - output = void 0; - } - } - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(base_coerceToDict(output, "output")); - } - async batch(inputs, options, batchOptions) { - if (batchOptions?.returnExceptions) throw new Error("Not implemented."); - const configList = this._getOptionsList(options ?? {}, inputs.length); - const callbackManagers = await Promise.all(configList.map((config) => getCallbackManagerForConfig(config))); - const runManagers = await Promise.all(callbackManagers.map(async (callbackManager, i) => { - const handleStartRes = await callbackManager?.handleChainStart(this.toJSON(), base_coerceToDict(inputs[i], "input"), configList[i].runId, void 0, void 0, void 0, configList[i].runName); - delete configList[i].runId; - return handleStartRes; - })); - let firstError; - for (const runnable of this.runnables()) { - configList[0].signal?.throwIfAborted(); - try { - const outputs = await runnable.batch(inputs, runManagers.map((runManager, j) => config_patchConfig(configList[j], { callbacks: runManager?.getChild() })), batchOptions); - await Promise.all(runManagers.map((runManager, i) => runManager?.handleChainEnd(base_coerceToDict(outputs[i], "output")))); - return outputs; - } catch (e) { - if (firstError === void 0) firstError = e; - } - } - if (!firstError) throw new Error("No error stored at end of fallbacks."); - await Promise.all(runManagers.map((runManager) => runManager?.handleChainError(firstError))); - throw firstError; - } -}; -function _coerceToRunnable(coerceable) { - if (typeof coerceable === "function") return new RunnableLambda({ func: coerceable }); - else if (Runnable.isRunnable(coerceable)) return coerceable; - else if (!Array.isArray(coerceable) && typeof coerceable === "object") { - const runnables = {}; - for (const [key, value] of Object.entries(coerceable)) runnables[key] = _coerceToRunnable(value); - return new RunnableMap({ steps: runnables }); - } else throw new Error(`Expected a Runnable, function or object.\nInstead got an unsupported type.`); -} -/** -* A runnable that assigns key-value pairs to inputs of type `Record`. -* @example -* ```typescript -* import { -* RunnableAssign, -* RunnableLambda, -* RunnableParallel, -* } from "@langchain/core/runnables"; -* -* const calculateAge = (x: { birthYear: number }): { age: number } => { -* const currentYear = new Date().getFullYear(); -* return { age: currentYear - x.birthYear }; -* }; -* -* const createGreeting = (x: { name: string }): { greeting: string } => { -* return { greeting: `Hello, ${x.name}!` }; -* }; -* -* const mapper = RunnableParallel.from({ -* age_step: RunnableLambda.from(calculateAge), -* greeting_step: RunnableLambda.from(createGreeting), -* }); -* -* const runnableAssign = new RunnableAssign({ mapper }); -* -* const res = await runnableAssign.invoke({ name: "Alice", birthYear: 1990 }); -* -* // { name: "Alice", birthYear: 1990, age_step: { age: 34 }, greeting_step: { greeting: "Hello, Alice!" } } -* ``` -*/ -var RunnableAssign = class extends Runnable { - static lc_name() { - return "RunnableAssign"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - mapper; - constructor(fields) { - if (fields instanceof RunnableMap) fields = { mapper: fields }; - super(fields); - this.mapper = fields.mapper; - } - async invoke(input, options) { - const mapperResult = await this.mapper.invoke(input, options); - return { - ...input, - ...mapperResult - }; - } - async *_transform(generator, runManager, options) { - const mapperKeys = this.mapper.getStepsKeys(); - const [forPassthrough, forMapper] = atee(generator); - const mapperOutput = this.mapper.transform(forMapper, config_patchConfig(options, { callbacks: runManager?.getChild() })); - const firstMapperChunkPromise = mapperOutput.next(); - for await (const chunk of forPassthrough) { - if (typeof chunk !== "object" || Array.isArray(chunk)) throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof chunk}`); - const filtered = Object.fromEntries(Object.entries(chunk).filter(([key]) => !mapperKeys.includes(key))); - if (Object.keys(filtered).length > 0) yield filtered; - } - yield (await firstMapperChunkPromise).value; - for await (const chunk of mapperOutput) yield chunk; - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -}; -/** -* A runnable that assigns key-value pairs to inputs of type `Record`. -* Useful for streaming, can be automatically created and chained by calling `runnable.pick();`. -* @example -* ```typescript -* import { RunnablePick } from "@langchain/core/runnables"; -* -* const inputData = { -* name: "John", -* age: 30, -* city: "New York", -* country: "USA", -* email: "john.doe@example.com", -* phone: "+1234567890", -* }; -* -* const basicInfoRunnable = new RunnablePick(["name", "city"]); -* -* // Example invocation -* const res = await basicInfoRunnable.invoke(inputData); -* -* // { name: 'John', city: 'New York' } -* ``` -*/ -var RunnablePick = class extends Runnable { - static lc_name() { - return "RunnablePick"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - keys; - constructor(fields) { - if (typeof fields === "string" || Array.isArray(fields)) fields = { keys: fields }; - super(fields); - this.keys = fields.keys; - } - async _pick(input) { - if (typeof this.keys === "string") return input[this.keys]; - else { - const picked = this.keys.map((key) => [key, input[key]]).filter((v) => v[1] !== void 0); - return picked.length === 0 ? void 0 : Object.fromEntries(picked); - } - } - async invoke(input, options) { - return this._callWithConfig(this._pick.bind(this), input, options); - } - async *_transform(generator) { - for await (const chunk of generator) { - const picked = await this._pick(chunk); - if (picked !== void 0) yield picked; - } - } - transform(generator, options) { - return this._transformStreamWithConfig(generator, this._transform.bind(this), options); - } - async stream(input, options) { - async function* generator() { - yield input; - } - const config = ensureConfig(options); - const wrappedGenerator = new AsyncGeneratorWithSetup({ - generator: this.transform(generator(), config), - config - }); - await wrappedGenerator.setup; - return IterableReadableStream.fromAsyncGenerator(wrappedGenerator); - } -}; -var RunnableToolLike = class extends RunnableBinding { - name; - description; - schema; - constructor(fields) { - const sequence = RunnableSequence.from([RunnableLambda.from(async (input) => { - let toolInput; - if (_isToolCall(input)) try { - toolInput = await interopParseAsync(this.schema, input.args); - } catch { - throw new ToolInputParsingException(`Received tool input did not match expected schema`, JSON.stringify(input.args)); - } - else toolInput = input; - return toolInput; - }).withConfig({ runName: `${fields.name}:parse_input` }), fields.bound]).withConfig({ runName: fields.name }); - super({ - bound: sequence, - config: fields.config ?? {} - }); - this.name = fields.name; - this.description = fields.description; - this.schema = fields.schema; - } - static lc_name() { - return "RunnableToolLike"; - } -}; -/** -* Given a runnable and a Zod schema, convert the runnable to a tool. -* -* @template RunInput The input type for the runnable. -* @template RunOutput The output type for the runnable. -* -* @param {Runnable} runnable The runnable to convert to a tool. -* @param fields -* @param {string | undefined} [fields.name] The name of the tool. If not provided, it will default to the name of the runnable. -* @param {string | undefined} [fields.description] The description of the tool. Falls back to the description on the Zod schema if not provided, or undefined if neither are provided. -* @param {InteropZodType} [fields.schema] The Zod schema for the input of the tool. Infers the Zod type from the input type of the runnable. -* @returns {RunnableToolLike, RunOutput>} An instance of `RunnableToolLike` which is a runnable that can be used as a tool. -*/ -function convertRunnableToTool(runnable, fields) { - const name = fields.name ?? runnable.getName(); - const description = fields.description ?? getSchemaDescription(fields.schema); - if (isSimpleStringZodSchema(fields.schema)) return new RunnableToolLike({ - name, - description, - schema: objectType({ input: stringType() }).transform((input) => input.input), - bound: runnable - }); - return new RunnableToolLike({ - name, - description, - schema: fields.schema, - bound: runnable - }); -} - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/transformers.js - - - - - - - - - - - -//#region src/messages/transformers.ts -const _isMessageType = (msg, types) => { - const typesAsStrings = [...new Set(types?.map((t) => { - if (typeof t === "string") return t; - const instantiatedMsgClass = new t({}); - if (!("getType" in instantiatedMsgClass) || typeof instantiatedMsgClass.getType !== "function") throw new Error("Invalid type provided."); - return instantiatedMsgClass.getType(); - }))]; - const msgType = msg.getType(); - return typesAsStrings.some((t) => t === msgType); -}; -function filterMessages(messagesOrOptions, options) { - if (Array.isArray(messagesOrOptions)) return _filterMessages(messagesOrOptions, options); - return RunnableLambda.from((input) => { - return _filterMessages(input, messagesOrOptions); - }); -} -function _filterMessages(messages, options = {}) { - const { includeNames, excludeNames, includeTypes, excludeTypes, includeIds, excludeIds } = options; - const filtered = []; - for (const msg of messages) { - if (excludeNames && msg.name && excludeNames.includes(msg.name)) continue; - else if (excludeTypes && _isMessageType(msg, excludeTypes)) continue; - else if (excludeIds && msg.id && excludeIds.includes(msg.id)) continue; - if (!(includeTypes || includeIds || includeNames)) filtered.push(msg); - else if (includeNames && msg.name && includeNames.some((iName) => iName === msg.name)) filtered.push(msg); - else if (includeTypes && _isMessageType(msg, includeTypes)) filtered.push(msg); - else if (includeIds && msg.id && includeIds.some((id) => id === msg.id)) filtered.push(msg); - } - return filtered; -} -function mergeMessageRuns(messages) { - if (Array.isArray(messages)) return _mergeMessageRuns(messages); - return RunnableLambda.from(_mergeMessageRuns); -} -function _mergeMessageRuns(messages) { - if (!messages.length) return []; - const merged = []; - for (const msg of messages) { - const curr = msg; - const last = merged.pop(); - if (!last) merged.push(curr); - else if (curr.getType() === "tool" || !(curr.getType() === last.getType())) merged.push(last, curr); - else { - const lastChunk = convertToChunk(last); - const currChunk = convertToChunk(curr); - const mergedChunks = lastChunk.concat(currChunk); - if (typeof lastChunk.content === "string" && typeof currChunk.content === "string") mergedChunks.content = `${lastChunk.content}\n${currChunk.content}`; - merged.push(_chunkToMsg(mergedChunks)); - } - } - return merged; -} -function trimMessages(messagesOrOptions, options) { - if (Array.isArray(messagesOrOptions)) { - const messages = messagesOrOptions; - if (!options) throw new Error("Options parameter is required when providing messages."); - return _trimMessagesHelper(messages, options); - } else { - const trimmerOptions = messagesOrOptions; - return RunnableLambda.from((input) => _trimMessagesHelper(input, trimmerOptions)).withConfig({ runName: "trim_messages" }); - } -} -async function _trimMessagesHelper(messages, options) { - const { maxTokens, tokenCounter, strategy = "last", allowPartial = false, endOn, startOn, includeSystem = false, textSplitter } = options; - if (startOn && strategy === "first") throw new Error("`startOn` should only be specified if `strategy` is 'last'."); - if (includeSystem && strategy === "first") throw new Error("`includeSystem` should only be specified if `strategy` is 'last'."); - let listTokenCounter; - if ("getNumTokens" in tokenCounter) listTokenCounter = async (msgs) => { - const tokenCounts = await Promise.all(msgs.map((msg) => tokenCounter.getNumTokens(msg.content))); - return tokenCounts.reduce((sum, count) => sum + count, 0); - }; - else listTokenCounter = async (msgs) => tokenCounter(msgs); - let textSplitterFunc = defaultTextSplitter; - if (textSplitter) if ("splitText" in textSplitter) textSplitterFunc = textSplitter.splitText; - else textSplitterFunc = async (text) => textSplitter(text); - if (strategy === "first") return _firstMaxTokens(messages, { - maxTokens, - tokenCounter: listTokenCounter, - textSplitter: textSplitterFunc, - partialStrategy: allowPartial ? "first" : void 0, - endOn - }); - else if (strategy === "last") return _lastMaxTokens(messages, { - maxTokens, - tokenCounter: listTokenCounter, - textSplitter: textSplitterFunc, - allowPartial, - includeSystem, - startOn, - endOn - }); - else throw new Error(`Unrecognized strategy: '${strategy}'. Must be one of 'first' or 'last'.`); -} -async function _firstMaxTokens(messages, options) { - const { maxTokens, tokenCounter, textSplitter, partialStrategy, endOn } = options; - let messagesCopy = [...messages]; - let idx = 0; - for (let i = 0; i < messagesCopy.length; i += 1) { - const remainingMessages = i > 0 ? messagesCopy.slice(0, -i) : messagesCopy; - if (await tokenCounter(remainingMessages) <= maxTokens) { - idx = messagesCopy.length - i; - break; - } - } - if (idx < messagesCopy.length && partialStrategy) { - let includedPartial = false; - if (Array.isArray(messagesCopy[idx].content)) { - const excluded = messagesCopy[idx]; - if (typeof excluded.content === "string") throw new Error("Expected content to be an array."); - const numBlock = excluded.content.length; - const reversedContent = partialStrategy === "last" ? [...excluded.content].reverse() : excluded.content; - for (let i = 1; i <= numBlock; i += 1) { - const partialContent = partialStrategy === "first" ? reversedContent.slice(0, i) : reversedContent.slice(-i); - const fields = Object.fromEntries(Object.entries(excluded).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); - const updatedMessage = _switchTypeToMessage(excluded.getType(), { - ...fields, - content: partialContent - }); - const slicedMessages = [...messagesCopy.slice(0, idx), updatedMessage]; - if (await tokenCounter(slicedMessages) <= maxTokens) { - messagesCopy = slicedMessages; - idx += 1; - includedPartial = true; - } else break; - } - if (includedPartial && partialStrategy === "last") excluded.content = [...reversedContent].reverse(); - } - if (!includedPartial) { - const excluded = messagesCopy[idx]; - let text; - if (Array.isArray(excluded.content) && excluded.content.some((block) => typeof block === "string" || block.type === "text")) { - const textBlock = excluded.content.find((block) => block.type === "text" && block.text); - text = textBlock?.text; - } else if (typeof excluded.content === "string") text = excluded.content; - if (text) { - const splitTexts = await textSplitter(text); - const numSplits = splitTexts.length; - if (partialStrategy === "last") splitTexts.reverse(); - for (let _ = 0; _ < numSplits - 1; _ += 1) { - splitTexts.pop(); - excluded.content = splitTexts.join(""); - if (await tokenCounter([...messagesCopy.slice(0, idx), excluded]) <= maxTokens) { - if (partialStrategy === "last") excluded.content = [...splitTexts].reverse().join(""); - messagesCopy = [...messagesCopy.slice(0, idx), excluded]; - idx += 1; - break; - } - } - } - } - } - if (endOn) { - const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; - while (idx > 0 && !_isMessageType(messagesCopy[idx - 1], endOnArr)) idx -= 1; - } - return messagesCopy.slice(0, idx); -} -async function _lastMaxTokens(messages, options) { - const { allowPartial = false, includeSystem = false, endOn, startOn,...rest } = options; - let messagesCopy = messages.map((message) => { - const fields = Object.fromEntries(Object.entries(message).filter(([k]) => k !== "type" && !k.startsWith("lc_"))); - return _switchTypeToMessage(message.getType(), fields, isBaseMessageChunk(message)); - }); - if (endOn) { - const endOnArr = Array.isArray(endOn) ? endOn : [endOn]; - while (messagesCopy.length > 0 && !_isMessageType(messagesCopy[messagesCopy.length - 1], endOnArr)) messagesCopy = messagesCopy.slice(0, -1); - } - const swappedSystem = includeSystem && messagesCopy[0]?.getType() === "system"; - let reversed_ = swappedSystem ? messagesCopy.slice(0, 1).concat(messagesCopy.slice(1).reverse()) : messagesCopy.reverse(); - reversed_ = await _firstMaxTokens(reversed_, { - ...rest, - partialStrategy: allowPartial ? "last" : void 0, - endOn: startOn - }); - if (swappedSystem) return [reversed_[0], ...reversed_.slice(1).reverse()]; - else return reversed_.reverse(); -} -const _MSG_CHUNK_MAP = { - human: { - message: HumanMessage, - messageChunk: HumanMessageChunk - }, - ai: { - message: AIMessage, - messageChunk: AIMessageChunk - }, - system: { - message: SystemMessage, - messageChunk: SystemMessageChunk - }, - developer: { - message: SystemMessage, - messageChunk: SystemMessageChunk - }, - tool: { - message: ToolMessage, - messageChunk: ToolMessageChunk - }, - function: { - message: FunctionMessage, - messageChunk: FunctionMessageChunk - }, - generic: { - message: ChatMessage, - messageChunk: ChatMessageChunk - }, - remove: { - message: RemoveMessage, - messageChunk: RemoveMessage - } -}; -function _switchTypeToMessage(messageType, fields, returnChunk) { - let chunk; - let msg; - switch (messageType) { - case "human": - if (returnChunk) chunk = new HumanMessageChunk(fields); - else msg = new HumanMessage(fields); - break; - case "ai": - if (returnChunk) { - let aiChunkFields = { ...fields }; - if ("tool_calls" in aiChunkFields) aiChunkFields = { - ...aiChunkFields, - tool_call_chunks: aiChunkFields.tool_calls?.map((tc) => ({ - ...tc, - type: "tool_call_chunk", - index: void 0, - args: JSON.stringify(tc.args) - })) - }; - chunk = new AIMessageChunk(aiChunkFields); - } else msg = new AIMessage(fields); - break; - case "system": - if (returnChunk) chunk = new SystemMessageChunk(fields); - else msg = new SystemMessage(fields); - break; - case "developer": - if (returnChunk) chunk = new SystemMessageChunk({ - ...fields, - additional_kwargs: { - ...fields.additional_kwargs, - __openai_role__: "developer" - } - }); - else msg = new SystemMessage({ - ...fields, - additional_kwargs: { - ...fields.additional_kwargs, - __openai_role__: "developer" - } - }); - break; - case "tool": - if ("tool_call_id" in fields) if (returnChunk) chunk = new ToolMessageChunk(fields); - else msg = new ToolMessage(fields); - else throw new Error("Can not convert ToolMessage to ToolMessageChunk if 'tool_call_id' field is not defined."); - break; - case "function": - if (returnChunk) chunk = new FunctionMessageChunk(fields); - else { - if (!fields.name) throw new Error("FunctionMessage must have a 'name' field"); - msg = new FunctionMessage(fields); - } - break; - case "generic": - if ("role" in fields) if (returnChunk) chunk = new ChatMessageChunk(fields); - else msg = new ChatMessage(fields); - else throw new Error("Can not convert ChatMessage to ChatMessageChunk if 'role' field is not defined."); - break; - default: throw new Error(`Unrecognized message type ${messageType}`); - } - if (returnChunk && chunk) return chunk; - if (msg) return msg; - throw new Error(`Unrecognized message type ${messageType}`); -} -function _chunkToMsg(chunk) { - const chunkType = chunk.getType(); - let msg; - const fields = Object.fromEntries(Object.entries(chunk).filter(([k]) => !["type", "tool_call_chunks"].includes(k) && !k.startsWith("lc_"))); - if (chunkType in _MSG_CHUNK_MAP) msg = _switchTypeToMessage(chunkType, fields); - if (!msg) throw new Error(`Unrecognized message chunk class ${chunkType}. Supported classes are ${Object.keys(_MSG_CHUNK_MAP)}`); - return msg; -} -/** -* The default text splitter function that splits text by newlines. -* -* @param {string} text -* @returns A promise that resolves to an array of strings split by newlines. -*/ -function defaultTextSplitter(text) { - const splits = text.split("\n"); - return Promise.resolve([...splits.slice(0, -1).map((s) => `${s}\n`), splits[splits.length - 1]]); -} - -//#endregion - -//# sourceMappingURL=transformers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/tools.js -//#region src/messages/content/tools.ts -const KNOWN_BLOCK_TYPES = [ - "tool_call", - "tool_call_chunk", - "invalid_tool_call", - "server_tool_call", - "server_tool_call_chunk", - "server_tool_call_result" -]; - -//#endregion - -//# sourceMappingURL=tools.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/multimodal.js -//#region src/messages/content/multimodal.ts -const multimodal_KNOWN_BLOCK_TYPES = [ - "image", - "video", - "audio", - "text-plain", - "file" -]; - -//#endregion - -//# sourceMappingURL=multimodal.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/content/index.js - - - -//#region src/messages/content/index.ts -const KNOWN_BLOCK_TYPES$2 = [ - "text", - "reasoning", - ...KNOWN_BLOCK_TYPES, - ...multimodal_KNOWN_BLOCK_TYPES -]; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/messages/index.js - - - - - - - - - - - - - - - - -//#region src/messages/index.ts -var messages_exports = {}; -__export(messages_exports, { - AIMessage: () => AIMessage, - AIMessageChunk: () => AIMessageChunk, - BaseMessage: () => BaseMessage, - BaseMessageChunk: () => BaseMessageChunk, - ChatMessage: () => ChatMessage, - ChatMessageChunk: () => ChatMessageChunk, - FunctionMessage: () => FunctionMessage, - FunctionMessageChunk: () => FunctionMessageChunk, - HumanMessage: () => HumanMessage, - HumanMessageChunk: () => HumanMessageChunk, - KNOWN_BLOCK_TYPES: () => KNOWN_BLOCK_TYPES$2, - RemoveMessage: () => RemoveMessage, - SystemMessage: () => SystemMessage, - SystemMessageChunk: () => SystemMessageChunk, - ToolMessage: () => ToolMessage, - ToolMessageChunk: () => ToolMessageChunk, - _isMessageFieldWithRole: () => _isMessageFieldWithRole, - _mergeDicts: () => _mergeDicts, - _mergeLists: () => _mergeLists, - _mergeObj: () => _mergeObj, - _mergeStatus: () => _mergeStatus, - coerceMessageLikeToMessage: () => utils_coerceMessageLikeToMessage, - collapseToolCallChunks: () => collapseToolCallChunks, - convertToChunk: () => convertToChunk, - convertToOpenAIImageBlock: () => convertToOpenAIImageBlock, - convertToProviderContentBlock: () => convertToProviderContentBlock, - defaultTextSplitter: () => defaultTextSplitter, - defaultToolCallParser: () => defaultToolCallParser, - filterMessages: () => filterMessages, - getBufferString: () => getBufferString, - iife: () => utils_iife, - isAIMessage: () => isAIMessage, - isAIMessageChunk: () => isAIMessageChunk, - isBase64ContentBlock: () => isBase64ContentBlock, - isBaseMessage: () => isBaseMessage, - isBaseMessageChunk: () => isBaseMessageChunk, - isChatMessage: () => isChatMessage, - isChatMessageChunk: () => isChatMessageChunk, - isDataContentBlock: () => isDataContentBlock, - isDirectToolOutput: () => isDirectToolOutput, - isFunctionMessage: () => isFunctionMessage, - isFunctionMessageChunk: () => isFunctionMessageChunk, - isHumanMessage: () => isHumanMessage, - isHumanMessageChunk: () => isHumanMessageChunk, - isIDContentBlock: () => isIDContentBlock, - isMessage: () => isMessage, - isOpenAIToolCallArray: () => isOpenAIToolCallArray, - isPlainTextContentBlock: () => isPlainTextContentBlock, - isSystemMessage: () => isSystemMessage, - isSystemMessageChunk: () => isSystemMessageChunk, - isToolMessage: () => isToolMessage, - isToolMessageChunk: () => isToolMessageChunk, - isURLContentBlock: () => isURLContentBlock, - mapChatMessagesToStoredMessages: () => mapChatMessagesToStoredMessages, - mapStoredMessageToChatMessage: () => mapStoredMessageToChatMessage, - mapStoredMessagesToChatMessages: () => mapStoredMessagesToChatMessages, - mergeContent: () => mergeContent, - mergeMessageRuns: () => mergeMessageRuns, - mergeResponseMetadata: () => mergeResponseMetadata, - mergeUsageMetadata: () => mergeUsageMetadata, - parseBase64DataUrl: () => parseBase64DataUrl, - parseMimeType: () => parseMimeType, - trimMessages: () => trimMessages -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/chat_history.js - - - - - - -//#region src/chat_history.ts -var chat_history_exports = {}; -__export(chat_history_exports, { - BaseChatMessageHistory: () => BaseChatMessageHistory, - BaseListChatMessageHistory: () => BaseListChatMessageHistory, - InMemoryChatMessageHistory: () => InMemoryChatMessageHistory -}); -/** -* Base class for all chat message histories. All chat message histories -* should extend this class. -*/ -var BaseChatMessageHistory = class extends Serializable { - /** - * Add a list of messages. - * - * Implementations should override this method to handle bulk addition of messages - * in an efficient manner to avoid unnecessary round-trips to the underlying store. - * - * @param messages - A list of BaseMessage objects to store. - */ - async addMessages(messages) { - for (const message of messages) await this.addMessage(message); - } -}; -/** -* Base class for all list chat message histories. All list chat message -* histories should extend this class. -*/ -var BaseListChatMessageHistory = class extends Serializable { - /** - * This is a convenience method for adding a human message string to the store. - * Please note that this is a convenience method. Code should favor the - * bulk addMessages interface instead to save on round-trips to the underlying - * persistence layer. - * This method may be deprecated in a future release. - */ - addUserMessage(message) { - return this.addMessage(new HumanMessage(message)); - } - /** - * This is a convenience method for adding an AI message string to the store. - * Please note that this is a convenience method. Code should favor the bulk - * addMessages interface instead to save on round-trips to the underlying - * persistence layer. - * This method may be deprecated in a future release. - */ - addAIMessage(message) { - return this.addMessage(new AIMessage(message)); - } - /** - * Add a list of messages. - * - * Implementations should override this method to handle bulk addition of messages - * in an efficient manner to avoid unnecessary round-trips to the underlying store. - * - * @param messages - A list of BaseMessage objects to store. - */ - async addMessages(messages) { - for (const message of messages) await this.addMessage(message); - } - /** - * Remove all messages from the store. - */ - clear() { - throw new Error("Not implemented."); - } -}; -/** -* Class for storing chat message history in-memory. It extends the -* BaseListChatMessageHistory class and provides methods to get, add, and -* clear messages. -*/ -var InMemoryChatMessageHistory = class extends BaseListChatMessageHistory { - lc_namespace = [ - "langchain", - "stores", - "message", - "in_memory" - ]; - messages = []; - constructor(messages) { - super(...arguments); - this.messages = messages ?? []; - } - /** - * Method to get all the messages stored in the ChatMessageHistory - * instance. - * @returns Array of stored BaseMessage instances. - */ - async getMessages() { - return this.messages; - } - /** - * Method to add a new message to the ChatMessageHistory instance. - * @param message The BaseMessage instance to add. - * @returns A promise that resolves when the message has been added. - */ - async addMessage(message) { - this.messages.push(message); - } - /** - * Method to clear all the messages from the ChatMessageHistory instance. - * @returns A promise that resolves when all messages have been cleared. - */ - async clear() { - this.messages = []; - } -}; - -//#endregion - -//# sourceMappingURL=chat_history.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/embeddings.js - - - -//#region src/embeddings.ts -var embeddings_exports = {}; -__export(embeddings_exports, { Embeddings: () => Embeddings }); -/** -* An abstract class that provides methods for embedding documents and -* queries using LangChain. -*/ -var Embeddings = class { - /** - * The async caller should be used by subclasses to make any async calls, - * which will thus benefit from the concurrency and retry logic. - */ - caller; - constructor(params) { - this.caller = new async_caller_AsyncCaller(params ?? {}); - } -}; - -//#endregion - -//# sourceMappingURL=embeddings.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/index.js -//#region src/index.ts -var src_exports = {}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/memory.js - - -//#region src/memory.ts -var memory_exports = {}; -__export(memory_exports, { - BaseMemory: () => BaseMemory, - getInputValue: () => getInputValue, - getOutputValue: () => getOutputValue, - getPromptInputKey: () => getPromptInputKey -}); -/** -* Abstract base class for memory in LangChain's Chains. Memory refers to -* the state in Chains. It can be used to store information about past -* executions of a Chain and inject that information into the inputs of -* future executions of the Chain. -*/ -var BaseMemory = class {}; -const getValue = (values, key) => { - if (key !== void 0) return values[key]; - const keys = Object.keys(values); - if (keys.length === 1) return values[keys[0]]; -}; -/** -* This function is used by memory classes to select the input value -* to use for the memory. If there is only one input value, it is used. -* If there are multiple input values, the inputKey must be specified. -*/ -const getInputValue = (inputValues, inputKey) => { - const value = getValue(inputValues, inputKey); - if (!value) { - const keys = Object.keys(inputValues); - throw new Error(`input values have ${keys.length} keys, you must specify an input key or pass only 1 key as input`); - } - return value; -}; -/** -* This function is used by memory classes to select the output value -* to use for the memory. If there is only one output value, it is used. -* If there are multiple output values, the outputKey must be specified. -* If no outputKey is specified, an error is thrown. -*/ -const getOutputValue = (outputValues, outputKey) => { - const value = getValue(outputValues, outputKey); - if (!value && value !== "") { - const keys = Object.keys(outputValues); - throw new Error(`output values have ${keys.length} keys, you must specify an output key or pass only 1 key as output`); - } - return value; -}; -/** -* Function used by memory classes to get the key of the prompt input, -* excluding any keys that are memory variables or the "stop" key. If -* there is not exactly one prompt input key, an error is thrown. -*/ -function getPromptInputKey(inputs, memoryVariables) { - const promptInputKeys = Object.keys(inputs).filter((key) => !memoryVariables.includes(key) && key !== "stop"); - if (promptInputKeys.length !== 1) throw new Error(`One input key expected, but got ${promptInputKeys.length}`); - return promptInputKeys[0]; -} - -//#endregion - -//# sourceMappingURL=memory.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompt_values.js - - - - - -//#region src/prompt_values.ts -var prompt_values_exports = {}; -__export(prompt_values_exports, { - BasePromptValue: () => BasePromptValue, - ChatPromptValue: () => ChatPromptValue, - ImagePromptValue: () => ImagePromptValue, - StringPromptValue: () => StringPromptValue -}); -/** -* Base PromptValue class. All prompt values should extend this class. -*/ -var BasePromptValue = class extends Serializable {}; -/** -* Represents a prompt value as a string. It extends the BasePromptValue -* class and overrides the toString and toChatMessages methods. -*/ -var StringPromptValue = class extends BasePromptValue { - static lc_name() { - return "StringPromptValue"; - } - lc_namespace = ["langchain_core", "prompt_values"]; - lc_serializable = true; - value; - constructor(value) { - super({ value }); - this.value = value; - } - toString() { - return this.value; - } - toChatMessages() { - return [new HumanMessage(this.value)]; - } -}; -/** -* Class that represents a chat prompt value. It extends the -* BasePromptValue and includes an array of BaseMessage instances. -*/ -var ChatPromptValue = class extends BasePromptValue { - lc_namespace = ["langchain_core", "prompt_values"]; - lc_serializable = true; - static lc_name() { - return "ChatPromptValue"; - } - messages; - constructor(fields) { - if (Array.isArray(fields)) fields = { messages: fields }; - super(fields); - this.messages = fields.messages; - } - toString() { - return getBufferString(this.messages); - } - toChatMessages() { - return this.messages; - } -}; -/** -* Class that represents an image prompt value. It extends the -* BasePromptValue and includes an ImageURL instance. -*/ -var ImagePromptValue = class extends BasePromptValue { - lc_namespace = ["langchain_core", "prompt_values"]; - lc_serializable = true; - static lc_name() { - return "ImagePromptValue"; - } - imageUrl; - /** @ignore */ - value; - constructor(fields) { - if (!("imageUrl" in fields)) fields = { imageUrl: fields }; - super(fields); - this.imageUrl = fields.imageUrl; - } - toString() { - return this.imageUrl.url; - } - toChatMessages() { - return [new HumanMessage({ content: [{ - type: "image_url", - image_url: { - detail: this.imageUrl.detail, - url: this.imageUrl.url - } - }] })]; - } -}; - -//#endregion - -//# sourceMappingURL=prompt_values.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/stores.js - - - -//#region src/stores.ts -var stores_exports = {}; -__export(stores_exports, { - BaseStore: () => BaseStore, - InMemoryStore: () => InMemoryStore -}); -/** -* Abstract interface for a key-value store. -*/ -var BaseStore = class extends Serializable {}; -/** -* In-memory implementation of the BaseStore using a dictionary. Used for -* storing key-value pairs in memory. -* @example -* ```typescript -* const store = new InMemoryStore(); -* await store.mset( -* Array.from({ length: 5 }).map((_, index) => [ -* `message:id:${index}`, -* index % 2 === 0 -* ? new AIMessage("ai stuff...") -* : new HumanMessage("human stuff..."), -* ]), -* ); -* -* const retrievedMessages = await store.mget(["message:id:0", "message:id:1"]); -* await store.mdelete(await store.yieldKeys("message:id:").toArray()); -* ``` -*/ -var InMemoryStore = class extends BaseStore { - lc_namespace = ["langchain", "storage"]; - store = {}; - /** - * Retrieves the values associated with the given keys from the store. - * @param keys Keys to retrieve values for. - * @returns Array of values associated with the given keys. - */ - async mget(keys) { - return keys.map((key) => this.store[key]); - } - /** - * Sets the values for the given keys in the store. - * @param keyValuePairs Array of key-value pairs to set in the store. - * @returns Promise that resolves when all key-value pairs have been set. - */ - async mset(keyValuePairs) { - for (const [key, value] of keyValuePairs) this.store[key] = value; - } - /** - * Deletes the given keys and their associated values from the store. - * @param keys Keys to delete from the store. - * @returns Promise that resolves when all keys have been deleted. - */ - async mdelete(keys) { - for (const key of keys) delete this.store[key]; - } - /** - * Asynchronous generator that yields keys from the store. If a prefix is - * provided, it only yields keys that start with the prefix. - * @param prefix Optional prefix to filter keys. - * @returns AsyncGenerator that yields keys from the store. - */ - async *yieldKeys(prefix) { - const keys = Object.keys(this.store); - for (const key of keys) if (prefix === void 0 || key.startsWith(prefix)) yield key; - } -}; - -//#endregion - -//# sourceMappingURL=stores.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/retrievers/index.js - - - - - -//#region src/retrievers/index.ts -var retrievers_exports = {}; -__export(retrievers_exports, { BaseRetriever: () => BaseRetriever }); -/** -* Abstract base class for a document retrieval system, designed to -* process string queries and return the most relevant documents from a source. -* -* `BaseRetriever` provides common properties and methods for derived retrievers, -* such as callbacks, tagging, and verbose logging. Custom retrieval systems -* should extend this class and implement `_getRelevantDocuments` to define -* the specific retrieval logic. -* -* @template Metadata - The type of metadata associated with each document, -* defaulting to `Record`. -*/ -var BaseRetriever = class extends Runnable { - /** - * Optional callbacks to handle various events in the retrieval process. - */ - callbacks; - /** - * Tags to label or categorize the retrieval operation. - */ - tags; - /** - * Metadata to provide additional context or information about the retrieval - * operation. - */ - metadata; - /** - * If set to `true`, enables verbose logging for the retrieval process. - */ - verbose; - /** - * Constructs a new `BaseRetriever` instance with optional configuration fields. - * - * @param fields - Optional input configuration that can include `callbacks`, - * `tags`, `metadata`, and `verbose` settings for custom retriever behavior. - */ - constructor(fields) { - super(fields); - this.callbacks = fields?.callbacks; - this.tags = fields?.tags ?? []; - this.metadata = fields?.metadata ?? {}; - this.verbose = fields?.verbose ?? false; - } - /** - * TODO: This should be an abstract method, but we'd like to avoid breaking - * changes to people currently using subclassed custom retrievers. - * Change it on next major release. - */ - /** - * Placeholder method for retrieving relevant documents based on a query. - * - * This method is intended to be implemented by subclasses and will be - * converted to an abstract method in the next major release. Currently, it - * throws an error if not implemented, ensuring that custom retrievers define - * the specific retrieval logic. - * - * @param _query - The query string used to search for relevant documents. - * @param _callbacks - (optional) Callback manager for managing callbacks - * during retrieval. - * @returns A promise resolving to an array of `DocumentInterface` instances relevant to the query. - * @throws {Error} Throws an error indicating the method is not implemented. - */ - _getRelevantDocuments(_query, _callbacks) { - throw new Error("Not implemented!"); - } - /** - * Executes a retrieval operation. - * - * @param input - The query string used to search for relevant documents. - * @param options - (optional) Configuration options for the retrieval run, - * which may include callbacks, tags, and metadata. - * @returns A promise that resolves to an array of `DocumentInterface` instances - * representing the most relevant documents to the query. - */ - async invoke(input, options) { - const parsedConfig = ensureConfig(parseCallbackConfigArg(options)); - const callbackManager_ = await CallbackManager.configure(parsedConfig.callbacks, this.callbacks, parsedConfig.tags, this.tags, parsedConfig.metadata, this.metadata, { verbose: this.verbose }); - const runManager = await callbackManager_?.handleRetrieverStart(this.toJSON(), input, parsedConfig.runId, void 0, void 0, void 0, parsedConfig.runName); - try { - const results = await this._getRelevantDocuments(input, runManager); - await runManager?.handleRetrieverEnd(results); - return results; - } catch (error) { - await runManager?.handleRetrieverError(error); - throw error; - } - } -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/vectorstores.js - - - - -//#region src/vectorstores.ts -var vectorstores_exports = {}; -__export(vectorstores_exports, { - SaveableVectorStore: () => SaveableVectorStore, - VectorStore: () => VectorStore, - VectorStoreRetriever: () => VectorStoreRetriever -}); -/** -* Class for retrieving documents from a `VectorStore` based on vector similarity -* or maximal marginal relevance (MMR). -* -* `VectorStoreRetriever` extends `BaseRetriever`, implementing methods for -* adding documents to the underlying vector store and performing document -* retrieval with optional configurations. -* -* @class VectorStoreRetriever -* @extends BaseRetriever -* @implements VectorStoreRetrieverInterface -* @template V - Type of vector store implementing `VectorStoreInterface`. -*/ -var VectorStoreRetriever = class extends BaseRetriever { - static lc_name() { - return "VectorStoreRetriever"; - } - get lc_namespace() { - return ["langchain_core", "vectorstores"]; - } - /** - * The instance of `VectorStore` used for storing and retrieving document embeddings. - * This vector store must implement the `VectorStoreInterface` to be compatible - * with the retriever’s operations. - */ - vectorStore; - /** - * Specifies the number of documents to retrieve for each search query. - * Defaults to 4 if not specified, providing a basic result count for similarity or MMR searches. - */ - k = 4; - /** - * Determines the type of search operation to perform on the vector store. - * - * - `"similarity"` (default): Conducts a similarity search based purely on vector similarity - * to the query. - * - `"mmr"`: Executes a maximal marginal relevance (MMR) search, balancing relevance and - * diversity in the retrieved results. - */ - searchType = "similarity"; - /** - * Additional options specific to maximal marginal relevance (MMR) search, applicable - * only if `searchType` is set to `"mmr"`. - * - * Includes: - * - `fetchK`: The initial number of documents fetched before applying the MMR algorithm, - * allowing for a larger selection from which to choose the most diverse results. - * - `lambda`: A parameter between 0 and 1 to adjust the relevance-diversity balance, - * where 0 prioritizes diversity and 1 prioritizes relevance. - */ - searchKwargs; - /** - * Optional filter applied to search results, defined by the `FilterType` of the vector store. - * Allows for refined, targeted results by restricting the returned documents based - * on specified filter criteria. - */ - filter; - /** - * Returns the type of vector store, as defined by the `vectorStore` instance. - * - * @returns {string} The vector store type. - */ - _vectorstoreType() { - return this.vectorStore._vectorstoreType(); - } - /** - * Initializes a new instance of `VectorStoreRetriever` with the specified configuration. - * - * This constructor configures the retriever to interact with a given `VectorStore` - * and supports different retrieval strategies, including similarity search and maximal - * marginal relevance (MMR) search. Various options allow customization of the number - * of documents retrieved per query, filtering based on conditions, and fine-tuning - * MMR-specific parameters. - * - * @param fields - Configuration options for setting up the retriever: - * - * - `vectorStore` (required): The `VectorStore` instance implementing `VectorStoreInterface` - * that will be used to store and retrieve document embeddings. This is the core component - * of the retriever, enabling vector-based similarity and MMR searches. - * - * - `k` (optional): Specifies the number of documents to retrieve per search query. If not - * provided, defaults to 4. This count determines the number of most relevant documents returned - * for each search operation, balancing performance with comprehensiveness. - * - * - `searchType` (optional): Defines the search approach used by the retriever, allowing for - * flexibility between two methods: - * - `"similarity"` (default): A similarity-based search, retrieving documents with high vector - * similarity to the query. This type prioritizes relevance and is often used when diversity - * among results is less critical. - * - `"mmr"`: Maximal Marginal Relevance search, which combines relevance with diversity. MMR - * is useful for scenarios where varied content is essential, as it selects results that - * both match the query and introduce content diversity. - * - * - `filter` (optional): A filter of type `FilterType`, defined by the vector store, that allows - * for refined and targeted search results. This filter applies specified conditions to limit - * which documents are eligible for retrieval, offering control over the scope of results. - * - * - `searchKwargs` (optional, applicable only if `searchType` is `"mmr"`): Additional settings - * for configuring MMR-specific behavior. These parameters allow further tuning of the MMR - * search process: - * - `fetchK`: The initial number of documents fetched from the vector store before the MMR - * algorithm is applied. Fetching a larger set enables the algorithm to select a more - * diverse subset of documents. - * - `lambda`: A parameter controlling the relevance-diversity balance, where 0 emphasizes - * diversity and 1 prioritizes relevance. Intermediate values provide a blend of the two, - * allowing customization based on the importance of content variety relative to query relevance. - */ - constructor(fields) { - super(fields); - this.vectorStore = fields.vectorStore; - this.k = fields.k ?? this.k; - this.searchType = fields.searchType ?? this.searchType; - this.filter = fields.filter; - if (fields.searchType === "mmr") this.searchKwargs = fields.searchKwargs; - } - /** - * Retrieves relevant documents based on the specified query, using either - * similarity or maximal marginal relevance (MMR) search. - * - * If `searchType` is set to `"mmr"`, performs an MMR search to balance - * similarity and diversity among results. If `searchType` is `"similarity"`, - * retrieves results purely based on similarity to the query. - * - * @param query - The query string used to find relevant documents. - * @param runManager - Optional callback manager for tracking retrieval progress. - * @returns A promise that resolves to an array of `DocumentInterface` instances - * representing the most relevant documents to the query. - * @throws {Error} Throws an error if MMR search is requested but not supported - * by the vector store. - * @protected - */ - async _getRelevantDocuments(query, runManager) { - if (this.searchType === "mmr") { - if (typeof this.vectorStore.maxMarginalRelevanceSearch !== "function") throw new Error(`The vector store backing this retriever, ${this._vectorstoreType()} does not support max marginal relevance search.`); - return this.vectorStore.maxMarginalRelevanceSearch(query, { - k: this.k, - filter: this.filter, - ...this.searchKwargs - }, runManager?.getChild("vectorstore")); - } - return this.vectorStore.similaritySearch(query, this.k, this.filter, runManager?.getChild("vectorstore")); - } - /** - * Adds an array of documents to the vector store, embedding them as part of - * the storage process. - * - * This method delegates document embedding and storage to the `addDocuments` - * method of the underlying vector store. - * - * @param documents - An array of documents to embed and add to the vector store. - * @param options - Optional settings to customize document addition. - * @returns A promise that resolves to an array of document IDs or `void`, - * depending on the vector store's implementation. - */ - async addDocuments(documents, options) { - return this.vectorStore.addDocuments(documents, options); - } -}; -/** -* Abstract class representing a vector storage system for performing -* similarity searches on embedded documents. -* -* `VectorStore` provides methods for adding precomputed vectors or documents, -* removing documents based on criteria, and performing similarity searches -* with optional scoring. Subclasses are responsible for implementing specific -* storage mechanisms and the exact behavior of certain abstract methods. -* -* @abstract -* @extends Serializable -* @implements VectorStoreInterface -*/ -var VectorStore = class extends Serializable { - /** - * Namespace within LangChain to uniquely identify this vector store's - * location, based on the vector store type. - * - * @internal - */ - lc_namespace = [ - "langchain", - "vectorstores", - this._vectorstoreType() - ]; - /** - * Embeddings interface for generating vector embeddings from text queries, - * enabling vector-based similarity searches. - */ - embeddings; - /** - * Initializes a new vector store with embeddings and database configuration. - * - * @param embeddings - Instance of `EmbeddingsInterface` used to embed queries. - * @param dbConfig - Configuration settings for the database or storage system. - */ - constructor(embeddings, dbConfig) { - super(dbConfig); - this.embeddings = embeddings; - } - /** - * Deletes documents from the vector store based on the specified parameters. - * - * @param _params - Flexible key-value pairs defining conditions for document deletion. - * @returns A promise that resolves once the deletion is complete. - */ - async delete(_params) { - throw new Error("Not implemented."); - } - /** - * Searches for documents similar to a text query by embedding the query and - * performing a similarity search on the resulting vector. - * - * @param query - Text query for finding similar documents. - * @param k - Number of similar results to return. Defaults to 4. - * @param filter - Optional filter based on `FilterType`. - * @param _callbacks - Optional callbacks for monitoring search progress - * @returns A promise resolving to an array of `DocumentInterface` instances representing similar documents. - */ - async similaritySearch(query, k = 4, filter = void 0, _callbacks = void 0) { - const results = await this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query), k, filter); - return results.map((result) => result[0]); - } - /** - * Searches for documents similar to a text query by embedding the query, - * and returns results with similarity scores. - * - * @param query - Text query for finding similar documents. - * @param k - Number of similar results to return. Defaults to 4. - * @param filter - Optional filter based on `FilterType`. - * @param _callbacks - Optional callbacks for monitoring search progress - * @returns A promise resolving to an array of tuples, each containing a - * document and its similarity score. - */ - async similaritySearchWithScore(query, k = 4, filter = void 0, _callbacks = void 0) { - return this.similaritySearchVectorWithScore(await this.embeddings.embedQuery(query), k, filter); - } - /** - * Creates a `VectorStore` instance from an array of text strings and optional - * metadata, using the specified embeddings and database configuration. - * - * Subclasses must implement this method to define how text and metadata - * are embedded and stored in the vector store. Throws an error if not overridden. - * - * @param _texts - Array of strings representing the text documents to be stored. - * @param _metadatas - Metadata for the texts, either as an array (one for each text) - * or a single object (applied to all texts). - * @param _embeddings - Instance of `EmbeddingsInterface` to embed the texts. - * @param _dbConfig - Database configuration settings. - * @returns A promise that resolves to a new `VectorStore` instance. - * @throws {Error} Throws an error if this method is not overridden by a subclass. - */ - static fromTexts(_texts, _metadatas, _embeddings, _dbConfig) { - throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); - } - /** - * Creates a `VectorStore` instance from an array of documents, using the specified - * embeddings and database configuration. - * - * Subclasses must implement this method to define how documents are embedded - * and stored. Throws an error if not overridden. - * - * @param _docs - Array of `DocumentInterface` instances representing the documents to be stored. - * @param _embeddings - Instance of `EmbeddingsInterface` to embed the documents. - * @param _dbConfig - Database configuration settings. - * @returns A promise that resolves to a new `VectorStore` instance. - * @throws {Error} Throws an error if this method is not overridden by a subclass. - */ - static fromDocuments(_docs, _embeddings, _dbConfig) { - throw new Error("the Langchain vectorstore implementation you are using forgot to override this, please report a bug"); - } - /** - * Creates a `VectorStoreRetriever` instance with flexible configuration options. - * - * @param kOrFields - * - If a number is provided, it sets the `k` parameter (number of items to retrieve). - * - If an object is provided, it should contain various configuration options. - * @param filter - * - Optional filter criteria to limit the items retrieved based on the specified filter type. - * @param callbacks - * - Optional callbacks that may be triggered at specific stages of the retrieval process. - * @param tags - * - Tags to categorize or label the `VectorStoreRetriever`. Defaults to an empty array if not provided. - * @param metadata - * - Additional metadata as key-value pairs to add contextual information for the retrieval process. - * @param verbose - * - If `true`, enables detailed logging for the retrieval process. Defaults to `false`. - * - * @returns - * - A configured `VectorStoreRetriever` instance based on the provided parameters. - * - * @example - * Basic usage with a `k` value: - * ```typescript - * const retriever = myVectorStore.asRetriever(5); - * ``` - * - * Usage with a configuration object: - * ```typescript - * const retriever = myVectorStore.asRetriever({ - * k: 10, - * filter: myFilter, - * tags: ['example', 'test'], - * verbose: true, - * searchType: 'mmr', - * searchKwargs: { alpha: 0.5 }, - * }); - * ``` - */ - asRetriever(kOrFields, filter, callbacks, tags, metadata, verbose) { - if (typeof kOrFields === "number") return new VectorStoreRetriever({ - vectorStore: this, - k: kOrFields, - filter, - tags: [...tags ?? [], this._vectorstoreType()], - metadata, - verbose, - callbacks - }); - else { - const params = { - vectorStore: this, - k: kOrFields?.k, - filter: kOrFields?.filter, - tags: [...kOrFields?.tags ?? [], this._vectorstoreType()], - metadata: kOrFields?.metadata, - verbose: kOrFields?.verbose, - callbacks: kOrFields?.callbacks, - searchType: kOrFields?.searchType - }; - if (kOrFields?.searchType === "mmr") return new VectorStoreRetriever({ - ...params, - searchKwargs: kOrFields.searchKwargs - }); - return new VectorStoreRetriever({ ...params }); - } - } -}; -/** -* Abstract class extending `VectorStore` that defines a contract for saving -* and loading vector store instances. -* -* The `SaveableVectorStore` class allows vector store implementations to -* persist their data and retrieve it when needed.The format for saving and -* loading data is left to the implementing subclass. -* -* Subclasses must implement the `save` method to handle their custom -* serialization logic, while the `load` method enables reconstruction of a -* vector store from saved data, requiring compatible embeddings through the -* `EmbeddingsInterface`. -* -* @abstract -* @extends VectorStore -*/ -var SaveableVectorStore = class extends VectorStore { - /** - * Loads a vector store instance from the specified directory, using the - * provided embeddings to ensure compatibility. - * - * This static method reconstructs a `SaveableVectorStore` from previously - * saved data. Implementations should interpret the saved data format to - * recreate the vector store instance. - * - * @param _directory - The directory path from which the vector store - * data will be loaded. - * @param _embeddings - An instance of `EmbeddingsInterface` to align - * the embeddings with the loaded vector data. - * @returns A promise that resolves to a `SaveableVectorStore` instance - * constructed from the saved data. - */ - static load(_directory, _embeddings) { - throw new Error("Not implemented"); - } -}; - -//#endregion - -//# sourceMappingURL=vectorstores.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/js-sha256/hash.js - - -//#region src/utils/js-sha256/hash.ts -var HEX_CHARS = "0123456789abcdef".split(""); -var EXTRA = [ - -2147483648, - 8388608, - 32768, - 128 -]; -var SHIFT = [ - 24, - 16, - 8, - 0 -]; -var K = [ - 1116352408, - 1899447441, - 3049323471, - 3921009573, - 961987163, - 1508970993, - 2453635748, - 2870763221, - 3624381080, - 310598401, - 607225278, - 1426881987, - 1925078388, - 2162078206, - 2614888103, - 3248222580, - 3835390401, - 4022224774, - 264347078, - 604807628, - 770255983, - 1249150122, - 1555081692, - 1996064986, - 2554220882, - 2821834349, - 2952996808, - 3210313671, - 3336571891, - 3584528711, - 113926993, - 338241895, - 666307205, - 773529912, - 1294757372, - 1396182291, - 1695183700, - 1986661051, - 2177026350, - 2456956037, - 2730485921, - 2820302411, - 3259730800, - 3345764771, - 3516065817, - 3600352804, - 4094571909, - 275423344, - 430227734, - 506948616, - 659060556, - 883997877, - 958139571, - 1322822218, - 1537002063, - 1747873779, - 1955562222, - 2024104815, - 2227730452, - 2361852424, - 2428436474, - 2756734187, - 3204031479, - 3329325298 -]; -var blocks = []; -function Sha256(is224, sharedMemory) { - if (sharedMemory) { - blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] = blocks[4] = blocks[5] = blocks[6] = blocks[7] = blocks[8] = blocks[9] = blocks[10] = blocks[11] = blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0; - this.blocks = blocks; - } else this.blocks = [ - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0, - 0 - ]; - if (is224) { - this.h0 = 3238371032; - this.h1 = 914150663; - this.h2 = 812702999; - this.h3 = 4144912697; - this.h4 = 4290775857; - this.h5 = 1750603025; - this.h6 = 1694076839; - this.h7 = 3204075428; - } else { - this.h0 = 1779033703; - this.h1 = 3144134277; - this.h2 = 1013904242; - this.h3 = 2773480762; - this.h4 = 1359893119; - this.h5 = 2600822924; - this.h6 = 528734635; - this.h7 = 1541459225; - } - this.block = this.start = this.bytes = this.hBytes = 0; - this.finalized = this.hashed = false; - this.first = true; - this.is224 = is224; -} -Sha256.prototype.update = function(message) { - if (this.finalized) return; - var notString, type = typeof message; - if (type !== "string") { - if (type === "object") { - if (message === null) throw new Error(ERROR); - else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) message = new Uint8Array(message); - else if (!Array.isArray(message)) { - if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) throw new Error(ERROR); - } - } else throw new Error(ERROR); - notString = true; - } - var code, index = 0, i, length = message.length, blocks$1 = this.blocks; - while (index < length) { - if (this.hashed) { - this.hashed = false; - blocks$1[0] = this.block; - this.block = blocks$1[16] = blocks$1[1] = blocks$1[2] = blocks$1[3] = blocks$1[4] = blocks$1[5] = blocks$1[6] = blocks$1[7] = blocks$1[8] = blocks$1[9] = blocks$1[10] = blocks$1[11] = blocks$1[12] = blocks$1[13] = blocks$1[14] = blocks$1[15] = 0; - } - if (notString) for (i = this.start; index < length && i < 64; ++index) blocks$1[i >>> 2] |= message[index] << SHIFT[i++ & 3]; - else for (i = this.start; index < length && i < 64; ++index) { - code = message.charCodeAt(index); - if (code < 128) blocks$1[i >>> 2] |= code << SHIFT[i++ & 3]; - else if (code < 2048) { - blocks$1[i >>> 2] |= (192 | code >>> 6) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; - } else if (code < 55296 || code >= 57344) { - blocks$1[i >>> 2] |= (224 | code >>> 12) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; - } else { - code = 65536 + ((code & 1023) << 10 | message.charCodeAt(++index) & 1023); - blocks$1[i >>> 2] |= (240 | code >>> 18) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code >>> 12 & 63) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code >>> 6 & 63) << SHIFT[i++ & 3]; - blocks$1[i >>> 2] |= (128 | code & 63) << SHIFT[i++ & 3]; - } - } - this.lastByteIndex = i; - this.bytes += i - this.start; - if (i >= 64) { - this.block = blocks$1[16]; - this.start = i - 64; - this.hash(); - this.hashed = true; - } else this.start = i; - } - if (this.bytes > 4294967295) { - this.hBytes += this.bytes / 4294967296 << 0; - this.bytes = this.bytes % 4294967296; - } - return this; -}; -Sha256.prototype.finalize = function() { - if (this.finalized) return; - this.finalized = true; - var blocks$1 = this.blocks, i = this.lastByteIndex; - blocks$1[16] = this.block; - blocks$1[i >>> 2] |= EXTRA[i & 3]; - this.block = blocks$1[16]; - if (i >= 56) { - if (!this.hashed) this.hash(); - blocks$1[0] = this.block; - blocks$1[16] = blocks$1[1] = blocks$1[2] = blocks$1[3] = blocks$1[4] = blocks$1[5] = blocks$1[6] = blocks$1[7] = blocks$1[8] = blocks$1[9] = blocks$1[10] = blocks$1[11] = blocks$1[12] = blocks$1[13] = blocks$1[14] = blocks$1[15] = 0; - } - blocks$1[14] = this.hBytes << 3 | this.bytes >>> 29; - blocks$1[15] = this.bytes << 3; - this.hash(); -}; -Sha256.prototype.hash = function() { - var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6, h = this.h7, blocks$1 = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc; - for (j = 16; j < 64; ++j) { - t1 = blocks$1[j - 15]; - s0 = (t1 >>> 7 | t1 << 25) ^ (t1 >>> 18 | t1 << 14) ^ t1 >>> 3; - t1 = blocks$1[j - 2]; - s1 = (t1 >>> 17 | t1 << 15) ^ (t1 >>> 19 | t1 << 13) ^ t1 >>> 10; - blocks$1[j] = blocks$1[j - 16] + s0 + blocks$1[j - 7] + s1 << 0; - } - bc = b & c; - for (j = 0; j < 64; j += 4) { - if (this.first) { - if (this.is224) { - ab = 300032; - t1 = blocks$1[0] - 1413257819; - h = t1 - 150054599 << 0; - d = t1 + 24177077 << 0; - } else { - ab = 704751109; - t1 = blocks$1[0] - 210244248; - h = t1 - 1521486534 << 0; - d = t1 + 143694565 << 0; - } - this.first = false; - } else { - s0 = (a >>> 2 | a << 30) ^ (a >>> 13 | a << 19) ^ (a >>> 22 | a << 10); - s1 = (e >>> 6 | e << 26) ^ (e >>> 11 | e << 21) ^ (e >>> 25 | e << 7); - ab = a & b; - maj = ab ^ a & c ^ bc; - ch = e & f ^ ~e & g; - t1 = h + s1 + ch + K[j] + blocks$1[j]; - t2 = s0 + maj; - h = d + t1 << 0; - d = t1 + t2 << 0; - } - s0 = (d >>> 2 | d << 30) ^ (d >>> 13 | d << 19) ^ (d >>> 22 | d << 10); - s1 = (h >>> 6 | h << 26) ^ (h >>> 11 | h << 21) ^ (h >>> 25 | h << 7); - da = d & a; - maj = da ^ d & b ^ ab; - ch = g & h ^ ~g & e; - t1 = f + s1 + ch + K[j + 1] + blocks$1[j + 1]; - t2 = s0 + maj; - g = c + t1 << 0; - c = t1 + t2 << 0; - s0 = (c >>> 2 | c << 30) ^ (c >>> 13 | c << 19) ^ (c >>> 22 | c << 10); - s1 = (g >>> 6 | g << 26) ^ (g >>> 11 | g << 21) ^ (g >>> 25 | g << 7); - cd = c & d; - maj = cd ^ c & a ^ da; - ch = f & g ^ ~f & h; - t1 = e + s1 + ch + K[j + 2] + blocks$1[j + 2]; - t2 = s0 + maj; - f = b + t1 << 0; - b = t1 + t2 << 0; - s0 = (b >>> 2 | b << 30) ^ (b >>> 13 | b << 19) ^ (b >>> 22 | b << 10); - s1 = (f >>> 6 | f << 26) ^ (f >>> 11 | f << 21) ^ (f >>> 25 | f << 7); - bc = b & c; - maj = bc ^ b & d ^ cd; - ch = f & g ^ ~f & h; - t1 = e + s1 + ch + K[j + 3] + blocks$1[j + 3]; - t2 = s0 + maj; - e = a + t1 << 0; - a = t1 + t2 << 0; - this.chromeBugWorkAround = true; - } - this.h0 = this.h0 + a << 0; - this.h1 = this.h1 + b << 0; - this.h2 = this.h2 + c << 0; - this.h3 = this.h3 + d << 0; - this.h4 = this.h4 + e << 0; - this.h5 = this.h5 + f << 0; - this.h6 = this.h6 + g << 0; - this.h7 = this.h7 + h << 0; -}; -Sha256.prototype.hex = function() { - this.finalize(); - var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; - var hex = HEX_CHARS[h0 >>> 28 & 15] + HEX_CHARS[h0 >>> 24 & 15] + HEX_CHARS[h0 >>> 20 & 15] + HEX_CHARS[h0 >>> 16 & 15] + HEX_CHARS[h0 >>> 12 & 15] + HEX_CHARS[h0 >>> 8 & 15] + HEX_CHARS[h0 >>> 4 & 15] + HEX_CHARS[h0 & 15] + HEX_CHARS[h1 >>> 28 & 15] + HEX_CHARS[h1 >>> 24 & 15] + HEX_CHARS[h1 >>> 20 & 15] + HEX_CHARS[h1 >>> 16 & 15] + HEX_CHARS[h1 >>> 12 & 15] + HEX_CHARS[h1 >>> 8 & 15] + HEX_CHARS[h1 >>> 4 & 15] + HEX_CHARS[h1 & 15] + HEX_CHARS[h2 >>> 28 & 15] + HEX_CHARS[h2 >>> 24 & 15] + HEX_CHARS[h2 >>> 20 & 15] + HEX_CHARS[h2 >>> 16 & 15] + HEX_CHARS[h2 >>> 12 & 15] + HEX_CHARS[h2 >>> 8 & 15] + HEX_CHARS[h2 >>> 4 & 15] + HEX_CHARS[h2 & 15] + HEX_CHARS[h3 >>> 28 & 15] + HEX_CHARS[h3 >>> 24 & 15] + HEX_CHARS[h3 >>> 20 & 15] + HEX_CHARS[h3 >>> 16 & 15] + HEX_CHARS[h3 >>> 12 & 15] + HEX_CHARS[h3 >>> 8 & 15] + HEX_CHARS[h3 >>> 4 & 15] + HEX_CHARS[h3 & 15] + HEX_CHARS[h4 >>> 28 & 15] + HEX_CHARS[h4 >>> 24 & 15] + HEX_CHARS[h4 >>> 20 & 15] + HEX_CHARS[h4 >>> 16 & 15] + HEX_CHARS[h4 >>> 12 & 15] + HEX_CHARS[h4 >>> 8 & 15] + HEX_CHARS[h4 >>> 4 & 15] + HEX_CHARS[h4 & 15] + HEX_CHARS[h5 >>> 28 & 15] + HEX_CHARS[h5 >>> 24 & 15] + HEX_CHARS[h5 >>> 20 & 15] + HEX_CHARS[h5 >>> 16 & 15] + HEX_CHARS[h5 >>> 12 & 15] + HEX_CHARS[h5 >>> 8 & 15] + HEX_CHARS[h5 >>> 4 & 15] + HEX_CHARS[h5 & 15] + HEX_CHARS[h6 >>> 28 & 15] + HEX_CHARS[h6 >>> 24 & 15] + HEX_CHARS[h6 >>> 20 & 15] + HEX_CHARS[h6 >>> 16 & 15] + HEX_CHARS[h6 >>> 12 & 15] + HEX_CHARS[h6 >>> 8 & 15] + HEX_CHARS[h6 >>> 4 & 15] + HEX_CHARS[h6 & 15]; - if (!this.is224) hex += HEX_CHARS[h7 >>> 28 & 15] + HEX_CHARS[h7 >>> 24 & 15] + HEX_CHARS[h7 >>> 20 & 15] + HEX_CHARS[h7 >>> 16 & 15] + HEX_CHARS[h7 >>> 12 & 15] + HEX_CHARS[h7 >>> 8 & 15] + HEX_CHARS[h7 >>> 4 & 15] + HEX_CHARS[h7 & 15]; - return hex; -}; -Sha256.prototype.toString = Sha256.prototype.hex; -Sha256.prototype.digest = function() { - this.finalize(); - var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5, h6 = this.h6, h7 = this.h7; - var arr = [ - h0 >>> 24 & 255, - h0 >>> 16 & 255, - h0 >>> 8 & 255, - h0 & 255, - h1 >>> 24 & 255, - h1 >>> 16 & 255, - h1 >>> 8 & 255, - h1 & 255, - h2 >>> 24 & 255, - h2 >>> 16 & 255, - h2 >>> 8 & 255, - h2 & 255, - h3 >>> 24 & 255, - h3 >>> 16 & 255, - h3 >>> 8 & 255, - h3 & 255, - h4 >>> 24 & 255, - h4 >>> 16 & 255, - h4 >>> 8 & 255, - h4 & 255, - h5 >>> 24 & 255, - h5 >>> 16 & 255, - h5 >>> 8 & 255, - h5 & 255, - h6 >>> 24 & 255, - h6 >>> 16 & 255, - h6 >>> 8 & 255, - h6 & 255 - ]; - if (!this.is224) arr.push(h7 >>> 24 & 255, h7 >>> 16 & 255, h7 >>> 8 & 255, h7 & 255); - return arr; -}; -Sha256.prototype.array = Sha256.prototype.digest; -Sha256.prototype.arrayBuffer = function() { - this.finalize(); - var buffer = /* @__PURE__ */ new ArrayBuffer(this.is224 ? 28 : 32); - var dataView = new DataView(buffer); - dataView.setUint32(0, this.h0); - dataView.setUint32(4, this.h1); - dataView.setUint32(8, this.h2); - dataView.setUint32(12, this.h3); - dataView.setUint32(16, this.h4); - dataView.setUint32(20, this.h5); - dataView.setUint32(24, this.h6); - if (!this.is224) dataView.setUint32(28, this.h7); - return buffer; -}; -const sha256 = (...strings) => { - return new Sha256(false, true).update(strings.join("")).hex(); -}; - -//#endregion - -//# sourceMappingURL=hash.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/hash.js - - - -//#region src/utils/hash.ts -var hash_exports = {}; -__export(hash_exports, { sha256: () => sha256 }); - -//#endregion - -//# sourceMappingURL=hash.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/caches/index.js - - - - - -//#region src/caches/index.ts -var caches_exports = {}; -__export(caches_exports, { - BaseCache: () => caches_BaseCache, - InMemoryCache: () => InMemoryCache, - defaultHashKeyEncoder: () => defaultHashKeyEncoder, - deserializeStoredGeneration: () => deserializeStoredGeneration, - serializeGeneration: () => serializeGeneration -}); -const defaultHashKeyEncoder = (...strings) => sha256(strings.join("_")); -function deserializeStoredGeneration(storedGeneration) { - if (storedGeneration.message !== void 0) return { - text: storedGeneration.text, - message: mapStoredMessageToChatMessage(storedGeneration.message) - }; - else return { text: storedGeneration.text }; -} -function serializeGeneration(generation) { - const serializedValue = { text: generation.text }; - if (generation.message !== void 0) serializedValue.message = generation.message.toDict(); - return serializedValue; -} -/** -* Base class for all caches. All caches should extend this class. -*/ -var caches_BaseCache = class { - keyEncoder = defaultHashKeyEncoder; - /** - * Sets a custom key encoder function for the cache. - * This function should take a prompt and an LLM key and return a string - * that will be used as the cache key. - * @param keyEncoderFn The custom key encoder function. - */ - makeDefaultKeyEncoder(keyEncoderFn) { - this.keyEncoder = keyEncoderFn; - } -}; -const GLOBAL_MAP = /* @__PURE__ */ new Map(); -/** -* A cache for storing LLM generations that stores data in memory. -*/ -var InMemoryCache = class InMemoryCache extends caches_BaseCache { - cache; - constructor(map) { - super(); - this.cache = map ?? /* @__PURE__ */ new Map(); - } - /** - * Retrieves data from the cache using a prompt and an LLM key. If the - * data is not found, it returns null. - * @param prompt The prompt used to find the data. - * @param llmKey The LLM key used to find the data. - * @returns The data corresponding to the prompt and LLM key, or null if not found. - */ - lookup(prompt, llmKey) { - return Promise.resolve(this.cache.get(this.keyEncoder(prompt, llmKey)) ?? null); - } - /** - * Updates the cache with new data using a prompt and an LLM key. - * @param prompt The prompt used to store the data. - * @param llmKey The LLM key used to store the data. - * @param value The data to be stored. - */ - async update(prompt, llmKey, value) { - this.cache.set(this.keyEncoder(prompt, llmKey), value); - } - /** - * Returns a global instance of InMemoryCache using a predefined global - * map as the initial cache. - * @returns A global instance of InMemoryCache. - */ - static global() { - return new InMemoryCache(GLOBAL_MAP); - } -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/document_loaders/base.js - - -//#region src/document_loaders/base.ts -var document_loaders_base_base_exports = {}; -__export(document_loaders_base_base_exports, { BaseDocumentLoader: () => BaseDocumentLoader }); -/** -* Abstract class that provides a default implementation for the -* loadAndSplit() method from the DocumentLoader interface. The load() -* method is left abstract and needs to be implemented by subclasses. -*/ -var BaseDocumentLoader = class {}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/document_loaders/langsmith.js - - - - -//#region src/document_loaders/langsmith.ts -var langsmith_exports = {}; -__export(langsmith_exports, { LangSmithLoader: () => LangSmithLoader }); -/** -* Document loader integration with LangSmith. -* -* ## [Constructor args](https://api.js.langchain.com/interfaces/_langchain_core.document_loaders_langsmith.LangSmithLoaderFields.html) -* -*
-* Load -* -* ```typescript -* import { LangSmithLoader } from '@langchain/core/document_loaders/langsmith'; -* import { Client } from 'langsmith'; -* -* const langSmithClient = new Client({ -* apiKey: process.env.LANGSMITH_API_KEY, -* }) -* -* const loader = new LangSmithLoader({ -* datasetId: "9a3b36f7-b308-40a5-9b46-6613853b6330", -* limit: 1, -* }); -* -* const docs = await loader.load(); -* ``` -* -* ```txt -* [ -* { -* pageContent: '{\n "input_key_str": "string",\n "input_key_bool": true\n}', -* metadata: { -* id: '8523d9e9-c123-4b23-9b46-21021nds289e', -* created_at: '2024-08-19T17:09:14.806441+00:00', -* modified_at: '2024-08-19T17:09:14.806441+00:00', -* name: '#8517 @ brace-test-dataset', -* dataset_id: '9a3b36f7-b308-40a5-9b46-6613853b6330', -* source_run_id: null, -* metadata: [Object], -* inputs: [Object], -* outputs: [Object] -* } -* } -* ] -* ``` -*
-*/ -var LangSmithLoader = class extends BaseDocumentLoader { - datasetId; - datasetName; - exampleIds; - asOf; - splits; - inlineS3Urls; - offset; - limit; - metadata; - filter; - contentKey; - formatContent; - client; - constructor(fields) { - super(); - if (fields.client && fields.clientConfig) throw new Error("client and clientConfig cannot both be provided."); - this.client = fields.client ?? new Client(fields?.clientConfig); - this.contentKey = fields.contentKey ? fields.contentKey.split(".") : []; - this.formatContent = fields.formatContent ?? _stringify; - this.datasetId = fields.datasetId; - this.datasetName = fields.datasetName; - this.exampleIds = fields.exampleIds; - this.asOf = fields.asOf; - this.splits = fields.splits; - this.inlineS3Urls = fields.inlineS3Urls; - this.offset = fields.offset; - this.limit = fields.limit; - this.metadata = fields.metadata; - this.filter = fields.filter; - } - async load() { - const documents = []; - for await (const example of this.client.listExamples({ - datasetId: this.datasetId, - datasetName: this.datasetName, - exampleIds: this.exampleIds, - asOf: this.asOf, - splits: this.splits, - inlineS3Urls: this.inlineS3Urls, - offset: this.offset, - limit: this.limit, - metadata: this.metadata, - filter: this.filter - })) { - let content = example.inputs; - for (const key of this.contentKey) content = content[key]; - const contentStr = this.formatContent(content); - const metadata = example; - ["created_at", "modified_at"].forEach((k) => { - if (k in metadata) { - if (typeof metadata[k] === "object") metadata[k] = metadata[k].toString(); - } - }); - documents.push({ - pageContent: contentStr, - metadata - }); - } - return documents; - } -}; -function _stringify(x) { - if (typeof x === "string") return x; - else try { - return JSON.stringify(x, null, 2); - } catch { - return String(x); - } -} - -//#endregion - -//# sourceMappingURL=langsmith.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/documents/document.js -//#region src/documents/document.ts -/** -* Interface for interacting with a document. -*/ -var Document = class { - pageContent; - metadata; - /** - * An optional identifier for the document. - * - * Ideally this should be unique across the document collection and formatted - * as a UUID, but this will not be enforced. - */ - id; - constructor(fields) { - this.pageContent = fields.pageContent !== void 0 ? fields.pageContent.toString() : ""; - this.metadata = fields.metadata ?? {}; - this.id = fields.id; - } -}; - -//#endregion - -//# sourceMappingURL=document.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/documents/transformers.js - - -//#region src/documents/transformers.ts -/** -* Abstract base class for document transformation systems. -* -* A document transformation system takes an array of Documents and returns an -* array of transformed Documents. These arrays do not necessarily have to have -* the same length. -* -* One example of this is a text splitter that splits a large document into -* many smaller documents. -*/ -var BaseDocumentTransformer = class extends Runnable { - lc_namespace = [ - "langchain_core", - "documents", - "transformers" - ]; - /** - * Method to invoke the document transformation. This method calls the - * transformDocuments method with the provided input. - * @param input The input documents to be transformed. - * @param _options Optional configuration object to customize the behavior of callbacks. - * @returns A Promise that resolves to the transformed documents. - */ - invoke(input, _options) { - return this.transformDocuments(input); - } -}; -/** -* Class for document transformers that return exactly one transformed document -* for each input document. -*/ -var MappingDocumentTransformer = class extends BaseDocumentTransformer { - async transformDocuments(documents) { - const newDocuments = []; - for (const document of documents) { - const transformedDocument = await this._transformDocument(document); - newDocuments.push(transformedDocument); - } - return newDocuments; - } -}; - -//#endregion - -//# sourceMappingURL=transformers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/documents/index.js - - - - -//#region src/documents/index.ts -var documents_exports = {}; -__export(documents_exports, { - BaseDocumentTransformer: () => BaseDocumentTransformer, - Document: () => Document, - MappingDocumentTransformer: () => MappingDocumentTransformer -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/base.js - - -//#region src/example_selectors/base.ts -/** -* Base class for example selectors. -*/ -var BaseExampleSelector = class extends Serializable { - lc_namespace = [ - "langchain_core", - "example_selectors", - "base" - ]; -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/conditional.js -//#region src/example_selectors/conditional.ts -/** -* Abstract class that defines the interface for selecting a prompt for a -* given language model. -*/ -var BasePromptSelector = class { - /** - * Asynchronous version of `getPrompt` that also accepts an options object - * for partial variables. - * @param llm The language model for which to get a prompt. - * @param options Optional object for partial variables. - * @returns A Promise that resolves to a prompt template. - */ - async getPromptAsync(llm, options) { - const prompt = this.getPrompt(llm); - return prompt.partial(options?.partialVariables ?? {}); - } -}; -/** -* Concrete implementation of `BasePromptSelector` that selects a prompt -* based on a set of conditions. It has a default prompt that it returns -* if none of the conditions are met. -*/ -var ConditionalPromptSelector = class extends BasePromptSelector { - defaultPrompt; - conditionals; - constructor(default_prompt, conditionals = []) { - super(); - this.defaultPrompt = default_prompt; - this.conditionals = conditionals; - } - /** - * Method that selects a prompt based on a set of conditions. If none of - * the conditions are met, it returns the default prompt. - * @param llm The language model for which to get a prompt. - * @returns A prompt template. - */ - getPrompt(llm) { - for (const [condition, prompt] of this.conditionals) if (condition(llm)) return prompt; - return this.defaultPrompt; - } -}; -/** -* Type guard function that checks if a given language model is of type -* `BaseLLM`. -*/ -function isLLM(llm) { - return llm._modelType() === "base_llm"; -} -/** -* Type guard function that checks if a given language model is of type -* `BaseChatModel`. -*/ -function isChatModel(llm) { - return llm._modelType() === "base_chat_model"; -} - -//#endregion - -//# sourceMappingURL=conditional.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/length_based.js - - -//#region src/example_selectors/length_based.ts -/** -* Calculates the length of a text based on the number of words and lines. -*/ -function getLengthBased(text) { - return text.split(/\n| /).length; -} -/** -* A specialized example selector that selects examples based on their -* length, ensuring that the total length of the selected examples does -* not exceed a specified maximum length. -* @example -* ```typescript -* const exampleSelector = new LengthBasedExampleSelector( -* [ -* { input: "happy", output: "sad" }, -* { input: "tall", output: "short" }, -* { input: "energetic", output: "lethargic" }, -* { input: "sunny", output: "gloomy" }, -* { input: "windy", output: "calm" }, -* ], -* { -* examplePrompt: new PromptTemplate({ -* inputVariables: ["input", "output"], -* template: "Input: {input}\nOutput: {output}", -* }), -* maxLength: 25, -* }, -* ); -* const dynamicPrompt = new FewShotPromptTemplate({ -* exampleSelector, -* examplePrompt: new PromptTemplate({ -* inputVariables: ["input", "output"], -* template: "Input: {input}\nOutput: {output}", -* }), -* prefix: "Give the antonym of every input", -* suffix: "Input: {adjective}\nOutput:", -* inputVariables: ["adjective"], -* }); -* console.log(dynamicPrompt.format({ adjective: "big" })); -* console.log( -* dynamicPrompt.format({ -* adjective: -* "big and huge and massive and large and gigantic and tall and much much much much much bigger than everything else", -* }), -* ); -* ``` -*/ -var LengthBasedExampleSelector = class LengthBasedExampleSelector extends BaseExampleSelector { - examples = []; - examplePrompt; - getTextLength = getLengthBased; - maxLength = 2048; - exampleTextLengths = []; - constructor(data) { - super(data); - this.examplePrompt = data.examplePrompt; - this.maxLength = data.maxLength ?? 2048; - this.getTextLength = data.getTextLength ?? getLengthBased; - } - /** - * Adds an example to the list of examples and calculates its length. - * @param example The example to be added. - * @returns Promise that resolves when the example has been added and its length calculated. - */ - async addExample(example) { - this.examples.push(example); - const stringExample = await this.examplePrompt.format(example); - this.exampleTextLengths.push(this.getTextLength(stringExample)); - } - /** - * Calculates the lengths of the examples. - * @param v Array of lengths of the examples. - * @param values Instance of LengthBasedExampleSelector. - * @returns Promise that resolves with an array of lengths of the examples. - */ - async calculateExampleTextLengths(v, values) { - if (v.length > 0) return v; - const { examples, examplePrompt } = values; - const stringExamples = await Promise.all(examples.map((eg) => examplePrompt.format(eg))); - return stringExamples.map((eg) => this.getTextLength(eg)); - } - /** - * Selects examples until the total length of the selected examples - * reaches the maxLength. - * @param inputVariables The input variables for the examples. - * @returns Promise that resolves with an array of selected examples. - */ - async selectExamples(inputVariables) { - const inputs = Object.values(inputVariables).join(" "); - let remainingLength = this.maxLength - this.getTextLength(inputs); - let i = 0; - const examples = []; - while (remainingLength > 0 && i < this.examples.length) { - const newLength = remainingLength - this.exampleTextLengths[i]; - if (newLength < 0) break; - else { - examples.push(this.examples[i]); - remainingLength = newLength; - } - i += 1; - } - return examples; - } - /** - * Creates a new instance of LengthBasedExampleSelector and adds a list of - * examples to it. - * @param examples Array of examples to be added. - * @param args Input parameters for the LengthBasedExampleSelector. - * @returns Promise that resolves with a new instance of LengthBasedExampleSelector with the examples added. - */ - static async fromExamples(examples, args) { - const selector = new LengthBasedExampleSelector(args); - await Promise.all(examples.map((eg) => selector.addExample(eg))); - return selector; - } -}; - -//#endregion - -//# sourceMappingURL=length_based.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/semantic_similarity.js - - - -//#region src/example_selectors/semantic_similarity.ts -function sortedValues(values) { - return Object.keys(values).sort().map((key) => values[key]); -} -/** -* Class that selects examples based on semantic similarity. It extends -* the BaseExampleSelector class. -* @example -* ```typescript -* const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples( -* [ -* { input: "happy", output: "sad" }, -* { input: "tall", output: "short" }, -* { input: "energetic", output: "lethargic" }, -* { input: "sunny", output: "gloomy" }, -* { input: "windy", output: "calm" }, -* ], -* new OpenAIEmbeddings(), -* HNSWLib, -* { k: 1 }, -* ); -* const dynamicPrompt = new FewShotPromptTemplate({ -* exampleSelector, -* examplePrompt: PromptTemplate.fromTemplate( -* "Input: {input}\nOutput: {output}", -* ), -* prefix: "Give the antonym of every input", -* suffix: "Input: {adjective}\nOutput:", -* inputVariables: ["adjective"], -* }); -* console.log(await dynamicPrompt.format({ adjective: "rainy" })); -* ``` -*/ -var SemanticSimilarityExampleSelector = class SemanticSimilarityExampleSelector extends BaseExampleSelector { - vectorStoreRetriever; - exampleKeys; - inputKeys; - constructor(data) { - super(data); - this.exampleKeys = data.exampleKeys; - this.inputKeys = data.inputKeys; - if (data.vectorStore !== void 0) this.vectorStoreRetriever = data.vectorStore.asRetriever({ - k: data.k ?? 4, - filter: data.filter - }); - else if (data.vectorStoreRetriever) this.vectorStoreRetriever = data.vectorStoreRetriever; - else throw new Error(`You must specify one of "vectorStore" and "vectorStoreRetriever".`); - } - /** - * Method that adds a new example to the vectorStore. The example is - * converted to a string and added to the vectorStore as a document. - * @param example The example to be added to the vectorStore. - * @returns Promise that resolves when the example has been added to the vectorStore. - */ - async addExample(example) { - const inputKeys = this.inputKeys ?? Object.keys(example); - const stringExample = sortedValues(inputKeys.reduce((acc, key) => ({ - ...acc, - [key]: example[key] - }), {})).join(" "); - await this.vectorStoreRetriever.addDocuments([new Document({ - pageContent: stringExample, - metadata: example - })]); - } - /** - * Method that selects which examples to use based on semantic similarity. - * It performs a similarity search in the vectorStore using the input - * variables and returns the examples with the highest similarity. - * @param inputVariables The input variables used for the similarity search. - * @returns Promise that resolves with an array of the selected examples. - */ - async selectExamples(inputVariables) { - const inputKeys = this.inputKeys ?? Object.keys(inputVariables); - const query = sortedValues(inputKeys.reduce((acc, key) => ({ - ...acc, - [key]: inputVariables[key] - }), {})).join(" "); - const exampleDocs = await this.vectorStoreRetriever.invoke(query); - const examples = exampleDocs.map((doc) => doc.metadata); - if (this.exampleKeys) return examples.map((example) => this.exampleKeys.reduce((acc, key) => ({ - ...acc, - [key]: example[key] - }), {})); - return examples; - } - /** - * Static method that creates a new instance of - * SemanticSimilarityExampleSelector. It takes a list of examples, an - * instance of Embeddings, a VectorStore class, and an options object as - * parameters. It converts the examples to strings, creates a VectorStore - * from the strings and the embeddings, and returns a new - * SemanticSimilarityExampleSelector with the created VectorStore and the - * options provided. - * @param examples The list of examples to be used. - * @param embeddings The instance of Embeddings to be used. - * @param vectorStoreCls The VectorStore class to be used. - * @param options The options object for the SemanticSimilarityExampleSelector. - * @returns Promise that resolves with a new instance of SemanticSimilarityExampleSelector. - */ - static async fromExamples(examples, embeddings, vectorStoreCls, options = {}) { - const inputKeys = options.inputKeys ?? null; - const stringExamples = examples.map((example) => sortedValues(inputKeys ? inputKeys.reduce((acc, key) => ({ - ...acc, - [key]: example[key] - }), {}) : example).join(" ")); - const vectorStore = await vectorStoreCls.fromTexts(stringExamples, examples, embeddings, options); - return new SemanticSimilarityExampleSelector({ - vectorStore, - k: options.k ?? 4, - exampleKeys: options.exampleKeys, - inputKeys: options.inputKeys - }); - } -}; - -//#endregion - -//# sourceMappingURL=semantic_similarity.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/example_selectors/index.js - - - - - - -//#region src/example_selectors/index.ts -var example_selectors_exports = {}; -__export(example_selectors_exports, { - BaseExampleSelector: () => BaseExampleSelector, - BasePromptSelector: () => BasePromptSelector, - ConditionalPromptSelector: () => ConditionalPromptSelector, - LengthBasedExampleSelector: () => LengthBasedExampleSelector, - SemanticSimilarityExampleSelector: () => SemanticSimilarityExampleSelector, - isChatModel: () => isChatModel, - isLLM: () => isLLM -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/indexing/record_manager.js - - -//#region src/indexing/record_manager.ts -const UUIDV5_NAMESPACE = "10f90ea3-90a4-4962-bf75-83a0f3c1c62a"; -var RecordManager = class extends Serializable { - lc_namespace = ["langchain", "recordmanagers"]; -}; - -//#endregion - -//# sourceMappingURL=record_manager.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/indexing/base.js - - - - - - -//#region src/indexing/base.ts -/** -* HashedDocument is a Document with hashes calculated. -* Hashes are calculated based on page content and metadata. -* It is used for indexing. -*/ -var _HashedDocument = class { - uid; - hash_; - contentHash; - metadataHash; - pageContent; - metadata; - keyEncoder = sha256; - constructor(fields) { - this.uid = fields.uid; - this.pageContent = fields.pageContent; - this.metadata = fields.metadata; - } - makeDefaultKeyEncoder(keyEncoderFn) { - this.keyEncoder = keyEncoderFn; - } - calculateHashes() { - const forbiddenKeys = [ - "hash_", - "content_hash", - "metadata_hash" - ]; - for (const key of forbiddenKeys) if (key in this.metadata) throw new Error(`Metadata cannot contain key ${key} as it is reserved for internal use. Restricted keys: [${forbiddenKeys.join(", ")}]`); - const contentHash = this._hashStringToUUID(this.pageContent); - try { - const metadataHash = this._hashNestedDictToUUID(this.metadata); - this.contentHash = contentHash; - this.metadataHash = metadataHash; - } catch (e) { - throw new Error(`Failed to hash metadata: ${e}. Please use a dict that can be serialized using json.`); - } - this.hash_ = this._hashStringToUUID(this.contentHash + this.metadataHash); - if (!this.uid) this.uid = this.hash_; - } - toDocument() { - return new Document({ - pageContent: this.pageContent, - metadata: this.metadata - }); - } - static fromDocument(document, uid) { - const doc = new this({ - pageContent: document.pageContent, - metadata: document.metadata, - uid: uid || document.uid - }); - doc.calculateHashes(); - return doc; - } - _hashStringToUUID(inputString) { - const hash_value = this.keyEncoder(inputString); - return v5(hash_value, UUIDV5_NAMESPACE); - } - _hashNestedDictToUUID(data) { - const serialized_data = JSON.stringify(data, Object.keys(data).sort()); - const hash_value = this.keyEncoder(serialized_data); - return v5(hash_value, UUIDV5_NAMESPACE); - } -}; -function _batch(size, iterable) { - const batches = []; - let currentBatch = []; - iterable.forEach((item) => { - currentBatch.push(item); - if (currentBatch.length >= size) { - batches.push(currentBatch); - currentBatch = []; - } - }); - if (currentBatch.length > 0) batches.push(currentBatch); - return batches; -} -function _deduplicateInOrder(hashedDocuments) { - const seen = /* @__PURE__ */ new Set(); - const deduplicated = []; - for (const hashedDoc of hashedDocuments) { - if (!hashedDoc.hash_) throw new Error("Hashed document does not have a hash"); - if (!seen.has(hashedDoc.hash_)) { - seen.add(hashedDoc.hash_); - deduplicated.push(hashedDoc); - } - } - return deduplicated; -} -function _getSourceIdAssigner(sourceIdKey) { - if (sourceIdKey === null) return (_doc) => null; - else if (typeof sourceIdKey === "string") return (doc) => doc.metadata[sourceIdKey]; - else if (typeof sourceIdKey === "function") return sourceIdKey; - else throw new Error(`sourceIdKey should be null, a string or a function, got ${typeof sourceIdKey}`); -} -const _isBaseDocumentLoader = (arg) => { - if ("load" in arg && typeof arg.load === "function" && "loadAndSplit" in arg && typeof arg.loadAndSplit === "function") return true; - return false; -}; -/** -* Index data from the doc source into the vector store. -* -* Indexing functionality uses a manager to keep track of which documents -* are in the vector store. -* -* This allows us to keep track of which documents were updated, and which -* documents were deleted, which documents should be skipped. -* -* For the time being, documents are indexed using their hashes, and users -* are not able to specify the uid of the document. -* -* @param {IndexArgs} args -* @param {BaseDocumentLoader | DocumentInterface[]} args.docsSource The source of documents to index. Can be a DocumentLoader or a list of Documents. -* @param {RecordManagerInterface} args.recordManager The record manager to use for keeping track of indexed documents. -* @param {VectorStore} args.vectorStore The vector store to use for storing the documents. -* @param {IndexOptions | undefined} args.options Options for indexing. -* @returns {Promise} -*/ -async function index(args) { - const { docsSource, recordManager, vectorStore, options } = args; - const { batchSize = 100, cleanup, sourceIdKey, cleanupBatchSize = 1e3, forceUpdate = false } = options ?? {}; - if (cleanup === "incremental" && !sourceIdKey) throw new Error("sourceIdKey is required when cleanup mode is incremental. Please provide through 'options.sourceIdKey'."); - const docs = _isBaseDocumentLoader(docsSource) ? await docsSource.load() : docsSource; - const sourceIdAssigner = _getSourceIdAssigner(sourceIdKey ?? null); - const indexStartDt = await recordManager.getTime(); - let numAdded = 0; - let numDeleted = 0; - let numUpdated = 0; - let numSkipped = 0; - const batches = _batch(batchSize ?? 100, docs); - for (const batch of batches) { - const hashedDocs = _deduplicateInOrder(batch.map((doc) => _HashedDocument.fromDocument(doc))); - const sourceIds = hashedDocs.map((doc) => sourceIdAssigner(doc)); - if (cleanup === "incremental") hashedDocs.forEach((_hashedDoc, index$1) => { - const source = sourceIds[index$1]; - if (source === null) throw new Error("sourceIdKey must be provided when cleanup is incremental"); - }); - const batchExists = await recordManager.exists(hashedDocs.map((doc) => doc.uid)); - const uids = []; - const docsToIndex = []; - const docsToUpdate = []; - const seenDocs = /* @__PURE__ */ new Set(); - hashedDocs.forEach((hashedDoc, i) => { - const docExists = batchExists[i]; - if (docExists) if (forceUpdate) seenDocs.add(hashedDoc.uid); - else { - docsToUpdate.push(hashedDoc.uid); - return; - } - uids.push(hashedDoc.uid); - docsToIndex.push(hashedDoc.toDocument()); - }); - if (docsToUpdate.length > 0) { - await recordManager.update(docsToUpdate, { timeAtLeast: indexStartDt }); - numSkipped += docsToUpdate.length; - } - if (docsToIndex.length > 0) { - await vectorStore.addDocuments(docsToIndex, { ids: uids }); - numAdded += docsToIndex.length - seenDocs.size; - numUpdated += seenDocs.size; - } - await recordManager.update(hashedDocs.map((doc) => doc.uid), { - timeAtLeast: indexStartDt, - groupIds: sourceIds - }); - if (cleanup === "incremental") { - sourceIds.forEach((sourceId) => { - if (!sourceId) throw new Error("Source id cannot be null"); - }); - const uidsToDelete = await recordManager.listKeys({ - before: indexStartDt, - groupIds: sourceIds - }); - if (uidsToDelete.length > 0) { - await vectorStore.delete({ ids: uidsToDelete }); - await recordManager.deleteKeys(uidsToDelete); - numDeleted += uidsToDelete.length; - } - } - } - if (cleanup === "full") { - let uidsToDelete = await recordManager.listKeys({ - before: indexStartDt, - limit: cleanupBatchSize - }); - while (uidsToDelete.length > 0) { - await vectorStore.delete({ ids: uidsToDelete }); - await recordManager.deleteKeys(uidsToDelete); - numDeleted += uidsToDelete.length; - uidsToDelete = await recordManager.listKeys({ - before: indexStartDt, - limit: cleanupBatchSize - }); - } - } - return { - numAdded, - numDeleted, - numUpdated, - numSkipped - }; -} - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/indexing/index.js - - - - -//#region src/indexing/index.ts -var indexing_exports = {}; -__export(indexing_exports, { - RecordManager: () => RecordManager, - UUIDV5_NAMESPACE: () => UUIDV5_NAMESPACE, - _HashedDocument: () => _HashedDocument, - _batch: () => _batch, - _deduplicateInOrder: () => _deduplicateInOrder, - _getSourceIdAssigner: () => _getSourceIdAssigner, - _isBaseDocumentLoader: () => _isBaseDocumentLoader, - index: () => index -}); - -//#endregion - -//# sourceMappingURL=index.js.map -// EXTERNAL MODULE: ./node_modules/base64-js/index.js -var base64_js = __nccwpck_require__(8793); -;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/chunk-VL2OQCWN.js - - -var chunk_VL2OQCWN_defProp = Object.defineProperty; -var __defNormalProp = (obj, key, value) => key in obj ? chunk_VL2OQCWN_defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value; -var __publicField = (obj, key, value) => { - __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value); - return value; -}; - -// src/utils.ts -function never(_) { -} -function bytePairMerge(piece, ranks) { - let parts = Array.from( - { length: piece.length }, - (_, i) => ({ start: i, end: i + 1 }) - ); - while (parts.length > 1) { - let minRank = null; - for (let i = 0; i < parts.length - 1; i++) { - const slice = piece.slice(parts[i].start, parts[i + 1].end); - const rank = ranks.get(slice.join(",")); - if (rank == null) - continue; - if (minRank == null || rank < minRank[0]) { - minRank = [rank, i]; - } - } - if (minRank != null) { - const i = minRank[1]; - parts[i] = { start: parts[i].start, end: parts[i + 1].end }; - parts.splice(i + 1, 1); - } else { - break; - } - } - return parts; -} -function bytePairEncode(piece, ranks) { - if (piece.length === 1) - return [ranks.get(piece.join(","))]; - return bytePairMerge(piece, ranks).map((p) => ranks.get(piece.slice(p.start, p.end).join(","))).filter((x) => x != null); -} -function chunk_VL2OQCWN_escapeRegex(str) { - return str.replace(/[\\^$*+?.()|[\]{}]/g, "\\$&"); -} -var _Tiktoken = class { - /** @internal */ - specialTokens; - /** @internal */ - inverseSpecialTokens; - /** @internal */ - patStr; - /** @internal */ - textEncoder = new TextEncoder(); - /** @internal */ - textDecoder = new TextDecoder("utf-8"); - /** @internal */ - rankMap = /* @__PURE__ */ new Map(); - /** @internal */ - textMap = /* @__PURE__ */ new Map(); - constructor(ranks, extendedSpecialTokens) { - this.patStr = ranks.pat_str; - const uncompressed = ranks.bpe_ranks.split("\n").filter(Boolean).reduce((memo, x) => { - const [_, offsetStr, ...tokens] = x.split(" "); - const offset = Number.parseInt(offsetStr, 10); - tokens.forEach((token, i) => memo[token] = offset + i); - return memo; - }, {}); - for (const [token, rank] of Object.entries(uncompressed)) { - const bytes = base64_js.toByteArray(token); - this.rankMap.set(bytes.join(","), rank); - this.textMap.set(rank, bytes); - } - this.specialTokens = { ...ranks.special_tokens, ...extendedSpecialTokens }; - this.inverseSpecialTokens = Object.entries(this.specialTokens).reduce((memo, [text, rank]) => { - memo[rank] = this.textEncoder.encode(text); - return memo; - }, {}); - } - encode(text, allowedSpecial = [], disallowedSpecial = "all") { - const regexes = new RegExp(this.patStr, "ug"); - const specialRegex = _Tiktoken.specialTokenRegex( - Object.keys(this.specialTokens) - ); - const ret = []; - const allowedSpecialSet = new Set( - allowedSpecial === "all" ? Object.keys(this.specialTokens) : allowedSpecial - ); - const disallowedSpecialSet = new Set( - disallowedSpecial === "all" ? Object.keys(this.specialTokens).filter( - (x) => !allowedSpecialSet.has(x) - ) : disallowedSpecial - ); - if (disallowedSpecialSet.size > 0) { - const disallowedSpecialRegex = _Tiktoken.specialTokenRegex([ - ...disallowedSpecialSet - ]); - const specialMatch = text.match(disallowedSpecialRegex); - if (specialMatch != null) { - throw new Error( - `The text contains a special token that is not allowed: ${specialMatch[0]}` - ); - } - } - let start = 0; - while (true) { - let nextSpecial = null; - let startFind = start; - while (true) { - specialRegex.lastIndex = startFind; - nextSpecial = specialRegex.exec(text); - if (nextSpecial == null || allowedSpecialSet.has(nextSpecial[0])) - break; - startFind = nextSpecial.index + 1; - } - const end = nextSpecial?.index ?? text.length; - for (const match of text.substring(start, end).matchAll(regexes)) { - const piece = this.textEncoder.encode(match[0]); - const token2 = this.rankMap.get(piece.join(",")); - if (token2 != null) { - ret.push(token2); - continue; - } - ret.push(...bytePairEncode(piece, this.rankMap)); - } - if (nextSpecial == null) - break; - let token = this.specialTokens[nextSpecial[0]]; - ret.push(token); - start = nextSpecial.index + nextSpecial[0].length; - } - return ret; - } - decode(tokens) { - const res = []; - let length = 0; - for (let i2 = 0; i2 < tokens.length; ++i2) { - const token = tokens[i2]; - const bytes = this.textMap.get(token) ?? this.inverseSpecialTokens[token]; - if (bytes != null) { - res.push(bytes); - length += bytes.length; - } - } - const mergedArray = new Uint8Array(length); - let i = 0; - for (const bytes of res) { - mergedArray.set(bytes, i); - i += bytes.length; - } - return this.textDecoder.decode(mergedArray); - } -}; -var Tiktoken = _Tiktoken; -__publicField(Tiktoken, "specialTokenRegex", (tokens) => { - return new RegExp(tokens.map((i) => chunk_VL2OQCWN_escapeRegex(i)).join("|"), "g"); -}); -function getEncodingNameForModel(model) { - switch (model) { - case "gpt2": { - return "gpt2"; - } - case "code-cushman-001": - case "code-cushman-002": - case "code-davinci-001": - case "code-davinci-002": - case "cushman-codex": - case "davinci-codex": - case "davinci-002": - case "text-davinci-002": - case "text-davinci-003": { - return "p50k_base"; - } - case "code-davinci-edit-001": - case "text-davinci-edit-001": { - return "p50k_edit"; - } - case "ada": - case "babbage": - case "babbage-002": - case "code-search-ada-code-001": - case "code-search-babbage-code-001": - case "curie": - case "davinci": - case "text-ada-001": - case "text-babbage-001": - case "text-curie-001": - case "text-davinci-001": - case "text-search-ada-doc-001": - case "text-search-babbage-doc-001": - case "text-search-curie-doc-001": - case "text-search-davinci-doc-001": - case "text-similarity-ada-001": - case "text-similarity-babbage-001": - case "text-similarity-curie-001": - case "text-similarity-davinci-001": { - return "r50k_base"; - } - case "gpt-3.5-turbo-instruct-0914": - case "gpt-3.5-turbo-instruct": - case "gpt-3.5-turbo-16k-0613": - case "gpt-3.5-turbo-16k": - case "gpt-3.5-turbo-0613": - case "gpt-3.5-turbo-0301": - case "gpt-3.5-turbo": - case "gpt-4-32k-0613": - case "gpt-4-32k-0314": - case "gpt-4-32k": - case "gpt-4-0613": - case "gpt-4-0314": - case "gpt-4": - case "gpt-3.5-turbo-1106": - case "gpt-35-turbo": - case "gpt-4-1106-preview": - case "gpt-4-vision-preview": - case "gpt-3.5-turbo-0125": - case "gpt-4-turbo": - case "gpt-4-turbo-2024-04-09": - case "gpt-4-turbo-preview": - case "gpt-4-0125-preview": - case "text-embedding-ada-002": - case "text-embedding-3-small": - case "text-embedding-3-large": { - return "cl100k_base"; - } - case "gpt-4o": - case "gpt-4o-2024-05-13": - case "gpt-4o-2024-08-06": - case "gpt-4o-2024-11-20": - case "gpt-4o-mini-2024-07-18": - case "gpt-4o-mini": - case "gpt-4o-search-preview": - case "gpt-4o-search-preview-2025-03-11": - case "gpt-4o-mini-search-preview": - case "gpt-4o-mini-search-preview-2025-03-11": - case "gpt-4o-audio-preview": - case "gpt-4o-audio-preview-2024-12-17": - case "gpt-4o-audio-preview-2024-10-01": - case "gpt-4o-mini-audio-preview": - case "gpt-4o-mini-audio-preview-2024-12-17": - case "o1": - case "o1-2024-12-17": - case "o1-mini": - case "o1-mini-2024-09-12": - case "o1-preview": - case "o1-preview-2024-09-12": - case "o1-pro": - case "o1-pro-2025-03-19": - case "o3": - case "o3-2025-04-16": - case "o3-mini": - case "o3-mini-2025-01-31": - case "o4-mini": - case "o4-mini-2025-04-16": - case "chatgpt-4o-latest": - case "gpt-4o-realtime": - case "gpt-4o-realtime-preview-2024-10-01": - case "gpt-4o-realtime-preview-2024-12-17": - case "gpt-4o-mini-realtime-preview": - case "gpt-4o-mini-realtime-preview-2024-12-17": - case "gpt-4.1": - case "gpt-4.1-2025-04-14": - case "gpt-4.1-mini": - case "gpt-4.1-mini-2025-04-14": - case "gpt-4.1-nano": - case "gpt-4.1-nano-2025-04-14": - case "gpt-4.5-preview": - case "gpt-4.5-preview-2025-02-27": - case "gpt-5": - case "gpt-5-2025-08-07": - case "gpt-5-nano": - case "gpt-5-nano-2025-08-07": - case "gpt-5-mini": - case "gpt-5-mini-2025-08-07": - case "gpt-5-chat-latest": { - return "o200k_base"; - } - default: - throw new Error("Unknown model"); - } -} - - - -;// CONCATENATED MODULE: ./node_modules/js-tiktoken/dist/lite.js - - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/tiktoken.js - - - - -//#region src/utils/tiktoken.ts -var tiktoken_exports = {}; -__export(tiktoken_exports, { - encodingForModel: () => encodingForModel, - getEncoding: () => getEncoding -}); -const cache = {}; -const caller = /* @__PURE__ */ new async_caller_AsyncCaller({}); -async function getEncoding(encoding) { - if (!(encoding in cache)) cache[encoding] = caller.fetch(`https://tiktoken.pages.dev/js/${encoding}.json`).then((res) => res.json()).then((data) => new Tiktoken(data)).catch((e) => { - delete cache[encoding]; - throw e; - }); - return await cache[encoding]; -} -async function encodingForModel(model) { - return getEncoding(getEncodingNameForModel(model)); -} - -//#endregion - -//# sourceMappingURL=tiktoken.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/base.js - - - - - - - - -//#region src/language_models/base.ts -var language_models_base_base_exports = {}; -__export(language_models_base_base_exports, { - BaseLangChain: () => BaseLangChain, - BaseLanguageModel: () => BaseLanguageModel, - calculateMaxTokens: () => calculateMaxTokens, - getEmbeddingContextSize: () => getEmbeddingContextSize, - getModelContextSize: () => getModelContextSize, - getModelNameForTiktoken: () => getModelNameForTiktoken, - isOpenAITool: () => isOpenAITool -}); -const getModelNameForTiktoken = (modelName) => { - if (modelName.startsWith("gpt-5")) return "gpt-5"; - if (modelName.startsWith("gpt-3.5-turbo-16k")) return "gpt-3.5-turbo-16k"; - if (modelName.startsWith("gpt-3.5-turbo-")) return "gpt-3.5-turbo"; - if (modelName.startsWith("gpt-4-32k")) return "gpt-4-32k"; - if (modelName.startsWith("gpt-4-")) return "gpt-4"; - if (modelName.startsWith("gpt-4o")) return "gpt-4o"; - return modelName; -}; -const getEmbeddingContextSize = (modelName) => { - switch (modelName) { - case "text-embedding-ada-002": return 8191; - default: return 2046; - } -}; -/** -* Get the context window size (max input tokens) for a given model. -* -* Context window sizes are sourced from official model documentation: -* - OpenAI: https://platform.openai.com/docs/models -* - Anthropic: https://docs.anthropic.com/claude/docs/models-overview -* - Google: https://ai.google.dev/gemini/docs/models/gemini -* -* @param modelName - The name of the model -* @returns The context window size in tokens -*/ -const getModelContextSize = (modelName) => { - const normalizedName = getModelNameForTiktoken(modelName); - switch (normalizedName) { - case "gpt-5": - case "gpt-5-turbo": - case "gpt-5-turbo-preview": return 4e5; - case "gpt-4o": - case "gpt-4o-mini": - case "gpt-4o-2024-05-13": - case "gpt-4o-2024-08-06": return 128e3; - case "gpt-4-turbo": - case "gpt-4-turbo-preview": - case "gpt-4-turbo-2024-04-09": - case "gpt-4-0125-preview": - case "gpt-4-1106-preview": return 128e3; - case "gpt-4-32k": - case "gpt-4-32k-0314": - case "gpt-4-32k-0613": return 32768; - case "gpt-4": - case "gpt-4-0314": - case "gpt-4-0613": return 8192; - case "gpt-3.5-turbo-16k": - case "gpt-3.5-turbo-16k-0613": return 16384; - case "gpt-3.5-turbo": - case "gpt-3.5-turbo-0301": - case "gpt-3.5-turbo-0613": - case "gpt-3.5-turbo-1106": - case "gpt-3.5-turbo-0125": return 4096; - case "text-davinci-003": - case "text-davinci-002": return 4097; - case "text-davinci-001": return 2049; - case "text-curie-001": - case "text-babbage-001": - case "text-ada-001": return 2048; - case "code-davinci-002": - case "code-davinci-001": return 8e3; - case "code-cushman-001": return 2048; - case "claude-3-5-sonnet-20241022": - case "claude-3-5-sonnet-20240620": - case "claude-3-opus-20240229": - case "claude-3-sonnet-20240229": - case "claude-3-haiku-20240307": - case "claude-2.1": return 2e5; - case "claude-2.0": - case "claude-instant-1.2": return 1e5; - case "gemini-1.5-pro": - case "gemini-1.5-pro-latest": - case "gemini-1.5-flash": - case "gemini-1.5-flash-latest": return 1e6; - case "gemini-pro": - case "gemini-pro-vision": return 32768; - default: return 4097; - } -}; -/** -* Whether or not the input matches the OpenAI tool definition. -* @param {unknown} tool The input to check. -* @returns {boolean} Whether the input is an OpenAI tool definition. -*/ -function isOpenAITool(tool) { - if (typeof tool !== "object" || !tool) return false; - if ("type" in tool && tool.type === "function" && "function" in tool && typeof tool.function === "object" && tool.function && "name" in tool.function && "parameters" in tool.function) return true; - return false; -} -const calculateMaxTokens = async ({ prompt, modelName }) => { - let numTokens; - try { - numTokens = (await encodingForModel(getModelNameForTiktoken(modelName))).encode(prompt).length; - } catch { - console.warn("Failed to calculate number of tokens, falling back to approximate count"); - numTokens = Math.ceil(prompt.length / 4); - } - const maxTokens = getModelContextSize(modelName); - return maxTokens - numTokens; -}; -const getVerbosity = () => false; -/** -* Base class for language models, chains, tools. -*/ -var BaseLangChain = class extends Runnable { - /** - * Whether to print out response text. - */ - verbose; - callbacks; - tags; - metadata; - get lc_attributes() { - return { - callbacks: void 0, - verbose: void 0 - }; - } - constructor(params) { - super(params); - this.verbose = params.verbose ?? getVerbosity(); - this.callbacks = params.callbacks; - this.tags = params.tags ?? []; - this.metadata = params.metadata ?? {}; - } -}; -/** -* Base class for language models. -*/ -var BaseLanguageModel = class extends BaseLangChain { - /** - * Keys that the language model accepts as call options. - */ - get callKeys() { - return [ - "stop", - "timeout", - "signal", - "tags", - "metadata", - "callbacks" - ]; - } - /** - * The async caller should be used by subclasses to make any async calls, - * which will thus benefit from the concurrency and retry logic. - */ - caller; - cache; - constructor({ callbacks, callbackManager,...params }) { - const { cache,...rest } = params; - super({ - callbacks: callbacks ?? callbackManager, - ...rest - }); - if (typeof cache === "object") this.cache = cache; - else if (cache) this.cache = InMemoryCache.global(); - else this.cache = void 0; - this.caller = new async_caller_AsyncCaller(params ?? {}); - } - _encoding; - /** - * Get the number of tokens in the content. - * @param content The content to get the number of tokens for. - * @returns The number of tokens in the content. - */ - async getNumTokens(content) { - let textContent; - if (typeof content === "string") textContent = content; - else - /** - * Content is an array of ContentBlock - * - * ToDo(@christian-bromann): This is a temporary fix to get the number of tokens for the content. - * We need to find a better way to do this. - * @see https://github.com/langchain-ai/langchainjs/pull/8341#pullrequestreview-2933713116 - */ - textContent = content.map((item) => { - if (typeof item === "string") return item; - if (item.type === "text" && "text" in item) return item.text; - return ""; - }).join(""); - let numTokens = Math.ceil(textContent.length / 4); - if (!this._encoding) try { - this._encoding = await encodingForModel("modelName" in this ? getModelNameForTiktoken(this.modelName) : "gpt2"); - } catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count", error); - } - if (this._encoding) try { - numTokens = this._encoding.encode(textContent).length; - } catch (error) { - console.warn("Failed to calculate number of tokens, falling back to approximate count", error); - } - return numTokens; - } - static _convertInputToPromptValue(input) { - if (typeof input === "string") return new StringPromptValue(input); - else if (Array.isArray(input)) return new ChatPromptValue(input.map(utils_coerceMessageLikeToMessage)); - else return input; - } - /** - * Get the identifying parameters of the LLM. - */ - _identifyingParams() { - return {}; - } - /** - * Create a unique cache key for a specific call to a specific language model. - * @param callOptions Call options for the model - * @returns A unique cache key. - */ - _getSerializedCacheKeyParametersForCall({ config,...callOptions }) { - const params = { - ...this._identifyingParams(), - ...callOptions, - _type: this._llmType(), - _model: this._modelType() - }; - const filteredEntries = Object.entries(params).filter(([_, value]) => value !== void 0); - const serializedEntries = filteredEntries.map(([key, value]) => `${key}:${JSON.stringify(value)}`).sort().join(","); - return serializedEntries; - } - /** - * @deprecated - * Return a json-like object representing this LLM. - */ - serialize() { - return { - ...this._identifyingParams(), - _type: this._llmType(), - _model: this._modelType() - }; - } - /** - * @deprecated - * Load an LLM from a json-like object describing it. - */ - static async deserialize(_data) { - throw new Error("Use .toJSON() instead"); - } - /** - * Return profiling information for the model. - * - * @returns {ModelProfile} An object describing the model's capabilities and constraints - */ - get profile() { - return {}; - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/passthrough.js - - - - -//#region src/runnables/passthrough.ts -/** -* A runnable to passthrough inputs unchanged or with additional keys. -* -* This runnable behaves almost like the identity function, except that it -* can be configured to add additional keys to the output, if the input is -* an object. -* -* The example below demonstrates how to use `RunnablePassthrough to -* passthrough the input from the `.invoke()` -* -* @example -* ```typescript -* const chain = RunnableSequence.from([ -* { -* question: new RunnablePassthrough(), -* context: async () => loadContextFromStore(), -* }, -* prompt, -* llm, -* outputParser, -* ]); -* const response = await chain.invoke( -* "I can pass a single string instead of an object since I'm using `RunnablePassthrough`." -* ); -* ``` -*/ -var RunnablePassthrough = class extends Runnable { - static lc_name() { - return "RunnablePassthrough"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - func; - constructor(fields) { - super(fields); - if (fields) this.func = fields.func; - } - async invoke(input, options) { - const config = ensureConfig(options); - if (this.func) await this.func(input, config); - return this._callWithConfig((input$1) => Promise.resolve(input$1), input, config); - } - async *transform(generator, options) { - const config = ensureConfig(options); - let finalOutput; - let finalOutputSupported = true; - for await (const chunk of this._transformStreamWithConfig(generator, (input) => input, config)) { - yield chunk; - if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = concat(finalOutput, chunk); - } catch { - finalOutput = void 0; - finalOutputSupported = false; - } - } - if (this.func && finalOutput !== void 0) await this.func(finalOutput, config); - } - /** - * A runnable that assigns key-value pairs to the input. - * - * The example below shows how you could use it with an inline function. - * - * @example - * ```typescript - * const prompt = - * PromptTemplate.fromTemplate(`Write a SQL query to answer the question using the following schema: {schema} - * Question: {question} - * SQL Query:`); - * - * // The `RunnablePassthrough.assign()` is used here to passthrough the input from the `.invoke()` - * // call (in this example it's the question), along with any inputs passed to the `.assign()` method. - * // In this case, we're passing the schema. - * const sqlQueryGeneratorChain = RunnableSequence.from([ - * RunnablePassthrough.assign({ - * schema: async () => db.getTableInfo(), - * }), - * prompt, - * new ChatOpenAI({ model: "gpt-4o-mini" }).withConfig({ stop: ["\nSQLResult:"] }), - * new StringOutputParser(), - * ]); - * const result = await sqlQueryGeneratorChain.invoke({ - * question: "How many employees are there?", - * }); - * ``` - */ - static assign(mapping) { - return new RunnableAssign(new RunnableMap({ steps: mapping })); - } -}; - -//#endregion - -//# sourceMappingURL=passthrough.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/utils.js -//#region src/language_models/utils.ts -const language_models_utils_iife = (fn) => fn(); -function castStandardMessageContent(message) { - const Cls = message.constructor; - return new Cls({ - ...message, - content: message.contentBlocks, - response_metadata: { - ...message.response_metadata, - output_version: "v1" - } - }); -} - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/chat_models.js - - - - - - - - - - - - - - - - - - -//#region src/language_models/chat_models.ts -var chat_models_exports = {}; -__export(chat_models_exports, { - BaseChatModel: () => BaseChatModel, - SimpleChatModel: () => SimpleChatModel -}); -function _formatForTracing(messages) { - const messagesToTrace = []; - for (const message of messages) { - let messageToTrace = message; - if (Array.isArray(message.content)) for (let idx = 0; idx < message.content.length; idx++) { - const block = message.content[idx]; - if (isURLContentBlock(block) || isBase64ContentBlock(block)) { - if (messageToTrace === message) messageToTrace = new message.constructor({ - ...messageToTrace, - content: [ - ...message.content.slice(0, idx), - convertToOpenAIImageBlock(block), - ...message.content.slice(idx + 1) - ] - }); - } - } - messagesToTrace.push(messageToTrace); - } - return messagesToTrace; -} -/** -* Base class for chat models. It extends the BaseLanguageModel class and -* provides methods for generating chat based on input messages. -*/ -var BaseChatModel = class BaseChatModel extends BaseLanguageModel { - lc_namespace = [ - "langchain", - "chat_models", - this._llmType() - ]; - disableStreaming = false; - outputVersion; - get callKeys() { - return [...super.callKeys, "outputVersion"]; - } - constructor(fields) { - super(fields); - this.outputVersion = language_models_utils_iife(() => { - const outputVersion = fields.outputVersion ?? getEnvironmentVariable("LC_OUTPUT_VERSION"); - if (outputVersion && ["v0", "v1"].includes(outputVersion)) return outputVersion; - return "v0"; - }); - } - _separateRunnableConfigFromCallOptionsCompat(options) { - const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); - callOptions.signal = runnableConfig.signal; - return [runnableConfig, callOptions]; - } - /** - * Invokes the chat model with a single input. - * @param input The input for the language model. - * @param options The call options. - * @returns A Promise that resolves to a BaseMessageChunk. - */ - async invoke(input, options) { - const promptValue = BaseChatModel._convertInputToPromptValue(input); - const result = await this.generatePrompt([promptValue], options, options?.callbacks); - const chatGeneration = result.generations[0][0]; - return chatGeneration.message; - } - async *_streamResponseChunks(_messages, _options, _runManager) { - throw new Error("Not implemented."); - } - async *_streamIterator(input, options) { - if (this._streamResponseChunks === BaseChatModel.prototype._streamResponseChunks || this.disableStreaming) yield this.invoke(input, options); - else { - const prompt = BaseChatModel._convertInputToPromptValue(input); - const messages = prompt.toChatMessages(); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); - const inheritableMetadata = { - ...runnableConfig.metadata, - ...this.getLsParams(callOptions) - }; - const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: callOptions, - invocation_params: this?.invocationParams(callOptions), - batch_size: 1 - }; - const outputVersion = callOptions.outputVersion ?? this.outputVersion; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), [_formatForTracing(messages)], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName); - let generationChunk; - let llmOutput; - try { - for await (const chunk of this._streamResponseChunks(messages, callOptions, runManagers?.[0])) { - if (chunk.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) chunk.message._updateId(`run-${runId}`); - } - chunk.message.response_metadata = { - ...chunk.generationInfo, - ...chunk.message.response_metadata - }; - if (outputVersion === "v1") yield castStandardMessageContent(chunk.message); - else yield chunk.message; - if (!generationChunk) generationChunk = chunk; - else generationChunk = generationChunk.concat(chunk); - if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) llmOutput = { tokenUsage: { - promptTokens: chunk.message.usage_metadata.input_tokens, - completionTokens: chunk.message.usage_metadata.output_tokens, - totalTokens: chunk.message.usage_metadata.total_tokens - } }; - } - } catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ - generations: [[generationChunk]], - llmOutput - }))); - } - } - getLsParams(options) { - const providerName = this.getName().startsWith("Chat") ? this.getName().replace("Chat", "") : this.getName(); - return { - ls_model_type: "chat", - ls_stop: options.stop, - ls_provider: providerName - }; - } - /** @ignore */ - async _generateUncached(messages, parsedOptions, handledOptions, startedRunManagers) { - const baseMessages = messages.map((messageList) => messageList.map(utils_coerceMessageLikeToMessage)); - let runManagers; - if (startedRunManagers !== void 0 && startedRunManagers.length === baseMessages.length) runManagers = startedRunManagers; - else { - const inheritableMetadata = { - ...handledOptions.metadata, - ...this.getLsParams(parsedOptions) - }; - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: 1 - }; - runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName); - } - const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; - const generations = []; - const llmOutputs = []; - const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); - if (hasStreamingHandler && !this.disableStreaming && baseMessages.length === 1 && this._streamResponseChunks !== BaseChatModel.prototype._streamResponseChunks) try { - const stream = await this._streamResponseChunks(baseMessages[0], parsedOptions, runManagers?.[0]); - let aggregated; - let llmOutput; - for await (const chunk of stream) { - if (chunk.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) chunk.message._updateId(`run-${runId}`); - } - if (aggregated === void 0) aggregated = chunk; - else aggregated = concat(aggregated, chunk); - if (isAIMessageChunk(chunk.message) && chunk.message.usage_metadata !== void 0) llmOutput = { tokenUsage: { - promptTokens: chunk.message.usage_metadata.input_tokens, - completionTokens: chunk.message.usage_metadata.output_tokens, - totalTokens: chunk.message.usage_metadata.total_tokens - } }; - } - if (aggregated === void 0) throw new Error("Received empty response from chat model call."); - generations.push([aggregated]); - await runManagers?.[0].handleLLMEnd({ - generations, - llmOutput - }); - } catch (e) { - await runManagers?.[0].handleLLMError(e); - throw e; - } - else { - const results = await Promise.allSettled(baseMessages.map(async (messageList, i) => { - const generateResults = await this._generate(messageList, { - ...parsedOptions, - promptIndex: i - }, runManagers?.[i]); - if (outputVersion === "v1") for (const generation of generateResults.generations) generation.message = castStandardMessageContent(generation.message); - return generateResults; - })); - await Promise.all(results.map(async (pResult, i) => { - if (pResult.status === "fulfilled") { - const result = pResult.value; - for (const generation of result.generations) { - if (generation.message.id == null) { - const runId = runManagers?.at(0)?.runId; - if (runId != null) generation.message._updateId(`run-${runId}`); - } - generation.message.response_metadata = { - ...generation.generationInfo, - ...generation.message.response_metadata - }; - } - if (result.generations.length === 1) result.generations[0].message.response_metadata = { - ...result.llmOutput, - ...result.generations[0].message.response_metadata - }; - generations[i] = result.generations; - llmOutputs[i] = result.llmOutput; - return runManagers?.[i]?.handleLLMEnd({ - generations: [result.generations], - llmOutput: result.llmOutput - }); - } else { - await runManagers?.[i]?.handleLLMError(pResult.reason); - return Promise.reject(pResult.reason); - } - })); - } - const output = { - generations, - llmOutput: llmOutputs.length ? this._combineLLMOutput?.(...llmOutputs) : void 0 - }; - Object.defineProperty(output, RUN_KEY, { - value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, - configurable: true - }); - return output; - } - async _generateCached({ messages, cache, llmStringKey, parsedOptions, handledOptions }) { - const baseMessages = messages.map((messageList) => messageList.map(utils_coerceMessageLikeToMessage)); - const inheritableMetadata = { - ...handledOptions.metadata, - ...this.getLsParams(parsedOptions) - }; - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, inheritableMetadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: 1 - }; - const runManagers = await callbackManager_?.handleChatModelStart(this.toJSON(), baseMessages.map(_formatForTracing), handledOptions.runId, void 0, extra, void 0, void 0, handledOptions.runName); - const missingPromptIndices = []; - const results = await Promise.allSettled(baseMessages.map(async (baseMessage, index) => { - const prompt = BaseChatModel._convertInputToPromptValue(baseMessage).toString(); - const result = await cache.lookup(prompt, llmStringKey); - if (result == null) missingPromptIndices.push(index); - return result; - })); - const cachedResults = results.map((result, index) => ({ - result, - runManager: runManagers?.[index] - })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); - const outputVersion = parsedOptions.outputVersion ?? this.outputVersion; - const generations = []; - await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { - if (promiseResult.status === "fulfilled") { - const result = promiseResult.value; - generations[i] = result.map((result$1) => { - if ("message" in result$1 && isBaseMessage(result$1.message) && isAIMessage(result$1.message)) { - result$1.message.usage_metadata = { - input_tokens: 0, - output_tokens: 0, - total_tokens: 0 - }; - if (outputVersion === "v1") result$1.message = castStandardMessageContent(result$1.message); - } - result$1.generationInfo = { - ...result$1.generationInfo, - tokenUsage: {} - }; - return result$1; - }); - if (result.length) await runManager?.handleLLMNewToken(result[0].text); - return runManager?.handleLLMEnd({ generations: [result] }, void 0, void 0, void 0, { cached: true }); - } else { - await runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { cached: true }); - return Promise.reject(promiseResult.reason); - } - })); - const output = { - generations, - missingPromptIndices, - startedRunManagers: runManagers - }; - Object.defineProperty(output, RUN_KEY, { - value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, - configurable: true - }); - return output; - } - /** - * Generates chat based on the input messages. - * @param messages An array of arrays of BaseMessage instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to an LLMResult. - */ - async generate(messages, options, callbacks) { - let parsedOptions; - if (Array.isArray(options)) parsedOptions = { stop: options }; - else parsedOptions = options; - const baseMessages = messages.map((messageList) => messageList.map(utils_coerceMessageLikeToMessage)); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); - runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; - if (!this.cache) return this._generateUncached(baseMessages, callOptions, runnableConfig); - const { cache } = this; - const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); - const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ - messages: baseMessages, - cache, - llmStringKey, - parsedOptions: callOptions, - handledOptions: runnableConfig - }); - let llmOutput = {}; - if (missingPromptIndices.length > 0) { - const results = await this._generateUncached(missingPromptIndices.map((i) => baseMessages[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0); - await Promise.all(results.generations.map(async (generation, index) => { - const promptIndex = missingPromptIndices[index]; - generations[promptIndex] = generation; - const prompt = BaseChatModel._convertInputToPromptValue(baseMessages[promptIndex]).toString(); - return cache.update(prompt, llmStringKey, generation); - })); - llmOutput = results.llmOutput ?? {}; - } - return { - generations, - llmOutput - }; - } - /** - * Get the parameters used to invoke the model - */ - invocationParams(_options) { - return {}; - } - _modelType() { - return "base_chat_model"; - } - /** - * Generates a prompt based on the input prompt values. - * @param promptValues An array of BasePromptValue instances. - * @param options The call options or an array of stop sequences. - * @param callbacks The callbacks for the language model. - * @returns A Promise that resolves to an LLMResult. - */ - async generatePrompt(promptValues, options, callbacks) { - const promptMessages = promptValues.map((promptValue) => promptValue.toChatMessages()); - return this.generate(promptMessages, options, callbacks); - } - withStructuredOutput(outputSchema, config) { - if (typeof this.bindTools !== "function") throw new Error(`Chat model must implement ".bindTools()" to use withStructuredOutput.`); - if (config?.strict) throw new Error(`"strict" mode is not supported for this model by default.`); - const schema = outputSchema; - const name = config?.name; - const description = getSchemaDescription(schema) ?? "A function available to call."; - const method = config?.method; - const includeRaw = config?.includeRaw; - if (method === "jsonMode") throw new Error(`Base withStructuredOutput implementation only supports "functionCalling" as a method.`); - let functionName = name ?? "extract"; - let tools; - if (isInteropZodSchema(schema)) tools = [{ - type: "function", - function: { - name: functionName, - description, - parameters: toJsonSchema(schema) - } - }]; - else { - if ("name" in schema) functionName = schema.name; - tools = [{ - type: "function", - function: { - name: functionName, - description, - parameters: schema - } - }]; - } - const llm = this.bindTools(tools); - const outputParser = RunnableLambda.from((input) => { - if (!AIMessageChunk.isInstance(input)) throw new Error("Input is not an AIMessageChunk."); - if (!input.tool_calls || input.tool_calls.length === 0) throw new Error("No tool calls found in the response."); - const toolCall = input.tool_calls.find((tc) => tc.name === functionName); - if (!toolCall) throw new Error(`No tool call found with name ${functionName}.`); - return toolCall.args; - }); - if (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: "StructuredOutput" }); - const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); - const parserNone = RunnablePassthrough.assign({ parsed: () => null }); - const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); - return RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" }); - } -}; -/** -* An abstract class that extends BaseChatModel and provides a simple -* implementation of _generate. -*/ -var SimpleChatModel = class extends BaseChatModel { - async _generate(messages, options, runManager) { - const text = await this._call(messages, options, runManager); - const message = new AIMessage(text); - if (typeof message.content !== "string") throw new Error("Cannot generate with a simple chat model when output is not a string."); - return { generations: [{ - text: message.content, - message - }] }; - } -}; - -//#endregion - -//# sourceMappingURL=chat_models.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/llms.js - - - - - - - -//#region src/language_models/llms.ts -var llms_exports = {}; -__export(llms_exports, { - BaseLLM: () => BaseLLM, - LLM: () => LLM -}); -/** -* LLM Wrapper. Takes in a prompt (or prompts) and returns a string. -*/ -var BaseLLM = class BaseLLM extends BaseLanguageModel { - lc_namespace = [ - "langchain", - "llms", - this._llmType() - ]; - /** - * This method takes an input and options, and returns a string. It - * converts the input to a prompt value and generates a result based on - * the prompt. - * @param input Input for the LLM. - * @param options Options for the LLM call. - * @returns A string result based on the prompt. - */ - async invoke(input, options) { - const promptValue = BaseLLM._convertInputToPromptValue(input); - const result = await this.generatePrompt([promptValue], options, options?.callbacks); - return result.generations[0][0].text; - } - async *_streamResponseChunks(_input, _options, _runManager) { - throw new Error("Not implemented."); - } - _separateRunnableConfigFromCallOptionsCompat(options) { - const [runnableConfig, callOptions] = super._separateRunnableConfigFromCallOptions(options); - callOptions.signal = runnableConfig.signal; - return [runnableConfig, callOptions]; - } - async *_streamIterator(input, options) { - if (this._streamResponseChunks === BaseLLM.prototype._streamResponseChunks) yield this.invoke(input, options); - else { - const prompt = BaseLLM._convertInputToPromptValue(input); - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(options); - const callbackManager_ = await CallbackManager.configure(runnableConfig.callbacks, this.callbacks, runnableConfig.tags, this.tags, runnableConfig.metadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: callOptions, - invocation_params: this?.invocationParams(callOptions), - batch_size: 1 - }; - const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), [prompt.toString()], runnableConfig.runId, void 0, extra, void 0, void 0, runnableConfig.runName); - let generation = new GenerationChunk({ text: "" }); - try { - for await (const chunk of this._streamResponseChunks(prompt.toString(), callOptions, runManagers?.[0])) { - if (!generation) generation = chunk; - else generation = generation.concat(chunk); - if (typeof chunk.text === "string") yield chunk.text; - } - } catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMEnd({ generations: [[generation]] }))); - } - } - /** - * This method takes prompt values, options, and callbacks, and generates - * a result based on the prompts. - * @param promptValues Prompt values for the LLM. - * @param options Options for the LLM call. - * @param callbacks Callbacks for the LLM call. - * @returns An LLMResult based on the prompts. - */ - async generatePrompt(promptValues, options, callbacks) { - const prompts = promptValues.map((promptValue) => promptValue.toString()); - return this.generate(prompts, options, callbacks); - } - /** - * Get the parameters used to invoke the model - */ - invocationParams(_options) { - return {}; - } - _flattenLLMResult(llmResult) { - const llmResults = []; - for (let i = 0; i < llmResult.generations.length; i += 1) { - const genList = llmResult.generations[i]; - if (i === 0) llmResults.push({ - generations: [genList], - llmOutput: llmResult.llmOutput - }); - else { - const llmOutput = llmResult.llmOutput ? { - ...llmResult.llmOutput, - tokenUsage: {} - } : void 0; - llmResults.push({ - generations: [genList], - llmOutput - }); - } - } - return llmResults; - } - /** @ignore */ - async _generateUncached(prompts, parsedOptions, handledOptions, startedRunManagers) { - let runManagers; - if (startedRunManagers !== void 0 && startedRunManagers.length === prompts.length) runManagers = startedRunManagers; - else { - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: prompts.length - }; - runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, handledOptions.runId, void 0, extra, void 0, void 0, handledOptions?.runName); - } - const hasStreamingHandler = !!runManagers?.[0].handlers.find(callbackHandlerPrefersStreaming); - let output; - if (hasStreamingHandler && prompts.length === 1 && this._streamResponseChunks !== BaseLLM.prototype._streamResponseChunks) try { - const stream = await this._streamResponseChunks(prompts[0], parsedOptions, runManagers?.[0]); - let aggregated; - for await (const chunk of stream) if (aggregated === void 0) aggregated = chunk; - else aggregated = concat(aggregated, chunk); - if (aggregated === void 0) throw new Error("Received empty response from chat model call."); - output = { - generations: [[aggregated]], - llmOutput: {} - }; - await runManagers?.[0].handleLLMEnd(output); - } catch (e) { - await runManagers?.[0].handleLLMError(e); - throw e; - } - else { - try { - output = await this._generate(prompts, parsedOptions, runManagers?.[0]); - } catch (err) { - await Promise.all((runManagers ?? []).map((runManager) => runManager?.handleLLMError(err))); - throw err; - } - const flattenedOutputs = this._flattenLLMResult(output); - await Promise.all((runManagers ?? []).map((runManager, i) => runManager?.handleLLMEnd(flattenedOutputs[i]))); - } - const runIds = runManagers?.map((manager) => manager.runId) || void 0; - Object.defineProperty(output, RUN_KEY, { - value: runIds ? { runIds } : void 0, - configurable: true - }); - return output; - } - async _generateCached({ prompts, cache, llmStringKey, parsedOptions, handledOptions, runId }) { - const callbackManager_ = await CallbackManager.configure(handledOptions.callbacks, this.callbacks, handledOptions.tags, this.tags, handledOptions.metadata, this.metadata, { verbose: this.verbose }); - const extra = { - options: parsedOptions, - invocation_params: this?.invocationParams(parsedOptions), - batch_size: prompts.length - }; - const runManagers = await callbackManager_?.handleLLMStart(this.toJSON(), prompts, runId, void 0, extra, void 0, void 0, handledOptions?.runName); - const missingPromptIndices = []; - const results = await Promise.allSettled(prompts.map(async (prompt, index) => { - const result = await cache.lookup(prompt, llmStringKey); - if (result == null) missingPromptIndices.push(index); - return result; - })); - const cachedResults = results.map((result, index) => ({ - result, - runManager: runManagers?.[index] - })).filter(({ result }) => result.status === "fulfilled" && result.value != null || result.status === "rejected"); - const generations = []; - await Promise.all(cachedResults.map(async ({ result: promiseResult, runManager }, i) => { - if (promiseResult.status === "fulfilled") { - const result = promiseResult.value; - generations[i] = result.map((result$1) => { - result$1.generationInfo = { - ...result$1.generationInfo, - tokenUsage: {} - }; - return result$1; - }); - if (result.length) await runManager?.handleLLMNewToken(result[0].text); - return runManager?.handleLLMEnd({ generations: [result] }, void 0, void 0, void 0, { cached: true }); - } else { - await runManager?.handleLLMError(promiseResult.reason, void 0, void 0, void 0, { cached: true }); - return Promise.reject(promiseResult.reason); - } - })); - const output = { - generations, - missingPromptIndices, - startedRunManagers: runManagers - }; - Object.defineProperty(output, RUN_KEY, { - value: runManagers ? { runIds: runManagers?.map((manager) => manager.runId) } : void 0, - configurable: true - }); - return output; - } - /** - * Run the LLM on the given prompts and input, handling caching. - */ - async generate(prompts, options, callbacks) { - if (!Array.isArray(prompts)) throw new Error("Argument 'prompts' is expected to be a string[]"); - let parsedOptions; - if (Array.isArray(options)) parsedOptions = { stop: options }; - else parsedOptions = options; - const [runnableConfig, callOptions] = this._separateRunnableConfigFromCallOptionsCompat(parsedOptions); - runnableConfig.callbacks = runnableConfig.callbacks ?? callbacks; - if (!this.cache) return this._generateUncached(prompts, callOptions, runnableConfig); - const { cache } = this; - const llmStringKey = this._getSerializedCacheKeyParametersForCall(callOptions); - const { generations, missingPromptIndices, startedRunManagers } = await this._generateCached({ - prompts, - cache, - llmStringKey, - parsedOptions: callOptions, - handledOptions: runnableConfig, - runId: runnableConfig.runId - }); - let llmOutput = {}; - if (missingPromptIndices.length > 0) { - const results = await this._generateUncached(missingPromptIndices.map((i) => prompts[i]), callOptions, runnableConfig, startedRunManagers !== void 0 ? missingPromptIndices.map((i) => startedRunManagers?.[i]) : void 0); - await Promise.all(results.generations.map(async (generation, index) => { - const promptIndex = missingPromptIndices[index]; - generations[promptIndex] = generation; - return cache.update(prompts[promptIndex], llmStringKey, generation); - })); - llmOutput = results.llmOutput ?? {}; - } - return { - generations, - llmOutput - }; - } - /** - * Get the identifying parameters of the LLM. - */ - _identifyingParams() { - return {}; - } - _modelType() { - return "base_llm"; - } -}; -/** -* LLM class that provides a simpler interface to subclass than {@link BaseLLM}. -* -* Requires only implementing a simpler {@link _call} method instead of {@link _generate}. -* -* @augments BaseLLM -*/ -var LLM = class extends BaseLLM { - async _generate(prompts, options, runManager) { - const generations = await Promise.all(prompts.map((prompt, promptIndex) => this._call(prompt, { - ...options, - promptIndex - }, runManager).then((text) => [{ text }]))); - return { generations }; - } -}; - -//#endregion - -//# sourceMappingURL=llms.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/language_models/profile.js -//#region src/language_models/profile.ts -var profile_exports = {}; - -//#endregion - -//# sourceMappingURL=profile.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/retrievers/document_compressors/index.js - - -//#region src/retrievers/document_compressors/index.ts -var document_compressors_exports = {}; -__export(document_compressors_exports, { BaseDocumentCompressor: () => BaseDocumentCompressor }); -/** -* Base Document Compression class. All compressors should extend this class. -*/ -var BaseDocumentCompressor = class { - static isBaseDocumentCompressor(x) { - return x?.compressDocuments !== void 0; - } -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/base.js - - -//#region src/prompts/base.ts -/** -* Base class for prompt templates. Exposes a format method that returns a -* string prompt given a set of input values. -*/ -var BasePromptTemplate = class extends Runnable { - lc_serializable = true; - lc_namespace = [ - "langchain_core", - "prompts", - this._getPromptType() - ]; - get lc_attributes() { - return { partialVariables: void 0 }; - } - inputVariables; - outputParser; - partialVariables; - /** - * Metadata to be used for tracing. - */ - metadata; - /** Tags to be used for tracing. */ - tags; - constructor(input) { - super(input); - const { inputVariables } = input; - if (inputVariables.includes("stop")) throw new Error("Cannot have an input variable named 'stop', as it is used internally, please rename."); - Object.assign(this, input); - } - /** - * Merges partial variables and user variables. - * @param userVariables The user variables to merge with the partial variables. - * @returns A Promise that resolves to an object containing the merged variables. - */ - async mergePartialAndUserVariables(userVariables) { - const partialVariables = this.partialVariables ?? {}; - const partialValues = {}; - for (const [key, value] of Object.entries(partialVariables)) if (typeof value === "string") partialValues[key] = value; - else partialValues[key] = await value(); - const allKwargs = { - ...partialValues, - ...userVariables - }; - return allKwargs; - } - /** - * Invokes the prompt template with the given input and options. - * @param input The input to invoke the prompt template with. - * @param options Optional configuration for the callback. - * @returns A Promise that resolves to the output of the prompt template. - */ - async invoke(input, options) { - const metadata = { - ...this.metadata, - ...options?.metadata - }; - const tags = [...this.tags ?? [], ...options?.tags ?? []]; - return this._callWithConfig((input$1) => this.formatPromptValue(input$1), input, { - ...options, - tags, - metadata, - runType: "prompt" - }); - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/string.js - - - -//#region src/prompts/string.ts -/** -* Base class for string prompt templates. It extends the -* BasePromptTemplate class and overrides the formatPromptValue method to -* return a StringPromptValue. -*/ -var BaseStringPromptTemplate = class extends BasePromptTemplate { - /** - * Formats the prompt given the input values and returns a formatted - * prompt value. - * @param values The input values to format the prompt. - * @returns A Promise that resolves to a formatted prompt value. - */ - async formatPromptValue(values) { - const formattedPrompt = await this.format(values); - return new StringPromptValue(formattedPrompt); - } -}; - -//#endregion - -//# sourceMappingURL=string.js.map -;// CONCATENATED MODULE: ./node_modules/mustache/mustache.mjs -/*! - * mustache.js - Logic-less {{mustache}} templates with JavaScript - * http://github.com/janl/mustache.js - */ - -var mustache_objectToString = Object.prototype.toString; -var mustache_isArray = Array.isArray || function isArrayPolyfill (object) { - return mustache_objectToString.call(object) === '[object Array]'; -}; - -function isFunction (object) { - return typeof object === 'function'; -} - -/** - * More correct typeof string handling array - * which normally returns typeof 'object' - */ -function typeStr (obj) { - return mustache_isArray(obj) ? 'array' : typeof obj; -} - -function escapeRegExp (string) { - return string.replace(/[\-\[\]{}()*+?.,\\\^$|#\s]/g, '\\$&'); -} - -/** - * Null safe way of checking whether or not an object, - * including its prototype, has a given property - */ -function hasProperty (obj, propName) { - return obj != null && typeof obj === 'object' && (propName in obj); -} - -/** - * Safe way of detecting whether or not the given thing is a primitive and - * whether it has the given property - */ -function primitiveHasOwnProperty (primitive, propName) { - return ( - primitive != null - && typeof primitive !== 'object' - && primitive.hasOwnProperty - && primitive.hasOwnProperty(propName) - ); -} - -// Workaround for https://issues.apache.org/jira/browse/COUCHDB-577 -// See https://github.com/janl/mustache.js/issues/189 -var regExpTest = RegExp.prototype.test; -function testRegExp (re, string) { - return regExpTest.call(re, string); -} - -var nonSpaceRe = /\S/; -function isWhitespace (string) { - return !testRegExp(nonSpaceRe, string); -} - -var entityMap = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''', - '/': '/', - '`': '`', - '=': '=' -}; - -function escapeHtml (string) { - return String(string).replace(/[&<>"'`=\/]/g, function fromEntityMap (s) { - return entityMap[s]; - }); -} - -var whiteRe = /\s*/; -var spaceRe = /\s+/; -var equalsRe = /\s*=/; -var curlyRe = /\s*\}/; -var tagRe = /#|\^|\/|>|\{|&|=|!/; - -/** - * Breaks up the given `template` string into a tree of tokens. If the `tags` - * argument is given here it must be an array with two string values: the - * opening and closing tags used in the template (e.g. [ "<%", "%>" ]). Of - * course, the default is to use mustaches (i.e. mustache.tags). - * - * A token is an array with at least 4 elements. The first element is the - * mustache symbol that was used inside the tag, e.g. "#" or "&". If the tag - * did not contain a symbol (i.e. {{myValue}}) this element is "name". For - * all text that appears outside a symbol this element is "text". - * - * The second element of a token is its "value". For mustache tags this is - * whatever else was inside the tag besides the opening symbol. For text tokens - * this is the text itself. - * - * The third and fourth elements of the token are the start and end indices, - * respectively, of the token in the original template. - * - * Tokens that are the root node of a subtree contain two more elements: 1) an - * array of tokens in the subtree and 2) the index in the original template at - * which the closing tag for that section begins. - * - * Tokens for partials also contain two more elements: 1) a string value of - * indendation prior to that tag and 2) the index of that tag on that line - - * eg a value of 2 indicates the partial is the third tag on this line. - */ -function parseTemplate (template, tags) { - if (!template) - return []; - var lineHasNonSpace = false; - var sections = []; // Stack to hold section tokens - var tokens = []; // Buffer to hold the tokens - var spaces = []; // Indices of whitespace tokens on the current line - var hasTag = false; // Is there a {{tag}} on the current line? - var nonSpace = false; // Is there a non-space char on the current line? - var indentation = ''; // Tracks indentation for tags that use it - var tagIndex = 0; // Stores a count of number of tags encountered on a line - - // Strips all whitespace tokens array for the current line - // if there was a {{#tag}} on it and otherwise only space. - function stripSpace () { - if (hasTag && !nonSpace) { - while (spaces.length) - delete tokens[spaces.pop()]; - } else { - spaces = []; - } - - hasTag = false; - nonSpace = false; - } - - var openingTagRe, closingTagRe, closingCurlyRe; - function compileTags (tagsToCompile) { - if (typeof tagsToCompile === 'string') - tagsToCompile = tagsToCompile.split(spaceRe, 2); - - if (!mustache_isArray(tagsToCompile) || tagsToCompile.length !== 2) - throw new Error('Invalid tags: ' + tagsToCompile); - - openingTagRe = new RegExp(escapeRegExp(tagsToCompile[0]) + '\\s*'); - closingTagRe = new RegExp('\\s*' + escapeRegExp(tagsToCompile[1])); - closingCurlyRe = new RegExp('\\s*' + escapeRegExp('}' + tagsToCompile[1])); - } - - compileTags(tags || mustache.tags); - - var scanner = new Scanner(template); - - var start, type, value, chr, token, openSection; - while (!scanner.eos()) { - start = scanner.pos; - - // Match any text between tags. - value = scanner.scanUntil(openingTagRe); - - if (value) { - for (var i = 0, valueLength = value.length; i < valueLength; ++i) { - chr = value.charAt(i); - - if (isWhitespace(chr)) { - spaces.push(tokens.length); - indentation += chr; - } else { - nonSpace = true; - lineHasNonSpace = true; - indentation += ' '; - } - - tokens.push([ 'text', chr, start, start + 1 ]); - start += 1; - - // Check for whitespace on the current line. - if (chr === '\n') { - stripSpace(); - indentation = ''; - tagIndex = 0; - lineHasNonSpace = false; - } - } - } - - // Match the opening tag. - if (!scanner.scan(openingTagRe)) - break; - - hasTag = true; - - // Get the tag type. - type = scanner.scan(tagRe) || 'name'; - scanner.scan(whiteRe); - - // Get the tag value. - if (type === '=') { - value = scanner.scanUntil(equalsRe); - scanner.scan(equalsRe); - scanner.scanUntil(closingTagRe); - } else if (type === '{') { - value = scanner.scanUntil(closingCurlyRe); - scanner.scan(curlyRe); - scanner.scanUntil(closingTagRe); - type = '&'; - } else { - value = scanner.scanUntil(closingTagRe); - } - - // Match the closing tag. - if (!scanner.scan(closingTagRe)) - throw new Error('Unclosed tag at ' + scanner.pos); - - if (type == '>') { - token = [ type, value, start, scanner.pos, indentation, tagIndex, lineHasNonSpace ]; - } else { - token = [ type, value, start, scanner.pos ]; - } - tagIndex++; - tokens.push(token); - - if (type === '#' || type === '^') { - sections.push(token); - } else if (type === '/') { - // Check section nesting. - openSection = sections.pop(); - - if (!openSection) - throw new Error('Unopened section "' + value + '" at ' + start); - - if (openSection[1] !== value) - throw new Error('Unclosed section "' + openSection[1] + '" at ' + start); - } else if (type === 'name' || type === '{' || type === '&') { - nonSpace = true; - } else if (type === '=') { - // Set the tags for the next time around. - compileTags(value); - } - } - - stripSpace(); - - // Make sure there are no open sections when we're done. - openSection = sections.pop(); - - if (openSection) - throw new Error('Unclosed section "' + openSection[1] + '" at ' + scanner.pos); - - return nestTokens(squashTokens(tokens)); -} - -/** - * Combines the values of consecutive text tokens in the given `tokens` array - * to a single token. - */ -function squashTokens (tokens) { - var squashedTokens = []; - - var token, lastToken; - for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { - token = tokens[i]; - - if (token) { - if (token[0] === 'text' && lastToken && lastToken[0] === 'text') { - lastToken[1] += token[1]; - lastToken[3] = token[3]; - } else { - squashedTokens.push(token); - lastToken = token; - } - } - } - - return squashedTokens; -} - -/** - * Forms the given array of `tokens` into a nested tree structure where - * tokens that represent a section have two additional items: 1) an array of - * all tokens that appear in that section and 2) the index in the original - * template that represents the end of that section. - */ -function nestTokens (tokens) { - var nestedTokens = []; - var collector = nestedTokens; - var sections = []; - - var token, section; - for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { - token = tokens[i]; - - switch (token[0]) { - case '#': - case '^': - collector.push(token); - sections.push(token); - collector = token[4] = []; - break; - case '/': - section = sections.pop(); - section[5] = token[2]; - collector = sections.length > 0 ? sections[sections.length - 1][4] : nestedTokens; - break; - default: - collector.push(token); - } - } - - return nestedTokens; -} - -/** - * A simple string scanner that is used by the template parser to find - * tokens in template strings. - */ -function Scanner (string) { - this.string = string; - this.tail = string; - this.pos = 0; -} - -/** - * Returns `true` if the tail is empty (end of string). - */ -Scanner.prototype.eos = function eos () { - return this.tail === ''; -}; - -/** - * Tries to match the given regular expression at the current position. - * Returns the matched text if it can match, the empty string otherwise. - */ -Scanner.prototype.scan = function scan (re) { - var match = this.tail.match(re); - - if (!match || match.index !== 0) - return ''; - - var string = match[0]; - - this.tail = this.tail.substring(string.length); - this.pos += string.length; - - return string; -}; - -/** - * Skips all text until the given regular expression can be matched. Returns - * the skipped string, which is the entire tail if no match can be made. - */ -Scanner.prototype.scanUntil = function scanUntil (re) { - var index = this.tail.search(re), match; - - switch (index) { - case -1: - match = this.tail; - this.tail = ''; - break; - case 0: - match = ''; - break; - default: - match = this.tail.substring(0, index); - this.tail = this.tail.substring(index); - } - - this.pos += match.length; - - return match; -}; - -/** - * Represents a rendering context by wrapping a view object and - * maintaining a reference to the parent context. - */ -function Context (view, parentContext) { - this.view = view; - this.cache = { '.': this.view }; - this.parent = parentContext; -} - -/** - * Creates a new context using the given view with this context - * as the parent. - */ -Context.prototype.push = function push (view) { - return new Context(view, this); -}; - -/** - * Returns the value of the given name in this context, traversing - * up the context hierarchy if the value is absent in this context's view. - */ -Context.prototype.lookup = function lookup (name) { - var cache = this.cache; - - var value; - if (cache.hasOwnProperty(name)) { - value = cache[name]; - } else { - var context = this, intermediateValue, names, index, lookupHit = false; - - while (context) { - if (name.indexOf('.') > 0) { - intermediateValue = context.view; - names = name.split('.'); - index = 0; - - /** - * Using the dot notion path in `name`, we descend through the - * nested objects. - * - * To be certain that the lookup has been successful, we have to - * check if the last object in the path actually has the property - * we are looking for. We store the result in `lookupHit`. - * - * This is specially necessary for when the value has been set to - * `undefined` and we want to avoid looking up parent contexts. - * - * In the case where dot notation is used, we consider the lookup - * to be successful even if the last "object" in the path is - * not actually an object but a primitive (e.g., a string, or an - * integer), because it is sometimes useful to access a property - * of an autoboxed primitive, such as the length of a string. - **/ - while (intermediateValue != null && index < names.length) { - if (index === names.length - 1) - lookupHit = ( - hasProperty(intermediateValue, names[index]) - || primitiveHasOwnProperty(intermediateValue, names[index]) - ); - - intermediateValue = intermediateValue[names[index++]]; - } - } else { - intermediateValue = context.view[name]; - - /** - * Only checking against `hasProperty`, which always returns `false` if - * `context.view` is not an object. Deliberately omitting the check - * against `primitiveHasOwnProperty` if dot notation is not used. - * - * Consider this example: - * ``` - * Mustache.render("The length of a football field is {{#length}}{{length}}{{/length}}.", {length: "100 yards"}) - * ``` - * - * If we were to check also against `primitiveHasOwnProperty`, as we do - * in the dot notation case, then render call would return: - * - * "The length of a football field is 9." - * - * rather than the expected: - * - * "The length of a football field is 100 yards." - **/ - lookupHit = hasProperty(context.view, name); - } - - if (lookupHit) { - value = intermediateValue; - break; - } - - context = context.parent; - } - - cache[name] = value; - } - - if (isFunction(value)) - value = value.call(this.view); - - return value; -}; - -/** - * A Writer knows how to take a stream of tokens and render them to a - * string, given a context. It also maintains a cache of templates to - * avoid the need to parse the same template twice. - */ -function Writer () { - this.templateCache = { - _cache: {}, - set: function set (key, value) { - this._cache[key] = value; - }, - get: function get (key) { - return this._cache[key]; - }, - clear: function clear () { - this._cache = {}; - } - }; -} - -/** - * Clears all cached templates in this writer. - */ -Writer.prototype.clearCache = function clearCache () { - if (typeof this.templateCache !== 'undefined') { - this.templateCache.clear(); - } -}; - -/** - * Parses and caches the given `template` according to the given `tags` or - * `mustache.tags` if `tags` is omitted, and returns the array of tokens - * that is generated from the parse. - */ -Writer.prototype.parse = function parse (template, tags) { - var cache = this.templateCache; - var cacheKey = template + ':' + (tags || mustache.tags).join(':'); - var isCacheEnabled = typeof cache !== 'undefined'; - var tokens = isCacheEnabled ? cache.get(cacheKey) : undefined; - - if (tokens == undefined) { - tokens = parseTemplate(template, tags); - isCacheEnabled && cache.set(cacheKey, tokens); - } - return tokens; -}; - -/** - * High-level method that is used to render the given `template` with - * the given `view`. - * - * The optional `partials` argument may be an object that contains the - * names and templates of partials that are used in the template. It may - * also be a function that is used to load partial templates on the fly - * that takes a single argument: the name of the partial. - * - * If the optional `config` argument is given here, then it should be an - * object with a `tags` attribute or an `escape` attribute or both. - * If an array is passed, then it will be interpreted the same way as - * a `tags` attribute on a `config` object. - * - * The `tags` attribute of a `config` object must be an array with two - * string values: the opening and closing tags used in the template (e.g. - * [ "<%", "%>" ]). The default is to mustache.tags. - * - * The `escape` attribute of a `config` object must be a function which - * accepts a string as input and outputs a safely escaped string. - * If an `escape` function is not provided, then an HTML-safe string - * escaping function is used as the default. - */ -Writer.prototype.render = function render (template, view, partials, config) { - var tags = this.getConfigTags(config); - var tokens = this.parse(template, tags); - var context = (view instanceof Context) ? view : new Context(view, undefined); - return this.renderTokens(tokens, context, partials, template, config); -}; - -/** - * Low-level method that renders the given array of `tokens` using - * the given `context` and `partials`. - * - * Note: The `originalTemplate` is only ever used to extract the portion - * of the original template that was contained in a higher-order section. - * If the template doesn't use higher-order sections, this argument may - * be omitted. - */ -Writer.prototype.renderTokens = function renderTokens (tokens, context, partials, originalTemplate, config) { - var buffer = ''; - - var token, symbol, value; - for (var i = 0, numTokens = tokens.length; i < numTokens; ++i) { - value = undefined; - token = tokens[i]; - symbol = token[0]; - - if (symbol === '#') value = this.renderSection(token, context, partials, originalTemplate, config); - else if (symbol === '^') value = this.renderInverted(token, context, partials, originalTemplate, config); - else if (symbol === '>') value = this.renderPartial(token, context, partials, config); - else if (symbol === '&') value = this.unescapedValue(token, context); - else if (symbol === 'name') value = this.escapedValue(token, context, config); - else if (symbol === 'text') value = this.rawValue(token); - - if (value !== undefined) - buffer += value; - } - - return buffer; -}; - -Writer.prototype.renderSection = function renderSection (token, context, partials, originalTemplate, config) { - var self = this; - var buffer = ''; - var value = context.lookup(token[1]); - - // This function is used to render an arbitrary template - // in the current context by higher-order sections. - function subRender (template) { - return self.render(template, context, partials, config); - } - - if (!value) return; - - if (mustache_isArray(value)) { - for (var j = 0, valueLength = value.length; j < valueLength; ++j) { - buffer += this.renderTokens(token[4], context.push(value[j]), partials, originalTemplate, config); - } - } else if (typeof value === 'object' || typeof value === 'string' || typeof value === 'number') { - buffer += this.renderTokens(token[4], context.push(value), partials, originalTemplate, config); - } else if (isFunction(value)) { - if (typeof originalTemplate !== 'string') - throw new Error('Cannot use higher-order sections without the original template'); - - // Extract the portion of the original template that the section contains. - value = value.call(context.view, originalTemplate.slice(token[3], token[5]), subRender); - - if (value != null) - buffer += value; - } else { - buffer += this.renderTokens(token[4], context, partials, originalTemplate, config); - } - return buffer; -}; - -Writer.prototype.renderInverted = function renderInverted (token, context, partials, originalTemplate, config) { - var value = context.lookup(token[1]); - - // Use JavaScript's definition of falsy. Include empty arrays. - // See https://github.com/janl/mustache.js/issues/186 - if (!value || (mustache_isArray(value) && value.length === 0)) - return this.renderTokens(token[4], context, partials, originalTemplate, config); -}; - -Writer.prototype.indentPartial = function indentPartial (partial, indentation, lineHasNonSpace) { - var filteredIndentation = indentation.replace(/[^ \t]/g, ''); - var partialByNl = partial.split('\n'); - for (var i = 0; i < partialByNl.length; i++) { - if (partialByNl[i].length && (i > 0 || !lineHasNonSpace)) { - partialByNl[i] = filteredIndentation + partialByNl[i]; - } - } - return partialByNl.join('\n'); -}; - -Writer.prototype.renderPartial = function renderPartial (token, context, partials, config) { - if (!partials) return; - var tags = this.getConfigTags(config); - - var value = isFunction(partials) ? partials(token[1]) : partials[token[1]]; - if (value != null) { - var lineHasNonSpace = token[6]; - var tagIndex = token[5]; - var indentation = token[4]; - var indentedValue = value; - if (tagIndex == 0 && indentation) { - indentedValue = this.indentPartial(value, indentation, lineHasNonSpace); - } - var tokens = this.parse(indentedValue, tags); - return this.renderTokens(tokens, context, partials, indentedValue, config); - } -}; - -Writer.prototype.unescapedValue = function unescapedValue (token, context) { - var value = context.lookup(token[1]); - if (value != null) - return value; -}; - -Writer.prototype.escapedValue = function escapedValue (token, context, config) { - var escape = this.getConfigEscape(config) || mustache.escape; - var value = context.lookup(token[1]); - if (value != null) - return (typeof value === 'number' && escape === mustache.escape) ? String(value) : escape(value); -}; - -Writer.prototype.rawValue = function rawValue (token) { - return token[1]; -}; - -Writer.prototype.getConfigTags = function getConfigTags (config) { - if (mustache_isArray(config)) { - return config; - } - else if (config && typeof config === 'object') { - return config.tags; - } - else { - return undefined; - } -}; - -Writer.prototype.getConfigEscape = function getConfigEscape (config) { - if (config && typeof config === 'object' && !mustache_isArray(config)) { - return config.escape; - } - else { - return undefined; - } -}; - -var mustache = { - name: 'mustache.js', - version: '4.2.0', - tags: [ '{{', '}}' ], - clearCache: undefined, - escape: undefined, - parse: undefined, - render: undefined, - Scanner: undefined, - Context: undefined, - Writer: undefined, - /** - * Allows a user to override the default caching strategy, by providing an - * object with set, get and clear methods. This can also be used to disable - * the cache by setting it to the literal `undefined`. - */ - set templateCache (cache) { - defaultWriter.templateCache = cache; - }, - /** - * Gets the default or overridden caching object from the default writer. - */ - get templateCache () { - return defaultWriter.templateCache; - } -}; - -// All high-level mustache.* functions use this writer. -var defaultWriter = new Writer(); - -/** - * Clears all cached templates in the default writer. - */ -mustache.clearCache = function clearCache () { - return defaultWriter.clearCache(); -}; - -/** - * Parses and caches the given template in the default writer and returns the - * array of tokens it contains. Doing this ahead of time avoids the need to - * parse templates on the fly as they are rendered. - */ -mustache.parse = function parse (template, tags) { - return defaultWriter.parse(template, tags); -}; - -/** - * Renders the `template` with the given `view`, `partials`, and `config` - * using the default writer. - */ -mustache.render = function render (template, view, partials, config) { - if (typeof template !== 'string') { - throw new TypeError('Invalid template! Template should be a "string" ' + - 'but "' + typeStr(template) + '" was given as the first ' + - 'argument for mustache#render(template, view, partials)'); - } - - return defaultWriter.render(template, view, partials, config); -}; - -// Export the escaping function so that the user may override it. -// See https://github.com/janl/mustache.js/issues/244 -mustache.escape = escapeHtml; - -// Export these mainly for testing, but also for advanced usage. -mustache.Scanner = Scanner; -mustache.Context = Context; -mustache.Writer = Writer; - -/* harmony default export */ const mustache_mustache = (mustache); - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/template.js - - - -//#region src/prompts/template.ts -function configureMustache() { - mustache_mustache.escape = (text) => text; -} -const parseFString = (template) => { - const chars = template.split(""); - const nodes = []; - const nextBracket = (bracket, start) => { - for (let i$1 = start; i$1 < chars.length; i$1 += 1) if (bracket.includes(chars[i$1])) return i$1; - return -1; - }; - let i = 0; - while (i < chars.length) if (chars[i] === "{" && i + 1 < chars.length && chars[i + 1] === "{") { - nodes.push({ - type: "literal", - text: "{" - }); - i += 2; - } else if (chars[i] === "}" && i + 1 < chars.length && chars[i + 1] === "}") { - nodes.push({ - type: "literal", - text: "}" - }); - i += 2; - } else if (chars[i] === "{") { - const j = nextBracket("}", i); - if (j < 0) throw new Error("Unclosed '{' in template."); - nodes.push({ - type: "variable", - name: chars.slice(i + 1, j).join("") - }); - i = j + 1; - } else if (chars[i] === "}") throw new Error("Single '}' in template."); - else { - const next = nextBracket("{}", i); - const text = (next < 0 ? chars.slice(i) : chars.slice(i, next)).join(""); - nodes.push({ - type: "literal", - text - }); - i = next < 0 ? chars.length : next; - } - return nodes; -}; -/** -* Convert the result of mustache.parse into an array of ParsedTemplateNode, -* to make it compatible with other LangChain string parsing template formats. -* -* @param {mustache.TemplateSpans} template The result of parsing a mustache template with the mustache.js library. -* @param {string[]} context Array of section variable names for nested context -* @returns {ParsedTemplateNode[]} -*/ -const mustacheTemplateToNodes = (template, context = []) => { - const nodes = []; - for (const temp of template) if (temp[0] === "name") { - const name = temp[1].includes(".") ? temp[1].split(".")[0] : temp[1]; - nodes.push({ - type: "variable", - name - }); - } else if ([ - "#", - "&", - "^", - ">" - ].includes(temp[0])) { - nodes.push({ - type: "variable", - name: temp[1] - }); - if (temp[0] === "#" && temp.length > 4 && Array.isArray(temp[4])) { - const newContext = [...context, temp[1]]; - const nestedNodes = mustacheTemplateToNodes(temp[4], newContext); - nodes.push(...nestedNodes); - } - } else nodes.push({ - type: "literal", - text: temp[1] - }); - return nodes; -}; -const parseMustache = (template) => { - configureMustache(); - const parsed = mustache_mustache.parse(template); - return mustacheTemplateToNodes(parsed); -}; -const interpolateFString = (template, values) => { - return parseFString(template).reduce((res, node) => { - if (node.type === "variable") { - if (node.name in values) { - const stringValue = typeof values[node.name] === "string" ? values[node.name] : JSON.stringify(values[node.name]); - return res + stringValue; - } - throw new Error(`(f-string) Missing value for input ${node.name}`); - } - return res + node.text; - }, ""); -}; -const interpolateMustache = (template, values) => { - configureMustache(); - return mustache_mustache.render(template, values); -}; -const DEFAULT_FORMATTER_MAPPING = { - "f-string": interpolateFString, - mustache: interpolateMustache -}; -const DEFAULT_PARSER_MAPPING = { - "f-string": parseFString, - mustache: parseMustache -}; -const renderTemplate = (template, templateFormat, inputValues) => { - try { - return DEFAULT_FORMATTER_MAPPING[templateFormat](template, inputValues); - } catch (e) { - const error = addLangChainErrorFields(e, "INVALID_PROMPT_INPUT"); - throw error; - } -}; -const template_parseTemplate = (template, templateFormat) => DEFAULT_PARSER_MAPPING[templateFormat](template); -const checkValidTemplate = (template, templateFormat, inputVariables) => { - if (!(templateFormat in DEFAULT_FORMATTER_MAPPING)) { - const validFormats = Object.keys(DEFAULT_FORMATTER_MAPPING); - throw new Error(`Invalid template format. Got \`${templateFormat}\`; - should be one of ${validFormats}`); - } - try { - const dummyInputs = inputVariables.reduce((acc, v) => { - acc[v] = "foo"; - return acc; - }, {}); - if (Array.isArray(template)) template.forEach((message) => { - if (message.type === "text" && "text" in message && typeof message.text === "string") renderTemplate(message.text, templateFormat, dummyInputs); - else if (message.type === "image_url") { - if (typeof message.image_url === "string") renderTemplate(message.image_url, templateFormat, dummyInputs); - else if (typeof message.image_url === "object" && message.image_url !== null && "url" in message.image_url && typeof message.image_url.url === "string") { - const imageUrl = message.image_url.url; - renderTemplate(imageUrl, templateFormat, dummyInputs); - } - } else throw new Error(`Invalid message template received. ${JSON.stringify(message, null, 2)}`); - }); - else renderTemplate(template, templateFormat, dummyInputs); - } catch (e) { - throw new Error(`Invalid prompt schema: ${e.message}`); - } -}; - -//#endregion - -//# sourceMappingURL=template.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/prompt.js - - - -//#region src/prompts/prompt.ts -/** -* Schema to represent a basic prompt for an LLM. -* @augments BasePromptTemplate -* @augments PromptTemplateInput -* -* @example -* ```ts -* import { PromptTemplate } from "langchain/prompts"; -* -* const prompt = new PromptTemplate({ -* inputVariables: ["foo"], -* template: "Say {foo}", -* }); -* ``` -*/ -var PromptTemplate = class PromptTemplate extends BaseStringPromptTemplate { - static lc_name() { - return "PromptTemplate"; - } - template; - templateFormat = "f-string"; - validateTemplate = true; - /** - * Additional fields which should be included inside - * the message content array if using a complex message - * content. - */ - additionalContentFields; - constructor(input) { - super(input); - if (input.templateFormat === "mustache" && input.validateTemplate === void 0) this.validateTemplate = false; - Object.assign(this, input); - if (this.validateTemplate) { - if (this.templateFormat === "mustache") throw new Error("Mustache templates cannot be validated."); - let totalInputVariables = this.inputVariables; - if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate(this.template, this.templateFormat, totalInputVariables); - } - } - _getPromptType() { - return "prompt"; - } - /** - * Formats the prompt template with the provided values. - * @param values The values to be used to format the prompt template. - * @returns A promise that resolves to a string which is the formatted prompt. - */ - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - return renderTemplate(this.template, this.templateFormat, allValues); - } - /** - * Take examples in list format with prefix and suffix to create a prompt. - * - * Intended to be used a a way to dynamically create a prompt from examples. - * - * @param examples - List of examples to use in the prompt. - * @param suffix - String to go after the list of examples. Should generally set up the user's input. - * @param inputVariables - A list of variable names the final prompt template will expect - * @param exampleSeparator - The separator to use in between examples - * @param prefix - String that should go before any examples. Generally includes examples. - * - * @returns The final prompt template generated. - */ - static fromExamples(examples, suffix, inputVariables, exampleSeparator = "\n\n", prefix = "") { - const template = [ - prefix, - ...examples, - suffix - ].join(exampleSeparator); - return new PromptTemplate({ - inputVariables, - template - }); - } - static fromTemplate(template, options) { - const { templateFormat = "f-string",...rest } = options ?? {}; - const names = /* @__PURE__ */ new Set(); - template_parseTemplate(template, templateFormat).forEach((node) => { - if (node.type === "variable") names.add(node.name); - }); - return new PromptTemplate({ - inputVariables: [...names], - templateFormat, - template, - ...rest - }); - } - /** - * Partially applies values to the prompt template. - * @param values The values to be partially applied to the prompt template. - * @returns A new instance of PromptTemplate with the partially applied values. - */ - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new PromptTemplate(promptDict); - } - serialize() { - if (this.outputParser !== void 0) throw new Error("Cannot serialize a prompt template with an output parser"); - return { - _type: this._getPromptType(), - input_variables: this.inputVariables, - template: this.template, - template_format: this.templateFormat - }; - } - static async deserialize(data) { - if (!data.template) throw new Error("Prompt template must have a template"); - const res = new PromptTemplate({ - inputVariables: data.input_variables, - template: data.template, - templateFormat: data.template_format - }); - return res; - } -}; - -//#endregion - -//# sourceMappingURL=prompt.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/image.js - - - - -//#region src/prompts/image.ts -/** -* An image prompt template for a multimodal model. -*/ -var ImagePromptTemplate = class ImagePromptTemplate extends BasePromptTemplate { - static lc_name() { - return "ImagePromptTemplate"; - } - lc_namespace = [ - "langchain_core", - "prompts", - "image" - ]; - template; - templateFormat = "f-string"; - validateTemplate = true; - /** - * Additional fields which should be included inside - * the message content array if using a complex message - * content. - */ - additionalContentFields; - constructor(input) { - super(input); - this.template = input.template; - this.templateFormat = input.templateFormat ?? this.templateFormat; - this.validateTemplate = input.validateTemplate ?? this.validateTemplate; - this.additionalContentFields = input.additionalContentFields; - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate([{ - type: "image_url", - image_url: this.template - }], this.templateFormat, totalInputVariables); - } - } - _getPromptType() { - return "prompt"; - } - /** - * Partially applies values to the prompt template. - * @param values The values to be partially applied to the prompt template. - * @returns A new instance of ImagePromptTemplate with the partially applied values. - */ - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new ImagePromptTemplate(promptDict); - } - /** - * Formats the prompt template with the provided values. - * @param values The values to be used to format the prompt template. - * @returns A promise that resolves to a string which is the formatted prompt. - */ - async format(values) { - const formatted = {}; - for (const [key, value] of Object.entries(this.template)) if (typeof value === "string") formatted[key] = renderTemplate(value, this.templateFormat, values); - else formatted[key] = value; - const url = values.url || formatted.url; - const detail = values.detail || formatted.detail; - if (!url) throw new Error("Must provide either an image URL."); - if (typeof url !== "string") throw new Error("url must be a string."); - const output = { url }; - if (detail) output.detail = detail; - return output; - } - /** - * Formats the prompt given the input values and returns a formatted - * prompt value. - * @param values The input values to format the prompt. - * @returns A Promise that resolves to a formatted prompt value. - */ - async formatPromptValue(values) { - const formattedPrompt = await this.format(values); - return new ImagePromptValue(formattedPrompt); - } -}; - -//#endregion - -//# sourceMappingURL=image.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/dict.js - - - -//#region src/prompts/dict.ts -var DictPromptTemplate = class extends Runnable { - lc_namespace = [ - "langchain_core", - "prompts", - "dict" - ]; - lc_serializable = true; - template; - templateFormat; - inputVariables; - static lc_name() { - return "DictPromptTemplate"; - } - constructor(fields) { - const templateFormat = fields.templateFormat ?? "f-string"; - const inputVariables = _getInputVariables(fields.template, templateFormat); - super({ - inputVariables, - ...fields - }); - this.template = fields.template; - this.templateFormat = templateFormat; - this.inputVariables = inputVariables; - } - async format(values) { - return _insertInputVariables(this.template, values, this.templateFormat); - } - async invoke(values) { - return await this._callWithConfig(this.format.bind(this), values, { runType: "prompt" }); - } -}; -function _getInputVariables(template, templateFormat) { - const inputVariables = []; - for (const v of Object.values(template)) if (typeof v === "string") template_parseTemplate(v, templateFormat).forEach((t) => { - if (t.type === "variable") inputVariables.push(t.name); - }); - else if (Array.isArray(v)) { - for (const x of v) if (typeof x === "string") template_parseTemplate(x, templateFormat).forEach((t) => { - if (t.type === "variable") inputVariables.push(t.name); - }); - else if (typeof x === "object") inputVariables.push(..._getInputVariables(x, templateFormat)); - } else if (typeof v === "object" && v !== null) inputVariables.push(..._getInputVariables(v, templateFormat)); - return Array.from(new Set(inputVariables)); -} -function _insertInputVariables(template, inputs, templateFormat) { - const formatted = {}; - for (const [k, v] of Object.entries(template)) if (typeof v === "string") formatted[k] = renderTemplate(v, templateFormat, inputs); - else if (Array.isArray(v)) { - const formattedV = []; - for (const x of v) if (typeof x === "string") formattedV.push(renderTemplate(x, templateFormat, inputs)); - else if (typeof x === "object") formattedV.push(_insertInputVariables(x, inputs, templateFormat)); - formatted[k] = formattedV; - } else if (typeof v === "object" && v !== null) formatted[k] = _insertInputVariables(v, inputs, templateFormat); - else formatted[k] = v; - return formatted; -} - -//#endregion - -//# sourceMappingURL=dict.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/chat.js - - - - - - - - - - - - - - - - - -//#region src/prompts/chat.ts -/** -* Abstract class that serves as a base for creating message prompt -* templates. It defines how to format messages for different roles in a -* conversation. -*/ -var BaseMessagePromptTemplate = class extends Runnable { - lc_namespace = [ - "langchain_core", - "prompts", - "chat" - ]; - lc_serializable = true; - /** - * Calls the formatMessages method with the provided input and options. - * @param input Input for the formatMessages method - * @param options Optional BaseCallbackConfig - * @returns Formatted output messages - */ - async invoke(input, options) { - return this._callWithConfig((input$1) => this.formatMessages(input$1), input, { - ...options, - runType: "prompt" - }); - } -}; -/** -* Class that represents a placeholder for messages in a chat prompt. It -* extends the BaseMessagePromptTemplate. -*/ -var MessagesPlaceholder = class extends BaseMessagePromptTemplate { - static lc_name() { - return "MessagesPlaceholder"; - } - variableName; - optional; - constructor(fields) { - if (typeof fields === "string") fields = { variableName: fields }; - super(fields); - this.variableName = fields.variableName; - this.optional = fields.optional ?? false; - } - get inputVariables() { - return [this.variableName]; - } - async formatMessages(values) { - const input = values[this.variableName]; - if (this.optional && !input) return []; - else if (!input) { - const error = /* @__PURE__ */ new Error(`Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages as an input value. Received: undefined`); - error.name = "InputFormatError"; - throw error; - } - let formattedMessages; - try { - if (Array.isArray(input)) formattedMessages = input.map(utils_coerceMessageLikeToMessage); - else formattedMessages = [utils_coerceMessageLikeToMessage(input)]; - } catch (e) { - const readableInput = typeof input === "string" ? input : JSON.stringify(input, null, 2); - const error = new Error([ - `Field "${this.variableName}" in prompt uses a MessagesPlaceholder, which expects an array of BaseMessages or coerceable values as input.`, - `Received value: ${readableInput}`, - `Additional message: ${e.message}` - ].join("\n\n")); - error.name = "InputFormatError"; - error.lc_error_code = e.lc_error_code; - throw error; - } - return formattedMessages; - } -}; -/** -* Abstract class that serves as a base for creating message string prompt -* templates. It extends the BaseMessagePromptTemplate. -*/ -var BaseMessageStringPromptTemplate = class extends BaseMessagePromptTemplate { - prompt; - constructor(fields) { - if (!("prompt" in fields)) fields = { prompt: fields }; - super(fields); - this.prompt = fields.prompt; - } - get inputVariables() { - return this.prompt.inputVariables; - } - async formatMessages(values) { - return [await this.format(values)]; - } -}; -/** -* Abstract class that serves as a base for creating chat prompt -* templates. It extends the BasePromptTemplate. -*/ -var BaseChatPromptTemplate = class extends BasePromptTemplate { - constructor(input) { - super(input); - } - async format(values) { - return (await this.formatPromptValue(values)).toString(); - } - async formatPromptValue(values) { - const resultMessages = await this.formatMessages(values); - return new ChatPromptValue(resultMessages); - } -}; -/** -* Class that represents a chat message prompt template. It extends the -* BaseMessageStringPromptTemplate. -*/ -var ChatMessagePromptTemplate = class extends BaseMessageStringPromptTemplate { - static lc_name() { - return "ChatMessagePromptTemplate"; - } - role; - constructor(fields, role) { - if (!("prompt" in fields)) fields = { - prompt: fields, - role - }; - super(fields); - this.role = fields.role; - } - async format(values) { - return new ChatMessage(await this.prompt.format(values), this.role); - } - static fromTemplate(template, role, options) { - return new this(PromptTemplate.fromTemplate(template, { templateFormat: options?.templateFormat }), role); - } -}; -function isTextTemplateParam(param) { - if (param === null || typeof param !== "object" || Array.isArray(param)) return false; - return Object.keys(param).length === 1 && "text" in param && typeof param.text === "string"; -} -function isImageTemplateParam(param) { - if (param === null || typeof param !== "object" || Array.isArray(param)) return false; - return "image_url" in param && (typeof param.image_url === "string" || typeof param.image_url === "object" && param.image_url !== null && "url" in param.image_url && typeof param.image_url.url === "string"); -} -var _StringImageMessagePromptTemplate = class extends BaseMessagePromptTemplate { - lc_namespace = [ - "langchain_core", - "prompts", - "chat" - ]; - lc_serializable = true; - inputVariables = []; - additionalOptions = {}; - prompt; - messageClass; - static _messageClass() { - throw new Error("Can not invoke _messageClass from inside _StringImageMessagePromptTemplate"); - } - chatMessageClass; - constructor(fields, additionalOptions) { - if (!("prompt" in fields)) fields = { prompt: fields }; - super(fields); - this.prompt = fields.prompt; - if (Array.isArray(this.prompt)) { - let inputVariables = []; - this.prompt.forEach((prompt) => { - if ("inputVariables" in prompt) inputVariables = inputVariables.concat(prompt.inputVariables); - }); - this.inputVariables = inputVariables; - } else this.inputVariables = this.prompt.inputVariables; - this.additionalOptions = additionalOptions ?? this.additionalOptions; - } - createMessage(content) { - const constructor = this.constructor; - if (constructor._messageClass()) { - const MsgClass = constructor._messageClass(); - return new MsgClass({ content }); - } else if (constructor.chatMessageClass) { - const MsgClass = constructor.chatMessageClass(); - return new MsgClass({ - content, - role: this.getRoleFromMessageClass(MsgClass.lc_name()) - }); - } else throw new Error("No message class defined"); - } - getRoleFromMessageClass(name) { - switch (name) { - case "HumanMessage": return "human"; - case "AIMessage": return "ai"; - case "SystemMessage": return "system"; - case "ChatMessage": return "chat"; - default: throw new Error("Invalid message class name"); - } - } - static fromTemplate(template, additionalOptions) { - if (typeof template === "string") return new this(PromptTemplate.fromTemplate(template, additionalOptions)); - const prompt = []; - for (const item of template) if (typeof item === "string") prompt.push(PromptTemplate.fromTemplate(item, additionalOptions)); - else if (item === null) {} else if (isTextTemplateParam(item)) { - let text = ""; - if (typeof item.text === "string") text = item.text ?? ""; - const options = { - ...additionalOptions, - additionalContentFields: item - }; - prompt.push(PromptTemplate.fromTemplate(text, options)); - } else if (isImageTemplateParam(item)) { - let imgTemplate = item.image_url ?? ""; - let imgTemplateObject; - let inputVariables = []; - if (typeof imgTemplate === "string") { - let parsedTemplate; - if (additionalOptions?.templateFormat === "mustache") parsedTemplate = parseMustache(imgTemplate); - else parsedTemplate = parseFString(imgTemplate); - const variables = parsedTemplate.flatMap((item$1) => item$1.type === "variable" ? [item$1.name] : []); - if ((variables?.length ?? 0) > 0) { - if (variables.length > 1) throw new Error(`Only one format variable allowed per image template.\nGot: ${variables}\nFrom: ${imgTemplate}`); - inputVariables = [variables[0]]; - } else inputVariables = []; - imgTemplate = { url: imgTemplate }; - imgTemplateObject = new ImagePromptTemplate({ - template: imgTemplate, - inputVariables, - templateFormat: additionalOptions?.templateFormat, - additionalContentFields: item - }); - } else if (typeof imgTemplate === "object") { - if ("url" in imgTemplate) { - let parsedTemplate; - if (additionalOptions?.templateFormat === "mustache") parsedTemplate = parseMustache(imgTemplate.url); - else parsedTemplate = parseFString(imgTemplate.url); - inputVariables = parsedTemplate.flatMap((item$1) => item$1.type === "variable" ? [item$1.name] : []); - } else inputVariables = []; - imgTemplateObject = new ImagePromptTemplate({ - template: imgTemplate, - inputVariables, - templateFormat: additionalOptions?.templateFormat, - additionalContentFields: item - }); - } else throw new Error("Invalid image template"); - prompt.push(imgTemplateObject); - } else if (typeof item === "object") prompt.push(new DictPromptTemplate({ - template: item, - templateFormat: additionalOptions?.templateFormat - })); - return new this({ - prompt, - additionalOptions - }); - } - async format(input) { - if (this.prompt instanceof BaseStringPromptTemplate) { - const text = await this.prompt.format(input); - return this.createMessage(text); - } else { - const content = []; - for (const prompt of this.prompt) { - let inputs = {}; - if (!("inputVariables" in prompt)) throw new Error(`Prompt ${prompt} does not have inputVariables defined.`); - for (const item of prompt.inputVariables) { - if (!inputs) inputs = { [item]: input[item] }; - inputs = { - ...inputs, - [item]: input[item] - }; - } - if (prompt instanceof BaseStringPromptTemplate) { - const formatted = await prompt.format(inputs); - let additionalContentFields; - if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; - if (formatted !== "") content.push({ - ...additionalContentFields, - type: "text", - text: formatted - }); - } else if (prompt instanceof ImagePromptTemplate) { - const formatted = await prompt.format(inputs); - let additionalContentFields; - if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; - content.push({ - ...additionalContentFields, - type: "image_url", - image_url: formatted - }); - } else if (prompt instanceof DictPromptTemplate) { - const formatted = await prompt.format(inputs); - let additionalContentFields; - if ("additionalContentFields" in prompt) additionalContentFields = prompt.additionalContentFields; - content.push({ - ...additionalContentFields, - ...formatted - }); - } - } - return this.createMessage(content); - } - } - async formatMessages(values) { - return [await this.format(values)]; - } -}; -/** -* Class that represents a human message prompt template. It extends the -* BaseMessageStringPromptTemplate. -* @example -* ```typescript -* const message = HumanMessagePromptTemplate.fromTemplate("{text}"); -* const formatted = await message.format({ text: "Hello world!" }); -* -* const chatPrompt = ChatPromptTemplate.fromMessages([message]); -* const formattedChatPrompt = await chatPrompt.invoke({ -* text: "Hello world!", -* }); -* ``` -*/ -var HumanMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return HumanMessage; - } - static lc_name() { - return "HumanMessagePromptTemplate"; - } -}; -/** -* Class that represents an AI message prompt template. It extends the -* BaseMessageStringPromptTemplate. -*/ -var AIMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return AIMessage; - } - static lc_name() { - return "AIMessagePromptTemplate"; - } -}; -/** -* Class that represents a system message prompt template. It extends the -* BaseMessageStringPromptTemplate. -* @example -* ```typescript -* const message = SystemMessagePromptTemplate.fromTemplate("{text}"); -* const formatted = await message.format({ text: "Hello world!" }); -* -* const chatPrompt = ChatPromptTemplate.fromMessages([message]); -* const formattedChatPrompt = await chatPrompt.invoke({ -* text: "Hello world!", -* }); -* ``` -*/ -var SystemMessagePromptTemplate = class extends _StringImageMessagePromptTemplate { - static _messageClass() { - return SystemMessage; - } - static lc_name() { - return "SystemMessagePromptTemplate"; - } -}; -function _isBaseMessagePromptTemplate(baseMessagePromptTemplateLike) { - return typeof baseMessagePromptTemplateLike.formatMessages === "function"; -} -function _coerceMessagePromptTemplateLike(messagePromptTemplateLike, extra) { - if (_isBaseMessagePromptTemplate(messagePromptTemplateLike) || isBaseMessage(messagePromptTemplateLike)) return messagePromptTemplateLike; - if (Array.isArray(messagePromptTemplateLike) && messagePromptTemplateLike[0] === "placeholder") { - const messageContent = messagePromptTemplateLike[1]; - if (extra?.templateFormat === "mustache" && typeof messageContent === "string" && messageContent.slice(0, 2) === "{{" && messageContent.slice(-2) === "}}") { - const variableName = messageContent.slice(2, -2); - return new MessagesPlaceholder({ - variableName, - optional: true - }); - } else if (typeof messageContent === "string" && messageContent[0] === "{" && messageContent[messageContent.length - 1] === "}") { - const variableName = messageContent.slice(1, -1); - return new MessagesPlaceholder({ - variableName, - optional: true - }); - } - throw new Error(`Invalid placeholder template for format ${extra?.templateFormat ?? `"f-string"`}: "${messagePromptTemplateLike[1]}". Expected a variable name surrounded by ${extra?.templateFormat === "mustache" ? "double" : "single"} curly braces.`); - } - const message = utils_coerceMessageLikeToMessage(messagePromptTemplateLike); - let templateData; - if (typeof message.content === "string") templateData = message.content; - else templateData = message.content.map((item) => { - if ("text" in item) return { - ...item, - text: item.text - }; - else if ("image_url" in item) return { - ...item, - image_url: item.image_url - }; - else return item; - }); - if (message._getType() === "human") return HumanMessagePromptTemplate.fromTemplate(templateData, extra); - else if (message._getType() === "ai") return AIMessagePromptTemplate.fromTemplate(templateData, extra); - else if (message._getType() === "system") return SystemMessagePromptTemplate.fromTemplate(templateData, extra); - else if (ChatMessage.isInstance(message)) return ChatMessagePromptTemplate.fromTemplate(message.content, message.role, extra); - else throw new Error(`Could not coerce message prompt template from input. Received message type: "${message._getType()}".`); -} -function isMessagesPlaceholder(x) { - return x.constructor.lc_name() === "MessagesPlaceholder"; -} -/** -* Class that represents a chat prompt. It extends the -* BaseChatPromptTemplate and uses an array of BaseMessagePromptTemplate -* instances to format a series of messages for a conversation. -* @example -* ```typescript -* const message = SystemMessagePromptTemplate.fromTemplate("{text}"); -* const chatPrompt = ChatPromptTemplate.fromMessages([ -* ["ai", "You are a helpful assistant."], -* message, -* ]); -* const formattedChatPrompt = await chatPrompt.invoke({ -* text: "Hello world!", -* }); -* ``` -*/ -var ChatPromptTemplate = class ChatPromptTemplate extends BaseChatPromptTemplate { - static lc_name() { - return "ChatPromptTemplate"; - } - get lc_aliases() { - return { promptMessages: "messages" }; - } - promptMessages; - validateTemplate = true; - templateFormat = "f-string"; - constructor(input) { - super(input); - if (input.templateFormat === "mustache" && input.validateTemplate === void 0) this.validateTemplate = false; - Object.assign(this, input); - if (this.validateTemplate) { - const inputVariablesMessages = /* @__PURE__ */ new Set(); - for (const promptMessage of this.promptMessages) { - if (promptMessage instanceof BaseMessage) continue; - for (const inputVariable of promptMessage.inputVariables) inputVariablesMessages.add(inputVariable); - } - const totalInputVariables = this.inputVariables; - const inputVariablesInstance = new Set(this.partialVariables ? totalInputVariables.concat(Object.keys(this.partialVariables)) : totalInputVariables); - const difference = new Set([...inputVariablesInstance].filter((x) => !inputVariablesMessages.has(x))); - if (difference.size > 0) throw new Error(`Input variables \`${[...difference]}\` are not used in any of the prompt messages.`); - const otherDifference = new Set([...inputVariablesMessages].filter((x) => !inputVariablesInstance.has(x))); - if (otherDifference.size > 0) throw new Error(`Input variables \`${[...otherDifference]}\` are used in prompt messages but not in the prompt template.`); - } - } - _getPromptType() { - return "chat"; - } - async _parseImagePrompts(message, inputValues) { - if (typeof message.content === "string") return message; - const formattedMessageContent = await Promise.all(message.content.map(async (item) => { - if (item.type !== "image_url") return item; - let imageUrl = ""; - if (typeof item.image_url === "string") imageUrl = item.image_url; - else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url && typeof item.image_url.url === "string") imageUrl = item.image_url.url; - const promptTemplatePlaceholder = PromptTemplate.fromTemplate(imageUrl, { templateFormat: this.templateFormat }); - const formattedUrl = await promptTemplatePlaceholder.format(inputValues); - if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) item.image_url.url = formattedUrl; - else item.image_url = formattedUrl; - return item; - })); - message.content = formattedMessageContent; - return message; - } - async formatMessages(values) { - const allValues = await this.mergePartialAndUserVariables(values); - let resultMessages = []; - for (const promptMessage of this.promptMessages) if (promptMessage instanceof BaseMessage) resultMessages.push(await this._parseImagePrompts(promptMessage, allValues)); - else { - let inputValues; - if (this.templateFormat === "mustache") inputValues = { ...allValues }; - else inputValues = promptMessage.inputVariables.reduce((acc, inputVariable) => { - if (!(inputVariable in allValues) && !(isMessagesPlaceholder(promptMessage) && promptMessage.optional)) { - const error = addLangChainErrorFields(/* @__PURE__ */ new Error(`Missing value for input variable \`${inputVariable.toString()}\``), "INVALID_PROMPT_INPUT"); - throw error; - } - acc[inputVariable] = allValues[inputVariable]; - return acc; - }, {}); - const message = await promptMessage.formatMessages(inputValues); - resultMessages = resultMessages.concat(message); - } - return resultMessages; - } - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new ChatPromptTemplate(promptDict); - } - static fromTemplate(template, options) { - const prompt = PromptTemplate.fromTemplate(template, options); - const humanTemplate = new HumanMessagePromptTemplate({ prompt }); - return this.fromMessages([humanTemplate]); - } - /** - * Create a chat model-specific prompt from individual chat messages - * or message-like tuples. - * @param promptMessages Messages to be passed to the chat model - * @returns A new ChatPromptTemplate - */ - static fromMessages(promptMessages, extra) { - const flattenedMessages = promptMessages.reduce((acc, promptMessage) => acc.concat(promptMessage instanceof ChatPromptTemplate ? promptMessage.promptMessages : [_coerceMessagePromptTemplateLike(promptMessage, extra)]), []); - const flattenedPartialVariables = promptMessages.reduce((acc, promptMessage) => promptMessage instanceof ChatPromptTemplate ? Object.assign(acc, promptMessage.partialVariables) : acc, Object.create(null)); - const inputVariables = /* @__PURE__ */ new Set(); - for (const promptMessage of flattenedMessages) { - if (promptMessage instanceof BaseMessage) continue; - for (const inputVariable of promptMessage.inputVariables) { - if (inputVariable in flattenedPartialVariables) continue; - inputVariables.add(inputVariable); - } - } - return new this({ - ...extra, - inputVariables: [...inputVariables], - promptMessages: flattenedMessages, - partialVariables: flattenedPartialVariables, - templateFormat: extra?.templateFormat - }); - } -}; - -//#endregion - -//# sourceMappingURL=chat.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/few_shot.js - - - - - -//#region src/prompts/few_shot.ts -/** -* Prompt template that contains few-shot examples. -* @augments BasePromptTemplate -* @augments FewShotPromptTemplateInput -* @example -* ```typescript -* const examplePrompt = PromptTemplate.fromTemplate( -* "Input: {input}\nOutput: {output}", -* ); -* -* const exampleSelector = await SemanticSimilarityExampleSelector.fromExamples( -* [ -* { input: "happy", output: "sad" }, -* { input: "tall", output: "short" }, -* { input: "energetic", output: "lethargic" }, -* { input: "sunny", output: "gloomy" }, -* { input: "windy", output: "calm" }, -* ], -* new OpenAIEmbeddings(), -* HNSWLib, -* { k: 1 }, -* ); -* -* const dynamicPrompt = new FewShotPromptTemplate({ -* exampleSelector, -* examplePrompt, -* prefix: "Give the antonym of every input", -* suffix: "Input: {adjective}\nOutput:", -* inputVariables: ["adjective"], -* }); -* -* // Format the dynamic prompt with the input 'rainy' -* console.log(await dynamicPrompt.format({ adjective: "rainy" })); -* -* ``` -*/ -var FewShotPromptTemplate = class FewShotPromptTemplate extends BaseStringPromptTemplate { - lc_serializable = false; - examples; - exampleSelector; - examplePrompt; - suffix = ""; - exampleSeparator = "\n\n"; - prefix = ""; - templateFormat = "f-string"; - validateTemplate = true; - constructor(input) { - super(input); - Object.assign(this, input); - if (this.examples !== void 0 && this.exampleSelector !== void 0) throw new Error("Only one of 'examples' and 'example_selector' should be provided"); - if (this.examples === void 0 && this.exampleSelector === void 0) throw new Error("One of 'examples' and 'example_selector' should be provided"); - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); - } - } - _getPromptType() { - return "few_shot"; - } - static lc_name() { - return "FewShotPromptTemplate"; - } - async getExamples(inputVariables) { - if (this.examples !== void 0) return this.examples; - if (this.exampleSelector !== void 0) return this.exampleSelector.selectExamples(inputVariables); - throw new Error("One of 'examples' and 'example_selector' should be provided"); - } - async partial(values) { - const newInputVariables = this.inputVariables.filter((iv) => !(iv in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new FewShotPromptTemplate(promptDict); - } - /** - * Formats the prompt with the given values. - * @param values The values to format the prompt with. - * @returns A promise that resolves to a string representing the formatted prompt. - */ - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - const examples = await this.getExamples(allValues); - const exampleStrings = await Promise.all(examples.map((example) => this.examplePrompt.format(example))); - const template = [ - this.prefix, - ...exampleStrings, - this.suffix - ].join(this.exampleSeparator); - return renderTemplate(template, this.templateFormat, allValues); - } - serialize() { - if (this.exampleSelector || !this.examples) throw new Error("Serializing an example selector is not currently supported"); - if (this.outputParser !== void 0) throw new Error("Serializing an output parser is not currently supported"); - return { - _type: this._getPromptType(), - input_variables: this.inputVariables, - example_prompt: this.examplePrompt.serialize(), - example_separator: this.exampleSeparator, - suffix: this.suffix, - prefix: this.prefix, - template_format: this.templateFormat, - examples: this.examples - }; - } - static async deserialize(data) { - const { example_prompt } = data; - if (!example_prompt) throw new Error("Missing example prompt"); - const examplePrompt = await PromptTemplate.deserialize(example_prompt); - let examples; - if (Array.isArray(data.examples)) examples = data.examples; - else throw new Error("Invalid examples format. Only list or string are supported."); - return new FewShotPromptTemplate({ - inputVariables: data.input_variables, - examplePrompt, - examples, - exampleSeparator: data.example_separator, - prefix: data.prefix, - suffix: data.suffix, - templateFormat: data.template_format - }); - } -}; -/** -* Chat prompt template that contains few-shot examples. -* @augments BasePromptTemplateInput -* @augments FewShotChatMessagePromptTemplateInput -*/ -var FewShotChatMessagePromptTemplate = class FewShotChatMessagePromptTemplate extends BaseChatPromptTemplate { - lc_serializable = true; - examples; - exampleSelector; - examplePrompt; - suffix = ""; - exampleSeparator = "\n\n"; - prefix = ""; - templateFormat = "f-string"; - validateTemplate = true; - _getPromptType() { - return "few_shot_chat"; - } - static lc_name() { - return "FewShotChatMessagePromptTemplate"; - } - constructor(fields) { - super(fields); - this.examples = fields.examples; - this.examplePrompt = fields.examplePrompt; - this.exampleSeparator = fields.exampleSeparator ?? "\n\n"; - this.exampleSelector = fields.exampleSelector; - this.prefix = fields.prefix ?? ""; - this.suffix = fields.suffix ?? ""; - this.templateFormat = fields.templateFormat ?? "f-string"; - this.validateTemplate = fields.validateTemplate ?? true; - if (this.examples !== void 0 && this.exampleSelector !== void 0) throw new Error("Only one of 'examples' and 'example_selector' should be provided"); - if (this.examples === void 0 && this.exampleSelector === void 0) throw new Error("One of 'examples' and 'example_selector' should be provided"); - if (this.validateTemplate) { - let totalInputVariables = this.inputVariables; - if (this.partialVariables) totalInputVariables = totalInputVariables.concat(Object.keys(this.partialVariables)); - checkValidTemplate(this.prefix + this.suffix, this.templateFormat, totalInputVariables); - } - } - async getExamples(inputVariables) { - if (this.examples !== void 0) return this.examples; - if (this.exampleSelector !== void 0) return this.exampleSelector.selectExamples(inputVariables); - throw new Error("One of 'examples' and 'example_selector' should be provided"); - } - /** - * Formats the list of values and returns a list of formatted messages. - * @param values The values to format the prompt with. - * @returns A promise that resolves to a string representing the formatted prompt. - */ - async formatMessages(values) { - const allValues = await this.mergePartialAndUserVariables(values); - let examples = await this.getExamples(allValues); - examples = examples.map((example) => { - const result = {}; - this.examplePrompt.inputVariables.forEach((inputVariable) => { - result[inputVariable] = example[inputVariable]; - }); - return result; - }); - const messages = []; - for (const example of examples) { - const exampleMessages = await this.examplePrompt.formatMessages(example); - messages.push(...exampleMessages); - } - return messages; - } - /** - * Formats the prompt with the given values. - * @param values The values to format the prompt with. - * @returns A promise that resolves to a string representing the formatted prompt. - */ - async format(values) { - const allValues = await this.mergePartialAndUserVariables(values); - const examples = await this.getExamples(allValues); - const exampleMessages = await Promise.all(examples.map((example) => this.examplePrompt.formatMessages(example))); - const exampleStrings = exampleMessages.flat().map((message) => message.content); - const template = [ - this.prefix, - ...exampleStrings, - this.suffix - ].join(this.exampleSeparator); - return renderTemplate(template, this.templateFormat, allValues); - } - /** - * Partially formats the prompt with the given values. - * @param values The values to partially format the prompt with. - * @returns A promise that resolves to an instance of `FewShotChatMessagePromptTemplate` with the given values partially formatted. - */ - async partial(values) { - const newInputVariables = this.inputVariables.filter((variable) => !(variable in values)); - const newPartialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - const promptDict = { - ...this, - inputVariables: newInputVariables, - partialVariables: newPartialVariables - }; - return new FewShotChatMessagePromptTemplate(promptDict); - } -}; - -//#endregion - -//# sourceMappingURL=few_shot.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/pipeline.js - - - -//#region src/prompts/pipeline.ts -/** -* Class that handles a sequence of prompts, each of which may require -* different input variables. Includes methods for formatting these -* prompts, extracting required input values, and handling partial -* prompts. -* @example -* ```typescript -* const composedPrompt = new PipelinePromptTemplate({ -* pipelinePrompts: [ -* { -* name: "introduction", -* prompt: PromptTemplate.fromTemplate(`You are impersonating {person}.`), -* }, -* { -* name: "example", -* prompt: PromptTemplate.fromTemplate( -* `Here's an example of an interaction: -* Q: {example_q} -* A: {example_a}`, -* ), -* }, -* { -* name: "start", -* prompt: PromptTemplate.fromTemplate( -* `Now, do this for real! -* Q: {input} -* A:`, -* ), -* }, -* ], -* finalPrompt: PromptTemplate.fromTemplate( -* `{introduction} -* {example} -* {start}`, -* ), -* }); -* -* const formattedPrompt = await composedPrompt.format({ -* person: "Elon Musk", -* example_q: `What's your favorite car?`, -* example_a: "Tesla", -* input: `What's your favorite social media site?`, -* }); -* ``` -*/ -var PipelinePromptTemplate = class PipelinePromptTemplate extends BasePromptTemplate { - static lc_name() { - return "PipelinePromptTemplate"; - } - pipelinePrompts; - finalPrompt; - constructor(input) { - super({ - ...input, - inputVariables: [] - }); - this.pipelinePrompts = input.pipelinePrompts; - this.finalPrompt = input.finalPrompt; - this.inputVariables = this.computeInputValues(); - } - /** - * Computes the input values required by the pipeline prompts. - * @returns Array of input values required by the pipeline prompts. - */ - computeInputValues() { - const intermediateValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.name); - const inputValues = this.pipelinePrompts.map((pipelinePrompt) => pipelinePrompt.prompt.inputVariables.filter((inputValue) => !intermediateValues.includes(inputValue))).flat(); - return [...new Set(inputValues)]; - } - static extractRequiredInputValues(allValues, requiredValueNames) { - return requiredValueNames.reduce((requiredValues, valueName) => { - requiredValues[valueName] = allValues[valueName]; - return requiredValues; - }, {}); - } - /** - * Formats the pipeline prompts based on the provided input values. - * @param values Input values to format the pipeline prompts. - * @returns Promise that resolves with the formatted input values. - */ - async formatPipelinePrompts(values) { - const allValues = await this.mergePartialAndUserVariables(values); - for (const { name: pipelinePromptName, prompt: pipelinePrompt } of this.pipelinePrompts) { - const pipelinePromptInputValues = PipelinePromptTemplate.extractRequiredInputValues(allValues, pipelinePrompt.inputVariables); - if (pipelinePrompt instanceof ChatPromptTemplate) allValues[pipelinePromptName] = await pipelinePrompt.formatMessages(pipelinePromptInputValues); - else allValues[pipelinePromptName] = await pipelinePrompt.format(pipelinePromptInputValues); - } - return PipelinePromptTemplate.extractRequiredInputValues(allValues, this.finalPrompt.inputVariables); - } - /** - * Formats the final prompt value based on the provided input values. - * @param values Input values to format the final prompt value. - * @returns Promise that resolves with the formatted final prompt value. - */ - async formatPromptValue(values) { - return this.finalPrompt.formatPromptValue(await this.formatPipelinePrompts(values)); - } - async format(values) { - return this.finalPrompt.format(await this.formatPipelinePrompts(values)); - } - /** - * Handles partial prompts, which are prompts that have been partially - * filled with input values. - * @param values Partial input values. - * @returns Promise that resolves with a new PipelinePromptTemplate instance with updated input variables. - */ - async partial(values) { - const promptDict = { ...this }; - promptDict.inputVariables = this.inputVariables.filter((iv) => !(iv in values)); - promptDict.partialVariables = { - ...this.partialVariables ?? {}, - ...values - }; - return new PipelinePromptTemplate(promptDict); - } - serialize() { - throw new Error("Not implemented."); - } - _getPromptType() { - return "pipeline"; - } -}; - -//#endregion - -//# sourceMappingURL=pipeline.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/structured.js - - - -//#region src/prompts/structured.ts -function isWithStructuredOutput(x) { - return typeof x === "object" && x != null && "withStructuredOutput" in x && typeof x.withStructuredOutput === "function"; -} -function isRunnableBinding(x) { - return typeof x === "object" && x != null && "lc_id" in x && Array.isArray(x.lc_id) && x.lc_id.join("/") === "langchain_core/runnables/RunnableBinding"; -} -var StructuredPrompt = class StructuredPrompt extends ChatPromptTemplate { - schema; - method; - lc_namespace = [ - "langchain_core", - "prompts", - "structured" - ]; - get lc_aliases() { - return { - ...super.lc_aliases, - schema: "schema_" - }; - } - constructor(input) { - super(input); - this.schema = input.schema; - this.method = input.method; - } - pipe(coerceable) { - if (isWithStructuredOutput(coerceable)) return super.pipe(coerceable.withStructuredOutput(this.schema)); - if (isRunnableBinding(coerceable) && isWithStructuredOutput(coerceable.bound)) return super.pipe(new RunnableBinding({ - bound: coerceable.bound.withStructuredOutput(this.schema, ...this.method ? [{ method: this.method }] : []), - kwargs: coerceable.kwargs ?? {}, - config: coerceable.config, - configFactories: coerceable.configFactories - })); - throw new Error(`Structured prompts need to be piped to a language model that supports the "withStructuredOutput()" method.`); - } - static fromMessagesAndSchema(promptMessages, schema, method) { - return StructuredPrompt.fromMessages(promptMessages, { - schema, - method - }); - } -}; - -//#endregion - -//# sourceMappingURL=structured.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/prompts/index.js - - - - - - - - - - - - -//#region src/prompts/index.ts -var prompts_exports = {}; -__export(prompts_exports, { - AIMessagePromptTemplate: () => AIMessagePromptTemplate, - BaseChatPromptTemplate: () => BaseChatPromptTemplate, - BaseMessagePromptTemplate: () => BaseMessagePromptTemplate, - BaseMessageStringPromptTemplate: () => BaseMessageStringPromptTemplate, - BasePromptTemplate: () => BasePromptTemplate, - BaseStringPromptTemplate: () => BaseStringPromptTemplate, - ChatMessagePromptTemplate: () => ChatMessagePromptTemplate, - ChatPromptTemplate: () => ChatPromptTemplate, - DEFAULT_FORMATTER_MAPPING: () => DEFAULT_FORMATTER_MAPPING, - DEFAULT_PARSER_MAPPING: () => DEFAULT_PARSER_MAPPING, - DictPromptTemplate: () => DictPromptTemplate, - FewShotChatMessagePromptTemplate: () => FewShotChatMessagePromptTemplate, - FewShotPromptTemplate: () => FewShotPromptTemplate, - HumanMessagePromptTemplate: () => HumanMessagePromptTemplate, - ImagePromptTemplate: () => ImagePromptTemplate, - MessagesPlaceholder: () => MessagesPlaceholder, - PipelinePromptTemplate: () => PipelinePromptTemplate, - PromptTemplate: () => PromptTemplate, - StructuredPrompt: () => StructuredPrompt, - SystemMessagePromptTemplate: () => SystemMessagePromptTemplate, - checkValidTemplate: () => checkValidTemplate, - interpolateFString: () => interpolateFString, - interpolateMustache: () => interpolateMustache, - parseFString: () => parseFString, - parseMustache: () => parseMustache, - parseTemplate: () => template_parseTemplate, - renderTemplate: () => renderTemplate -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/router.js - - - -//#region src/runnables/router.ts -/** -* A runnable that routes to a set of runnables based on Input['key']. -* Returns the output of the selected runnable. -* @example -* ```typescript -* import { RouterRunnable, RunnableLambda } from "@langchain/core/runnables"; -* -* const router = new RouterRunnable({ -* runnables: { -* toUpperCase: RunnableLambda.from((text: string) => text.toUpperCase()), -* reverseText: RunnableLambda.from((text: string) => -* text.split("").reverse().join("") -* ), -* }, -* }); -* -* // Invoke the 'reverseText' runnable -* const result1 = router.invoke({ key: "reverseText", input: "Hello World" }); -* -* // "dlroW olleH" -* -* // Invoke the 'toUpperCase' runnable -* const result2 = router.invoke({ key: "toUpperCase", input: "Hello World" }); -* -* // "HELLO WORLD" -* ``` -*/ -var RouterRunnable = class extends Runnable { - static lc_name() { - return "RouterRunnable"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - runnables; - constructor(fields) { - super(fields); - this.runnables = fields.runnables; - } - async invoke(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === void 0) throw new Error(`No runnable associated with key "${key}".`); - return runnable.invoke(actualInput, ensureConfig(options)); - } - async batch(inputs, options, batchOptions) { - const keys = inputs.map((input) => input.key); - const actualInputs = inputs.map((input) => input.input); - const missingKey = keys.find((key) => this.runnables[key] === void 0); - if (missingKey !== void 0) throw new Error(`One or more keys do not have a corresponding runnable.`); - const runnables = keys.map((key) => this.runnables[key]); - const optionsList = this._getOptionsList(options ?? {}, inputs.length); - const maxConcurrency = optionsList[0]?.maxConcurrency ?? batchOptions?.maxConcurrency; - const batchSize = maxConcurrency && maxConcurrency > 0 ? maxConcurrency : inputs.length; - const batchResults = []; - for (let i = 0; i < actualInputs.length; i += batchSize) { - const batchPromises = actualInputs.slice(i, i + batchSize).map((actualInput, i$1) => runnables[i$1].invoke(actualInput, optionsList[i$1])); - const batchResult = await Promise.all(batchPromises); - batchResults.push(batchResult); - } - return batchResults.flat(); - } - async stream(input, options) { - const { key, input: actualInput } = input; - const runnable = this.runnables[key]; - if (runnable === void 0) throw new Error(`No runnable associated with key "${key}".`); - return runnable.stream(actualInput, options); - } -}; - -//#endregion - -//# sourceMappingURL=router.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/branch.js - - - - -//#region src/runnables/branch.ts -/** -* Class that represents a runnable branch. The RunnableBranch is -* initialized with an array of branches and a default branch. When invoked, -* it evaluates the condition of each branch in order and executes the -* corresponding branch if the condition is true. If none of the conditions -* are true, it executes the default branch. -* @example -* ```typescript -* const branch = RunnableBranch.from([ -* [ -* (x: { topic: string; question: string }) => -* x.topic.toLowerCase().includes("anthropic"), -* anthropicChain, -* ], -* [ -* (x: { topic: string; question: string }) => -* x.topic.toLowerCase().includes("langchain"), -* langChainChain, -* ], -* generalChain, -* ]); -* -* const fullChain = RunnableSequence.from([ -* { -* topic: classificationChain, -* question: (input: { question: string }) => input.question, -* }, -* branch, -* ]); -* -* const result = await fullChain.invoke({ -* question: "how do I use LangChain?", -* }); -* ``` -*/ -var RunnableBranch = class extends Runnable { - static lc_name() { - return "RunnableBranch"; - } - lc_namespace = ["langchain_core", "runnables"]; - lc_serializable = true; - default; - branches; - constructor(fields) { - super(fields); - this.branches = fields.branches; - this.default = fields.default; - } - /** - * Convenience method for instantiating a RunnableBranch from - * RunnableLikes (objects, functions, or Runnables). - * - * Each item in the input except for the last one should be a - * tuple with two items. The first is a "condition" RunnableLike that - * returns "true" if the second RunnableLike in the tuple should run. - * - * The final item in the input should be a RunnableLike that acts as a - * default branch if no other branches match. - * - * @example - * ```ts - * import { RunnableBranch } from "@langchain/core/runnables"; - * - * const branch = RunnableBranch.from([ - * [(x: number) => x > 0, (x: number) => x + 1], - * [(x: number) => x < 0, (x: number) => x - 1], - * (x: number) => x - * ]); - * ``` - * @param branches An array where the every item except the last is a tuple of [condition, runnable] - * pairs. The last item is a default runnable which is invoked if no other condition matches. - * @returns A new RunnableBranch. - */ - static from(branches) { - if (branches.length < 1) throw new Error("RunnableBranch requires at least one branch"); - const branchLikes = branches.slice(0, -1); - const coercedBranches = branchLikes.map(([condition, runnable]) => [_coerceToRunnable(condition), _coerceToRunnable(runnable)]); - const defaultBranch = _coerceToRunnable(branches[branches.length - 1]); - return new this({ - branches: coercedBranches, - default: defaultBranch - }); - } - async _invoke(input, config, runManager) { - let result; - for (let i = 0; i < this.branches.length; i += 1) { - const [condition, branchRunnable] = this.branches[i]; - const conditionValue = await condition.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`condition:${i + 1}`) })); - if (conditionValue) { - result = await branchRunnable.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`branch:${i + 1}`) })); - break; - } - } - if (!result) result = await this.default.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild("branch:default") })); - return result; - } - async invoke(input, config = {}) { - return this._callWithConfig(this._invoke, input, config); - } - async *_streamIterator(input, config) { - const callbackManager_ = await getCallbackManagerForConfig(config); - const runManager = await callbackManager_?.handleChainStart(this.toJSON(), base_coerceToDict(input, "input"), config?.runId, void 0, void 0, void 0, config?.runName); - let finalOutput; - let finalOutputSupported = true; - let stream; - try { - for (let i = 0; i < this.branches.length; i += 1) { - const [condition, branchRunnable] = this.branches[i]; - const conditionValue = await condition.invoke(input, config_patchConfig(config, { callbacks: runManager?.getChild(`condition:${i + 1}`) })); - if (conditionValue) { - stream = await branchRunnable.stream(input, config_patchConfig(config, { callbacks: runManager?.getChild(`branch:${i + 1}`) })); - for await (const chunk of stream) { - yield chunk; - if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = concat(finalOutput, chunk); - } catch { - finalOutput = void 0; - finalOutputSupported = false; - } - } - break; - } - } - if (stream === void 0) { - stream = await this.default.stream(input, config_patchConfig(config, { callbacks: runManager?.getChild("branch:default") })); - for await (const chunk of stream) { - yield chunk; - if (finalOutputSupported) if (finalOutput === void 0) finalOutput = chunk; - else try { - finalOutput = concat(finalOutput, chunk); - } catch { - finalOutput = void 0; - finalOutputSupported = false; - } - } - } - } catch (e) { - await runManager?.handleChainError(e); - throw e; - } - await runManager?.handleChainEnd(finalOutput ?? {}); - } -}; - -//#endregion - -//# sourceMappingURL=branch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/history.js - - - - - - - -//#region src/runnables/history.ts -/** -* Wraps a LCEL chain and manages history. It appends input messages -* and chain outputs as history, and adds the current history messages to -* the chain input. -* @example -* ```typescript -* // pnpm install @langchain/anthropic @langchain/community @upstash/redis -* -* import { -* ChatPromptTemplate, -* MessagesPlaceholder, -* } from "@langchain/core/prompts"; -* import { ChatAnthropic } from "@langchain/anthropic"; -* import { UpstashRedisChatMessageHistory } from "@langchain/community/stores/message/upstash_redis"; -* // For demos, you can also use an in-memory store: -* // import { ChatMessageHistory } from "@langchain/classic/stores/message/in_memory"; -* -* const prompt = ChatPromptTemplate.fromMessages([ -* ["system", "You're an assistant who's good at {ability}"], -* new MessagesPlaceholder("history"), -* ["human", "{question}"], -* ]); -* -* const chain = prompt.pipe(new ChatAnthropic({})); -* -* const chainWithHistory = new RunnableWithMessageHistory({ -* runnable: chain, -* getMessageHistory: (sessionId) => -* new UpstashRedisChatMessageHistory({ -* sessionId, -* config: { -* url: process.env.UPSTASH_REDIS_REST_URL!, -* token: process.env.UPSTASH_REDIS_REST_TOKEN!, -* }, -* }), -* inputMessagesKey: "question", -* historyMessagesKey: "history", -* }); -* -* const result = await chainWithHistory.invoke( -* { -* ability: "math", -* question: "What does cosine mean?", -* }, -* { -* configurable: { -* sessionId: "some_string_identifying_a_user", -* }, -* } -* ); -* -* const result2 = await chainWithHistory.invoke( -* { -* ability: "math", -* question: "What's its inverse?", -* }, -* { -* configurable: { -* sessionId: "some_string_identifying_a_user", -* }, -* } -* ); -* ``` -*/ -var RunnableWithMessageHistory = class extends RunnableBinding { - runnable; - inputMessagesKey; - outputMessagesKey; - historyMessagesKey; - getMessageHistory; - constructor(fields) { - let historyChain = RunnableLambda.from((input, options) => this._enterHistory(input, options ?? {})).withConfig({ runName: "loadHistory" }); - const messagesKey = fields.historyMessagesKey ?? fields.inputMessagesKey; - if (messagesKey) historyChain = RunnablePassthrough.assign({ [messagesKey]: historyChain }).withConfig({ runName: "insertHistory" }); - const bound = historyChain.pipe(fields.runnable.withListeners({ onEnd: (run, config$1) => this._exitHistory(run, config$1 ?? {}) })).withConfig({ runName: "RunnableWithMessageHistory" }); - const config = fields.config ?? {}; - super({ - ...fields, - config, - bound - }); - this.runnable = fields.runnable; - this.getMessageHistory = fields.getMessageHistory; - this.inputMessagesKey = fields.inputMessagesKey; - this.outputMessagesKey = fields.outputMessagesKey; - this.historyMessagesKey = fields.historyMessagesKey; - } - _getInputMessages(inputValue) { - let parsedInputValue; - if (typeof inputValue === "object" && !Array.isArray(inputValue) && !isBaseMessage(inputValue)) { - let key; - if (this.inputMessagesKey) key = this.inputMessagesKey; - else if (Object.keys(inputValue).length === 1) key = Object.keys(inputValue)[0]; - else key = "input"; - if (Array.isArray(inputValue[key]) && Array.isArray(inputValue[key][0])) parsedInputValue = inputValue[key][0]; - else parsedInputValue = inputValue[key]; - } else parsedInputValue = inputValue; - if (typeof parsedInputValue === "string") return [new HumanMessage(parsedInputValue)]; - else if (Array.isArray(parsedInputValue)) return parsedInputValue; - else if (isBaseMessage(parsedInputValue)) return [parsedInputValue]; - else throw new Error(`Expected a string, BaseMessage, or array of BaseMessages.\nGot ${JSON.stringify(parsedInputValue, null, 2)}`); - } - _getOutputMessages(outputValue) { - let parsedOutputValue; - if (!Array.isArray(outputValue) && !isBaseMessage(outputValue) && typeof outputValue !== "string") { - let key; - if (this.outputMessagesKey !== void 0) key = this.outputMessagesKey; - else if (Object.keys(outputValue).length === 1) key = Object.keys(outputValue)[0]; - else key = "output"; - if (outputValue.generations !== void 0) parsedOutputValue = outputValue.generations[0][0].message; - else parsedOutputValue = outputValue[key]; - } else parsedOutputValue = outputValue; - if (typeof parsedOutputValue === "string") return [new AIMessage(parsedOutputValue)]; - else if (Array.isArray(parsedOutputValue)) return parsedOutputValue; - else if (isBaseMessage(parsedOutputValue)) return [parsedOutputValue]; - else throw new Error(`Expected a string, BaseMessage, or array of BaseMessages. Received: ${JSON.stringify(parsedOutputValue, null, 2)}`); - } - async _enterHistory(input, kwargs) { - const history = kwargs?.configurable?.messageHistory; - const messages = await history.getMessages(); - if (this.historyMessagesKey === void 0) return messages.concat(this._getInputMessages(input)); - return messages; - } - async _exitHistory(run, config) { - const history = config.configurable?.messageHistory; - let inputs; - if (Array.isArray(run.inputs) && Array.isArray(run.inputs[0])) inputs = run.inputs[0]; - else inputs = run.inputs; - let inputMessages = this._getInputMessages(inputs); - if (this.historyMessagesKey === void 0) { - const existingMessages = await history.getMessages(); - inputMessages = inputMessages.slice(existingMessages.length); - } - const outputValue = run.outputs; - if (!outputValue) throw new Error(`Output values from 'Run' undefined. Run: ${JSON.stringify(run, null, 2)}`); - const outputMessages = this._getOutputMessages(outputValue); - await history.addMessages([...inputMessages, ...outputMessages]); - } - async _mergeConfig(...configs) { - const config = await super._mergeConfig(...configs); - if (!config.configurable || !config.configurable.sessionId) { - const exampleInput = { [this.inputMessagesKey ?? "input"]: "foo" }; - const exampleConfig = { configurable: { sessionId: "123" } }; - throw new Error(`sessionId is required. Pass it in as part of the config argument to .invoke() or .stream()\neg. chain.invoke(${JSON.stringify(exampleInput)}, ${JSON.stringify(exampleConfig)})`); - } - const { sessionId } = config.configurable; - config.configurable.messageHistory = await this.getMessageHistory(sessionId); - return config; - } -}; - -//#endregion - -//# sourceMappingURL=history.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/runnables/index.js - - - - - - - - - -//#region src/runnables/index.ts -var runnables_exports = {}; -__export(runnables_exports, { - RouterRunnable: () => RouterRunnable, - Runnable: () => Runnable, - RunnableAssign: () => RunnableAssign, - RunnableBinding: () => RunnableBinding, - RunnableBranch: () => RunnableBranch, - RunnableEach: () => RunnableEach, - RunnableLambda: () => RunnableLambda, - RunnableMap: () => RunnableMap, - RunnableParallel: () => RunnableParallel, - RunnablePassthrough: () => RunnablePassthrough, - RunnablePick: () => RunnablePick, - RunnableRetry: () => RunnableRetry, - RunnableSequence: () => RunnableSequence, - RunnableToolLike: () => RunnableToolLike, - RunnableWithFallbacks: () => RunnableWithFallbacks, - RunnableWithMessageHistory: () => RunnableWithMessageHistory, - _coerceToRunnable: () => _coerceToRunnable, - ensureConfig: () => ensureConfig, - getCallbackManagerForConfig: () => getCallbackManagerForConfig, - mergeConfigs: () => mergeConfigs, - patchConfig: () => config_patchConfig, - pickRunnableConfigKeys: () => config_pickRunnableConfigKeys, - raceWithSignal: () => raceWithSignal -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/json_patch.js - - - - - -//#region src/utils/json_patch.ts -var json_patch_exports = {}; -__export(json_patch_exports, { - applyPatch: () => applyPatch, - compare: () => compare -}); - -//#endregion - -//# sourceMappingURL=json_patch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/base.js - - - - -//#region src/output_parsers/base.ts -/** -* Abstract base class for parsing the output of a Large Language Model -* (LLM) call. It provides methods for parsing the result of an LLM call -* and invoking the parser with a given input. -*/ -var BaseLLMOutputParser = class extends Runnable { - /** - * Parses the result of an LLM call with a given prompt. By default, it - * simply calls `parseResult`. - * @param generations The generations from an LLM call. - * @param _prompt The prompt used in the LLM call. - * @param callbacks Optional callbacks. - * @returns A promise of the parsed output. - */ - parseResultWithPrompt(generations, _prompt, callbacks) { - return this.parseResult(generations, callbacks); - } - _baseMessageToString(message) { - return typeof message.content === "string" ? message.content : this._baseMessageContentToString(message.content); - } - _baseMessageContentToString(content) { - return JSON.stringify(content); - } - /** - * Calls the parser with a given input and optional configuration options. - * If the input is a string, it creates a generation with the input as - * text and calls `parseResult`. If the input is a `BaseMessage`, it - * creates a generation with the input as a message and the content of the - * input as text, and then calls `parseResult`. - * @param input The input to the parser, which can be a string or a `BaseMessage`. - * @param options Optional configuration options. - * @returns A promise of the parsed output. - */ - async invoke(input, options) { - if (typeof input === "string") return this._callWithConfig(async (input$1, options$1) => this.parseResult([{ text: input$1 }], options$1?.callbacks), input, { - ...options, - runType: "parser" - }); - else return this._callWithConfig(async (input$1, options$1) => this.parseResult([{ - message: input$1, - text: this._baseMessageToString(input$1) - }], options$1?.callbacks), input, { - ...options, - runType: "parser" - }); - } -}; -/** -* Class to parse the output of an LLM call. -*/ -var BaseOutputParser = class extends BaseLLMOutputParser { - parseResult(generations, callbacks) { - return this.parse(generations[0].text, callbacks); - } - async parseWithPrompt(text, _prompt, callbacks) { - return this.parse(text, callbacks); - } - /** - * Return the string type key uniquely identifying this class of parser - */ - _type() { - throw new Error("_type not implemented"); - } -}; -/** -* Exception that output parsers should raise to signify a parsing error. -* -* This exists to differentiate parsing errors from other code or execution errors -* that also may arise inside the output parser. OutputParserExceptions will be -* available to catch and handle in ways to fix the parsing error, while other -* errors will be raised. -* -* @param message - The error that's being re-raised or an error message. -* @param llmOutput - String model output which is error-ing. -* @param observation - String explanation of error which can be passed to a -* model to try and remediate the issue. -* @param sendToLLM - Whether to send the observation and llm_output back to an Agent -* after an OutputParserException has been raised. This gives the underlying -* model driving the agent the context that the previous output was improperly -* structured, in the hopes that it will update the output to the correct -* format. -*/ -var OutputParserException = class extends Error { - llmOutput; - observation; - sendToLLM; - constructor(message, llmOutput, observation, sendToLLM = false) { - super(message); - this.llmOutput = llmOutput; - this.observation = observation; - this.sendToLLM = sendToLLM; - if (sendToLLM) { - if (observation === void 0 || llmOutput === void 0) throw new Error("Arguments 'observation' & 'llmOutput' are required if 'sendToLlm' is true"); - } - addLangChainErrorFields(this, "OUTPUT_PARSING_FAILURE"); - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/transform.js - - - - - - -//#region src/output_parsers/transform.ts -/** -* Class to parse the output of an LLM call that also allows streaming inputs. -*/ -var BaseTransformOutputParser = class extends BaseOutputParser { - async *_transform(inputGenerator) { - for await (const chunk of inputGenerator) if (typeof chunk === "string") yield this.parseResult([{ text: chunk }]); - else yield this.parseResult([{ - message: chunk, - text: this._baseMessageToString(chunk) - }]); - } - /** - * Transforms an asynchronous generator of input into an asynchronous - * generator of parsed output. - * @param inputGenerator An asynchronous generator of input. - * @param options A configuration object. - * @returns An asynchronous generator of parsed output. - */ - async *transform(inputGenerator, options) { - yield* this._transformStreamWithConfig(inputGenerator, this._transform.bind(this), { - ...options, - runType: "parser" - }); - } -}; -/** -* A base class for output parsers that can handle streaming input. It -* extends the `BaseTransformOutputParser` class and provides a method for -* converting parsed outputs into a diff format. -*/ -var BaseCumulativeTransformOutputParser = class extends BaseTransformOutputParser { - diff = false; - constructor(fields) { - super(fields); - this.diff = fields?.diff ?? this.diff; - } - async *_transform(inputGenerator) { - let prevParsed; - let accGen; - for await (const chunk of inputGenerator) { - if (typeof chunk !== "string" && typeof chunk.content !== "string") throw new Error("Cannot handle non-string output."); - let chunkGen; - if (isBaseMessageChunk(chunk)) { - if (typeof chunk.content !== "string") throw new Error("Cannot handle non-string message output."); - chunkGen = new ChatGenerationChunk({ - message: chunk, - text: chunk.content - }); - } else if (isBaseMessage(chunk)) { - if (typeof chunk.content !== "string") throw new Error("Cannot handle non-string message output."); - chunkGen = new ChatGenerationChunk({ - message: convertToChunk(chunk), - text: chunk.content - }); - } else chunkGen = new GenerationChunk({ text: chunk }); - if (accGen === void 0) accGen = chunkGen; - else accGen = accGen.concat(chunkGen); - const parsed = await this.parsePartialResult([accGen]); - if (parsed !== void 0 && parsed !== null && !deepCompareStrict(parsed, prevParsed)) { - if (this.diff) yield this._diff(prevParsed, parsed); - else yield parsed; - prevParsed = parsed; - } - } - } - getFormatInstructions() { - return ""; - } -}; - -//#endregion - -//# sourceMappingURL=transform.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/json.js - - - - - -//#region src/output_parsers/json.ts -/** -* Class for parsing the output of an LLM into a JSON object. -*/ -var JsonOutputParser = class extends BaseCumulativeTransformOutputParser { - static lc_name() { - return "JsonOutputParser"; - } - lc_namespace = ["langchain_core", "output_parsers"]; - lc_serializable = true; - /** @internal */ - _concatOutputChunks(first, second) { - if (this.diff) return super._concatOutputChunks(first, second); - return second; - } - _diff(prev, next) { - if (!next) return void 0; - if (!prev) return [{ - op: "replace", - path: "", - value: next - }]; - return compare(prev, next); - } - async parsePartialResult(generations) { - return parseJsonMarkdown(generations[0].text); - } - async parse(text) { - return parseJsonMarkdown(text, JSON.parse); - } - getFormatInstructions() { - return ""; - } -}; - -//#endregion - -//# sourceMappingURL=json.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_tools/json_output_tools_parsers.js - - - - - - - -//#region src/output_parsers/openai_tools/json_output_tools_parsers.ts -function parseToolCall(rawToolCall, options) { - if (rawToolCall.function === void 0) return void 0; - let functionArgs; - if (options?.partial) try { - functionArgs = parsePartialJson(rawToolCall.function.arguments ?? "{}"); - } catch { - return void 0; - } - else try { - functionArgs = JSON.parse(rawToolCall.function.arguments); - } catch (e) { - throw new OutputParserException([ - `Function "${rawToolCall.function.name}" arguments:`, - ``, - rawToolCall.function.arguments, - ``, - `are not valid JSON.`, - `Error: ${e.message}` - ].join("\n")); - } - const parsedToolCall = { - name: rawToolCall.function.name, - args: functionArgs, - type: "tool_call" - }; - if (options?.returnId) parsedToolCall.id = rawToolCall.id; - return parsedToolCall; -} -function convertLangChainToolCallToOpenAI(toolCall) { - if (toolCall.id === void 0) throw new Error(`All OpenAI tool calls must have an "id" field.`); - return { - id: toolCall.id, - type: "function", - function: { - name: toolCall.name, - arguments: JSON.stringify(toolCall.args) - } - }; -} -function makeInvalidToolCall(rawToolCall, errorMsg) { - return { - name: rawToolCall.function?.name, - args: rawToolCall.function?.arguments, - id: rawToolCall.id, - error: errorMsg, - type: "invalid_tool_call" - }; -} -/** -* Class for parsing the output of a tool-calling LLM into a JSON object. -*/ -var JsonOutputToolsParser = class extends BaseCumulativeTransformOutputParser { - static lc_name() { - return "JsonOutputToolsParser"; - } - returnId = false; - lc_namespace = [ - "langchain", - "output_parsers", - "openai_tools" - ]; - lc_serializable = true; - constructor(fields) { - super(fields); - this.returnId = fields?.returnId ?? this.returnId; - } - _diff() { - throw new Error("Not supported."); - } - async parse() { - throw new Error("Not implemented."); - } - async parseResult(generations) { - const result = await this.parsePartialResult(generations, false); - return result; - } - /** - * Parses the output and returns a JSON object. If `argsOnly` is true, - * only the arguments of the function call are returned. - * @param generations The output of the LLM to parse. - * @returns A JSON object representation of the function call or its arguments. - */ - async parsePartialResult(generations, partial = true) { - const message = generations[0].message; - let toolCalls; - if (isAIMessage(message) && message.tool_calls?.length) toolCalls = message.tool_calls.map((toolCall) => { - const { id,...rest } = toolCall; - if (!this.returnId) return rest; - return { - id, - ...rest - }; - }); - else if (message.additional_kwargs.tool_calls !== void 0) { - const rawToolCalls = JSON.parse(JSON.stringify(message.additional_kwargs.tool_calls)); - toolCalls = rawToolCalls.map((rawToolCall) => { - return parseToolCall(rawToolCall, { - returnId: this.returnId, - partial - }); - }); - } - if (!toolCalls) return []; - const parsedToolCalls = []; - for (const toolCall of toolCalls) if (toolCall !== void 0) { - const backwardsCompatibleToolCall = { - type: toolCall.name, - args: toolCall.args, - id: toolCall.id - }; - parsedToolCalls.push(backwardsCompatibleToolCall); - } - return parsedToolCalls; - } -}; -/** -* Class for parsing the output of a tool-calling LLM into a JSON object if you are -* expecting only a single tool to be called. -*/ -var JsonOutputKeyToolsParser = class extends JsonOutputToolsParser { - static lc_name() { - return "JsonOutputKeyToolsParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_tools" - ]; - lc_serializable = true; - returnId = false; - /** The type of tool calls to return. */ - keyName; - /** Whether to return only the first tool call. */ - returnSingle = false; - zodSchema; - constructor(params) { - super(params); - this.keyName = params.keyName; - this.returnSingle = params.returnSingle ?? this.returnSingle; - this.zodSchema = params.zodSchema; - } - async _validateResult(result) { - if (this.zodSchema === void 0) return result; - const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result); - if (zodParsedResult.success) return zodParsedResult.data; - else throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error?.issues)}`, JSON.stringify(result, null, 2)); - } - async parsePartialResult(generations) { - const results = await super.parsePartialResult(generations); - const matchingResults = results.filter((result) => result.type === this.keyName); - let returnedValues = matchingResults; - if (!matchingResults.length) return void 0; - if (!this.returnId) returnedValues = matchingResults.map((result) => result.args); - if (this.returnSingle) return returnedValues[0]; - return returnedValues; - } - async parseResult(generations) { - const results = await super.parsePartialResult(generations, false); - const matchingResults = results.filter((result) => result.type === this.keyName); - let returnedValues = matchingResults; - if (!matchingResults.length) return void 0; - if (!this.returnId) returnedValues = matchingResults.map((result) => result.args); - if (this.returnSingle) return this._validateResult(returnedValues[0]); - const toolCallResults = await Promise.all(returnedValues.map((value) => this._validateResult(value))); - return toolCallResults; - } -}; - -//#endregion - -//# sourceMappingURL=json_output_tools_parsers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_tools/index.js - - - -//#region src/output_parsers/openai_tools/index.ts -var openai_tools_exports = {}; -__export(openai_tools_exports, { - JsonOutputKeyToolsParser: () => JsonOutputKeyToolsParser, - JsonOutputToolsParser: () => JsonOutputToolsParser, - convertLangChainToolCallToOpenAI: () => convertLangChainToolCallToOpenAI, - makeInvalidToolCall: () => makeInvalidToolCall, - parseToolCall: () => parseToolCall -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/types/stream.js -//#region src/types/stream.ts -var stream_stream_exports = {}; - -//#endregion - -//# sourceMappingURL=stream.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tracers/run_collector.js - - - -//#region src/tracers/run_collector.ts -var run_collector_exports = {}; -__export(run_collector_exports, { RunCollectorCallbackHandler: () => RunCollectorCallbackHandler }); -/** -* A callback handler that collects traced runs and makes it easy to fetch the traced run object from calls through any langchain object. -* For instance, it makes it easy to fetch the run ID and then do things with that, such as log feedback. -*/ -var RunCollectorCallbackHandler = class extends BaseTracer { - /** The name of the callback handler. */ - name = "run_collector"; - /** The ID of the example. */ - exampleId; - /** An array of traced runs. */ - tracedRuns; - /** - * Creates a new instance of the RunCollectorCallbackHandler class. - * @param exampleId The ID of the example. - */ - constructor({ exampleId } = {}) { - super({ _awaitHandler: true }); - this.exampleId = exampleId; - this.tracedRuns = []; - } - /** - * Persists the given run object. - * @param run The run object to persist. - */ - async persistRun(run) { - const run_ = { ...run }; - run_.reference_example_id = this.exampleId; - this.tracedRuns.push(run_); - } -}; - -//#endregion - -//# sourceMappingURL=run_collector.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/context.js - - -//#region src/utils/context.ts -var context_exports = {}; -__export(context_exports, { context: () => context }); -/** -* A tagged template function for creating formatted strings. -* -* This utility provides a clean, template literal-based API for string formatting -* that can be used for prompts, descriptions, and other text formatting needs. -* -* It automatically handles whitespace normalization and indentation, making it -* ideal for multi-line strings in code. -* -* When using this utility, it will: -* - Strip common leading indentation from all lines -* - Trim leading/trailing whitespace -* - Align multi-line interpolated values to match indentation -* - Support escape sequences: `\\n` (newline), `\\`` (backtick), `\\$` (dollar), `\\{` (brace) -* -* @example -* ```typescript -* import { context } from "@langchain/core/utils/context"; -* -* const role = "agent"; -* const prompt = context` -* You are an ${role}. -* Your task is to help users. -* `; -* // Returns: "You are an agent.\nYour task is to help users." -* ``` -* -* @example -* ```typescript -* // Multi-line interpolated values are aligned -* const items = "- Item 1\n- Item 2\n- Item 3"; -* const message = context` -* Shopping list: -* ${items} -* End of list. -* `; -* // The items will be indented to match " " (4 spaces) -* ``` -*/ -function context(strings, ...values) { - const raw = strings.raw; - let result = ""; - for (let i = 0; i < raw.length; i++) { - const next = raw[i].replace(/\\\n[ \t]*/g, "").replace(/\\`/g, "`").replace(/\\\$/g, "$").replace(/\\\{/g, "{"); - result += next; - if (i < values.length) { - const value = alignValue(values[i], result); - result += typeof value === "string" ? value : JSON.stringify(value); - } - } - result = stripIndent(result); - result = result.trim(); - result = result.replace(/\\n/g, "\n"); - return result; -} -/** -* Adjusts the indentation of a multi-line interpolated value to match the current line. -* -* @param value - The interpolated value -* @param precedingText - The text that comes before this value -* @returns The value with adjusted indentation -*/ -function alignValue(value, precedingText) { - if (typeof value !== "string" || !value.includes("\n")) return value; - const currentLine = precedingText.slice(precedingText.lastIndexOf("\n") + 1); - const indentMatch = currentLine.match(/^(\s+)/); - if (indentMatch) { - const indent = indentMatch[1]; - return value.replace(/\n/g, `\n${indent}`); - } - return value; -} -/** -* Strips common leading indentation from all lines. -* -* @param text - The text to process -* @returns The text with common indentation removed -*/ -function stripIndent(text) { - const lines = text.split("\n"); - let minIndent = null; - for (const line of lines) { - const match = line.match(/^(\s+)\S+/); - if (match) { - const indent = match[1].length; - if (minIndent === null) minIndent = indent; - else minIndent = Math.min(minIndent, indent); - } - } - if (minIndent === null) return text; - return lines.map((line) => line[0] === " " || line[0] === " " ? line.slice(minIndent) : line).join("\n"); -} - -//#endregion - -//# sourceMappingURL=context.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_functions/json_output_functions_parsers.js - - - - - - - -//#region src/output_parsers/openai_functions/json_output_functions_parsers.ts -/** -* Class for parsing the output of an LLM. Can be configured to return -* only the arguments of the function call in the output. -*/ -var OutputFunctionsParser = class extends BaseLLMOutputParser { - static lc_name() { - return "OutputFunctionsParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_functions" - ]; - lc_serializable = true; - argsOnly = true; - constructor(config) { - super(); - this.argsOnly = config?.argsOnly ?? this.argsOnly; - } - /** - * Parses the output and returns a string representation of the function - * call or its arguments. - * @param generations The output of the LLM to parse. - * @returns A string representation of the function call or its arguments. - */ - async parseResult(generations) { - if ("message" in generations[0]) { - const gen = generations[0]; - const functionCall = gen.message.additional_kwargs.function_call; - if (!functionCall) throw new Error(`No function_call in message ${JSON.stringify(generations)}`); - if (!functionCall.arguments) throw new Error(`No arguments in function_call ${JSON.stringify(generations)}`); - if (this.argsOnly) return functionCall.arguments; - return JSON.stringify(functionCall); - } else throw new Error(`No message in generations ${JSON.stringify(generations)}`); - } -}; -/** -* Class for parsing the output of an LLM into a JSON object. Uses an -* instance of `OutputFunctionsParser` to parse the output. -*/ -var JsonOutputFunctionsParser = class extends BaseCumulativeTransformOutputParser { - static lc_name() { - return "JsonOutputFunctionsParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_functions" - ]; - lc_serializable = true; - outputParser; - argsOnly = true; - constructor(config) { - super(config); - this.argsOnly = config?.argsOnly ?? this.argsOnly; - this.outputParser = new OutputFunctionsParser(config); - } - _diff(prev, next) { - if (!next) return void 0; - const ops = compare(prev ?? {}, next); - return ops; - } - async parsePartialResult(generations) { - const generation = generations[0]; - if (!generation.message) return void 0; - const { message } = generation; - const functionCall = message.additional_kwargs.function_call; - if (!functionCall) return void 0; - if (this.argsOnly) return parsePartialJson(functionCall.arguments); - return { - ...functionCall, - arguments: parsePartialJson(functionCall.arguments) - }; - } - /** - * Parses the output and returns a JSON object. If `argsOnly` is true, - * only the arguments of the function call are returned. - * @param generations The output of the LLM to parse. - * @returns A JSON object representation of the function call or its arguments. - */ - async parseResult(generations) { - const result = await this.outputParser.parseResult(generations); - if (!result) throw new Error(`No result from "OutputFunctionsParser" ${JSON.stringify(generations)}`); - return this.parse(result); - } - async parse(text) { - const parsedResult = JSON.parse(text); - if (this.argsOnly) return parsedResult; - parsedResult.arguments = JSON.parse(parsedResult.arguments); - return parsedResult; - } - getFormatInstructions() { - return ""; - } -}; -/** -* Class for parsing the output of an LLM into a JSON object and returning -* a specific attribute. Uses an instance of `JsonOutputFunctionsParser` -* to parse the output. -*/ -var JsonKeyOutputFunctionsParser = class extends BaseLLMOutputParser { - static lc_name() { - return "JsonKeyOutputFunctionsParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "openai_functions" - ]; - lc_serializable = true; - outputParser = new JsonOutputFunctionsParser(); - attrName; - get lc_aliases() { - return { attrName: "key_name" }; - } - constructor(fields) { - super(fields); - this.attrName = fields.attrName; - } - /** - * Parses the output and returns a specific attribute of the parsed JSON - * object. - * @param generations The output of the LLM to parse. - * @returns The value of a specific attribute of the parsed JSON object. - */ - async parseResult(generations) { - const result = await this.outputParser.parseResult(generations); - return result[this.attrName]; - } -}; - -//#endregion - -//# sourceMappingURL=json_output_functions_parsers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/openai_functions/index.js - - - -//#region src/output_parsers/openai_functions/index.ts -var openai_functions_exports = {}; -__export(openai_functions_exports, { - JsonKeyOutputFunctionsParser: () => JsonKeyOutputFunctionsParser, - JsonOutputFunctionsParser: () => JsonOutputFunctionsParser, - OutputFunctionsParser: () => OutputFunctionsParser -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/chunk_array.js - - -//#region src/utils/chunk_array.ts -var chunk_array_exports = {}; -__export(chunk_array_exports, { chunkArray: () => chunkArray }); -const chunkArray = (arr, chunkSize) => arr.reduce((chunks, elem, index) => { - const chunkIndex = Math.floor(index / chunkSize); - const chunk = chunks[chunkIndex] || []; - chunks[chunkIndex] = chunk.concat([elem]); - return chunks; -}, []); - -//#endregion - -//# sourceMappingURL=chunk_array.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/types.js - - - -//#region src/tools/types.ts -/** -* Confirm whether the inputted tool is an instance of `StructuredToolInterface`. -* -* @param {StructuredToolInterface | JSONSchema | undefined} tool The tool to check if it is an instance of `StructuredToolInterface`. -* @returns {tool is StructuredToolInterface} Whether the inputted tool is an instance of `StructuredToolInterface`. -*/ -function isStructuredTool(tool) { - return tool !== void 0 && Array.isArray(tool.lc_namespace); -} -/** -* Confirm whether the inputted tool is an instance of `RunnableToolLike`. -* -* @param {unknown | undefined} tool The tool to check if it is an instance of `RunnableToolLike`. -* @returns {tool is RunnableToolLike} Whether the inputted tool is an instance of `RunnableToolLike`. -*/ -function isRunnableToolLike(tool) { - return tool !== void 0 && Runnable.isRunnable(tool) && "lc_name" in tool.constructor && typeof tool.constructor.lc_name === "function" && tool.constructor.lc_name() === "RunnableToolLike"; -} -/** -* Confirm whether or not the tool contains the necessary properties to be considered a `StructuredToolParams`. -* -* @param {unknown | undefined} tool The object to check if it is a `StructuredToolParams`. -* @returns {tool is StructuredToolParams} Whether the inputted object is a `StructuredToolParams`. -*/ -function isStructuredToolParams(tool) { - return !!tool && typeof tool === "object" && "name" in tool && "schema" in tool && (isInteropZodSchema(tool.schema) || tool.schema != null && typeof tool.schema === "object" && "type" in tool.schema && typeof tool.schema.type === "string" && [ - "null", - "boolean", - "object", - "array", - "number", - "string" - ].includes(tool.schema.type)); -} -/** -* Whether or not the tool is one of StructuredTool, RunnableTool or StructuredToolParams. -* It returns `is StructuredToolParams` since that is the most minimal interface of the three, -* while still containing the necessary properties to be passed to a LLM for tool calling. -* -* @param {unknown | undefined} tool The tool to check if it is a LangChain tool. -* @returns {tool is StructuredToolParams} Whether the inputted tool is a LangChain tool. -*/ -function isLangChainTool(tool) { - return isStructuredToolParams(tool) || isRunnableToolLike(tool) || isStructuredTool(tool); -} - -//#endregion - -//# sourceMappingURL=types.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/function_calling.js - - - - -//#region src/utils/function_calling.ts -var function_calling_exports = {}; -__export(function_calling_exports, { - convertToOpenAIFunction: () => convertToOpenAIFunction, - convertToOpenAITool: () => convertToOpenAITool, - isLangChainTool: () => isLangChainTool, - isRunnableToolLike: () => isRunnableToolLike, - isStructuredTool: () => isStructuredTool, - isStructuredToolParams: () => isStructuredToolParams -}); -/** -* Formats a `StructuredTool` or `RunnableToolLike` instance into a format -* that is compatible with OpenAI function calling. If `StructuredTool` or -* `RunnableToolLike` has a zod schema, the output will be converted into a -* JSON schema, which is then used as the parameters for the OpenAI tool. -* -* @param {StructuredToolInterface | RunnableToolLike} tool The tool to convert to an OpenAI function. -* @returns {FunctionDefinition} The inputted tool in OpenAI function format. -*/ -function convertToOpenAIFunction(tool, fields) { - const fieldsCopy = typeof fields === "number" ? void 0 : fields; - return { - name: tool.name, - description: tool.description, - parameters: toJsonSchema(tool.schema), - ...fieldsCopy?.strict !== void 0 ? { strict: fieldsCopy.strict } : {} - }; -} -/** -* Formats a `StructuredTool` or `RunnableToolLike` instance into a -* format that is compatible with OpenAI tool calling. If `StructuredTool` or -* `RunnableToolLike` has a zod schema, the output will be converted into a -* JSON schema, which is then used as the parameters for the OpenAI tool. -* -* @param {StructuredToolInterface | Record | RunnableToolLike} tool The tool to convert to an OpenAI tool. -* @returns {ToolDefinition} The inputted tool in OpenAI tool format. -*/ -function convertToOpenAITool(tool, fields) { - const fieldsCopy = typeof fields === "number" ? void 0 : fields; - let toolDef; - if (isLangChainTool(tool)) toolDef = { - type: "function", - function: convertToOpenAIFunction(tool) - }; - else toolDef = tool; - if (fieldsCopy?.strict !== void 0) toolDef.function.strict = fieldsCopy.strict; - return toolDef; -} - -//#endregion - -//# sourceMappingURL=function_calling.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/ir.js -//#region src/structured_query/ir.ts -const Operators = { - and: "and", - or: "or", - not: "not" -}; -const Comparators = { - eq: "eq", - ne: "ne", - lt: "lt", - gt: "gt", - lte: "lte", - gte: "gte" -}; -/** -* Abstract class for visiting expressions. Subclasses must implement -* visitOperation, visitComparison, and visitStructuredQuery methods. -*/ -var Visitor = class {}; -/** -* Abstract class representing an expression. Subclasses must implement -* the exprName property and the accept method. -*/ -var Expression = class { - accept(visitor) { - if (this.exprName === "Operation") return visitor.visitOperation(this); - else if (this.exprName === "Comparison") return visitor.visitComparison(this); - else if (this.exprName === "StructuredQuery") return visitor.visitStructuredQuery(this); - else throw new Error("Unknown Expression type"); - } -}; -/** -* Abstract class representing a filter directive. It extends the -* Expression class. -*/ -var FilterDirective = class extends Expression {}; -/** -* Class representing a comparison filter directive. It extends the -* FilterDirective class. -*/ -var Comparison = class extends FilterDirective { - exprName = "Comparison"; - constructor(comparator, attribute, value) { - super(); - this.comparator = comparator; - this.attribute = attribute; - this.value = value; - } -}; -/** -* Class representing an operation filter directive. It extends the -* FilterDirective class. -*/ -var Operation = class extends FilterDirective { - exprName = "Operation"; - constructor(operator, args) { - super(); - this.operator = operator; - this.args = args; - } -}; -/** -* Class representing a structured query expression. It extends the -* Expression class. -*/ -var StructuredQuery = class extends Expression { - exprName = "StructuredQuery"; - constructor(query, filter) { - super(); - this.query = query; - this.filter = filter; - } -}; - -//#endregion - -//# sourceMappingURL=ir.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/utils.js -//#region src/structured_query/utils.ts -/** -* Checks if the provided argument is an object and not an array. -*/ -function isObject(obj) { - return obj && typeof obj === "object" && !Array.isArray(obj); -} -/** -* Checks if a provided filter is empty. The filter can be a function, an -* object, a string, or undefined. -*/ -function isFilterEmpty(filter) { - if (!filter) return true; - if (typeof filter === "string" && filter.length > 0) return false; - if (typeof filter === "function") return false; - return isObject(filter) && Object.keys(filter).length === 0; -} -/** -* Checks if the provided value is an integer. -*/ -function isInt(value) { - if (typeof value === "number") return value % 1 === 0; - else if (typeof value === "string") { - const numberValue = parseInt(value, 10); - return !Number.isNaN(numberValue) && numberValue % 1 === 0 && numberValue.toString() === value; - } - return false; -} -/** -* Checks if the provided value is a floating-point number. -*/ -function isFloat(value) { - if (typeof value === "number") return value % 1 !== 0; - else if (typeof value === "string") { - const numberValue = parseFloat(value); - return !Number.isNaN(numberValue) && numberValue % 1 !== 0 && numberValue.toString() === value; - } - return false; -} -/** -* Checks if the provided value is a string that cannot be parsed into a -* number. -*/ -function isString(value) { - return typeof value === "string" && (Number.isNaN(parseFloat(value)) || parseFloat(value).toString() !== value); -} -/** -* Checks if the provided value is a boolean. -*/ -function isBoolean(value) { - return typeof value === "boolean"; -} -/** -* Casts a value that might be string or number to actual string or number. -* Since LLM might return back an integer/float as a string, we need to cast -* it back to a number, as many vector databases can't handle number as string -* values as a comparator. -*/ -function castValue(input) { - let value; - if (isString(input)) value = input; - else if (isInt(input)) value = parseInt(input, 10); - else if (isFloat(input)) value = parseFloat(input); - else if (isBoolean(input)) value = Boolean(input); - else throw new Error("Unsupported value type"); - return value; -} - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/base.js - - - -//#region src/structured_query/base.ts -/** -* Abstract class that provides a blueprint for creating specific -* translator classes. Defines two abstract methods: formatFunction and -* mergeFilters. -*/ -var BaseTranslator = class extends Visitor {}; -/** -* Class that extends the BaseTranslator class and provides concrete -* implementations for the abstract methods. Also declares three types: -* VisitOperationOutput, VisitComparisonOutput, and -* VisitStructuredQueryOutput, which are used as the return types for the -* visitOperation, visitComparison, and visitStructuredQuery methods -* respectively. -*/ -var BasicTranslator = class extends BaseTranslator { - allowedOperators; - allowedComparators; - constructor(opts) { - super(); - this.allowedOperators = opts?.allowedOperators ?? [Operators.and, Operators.or]; - this.allowedComparators = opts?.allowedComparators ?? [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - } - formatFunction(func) { - if (func in Comparators) { - if (this.allowedComparators.length > 0 && this.allowedComparators.indexOf(func) === -1) throw new Error(`Comparator ${func} not allowed. Allowed comparators: ${this.allowedComparators.join(", ")}`); - } else if (func in Operators) { - if (this.allowedOperators.length > 0 && this.allowedOperators.indexOf(func) === -1) throw new Error(`Operator ${func} not allowed. Allowed operators: ${this.allowedOperators.join(", ")}`); - } else throw new Error("Unknown comparator or operator"); - return `$${func}`; - } - /** - * Visits an operation and returns a result. - * @param operation The operation to visit. - * @returns The result of visiting the operation. - */ - visitOperation(operation) { - const args = operation.args?.map((arg) => arg.accept(this)); - return { [this.formatFunction(operation.operator)]: args }; - } - /** - * Visits a comparison and returns a result. - * @param comparison The comparison to visit. - * @returns The result of visiting the comparison. - */ - visitComparison(comparison) { - return { [comparison.attribute]: { [this.formatFunction(comparison.comparator)]: castValue(comparison.value) } }; - } - /** - * Visits a structured query and returns a result. - * @param query The structured query to visit. - * @returns The result of visiting the structured query. - */ - visitStructuredQuery(query) { - let nextArg = {}; - if (query.filter) nextArg = { filter: query.filter.accept(this) }; - return nextArg; - } - mergeFilters(defaultFilter, generatedFilter, mergeType = "and", forceDefaultFilter = false) { - if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) return void 0; - if (isFilterEmpty(defaultFilter) || mergeType === "replace") { - if (isFilterEmpty(generatedFilter)) return void 0; - return generatedFilter; - } - if (isFilterEmpty(generatedFilter)) { - if (forceDefaultFilter) return defaultFilter; - if (mergeType === "and") return void 0; - return defaultFilter; - } - if (mergeType === "and") return { $and: [defaultFilter, generatedFilter] }; - else if (mergeType === "or") return { $or: [defaultFilter, generatedFilter] }; - else throw new Error("Unknown merge type"); - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/functional.js - - - - -//#region src/structured_query/functional.ts -/** -* A class that extends `BaseTranslator` to translate structured queries -* into functional filters. -* @example -* ```typescript -* const functionalTranslator = new FunctionalTranslator(); -* const relevantDocuments = await functionalTranslator.getRelevantDocuments( -* "Which movies are rated higher than 8.5?", -* ); -* ``` -*/ -var FunctionalTranslator = class extends BaseTranslator { - allowedOperators = [Operators.and, Operators.or]; - allowedComparators = [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - formatFunction() { - throw new Error("Not implemented"); - } - /** - * Returns the allowed comparators for a given data type. - * @param input The input value to get the allowed comparators for. - * @returns An array of allowed comparators for the input data type. - */ - getAllowedComparatorsForType(inputType) { - switch (inputType) { - case "string": return [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - case "number": return [ - Comparators.eq, - Comparators.ne, - Comparators.gt, - Comparators.gte, - Comparators.lt, - Comparators.lte - ]; - case "boolean": return [Comparators.eq, Comparators.ne]; - default: throw new Error(`Unsupported data type: ${inputType}`); - } - } - /** - * Returns a function that performs a comparison based on the provided - * comparator. - * @param comparator The comparator to base the comparison function on. - * @returns A function that takes two arguments and returns a boolean based on the comparison. - */ - getComparatorFunction(comparator) { - switch (comparator) { - case Comparators.eq: return (a, b) => a === b; - case Comparators.ne: return (a, b) => a !== b; - case Comparators.gt: return (a, b) => a > b; - case Comparators.gte: return (a, b) => a >= b; - case Comparators.lt: return (a, b) => a < b; - case Comparators.lte: return (a, b) => a <= b; - default: throw new Error("Unknown comparator"); - } - } - /** - * Returns a function that performs an operation based on the provided - * operator. - * @param operator The operator to base the operation function on. - * @returns A function that takes two boolean arguments and returns a boolean based on the operation. - */ - getOperatorFunction(operator) { - switch (operator) { - case Operators.and: return (a, b) => a && b; - case Operators.or: return (a, b) => a || b; - default: throw new Error("Unknown operator"); - } - } - /** - * Visits the operation part of a structured query and translates it into - * a functional filter. - * @param operation The operation part of a structured query. - * @returns A function that takes a `Document` as an argument and returns a boolean based on the operation. - */ - visitOperation(operation) { - const { operator, args } = operation; - if (this.allowedOperators.includes(operator)) { - const operatorFunction = this.getOperatorFunction(operator); - return (document) => { - if (!args) return true; - return args.reduce((acc, arg) => { - const result = arg.accept(this); - if (typeof result === "function") return operatorFunction(acc, result(document)); - else throw new Error("Filter is not a function"); - }, true); - }; - } else throw new Error("Operator not allowed"); - } - /** - * Visits the comparison part of a structured query and translates it into - * a functional filter. - * @param comparison The comparison part of a structured query. - * @returns A function that takes a `Document` as an argument and returns a boolean based on the comparison. - */ - visitComparison(comparison) { - const { comparator, attribute, value } = comparison; - const undefinedTrue = [Comparators.ne]; - if (this.allowedComparators.includes(comparator)) { - if (!this.getAllowedComparatorsForType(typeof value).includes(comparator)) throw new Error(`'${comparator}' comparator not allowed to be used with ${typeof value}`); - const comparatorFunction = this.getComparatorFunction(comparator); - return (document) => { - const documentValue = document.metadata[attribute]; - if (documentValue === void 0) { - if (undefinedTrue.includes(comparator)) return true; - return false; - } - return comparatorFunction(documentValue, castValue(value)); - }; - } else throw new Error("Comparator not allowed"); - } - /** - * Visits a structured query and translates it into a functional filter. - * @param query The structured query to translate. - * @returns An object containing a `filter` property, which is a function that takes a `Document` as an argument and returns a boolean based on the structured query. - */ - visitStructuredQuery(query) { - if (!query.filter) return {}; - const filterFunction = query.filter?.accept(this); - if (typeof filterFunction !== "function") throw new Error("Structured query filter is not a function"); - return { filter: filterFunction }; - } - /** - * Merges two filters into one, based on the specified merge type. - * @param defaultFilter The default filter function. - * @param generatedFilter The generated filter function. - * @param mergeType The type of merge to perform. Can be 'and', 'or', or 'replace'. Default is 'and'. - * @returns A function that takes a `Document` as an argument and returns a boolean based on the merged filters, or `undefined` if both filters are empty. - */ - mergeFilters(defaultFilter, generatedFilter, mergeType = "and") { - if (isFilterEmpty(defaultFilter) && isFilterEmpty(generatedFilter)) return void 0; - if (isFilterEmpty(defaultFilter) || mergeType === "replace") { - if (isFilterEmpty(generatedFilter)) return void 0; - return generatedFilter; - } - if (isFilterEmpty(generatedFilter)) { - if (mergeType === "and") return void 0; - return defaultFilter; - } - if (mergeType === "and") return (document) => defaultFilter(document) && generatedFilter(document); - else if (mergeType === "or") return (document) => defaultFilter(document) || generatedFilter(document); - else throw new Error("Unknown merge type"); - } -}; - -//#endregion - -//# sourceMappingURL=functional.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/structured_query/index.js - - - - - - -//#region src/structured_query/index.ts -var structured_query_exports = {}; -__export(structured_query_exports, { - BaseTranslator: () => BaseTranslator, - BasicTranslator: () => BasicTranslator, - Comparators: () => Comparators, - Comparison: () => Comparison, - Expression: () => Expression, - FilterDirective: () => FilterDirective, - FunctionalTranslator: () => FunctionalTranslator, - Operation: () => Operation, - Operators: () => Operators, - StructuredQuery: () => StructuredQuery, - Visitor: () => Visitor, - castValue: () => castValue, - isBoolean: () => isBoolean, - isFilterEmpty: () => isFilterEmpty, - isFloat: () => isFloat, - isInt: () => isInt, - isObject: () => isObject, - isString: () => isString -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/checks.js - - -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/iso.js - - -const ZodISODateTime = /*@__PURE__*/ $constructor("ZodISODateTime", (inst, def) => { - $ZodISODateTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function iso_datetime(params) { - return _isoDateTime(ZodISODateTime, params); -} -const ZodISODate = /*@__PURE__*/ $constructor("ZodISODate", (inst, def) => { - $ZodISODate.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function iso_date(params) { - return _isoDate(ZodISODate, params); -} -const ZodISOTime = /*@__PURE__*/ $constructor("ZodISOTime", (inst, def) => { - $ZodISOTime.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function iso_time(params) { - return _isoTime(ZodISOTime, params); -} -const ZodISODuration = /*@__PURE__*/ $constructor("ZodISODuration", (inst, def) => { - $ZodISODuration.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function iso_duration(params) { - return _isoDuration(ZodISODuration, params); -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/errors.js - - - -const errors_initializer = (inst, issues) => { - $ZodError.init(inst, issues); - inst.name = "ZodError"; - Object.defineProperties(inst, { - format: { - value: (mapper) => formatError(inst, mapper), - // enumerable: false, - }, - flatten: { - value: (mapper) => flattenError(inst, mapper), - // enumerable: false, - }, - addIssue: { - value: (issue) => { - inst.issues.push(issue); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - }, - // enumerable: false, - }, - addIssues: { - value: (issues) => { - inst.issues.push(...issues); - inst.message = JSON.stringify(inst.issues, jsonStringifyReplacer, 2); - }, - // enumerable: false, - }, - isEmpty: { - get() { - return inst.issues.length === 0; - }, - // enumerable: false, - }, - }); - // Object.defineProperty(inst, "isEmpty", { - // get() { - // return inst.issues.length === 0; - // }, - // }); -}; -const errors_ZodError = $constructor("ZodError", errors_initializer); -const ZodRealError = $constructor("ZodError", errors_initializer, { - Parent: Error, -}); -// /** @deprecated Use `z.core.$ZodErrorMapCtx` instead. */ -// export type ErrorMapCtx = core.$ZodErrorMapCtx; - -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/parse.js - - -const classic_parse_parse = /* @__PURE__ */ _parse(ZodRealError); -const parse_parseAsync = /* @__PURE__ */ _parseAsync(ZodRealError); -const parse_safeParse = /* @__PURE__ */ _safeParse(ZodRealError); -const parse_safeParseAsync = /* @__PURE__ */ _safeParseAsync(ZodRealError); -// Codec functions -const parse_encode = /* @__PURE__ */ _encode(ZodRealError); -const parse_decode = /* @__PURE__ */ _decode(ZodRealError); -const parse_encodeAsync = /* @__PURE__ */ _encodeAsync(ZodRealError); -const parse_decodeAsync = /* @__PURE__ */ _decodeAsync(ZodRealError); -const parse_safeEncode = /* @__PURE__ */ _safeEncode(ZodRealError); -const parse_safeDecode = /* @__PURE__ */ _safeDecode(ZodRealError); -const parse_safeEncodeAsync = /* @__PURE__ */ _safeEncodeAsync(ZodRealError); -const parse_safeDecodeAsync = /* @__PURE__ */ _safeDecodeAsync(ZodRealError); - -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/schemas.js - - - - - - - -const schemas_ZodType = /*@__PURE__*/ $constructor("ZodType", (inst, def) => { - $ZodType.init(inst, def); - Object.assign(inst["~standard"], { - jsonSchema: { - input: createStandardJSONSchemaMethod(inst, "input"), - output: createStandardJSONSchemaMethod(inst, "output"), - }, - }); - inst.toJSONSchema = createToJSONSchemaMethod(inst, {}); - inst.def = def; - inst.type = def.type; - Object.defineProperty(inst, "_def", { value: def }); - // base methods - inst.check = (...checks) => { - return inst.clone(mergeDefs(def, { - checks: [ - ...(def.checks ?? []), - ...checks.map((ch) => typeof ch === "function" ? { _zod: { check: ch, def: { check: "custom" }, onattach: [] } } : ch), - ], - })); - }; - inst.clone = (def, params) => clone(inst, def, params); - inst.brand = () => inst; - inst.register = ((reg, meta) => { - reg.add(inst, meta); - return inst; - }); - // parsing - inst.parse = (data, params) => classic_parse_parse(inst, data, params, { callee: inst.parse }); - inst.safeParse = (data, params) => parse_safeParse(inst, data, params); - inst.parseAsync = async (data, params) => parse_parseAsync(inst, data, params, { callee: inst.parseAsync }); - inst.safeParseAsync = async (data, params) => parse_safeParseAsync(inst, data, params); - inst.spa = inst.safeParseAsync; - // encoding/decoding - inst.encode = (data, params) => parse_encode(inst, data, params); - inst.decode = (data, params) => parse_decode(inst, data, params); - inst.encodeAsync = async (data, params) => parse_encodeAsync(inst, data, params); - inst.decodeAsync = async (data, params) => parse_decodeAsync(inst, data, params); - inst.safeEncode = (data, params) => parse_safeEncode(inst, data, params); - inst.safeDecode = (data, params) => parse_safeDecode(inst, data, params); - inst.safeEncodeAsync = async (data, params) => parse_safeEncodeAsync(inst, data, params); - inst.safeDecodeAsync = async (data, params) => parse_safeDecodeAsync(inst, data, params); - // refinements - inst.refine = (check, params) => inst.check(refine(check, params)); - inst.superRefine = (refinement) => inst.check(superRefine(refinement)); - inst.overwrite = (fn) => inst.check(_overwrite(fn)); - // wrappers - inst.optional = () => optional(inst); - inst.nullable = () => nullable(inst); - inst.nullish = () => optional(nullable(inst)); - inst.nonoptional = (params) => nonoptional(inst, params); - inst.array = () => array(inst); - inst.or = (arg) => union([inst, arg]); - inst.and = (arg) => intersection(inst, arg); - inst.transform = (tx) => pipe(inst, transform(tx)); - inst.default = (def) => schemas_default(inst, def); - inst.prefault = (def) => prefault(inst, def); - // inst.coalesce = (def, params) => coalesce(inst, def, params); - inst.catch = (params) => schemas_catch(inst, params); - inst.pipe = (target) => pipe(inst, target); - inst.readonly = () => readonly(inst); - // meta - inst.describe = (description) => { - const cl = inst.clone(); - globalRegistry.add(cl, { description }); - return cl; - }; - Object.defineProperty(inst, "description", { - get() { - return globalRegistry.get(inst)?.description; - }, - configurable: true, - }); - inst.meta = (...args) => { - if (args.length === 0) { - return globalRegistry.get(inst); - } - const cl = inst.clone(); - globalRegistry.add(cl, args[0]); - return cl; - }; - // helpers - inst.isOptional = () => inst.safeParse(undefined).success; - inst.isNullable = () => inst.safeParse(null).success; - return inst; -}); -/** @internal */ -const _ZodString = /*@__PURE__*/ $constructor("_ZodString", (inst, def) => { - $ZodString.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => stringProcessor(inst, ctx, json, params); - const bag = inst._zod.bag; - inst.format = bag.format ?? null; - inst.minLength = bag.minimum ?? null; - inst.maxLength = bag.maximum ?? null; - // validations - inst.regex = (...args) => inst.check(_regex(...args)); - inst.includes = (...args) => inst.check(_includes(...args)); - inst.startsWith = (...args) => inst.check(_startsWith(...args)); - inst.endsWith = (...args) => inst.check(_endsWith(...args)); - inst.min = (...args) => inst.check(_minLength(...args)); - inst.max = (...args) => inst.check(_maxLength(...args)); - inst.length = (...args) => inst.check(_length(...args)); - inst.nonempty = (...args) => inst.check(_minLength(1, ...args)); - inst.lowercase = (params) => inst.check(_lowercase(params)); - inst.uppercase = (params) => inst.check(_uppercase(params)); - // transforms - inst.trim = () => inst.check(_trim()); - inst.normalize = (...args) => inst.check(_normalize(...args)); - inst.toLowerCase = () => inst.check(_toLowerCase()); - inst.toUpperCase = () => inst.check(_toUpperCase()); - inst.slugify = () => inst.check(_slugify()); -}); -const schemas_ZodString = /*@__PURE__*/ $constructor("ZodString", (inst, def) => { - $ZodString.init(inst, def); - _ZodString.init(inst, def); - inst.email = (params) => inst.check(_email(ZodEmail, params)); - inst.url = (params) => inst.check(_url(ZodURL, params)); - inst.jwt = (params) => inst.check(_jwt(ZodJWT, params)); - inst.emoji = (params) => inst.check(api_emoji(ZodEmoji, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.uuid = (params) => inst.check(_uuid(ZodUUID, params)); - inst.uuidv4 = (params) => inst.check(_uuidv4(ZodUUID, params)); - inst.uuidv6 = (params) => inst.check(_uuidv6(ZodUUID, params)); - inst.uuidv7 = (params) => inst.check(_uuidv7(ZodUUID, params)); - inst.nanoid = (params) => inst.check(_nanoid(ZodNanoID, params)); - inst.guid = (params) => inst.check(_guid(ZodGUID, params)); - inst.cuid = (params) => inst.check(_cuid(ZodCUID, params)); - inst.cuid2 = (params) => inst.check(_cuid2(ZodCUID2, params)); - inst.ulid = (params) => inst.check(_ulid(ZodULID, params)); - inst.base64 = (params) => inst.check(_base64(ZodBase64, params)); - inst.base64url = (params) => inst.check(_base64url(ZodBase64URL, params)); - inst.xid = (params) => inst.check(_xid(ZodXID, params)); - inst.ksuid = (params) => inst.check(_ksuid(ZodKSUID, params)); - inst.ipv4 = (params) => inst.check(_ipv4(ZodIPv4, params)); - inst.ipv6 = (params) => inst.check(_ipv6(ZodIPv6, params)); - inst.cidrv4 = (params) => inst.check(_cidrv4(ZodCIDRv4, params)); - inst.cidrv6 = (params) => inst.check(_cidrv6(ZodCIDRv6, params)); - inst.e164 = (params) => inst.check(_e164(ZodE164, params)); - // iso - inst.datetime = (params) => inst.check(iso_datetime(params)); - inst.date = (params) => inst.check(iso_date(params)); - inst.time = (params) => inst.check(iso_time(params)); - inst.duration = (params) => inst.check(iso_duration(params)); -}); -function schemas_string(params) { - return _string(schemas_ZodString, params); -} -const ZodStringFormat = /*@__PURE__*/ $constructor("ZodStringFormat", (inst, def) => { - $ZodStringFormat.init(inst, def); - _ZodString.init(inst, def); -}); -const ZodEmail = /*@__PURE__*/ $constructor("ZodEmail", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmail.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_email(params) { - return _email(ZodEmail, params); -} -const ZodGUID = /*@__PURE__*/ $constructor("ZodGUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodGUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_guid(params) { - return _guid(ZodGUID, params); -} -const ZodUUID = /*@__PURE__*/ $constructor("ZodUUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodUUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_uuid(params) { - return _uuid(ZodUUID, params); -} -function uuidv4(params) { - return _uuidv4(ZodUUID, params); -} -// ZodUUIDv6 -function uuidv6(params) { - return _uuidv6(ZodUUID, params); -} -// ZodUUIDv7 -function schemas_uuidv7(params) { - return _uuidv7(ZodUUID, params); -} -const ZodURL = /*@__PURE__*/ $constructor("ZodURL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodURL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function url(params) { - return _url(ZodURL, params); -} -function httpUrl(params) { - return _url(ZodURL, { - protocol: /^https?$/, - hostname: domain, - ...normalizeParams(params), - }); -} -const ZodEmoji = /*@__PURE__*/ $constructor("ZodEmoji", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodEmoji.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_emoji(params) { - return api_emoji(ZodEmoji, params); -} -const ZodNanoID = /*@__PURE__*/ $constructor("ZodNanoID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodNanoID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_nanoid(params) { - return _nanoid(ZodNanoID, params); -} -const ZodCUID = /*@__PURE__*/ $constructor("ZodCUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cuid(params) { - return _cuid(ZodCUID, params); -} -const ZodCUID2 = /*@__PURE__*/ $constructor("ZodCUID2", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCUID2.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cuid2(params) { - return _cuid2(ZodCUID2, params); -} -const ZodULID = /*@__PURE__*/ $constructor("ZodULID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodULID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ulid(params) { - return _ulid(ZodULID, params); -} -const ZodXID = /*@__PURE__*/ $constructor("ZodXID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodXID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_xid(params) { - return _xid(ZodXID, params); -} -const ZodKSUID = /*@__PURE__*/ $constructor("ZodKSUID", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodKSUID.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ksuid(params) { - return _ksuid(ZodKSUID, params); -} -const ZodIPv4 = /*@__PURE__*/ $constructor("ZodIPv4", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv4(params) { - return _ipv4(ZodIPv4, params); -} -const ZodMAC = /*@__PURE__*/ $constructor("ZodMAC", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodMAC.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_mac(params) { - return _mac(ZodMAC, params); -} -const ZodIPv6 = /*@__PURE__*/ $constructor("ZodIPv6", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodIPv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_ipv6(params) { - return _ipv6(ZodIPv6, params); -} -const ZodCIDRv4 = /*@__PURE__*/ $constructor("ZodCIDRv4", (inst, def) => { - $ZodCIDRv4.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv4(params) { - return _cidrv4(ZodCIDRv4, params); -} -const ZodCIDRv6 = /*@__PURE__*/ $constructor("ZodCIDRv6", (inst, def) => { - $ZodCIDRv6.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_cidrv6(params) { - return _cidrv6(ZodCIDRv6, params); -} -const ZodBase64 = /*@__PURE__*/ $constructor("ZodBase64", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64(params) { - return _base64(ZodBase64, params); -} -const ZodBase64URL = /*@__PURE__*/ $constructor("ZodBase64URL", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodBase64URL.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_base64url(params) { - return _base64url(ZodBase64URL, params); -} -const ZodE164 = /*@__PURE__*/ $constructor("ZodE164", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodE164.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function schemas_e164(params) { - return _e164(ZodE164, params); -} -const ZodJWT = /*@__PURE__*/ $constructor("ZodJWT", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodJWT.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function jwt(params) { - return _jwt(ZodJWT, params); -} -const ZodCustomStringFormat = /*@__PURE__*/ $constructor("ZodCustomStringFormat", (inst, def) => { - // ZodStringFormat.init(inst, def); - $ZodCustomStringFormat.init(inst, def); - ZodStringFormat.init(inst, def); -}); -function stringFormat(format, fnOrRegex, _params = {}) { - return _stringFormat(ZodCustomStringFormat, format, fnOrRegex, _params); -} -function schemas_hostname(_params) { - return _stringFormat(ZodCustomStringFormat, "hostname", hostname, _params); -} -function schemas_hex(_params) { - return _stringFormat(ZodCustomStringFormat, "hex", hex, _params); -} -function hash(alg, params) { - const enc = params?.enc ?? "hex"; - const format = `${alg}_${enc}`; - const regex = regexes_namespaceObject[format]; - if (!regex) - throw new Error(`Unrecognized hash format: ${format}`); - return _stringFormat(ZodCustomStringFormat, format, regex, params); -} -const schemas_ZodNumber = /*@__PURE__*/ $constructor("ZodNumber", (inst, def) => { - $ZodNumber.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => numberProcessor(inst, ctx, json, params); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.int = (params) => inst.check(schemas_int(params)); - inst.safe = (params) => inst.check(schemas_int(params)); - inst.positive = (params) => inst.check(_gt(0, params)); - inst.nonnegative = (params) => inst.check(_gte(0, params)); - inst.negative = (params) => inst.check(_lt(0, params)); - inst.nonpositive = (params) => inst.check(_lte(0, params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - inst.step = (value, params) => inst.check(_multipleOf(value, params)); - // inst.finite = (params) => inst.check(core.finite(params)); - inst.finite = () => inst; - const bag = inst._zod.bag; - inst.minValue = - Math.max(bag.minimum ?? Number.NEGATIVE_INFINITY, bag.exclusiveMinimum ?? Number.NEGATIVE_INFINITY) ?? null; - inst.maxValue = - Math.min(bag.maximum ?? Number.POSITIVE_INFINITY, bag.exclusiveMaximum ?? Number.POSITIVE_INFINITY) ?? null; - inst.isInt = (bag.format ?? "").includes("int") || Number.isSafeInteger(bag.multipleOf ?? 0.5); - inst.isFinite = true; - inst.format = bag.format ?? null; -}); -function schemas_number(params) { - return _number(schemas_ZodNumber, params); -} -const ZodNumberFormat = /*@__PURE__*/ $constructor("ZodNumberFormat", (inst, def) => { - $ZodNumberFormat.init(inst, def); - schemas_ZodNumber.init(inst, def); -}); -function schemas_int(params) { - return _int(ZodNumberFormat, params); -} -function float32(params) { - return _float32(ZodNumberFormat, params); -} -function float64(params) { - return _float64(ZodNumberFormat, params); -} -function int32(params) { - return _int32(ZodNumberFormat, params); -} -function uint32(params) { - return _uint32(ZodNumberFormat, params); -} -const schemas_ZodBoolean = /*@__PURE__*/ $constructor("ZodBoolean", (inst, def) => { - $ZodBoolean.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => booleanProcessor(inst, ctx, json, params); -}); -function schemas_boolean(params) { - return _boolean(schemas_ZodBoolean, params); -} -const schemas_ZodBigInt = /*@__PURE__*/ $constructor("ZodBigInt", (inst, def) => { - $ZodBigInt.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => bigintProcessor(inst, ctx, json, params); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.gt = (value, params) => inst.check(_gt(value, params)); - inst.gte = (value, params) => inst.check(_gte(value, params)); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.lt = (value, params) => inst.check(_lt(value, params)); - inst.lte = (value, params) => inst.check(_lte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - inst.positive = (params) => inst.check(_gt(BigInt(0), params)); - inst.negative = (params) => inst.check(_lt(BigInt(0), params)); - inst.nonpositive = (params) => inst.check(_lte(BigInt(0), params)); - inst.nonnegative = (params) => inst.check(_gte(BigInt(0), params)); - inst.multipleOf = (value, params) => inst.check(_multipleOf(value, params)); - const bag = inst._zod.bag; - inst.minValue = bag.minimum ?? null; - inst.maxValue = bag.maximum ?? null; - inst.format = bag.format ?? null; -}); -function schemas_bigint(params) { - return _bigint(schemas_ZodBigInt, params); -} -const ZodBigIntFormat = /*@__PURE__*/ $constructor("ZodBigIntFormat", (inst, def) => { - $ZodBigIntFormat.init(inst, def); - schemas_ZodBigInt.init(inst, def); -}); -// int64 -function int64(params) { - return _int64(ZodBigIntFormat, params); -} -// uint64 -function uint64(params) { - return _uint64(ZodBigIntFormat, params); -} -const schemas_ZodSymbol = /*@__PURE__*/ $constructor("ZodSymbol", (inst, def) => { - $ZodSymbol.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => symbolProcessor(inst, ctx, json, params); -}); -function symbol(params) { - return _symbol(schemas_ZodSymbol, params); -} -const schemas_ZodUndefined = /*@__PURE__*/ $constructor("ZodUndefined", (inst, def) => { - $ZodUndefined.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => undefinedProcessor(inst, ctx, json, params); -}); -function schemas_undefined(params) { - return api_undefined(schemas_ZodUndefined, params); -} - -const schemas_ZodNull = /*@__PURE__*/ $constructor("ZodNull", (inst, def) => { - $ZodNull.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullProcessor(inst, ctx, json, params); -}); -function schemas_null(params) { - return api_null(schemas_ZodNull, params); -} - -const schemas_ZodAny = /*@__PURE__*/ $constructor("ZodAny", (inst, def) => { - $ZodAny.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => anyProcessor(inst, ctx, json, params); -}); -function any() { - return _any(schemas_ZodAny); -} -const schemas_ZodUnknown = /*@__PURE__*/ $constructor("ZodUnknown", (inst, def) => { - $ZodUnknown.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unknownProcessor(inst, ctx, json, params); -}); -function unknown() { - return _unknown(schemas_ZodUnknown); -} -const schemas_ZodNever = /*@__PURE__*/ $constructor("ZodNever", (inst, def) => { - $ZodNever.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => neverProcessor(inst, ctx, json, params); -}); -function schemas_never(params) { - return _never(schemas_ZodNever, params); -} -const schemas_ZodVoid = /*@__PURE__*/ $constructor("ZodVoid", (inst, def) => { - $ZodVoid.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => voidProcessor(inst, ctx, json, params); -}); -function schemas_void(params) { - return _void(schemas_ZodVoid, params); -} - -const schemas_ZodDate = /*@__PURE__*/ $constructor("ZodDate", (inst, def) => { - $ZodDate.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => dateProcessor(inst, ctx, json, params); - inst.min = (value, params) => inst.check(_gte(value, params)); - inst.max = (value, params) => inst.check(_lte(value, params)); - const c = inst._zod.bag; - inst.minDate = c.minimum ? new Date(c.minimum) : null; - inst.maxDate = c.maximum ? new Date(c.maximum) : null; -}); -function schemas_date(params) { - return _date(schemas_ZodDate, params); -} -const schemas_ZodArray = /*@__PURE__*/ $constructor("ZodArray", (inst, def) => { - $ZodArray.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => arrayProcessor(inst, ctx, json, params); - inst.element = def.element; - inst.min = (minLength, params) => inst.check(_minLength(minLength, params)); - inst.nonempty = (params) => inst.check(_minLength(1, params)); - inst.max = (maxLength, params) => inst.check(_maxLength(maxLength, params)); - inst.length = (len, params) => inst.check(_length(len, params)); - inst.unwrap = () => inst.element; -}); -function array(element, params) { - return _array(schemas_ZodArray, element, params); -} -// .keyof -function keyof(schema) { - const shape = schema._zod.def.shape; - return schemas_enum(Object.keys(shape)); -} -const schemas_ZodObject = /*@__PURE__*/ $constructor("ZodObject", (inst, def) => { - $ZodObjectJIT.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => objectProcessor(inst, ctx, json, params); - defineLazy(inst, "shape", () => { - return def.shape; - }); - inst.keyof = () => schemas_enum(Object.keys(inst._zod.def.shape)); - inst.catchall = (catchall) => inst.clone({ ...inst._zod.def, catchall: catchall }); - inst.passthrough = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.loose = () => inst.clone({ ...inst._zod.def, catchall: unknown() }); - inst.strict = () => inst.clone({ ...inst._zod.def, catchall: schemas_never() }); - inst.strip = () => inst.clone({ ...inst._zod.def, catchall: undefined }); - inst.extend = (incoming) => { - return extend(inst, incoming); - }; - inst.safeExtend = (incoming) => { - return safeExtend(inst, incoming); - }; - inst.merge = (other) => merge(inst, other); - inst.pick = (mask) => pick(inst, mask); - inst.omit = (mask) => omit(inst, mask); - inst.partial = (...args) => partial(schemas_ZodOptional, inst, args[0]); - inst.required = (...args) => required(ZodNonOptional, inst, args[0]); -}); -function object(shape, params) { - const def = { - type: "object", - shape: shape ?? {}, - ...normalizeParams(params), - }; - return new schemas_ZodObject(def); -} -// strictObject -function strictObject(shape, params) { - return new schemas_ZodObject({ - type: "object", - shape, - catchall: schemas_never(), - ...normalizeParams(params), - }); -} -// looseObject -function looseObject(shape, params) { - return new schemas_ZodObject({ - type: "object", - shape, - catchall: unknown(), - ...normalizeParams(params), - }); -} -const schemas_ZodUnion = /*@__PURE__*/ $constructor("ZodUnion", (inst, def) => { - $ZodUnion.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -function union(options, params) { - return new schemas_ZodUnion({ - type: "union", - options: options, - ...normalizeParams(params), - }); -} -const ZodXor = /*@__PURE__*/ $constructor("ZodXor", (inst, def) => { - schemas_ZodUnion.init(inst, def); - $ZodXor.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => unionProcessor(inst, ctx, json, params); - inst.options = def.options; -}); -/** Creates an exclusive union (XOR) where exactly one option must match. - * Unlike regular unions that succeed when any option matches, xor fails if - * zero or more than one option matches the input. */ -function xor(options, params) { - return new ZodXor({ - type: "union", - options: options, - inclusive: false, - ...normalizeParams(params), - }); -} -const schemas_ZodDiscriminatedUnion = /*@__PURE__*/ $constructor("ZodDiscriminatedUnion", (inst, def) => { - schemas_ZodUnion.init(inst, def); - $ZodDiscriminatedUnion.init(inst, def); -}); -function discriminatedUnion(discriminator, options, params) { - // const [options, params] = args; - return new schemas_ZodDiscriminatedUnion({ - type: "union", - options, - discriminator, - ...normalizeParams(params), - }); -} -const schemas_ZodIntersection = /*@__PURE__*/ $constructor("ZodIntersection", (inst, def) => { - $ZodIntersection.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => intersectionProcessor(inst, ctx, json, params); -}); -function intersection(left, right) { - return new schemas_ZodIntersection({ - type: "intersection", - left: left, - right: right, - }); -} -const schemas_ZodTuple = /*@__PURE__*/ $constructor("ZodTuple", (inst, def) => { - $ZodTuple.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => tupleProcessor(inst, ctx, json, params); - inst.rest = (rest) => inst.clone({ - ...inst._zod.def, - rest: rest, - }); -}); -function tuple(items, _paramsOrRest, _params) { - const hasRest = _paramsOrRest instanceof $ZodType; - const params = hasRest ? _params : _paramsOrRest; - const rest = hasRest ? _paramsOrRest : null; - return new schemas_ZodTuple({ - type: "tuple", - items: items, - rest, - ...normalizeParams(params), - }); -} -const schemas_ZodRecord = /*@__PURE__*/ $constructor("ZodRecord", (inst, def) => { - $ZodRecord.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => recordProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function record(keyType, valueType, params) { - return new schemas_ZodRecord({ - type: "record", - keyType, - valueType: valueType, - ...normalizeParams(params), - }); -} -// type alksjf = core.output; -function partialRecord(keyType, valueType, params) { - const k = clone(keyType); - k._zod.values = undefined; - return new schemas_ZodRecord({ - type: "record", - keyType: k, - valueType: valueType, - ...normalizeParams(params), - }); -} -function looseRecord(keyType, valueType, params) { - return new schemas_ZodRecord({ - type: "record", - keyType, - valueType: valueType, - mode: "loose", - ...normalizeParams(params), - }); -} -const schemas_ZodMap = /*@__PURE__*/ $constructor("ZodMap", (inst, def) => { - $ZodMap.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => mapProcessor(inst, ctx, json, params); - inst.keyType = def.keyType; - inst.valueType = def.valueType; -}); -function map(keyType, valueType, params) { - return new schemas_ZodMap({ - type: "map", - keyType: keyType, - valueType: valueType, - ...normalizeParams(params), - }); -} -const schemas_ZodSet = /*@__PURE__*/ $constructor("ZodSet", (inst, def) => { - $ZodSet.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => setProcessor(inst, ctx, json, params); - inst.min = (...args) => inst.check(_minSize(...args)); - inst.nonempty = (params) => inst.check(_minSize(1, params)); - inst.max = (...args) => inst.check(_maxSize(...args)); - inst.size = (...args) => inst.check(_size(...args)); -}); -function set(valueType, params) { - return new schemas_ZodSet({ - type: "set", - valueType: valueType, - ...normalizeParams(params), - }); -} -const schemas_ZodEnum = /*@__PURE__*/ $constructor("ZodEnum", (inst, def) => { - $ZodEnum.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => enumProcessor(inst, ctx, json, params); - inst.enum = def.entries; - inst.options = Object.values(def.entries); - const keys = new Set(Object.keys(def.entries)); - inst.extract = (values, params) => { - const newEntries = {}; - for (const value of values) { - if (keys.has(value)) { - newEntries[value] = def.entries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new schemas_ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; - inst.exclude = (values, params) => { - const newEntries = { ...def.entries }; - for (const value of values) { - if (keys.has(value)) { - delete newEntries[value]; - } - else - throw new Error(`Key ${value} not found in enum`); - } - return new schemas_ZodEnum({ - ...def, - checks: [], - ...normalizeParams(params), - entries: newEntries, - }); - }; -}); -function schemas_enum(values, params) { - const entries = Array.isArray(values) ? Object.fromEntries(values.map((v) => [v, v])) : values; - return new schemas_ZodEnum({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} - -/** @deprecated This API has been merged into `z.enum()`. Use `z.enum()` instead. - * - * ```ts - * enum Colors { red, green, blue } - * z.enum(Colors); - * ``` - */ -function nativeEnum(entries, params) { - return new schemas_ZodEnum({ - type: "enum", - entries, - ...normalizeParams(params), - }); -} -const schemas_ZodLiteral = /*@__PURE__*/ $constructor("ZodLiteral", (inst, def) => { - $ZodLiteral.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => literalProcessor(inst, ctx, json, params); - inst.values = new Set(def.values); - Object.defineProperty(inst, "value", { - get() { - if (def.values.length > 1) { - throw new Error("This schema contains multiple valid literal values. Use `.values` instead."); - } - return def.values[0]; - }, - }); -}); -function literal(value, params) { - return new schemas_ZodLiteral({ - type: "literal", - values: Array.isArray(value) ? value : [value], - ...normalizeParams(params), - }); -} -const ZodFile = /*@__PURE__*/ $constructor("ZodFile", (inst, def) => { - $ZodFile.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => fileProcessor(inst, ctx, json, params); - inst.min = (size, params) => inst.check(_minSize(size, params)); - inst.max = (size, params) => inst.check(_maxSize(size, params)); - inst.mime = (types, params) => inst.check(_mime(Array.isArray(types) ? types : [types], params)); -}); -function file(params) { - return _file(ZodFile, params); -} -const ZodTransform = /*@__PURE__*/ $constructor("ZodTransform", (inst, def) => { - $ZodTransform.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => transformProcessor(inst, ctx, json, params); - inst._zod.parse = (payload, _ctx) => { - if (_ctx.direction === "backward") { - throw new $ZodEncodeError(inst.constructor.name); - } - payload.addIssue = (issue) => { - if (typeof issue === "string") { - payload.issues.push(util_issue(issue, payload.value, def)); - } - else { - // for Zod 3 backwards compatibility - const _issue = issue; - if (_issue.fatal) - _issue.continue = false; - _issue.code ?? (_issue.code = "custom"); - _issue.input ?? (_issue.input = payload.value); - _issue.inst ?? (_issue.inst = inst); - // _issue.continue ??= true; - payload.issues.push(util_issue(_issue)); - } - }; - const output = def.transform(payload.value, payload); - if (output instanceof Promise) { - return output.then((output) => { - payload.value = output; - return payload; - }); - } - payload.value = output; - return payload; - }; -}); -function transform(fn) { - return new ZodTransform({ - type: "transform", - transform: fn, - }); -} -const schemas_ZodOptional = /*@__PURE__*/ $constructor("ZodOptional", (inst, def) => { - $ZodOptional.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => optionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function optional(innerType) { - return new schemas_ZodOptional({ - type: "optional", - innerType: innerType, - }); -} -const schemas_ZodNullable = /*@__PURE__*/ $constructor("ZodNullable", (inst, def) => { - $ZodNullable.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nullableProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nullable(innerType) { - return new schemas_ZodNullable({ - type: "nullable", - innerType: innerType, - }); -} -// nullish -function schemas_nullish(innerType) { - return optional(nullable(innerType)); -} -const schemas_ZodDefault = /*@__PURE__*/ $constructor("ZodDefault", (inst, def) => { - $ZodDefault.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => defaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeDefault = inst.unwrap; -}); -function schemas_default(innerType, defaultValue) { - return new schemas_ZodDefault({ - type: "default", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodPrefault = /*@__PURE__*/ $constructor("ZodPrefault", (inst, def) => { - $ZodPrefault.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => prefaultProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function prefault(innerType, defaultValue) { - return new ZodPrefault({ - type: "prefault", - innerType: innerType, - get defaultValue() { - return typeof defaultValue === "function" ? defaultValue() : shallowClone(defaultValue); - }, - }); -} -const ZodNonOptional = /*@__PURE__*/ $constructor("ZodNonOptional", (inst, def) => { - $ZodNonOptional.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nonoptionalProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function nonoptional(innerType, params) { - return new ZodNonOptional({ - type: "nonoptional", - innerType: innerType, - ...normalizeParams(params), - }); -} -const ZodSuccess = /*@__PURE__*/ $constructor("ZodSuccess", (inst, def) => { - $ZodSuccess.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => successProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function success(innerType) { - return new ZodSuccess({ - type: "success", - innerType: innerType, - }); -} -const schemas_ZodCatch = /*@__PURE__*/ $constructor("ZodCatch", (inst, def) => { - $ZodCatch.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => catchProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; - inst.removeCatch = inst.unwrap; -}); -function schemas_catch(innerType, catchValue) { - return new schemas_ZodCatch({ - type: "catch", - innerType: innerType, - catchValue: (typeof catchValue === "function" ? catchValue : () => catchValue), - }); -} - -const schemas_ZodNaN = /*@__PURE__*/ $constructor("ZodNaN", (inst, def) => { - $ZodNaN.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => nanProcessor(inst, ctx, json, params); -}); -function nan(params) { - return _nan(schemas_ZodNaN, params); -} -const ZodPipe = /*@__PURE__*/ $constructor("ZodPipe", (inst, def) => { - $ZodPipe.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => pipeProcessor(inst, ctx, json, params); - inst.in = def.in; - inst.out = def.out; -}); -function pipe(in_, out) { - return new ZodPipe({ - type: "pipe", - in: in_, - out: out, - // ...util.normalizeParams(params), - }); -} -const ZodCodec = /*@__PURE__*/ $constructor("ZodCodec", (inst, def) => { - ZodPipe.init(inst, def); - $ZodCodec.init(inst, def); -}); -function codec(in_, out, params) { - return new ZodCodec({ - type: "pipe", - in: in_, - out: out, - transform: params.decode, - reverseTransform: params.encode, - }); -} -const schemas_ZodReadonly = /*@__PURE__*/ $constructor("ZodReadonly", (inst, def) => { - $ZodReadonly.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => readonlyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function readonly(innerType) { - return new schemas_ZodReadonly({ - type: "readonly", - innerType: innerType, - }); -} -const ZodTemplateLiteral = /*@__PURE__*/ $constructor("ZodTemplateLiteral", (inst, def) => { - $ZodTemplateLiteral.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => templateLiteralProcessor(inst, ctx, json, params); -}); -function templateLiteral(parts, params) { - return new ZodTemplateLiteral({ - type: "template_literal", - parts, - ...normalizeParams(params), - }); -} -const schemas_ZodLazy = /*@__PURE__*/ $constructor("ZodLazy", (inst, def) => { - $ZodLazy.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => lazyProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.getter(); -}); -function lazy(getter) { - return new schemas_ZodLazy({ - type: "lazy", - getter: getter, - }); -} -const schemas_ZodPromise = /*@__PURE__*/ $constructor("ZodPromise", (inst, def) => { - $ZodPromise.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => promiseProcessor(inst, ctx, json, params); - inst.unwrap = () => inst._zod.def.innerType; -}); -function promise(innerType) { - return new schemas_ZodPromise({ - type: "promise", - innerType: innerType, - }); -} -const schemas_ZodFunction = /*@__PURE__*/ $constructor("ZodFunction", (inst, def) => { - $ZodFunction.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => functionProcessor(inst, ctx, json, params); -}); -function _function(params) { - return new schemas_ZodFunction({ - type: "function", - input: Array.isArray(params?.input) ? tuple(params?.input) : (params?.input ?? array(unknown())), - output: params?.output ?? unknown(), - }); -} - -const ZodCustom = /*@__PURE__*/ $constructor("ZodCustom", (inst, def) => { - $ZodCustom.init(inst, def); - schemas_ZodType.init(inst, def); - inst._zod.processJSONSchema = (ctx, json, params) => customProcessor(inst, ctx, json, params); -}); -// custom checks -function check(fn) { - const ch = new $ZodCheck({ - check: "custom", - // ...util.normalizeParams(params), - }); - ch._zod.check = fn; - return ch; -} -function schemas_custom(fn, _params) { - return _custom(ZodCustom, fn ?? (() => true), _params); -} -function refine(fn, _params = {}) { - return _refine(ZodCustom, fn, _params); -} -// superRefine -function superRefine(fn) { - return _superRefine(fn); -} -// Re-export describe and meta from core -const schemas_describe = describe; -const schemas_meta = meta; -function _instanceof(cls, params = { - error: `Input not instance of ${cls.name}`, -}) { - const inst = new ZodCustom({ - type: "custom", - check: "custom", - fn: (data) => data instanceof cls, - abort: true, - ...normalizeParams(params), - }); - inst._zod.bag.Class = cls; - return inst; -} - -// stringbool -const stringbool = (...args) => _stringbool({ - Codec: ZodCodec, - Boolean: schemas_ZodBoolean, - String: schemas_ZodString, -}, ...args); -function json(params) { - const jsonSchema = lazy(() => { - return union([schemas_string(params), schemas_number(), schemas_boolean(), schemas_null(), array(jsonSchema), record(schemas_string(), jsonSchema)]); - }); - return jsonSchema; -} -// preprocess -// /** @deprecated Use `z.pipe()` and `z.transform()` instead. */ -function preprocess(fn, schema) { - return pipe(transform(fn), schema); -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/compat.js -// Zod 3 compat layer - -/** @deprecated Use the raw string literal codes instead, e.g. "invalid_type". */ -const compat_ZodIssueCode = { - invalid_type: "invalid_type", - too_big: "too_big", - too_small: "too_small", - invalid_format: "invalid_format", - not_multiple_of: "not_multiple_of", - unrecognized_keys: "unrecognized_keys", - invalid_union: "invalid_union", - invalid_key: "invalid_key", - invalid_element: "invalid_element", - invalid_value: "invalid_value", - custom: "custom", -}; - -/** @deprecated Use `z.config(params)` instead. */ -function compat_setErrorMap(map) { - config({ - customError: map, - }); -} -/** @deprecated Use `z.config()` instead. */ -function compat_getErrorMap() { - return config().customError; -} -/** @deprecated Do not use. Stub definition, only included for zod-to-json-schema compatibility. */ -var compat_ZodFirstPartyTypeKind; -(function (ZodFirstPartyTypeKind) { -})(compat_ZodFirstPartyTypeKind || (compat_ZodFirstPartyTypeKind = {})); - -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/from-json-schema.js - - - -// Local z object to avoid circular dependency with ../index.js -const from_json_schema_z = { - ...classic_schemas_namespaceObject, - ...classic_checks_namespaceObject, - iso: iso_namespaceObject, -}; -function detectVersion(schema, defaultTarget) { - const $schema = schema.$schema; - if ($schema === "https://json-schema.org/draft/2020-12/schema") { - return "draft-2020-12"; - } - if ($schema === "http://json-schema.org/draft-07/schema#") { - return "draft-7"; - } - if ($schema === "http://json-schema.org/draft-04/schema#") { - return "draft-4"; - } - // Use defaultTarget if provided, otherwise default to draft-2020-12 - return defaultTarget ?? "draft-2020-12"; -} -function resolveRef(ref, ctx) { - if (!ref.startsWith("#")) { - throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); - } - const path = ref.slice(1).split("/").filter(Boolean); - // Handle root reference "#" - if (path.length === 0) { - return ctx.rootSchema; - } - const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; - if (path[0] === defsKey) { - const key = path[1]; - if (!key || !ctx.defs[key]) { - throw new Error(`Reference not found: ${ref}`); - } - return ctx.defs[key]; - } - throw new Error(`Reference not found: ${ref}`); -} -function convertBaseSchema(schema, ctx) { - // Handle unsupported features - if (schema.not !== undefined) { - // Special case: { not: {} } represents never - if (typeof schema.not === "object" && Object.keys(schema.not).length === 0) { - return from_json_schema_z.never(); - } - throw new Error("not is not supported in Zod (except { not: {} } for never)"); - } - if (schema.unevaluatedItems !== undefined) { - throw new Error("unevaluatedItems is not supported"); - } - if (schema.unevaluatedProperties !== undefined) { - throw new Error("unevaluatedProperties is not supported"); - } - if (schema.if !== undefined || schema.then !== undefined || schema.else !== undefined) { - throw new Error("Conditional schemas (if/then/else) are not supported"); - } - if (schema.dependentSchemas !== undefined || schema.dependentRequired !== undefined) { - throw new Error("dependentSchemas and dependentRequired are not supported"); - } - // Handle $ref - if (schema.$ref) { - const refPath = schema.$ref; - if (ctx.refs.has(refPath)) { - return ctx.refs.get(refPath); - } - if (ctx.processing.has(refPath)) { - // Circular reference - use lazy - return from_json_schema_z.lazy(() => { - if (!ctx.refs.has(refPath)) { - throw new Error(`Circular reference not resolved: ${refPath}`); - } - return ctx.refs.get(refPath); - }); - } - ctx.processing.add(refPath); - const resolved = resolveRef(refPath, ctx); - const zodSchema = convertSchema(resolved, ctx); - ctx.refs.set(refPath, zodSchema); - ctx.processing.delete(refPath); - return zodSchema; - } - // Handle enum - if (schema.enum !== undefined) { - const enumValues = schema.enum; - // Special case: OpenAPI 3.0 null representation { type: "string", nullable: true, enum: [null] } - if (ctx.version === "openapi-3.0" && - schema.nullable === true && - enumValues.length === 1 && - enumValues[0] === null) { - return from_json_schema_z.null(); - } - if (enumValues.length === 0) { - return from_json_schema_z.never(); - } - if (enumValues.length === 1) { - return from_json_schema_z.literal(enumValues[0]); - } - // Check if all values are strings - if (enumValues.every((v) => typeof v === "string")) { - return from_json_schema_z.enum(enumValues); - } - // Mixed types - use union of literals - const literalSchemas = enumValues.map((v) => from_json_schema_z.literal(v)); - if (literalSchemas.length < 2) { - return literalSchemas[0]; - } - return from_json_schema_z.union([literalSchemas[0], literalSchemas[1], ...literalSchemas.slice(2)]); - } - // Handle const - if (schema.const !== undefined) { - return from_json_schema_z.literal(schema.const); - } - // Handle type - const type = schema.type; - if (Array.isArray(type)) { - // Expand type array into anyOf union - const typeSchemas = type.map((t) => { - const typeSchema = { ...schema, type: t }; - return convertBaseSchema(typeSchema, ctx); - }); - if (typeSchemas.length === 0) { - return from_json_schema_z.never(); - } - if (typeSchemas.length === 1) { - return typeSchemas[0]; - } - return from_json_schema_z.union(typeSchemas); - } - if (!type) { - // No type specified - empty schema (any) - return from_json_schema_z.any(); - } - let zodSchema; - switch (type) { - case "string": { - let stringSchema = from_json_schema_z.string(); - // Apply format using .check() with Zod format functions - if (schema.format) { - const format = schema.format; - // Map common formats to Zod check functions - if (format === "email") { - stringSchema = stringSchema.check(from_json_schema_z.email()); - } - else if (format === "uri" || format === "uri-reference") { - stringSchema = stringSchema.check(from_json_schema_z.url()); - } - else if (format === "uuid" || format === "guid") { - stringSchema = stringSchema.check(from_json_schema_z.uuid()); - } - else if (format === "date-time") { - stringSchema = stringSchema.check(from_json_schema_z.iso.datetime()); - } - else if (format === "date") { - stringSchema = stringSchema.check(from_json_schema_z.iso.date()); - } - else if (format === "time") { - stringSchema = stringSchema.check(from_json_schema_z.iso.time()); - } - else if (format === "duration") { - stringSchema = stringSchema.check(from_json_schema_z.iso.duration()); - } - else if (format === "ipv4") { - stringSchema = stringSchema.check(from_json_schema_z.ipv4()); - } - else if (format === "ipv6") { - stringSchema = stringSchema.check(from_json_schema_z.ipv6()); - } - else if (format === "mac") { - stringSchema = stringSchema.check(from_json_schema_z.mac()); - } - else if (format === "cidr") { - stringSchema = stringSchema.check(from_json_schema_z.cidrv4()); - } - else if (format === "cidr-v6") { - stringSchema = stringSchema.check(from_json_schema_z.cidrv6()); - } - else if (format === "base64") { - stringSchema = stringSchema.check(from_json_schema_z.base64()); - } - else if (format === "base64url") { - stringSchema = stringSchema.check(from_json_schema_z.base64url()); - } - else if (format === "e164") { - stringSchema = stringSchema.check(from_json_schema_z.e164()); - } - else if (format === "jwt") { - stringSchema = stringSchema.check(from_json_schema_z.jwt()); - } - else if (format === "emoji") { - stringSchema = stringSchema.check(from_json_schema_z.emoji()); - } - else if (format === "nanoid") { - stringSchema = stringSchema.check(from_json_schema_z.nanoid()); - } - else if (format === "cuid") { - stringSchema = stringSchema.check(from_json_schema_z.cuid()); - } - else if (format === "cuid2") { - stringSchema = stringSchema.check(from_json_schema_z.cuid2()); - } - else if (format === "ulid") { - stringSchema = stringSchema.check(from_json_schema_z.ulid()); - } - else if (format === "xid") { - stringSchema = stringSchema.check(from_json_schema_z.xid()); - } - else if (format === "ksuid") { - stringSchema = stringSchema.check(from_json_schema_z.ksuid()); - } - // Note: json-string format is not currently supported by Zod - // Custom formats are ignored - keep as plain string - } - // Apply constraints - if (typeof schema.minLength === "number") { - stringSchema = stringSchema.min(schema.minLength); - } - if (typeof schema.maxLength === "number") { - stringSchema = stringSchema.max(schema.maxLength); - } - if (schema.pattern) { - // JSON Schema patterns are not implicitly anchored (match anywhere in string) - stringSchema = stringSchema.regex(new RegExp(schema.pattern)); - } - zodSchema = stringSchema; - break; - } - case "number": - case "integer": { - let numberSchema = type === "integer" ? from_json_schema_z.number().int() : from_json_schema_z.number(); - // Apply constraints - if (typeof schema.minimum === "number") { - numberSchema = numberSchema.min(schema.minimum); - } - if (typeof schema.maximum === "number") { - numberSchema = numberSchema.max(schema.maximum); - } - if (typeof schema.exclusiveMinimum === "number") { - numberSchema = numberSchema.gt(schema.exclusiveMinimum); - } - else if (schema.exclusiveMinimum === true && typeof schema.minimum === "number") { - numberSchema = numberSchema.gt(schema.minimum); - } - if (typeof schema.exclusiveMaximum === "number") { - numberSchema = numberSchema.lt(schema.exclusiveMaximum); - } - else if (schema.exclusiveMaximum === true && typeof schema.maximum === "number") { - numberSchema = numberSchema.lt(schema.maximum); - } - if (typeof schema.multipleOf === "number") { - numberSchema = numberSchema.multipleOf(schema.multipleOf); - } - zodSchema = numberSchema; - break; - } - case "boolean": { - zodSchema = from_json_schema_z.boolean(); - break; - } - case "null": { - zodSchema = from_json_schema_z.null(); - break; - } - case "object": { - const shape = {}; - const properties = schema.properties || {}; - const requiredSet = new Set(schema.required || []); - // Convert properties - mark optional ones - for (const [key, propSchema] of Object.entries(properties)) { - const propZodSchema = convertSchema(propSchema, ctx); - // If not in required array, make it optional - shape[key] = requiredSet.has(key) ? propZodSchema : propZodSchema.optional(); - } - // Handle propertyNames - if (schema.propertyNames) { - const keySchema = convertSchema(schema.propertyNames, ctx); - const valueSchema = schema.additionalProperties && typeof schema.additionalProperties === "object" - ? convertSchema(schema.additionalProperties, ctx) - : from_json_schema_z.any(); - // Case A: No properties (pure record) - if (Object.keys(shape).length === 0) { - zodSchema = from_json_schema_z.record(keySchema, valueSchema); - break; - } - // Case B: With properties (intersection of object and looseRecord) - const objectSchema = from_json_schema_z.object(shape).passthrough(); - const recordSchema = from_json_schema_z.looseRecord(keySchema, valueSchema); - zodSchema = from_json_schema_z.intersection(objectSchema, recordSchema); - break; - } - // Handle patternProperties - if (schema.patternProperties) { - // patternProperties: keys matching pattern must satisfy corresponding schema - // Use loose records so non-matching keys pass through - const patternProps = schema.patternProperties; - const patternKeys = Object.keys(patternProps); - const looseRecords = []; - for (const pattern of patternKeys) { - const patternValue = convertSchema(patternProps[pattern], ctx); - const keySchema = from_json_schema_z.string().regex(new RegExp(pattern)); - looseRecords.push(from_json_schema_z.looseRecord(keySchema, patternValue)); - } - // Build intersection: object schema + all pattern property records - const schemasToIntersect = []; - if (Object.keys(shape).length > 0) { - // Use passthrough so patternProperties can validate additional keys - schemasToIntersect.push(from_json_schema_z.object(shape).passthrough()); - } - schemasToIntersect.push(...looseRecords); - if (schemasToIntersect.length === 0) { - zodSchema = from_json_schema_z.object({}).passthrough(); - } - else if (schemasToIntersect.length === 1) { - zodSchema = schemasToIntersect[0]; - } - else { - // Chain intersections: (A & B) & C & D ... - let result = from_json_schema_z.intersection(schemasToIntersect[0], schemasToIntersect[1]); - for (let i = 2; i < schemasToIntersect.length; i++) { - result = from_json_schema_z.intersection(result, schemasToIntersect[i]); - } - zodSchema = result; - } - break; - } - // Handle additionalProperties - // In JSON Schema, additionalProperties defaults to true (allow any extra properties) - // In Zod, objects strip unknown keys by default, so we need to handle this explicitly - const objectSchema = from_json_schema_z.object(shape); - if (schema.additionalProperties === false) { - // Strict mode - no extra properties allowed - zodSchema = objectSchema.strict(); - } - else if (typeof schema.additionalProperties === "object") { - // Extra properties must match the specified schema - zodSchema = objectSchema.catchall(convertSchema(schema.additionalProperties, ctx)); - } - else { - // additionalProperties is true or undefined - allow any extra properties (passthrough) - zodSchema = objectSchema.passthrough(); - } - break; - } - case "array": { - // TODO: uniqueItems is not supported - // TODO: contains/minContains/maxContains are not supported - // Check if this is a tuple (prefixItems or items as array) - const prefixItems = schema.prefixItems; - const items = schema.items; - if (prefixItems && Array.isArray(prefixItems)) { - // Tuple with prefixItems (draft-2020-12) - const tupleItems = prefixItems.map((item) => convertSchema(item, ctx)); - const rest = items && typeof items === "object" && !Array.isArray(items) - ? convertSchema(items, ctx) - : undefined; - if (rest) { - zodSchema = from_json_schema_z.tuple(tupleItems).rest(rest); - } - else { - zodSchema = from_json_schema_z.tuple(tupleItems); - } - // Apply minItems/maxItems constraints to tuples - if (typeof schema.minItems === "number") { - zodSchema = zodSchema.check(from_json_schema_z.minLength(schema.minItems)); - } - if (typeof schema.maxItems === "number") { - zodSchema = zodSchema.check(from_json_schema_z.maxLength(schema.maxItems)); - } - } - else if (Array.isArray(items)) { - // Tuple with items array (draft-7) - const tupleItems = items.map((item) => convertSchema(item, ctx)); - const rest = schema.additionalItems && typeof schema.additionalItems === "object" - ? convertSchema(schema.additionalItems, ctx) - : undefined; // additionalItems: false means no rest, handled by default tuple behavior - if (rest) { - zodSchema = from_json_schema_z.tuple(tupleItems).rest(rest); - } - else { - zodSchema = from_json_schema_z.tuple(tupleItems); - } - // Apply minItems/maxItems constraints to tuples - if (typeof schema.minItems === "number") { - zodSchema = zodSchema.check(from_json_schema_z.minLength(schema.minItems)); - } - if (typeof schema.maxItems === "number") { - zodSchema = zodSchema.check(from_json_schema_z.maxLength(schema.maxItems)); - } - } - else if (items !== undefined) { - // Regular array - const element = convertSchema(items, ctx); - let arraySchema = from_json_schema_z.array(element); - // Apply constraints - if (typeof schema.minItems === "number") { - arraySchema = arraySchema.min(schema.minItems); - } - if (typeof schema.maxItems === "number") { - arraySchema = arraySchema.max(schema.maxItems); - } - zodSchema = arraySchema; - } - else { - // No items specified - array of any - zodSchema = from_json_schema_z.array(from_json_schema_z.any()); - } - break; - } - default: - throw new Error(`Unsupported type: ${type}`); - } - // Apply metadata - if (schema.description) { - zodSchema = zodSchema.describe(schema.description); - } - if (schema.default !== undefined) { - zodSchema = zodSchema.default(schema.default); - } - return zodSchema; -} -function convertSchema(schema, ctx) { - if (typeof schema === "boolean") { - return schema ? from_json_schema_z.any() : from_json_schema_z.never(); - } - // Convert base schema first (ignoring composition keywords) - let baseSchema = convertBaseSchema(schema, ctx); - const hasExplicitType = schema.type || schema.enum !== undefined || schema.const !== undefined; - // Process composition keywords LAST (they can appear together) - // Handle anyOf - wrap base schema with union - if (schema.anyOf && Array.isArray(schema.anyOf)) { - const options = schema.anyOf.map((s) => convertSchema(s, ctx)); - const anyOfUnion = from_json_schema_z.union(options); - baseSchema = hasExplicitType ? from_json_schema_z.intersection(baseSchema, anyOfUnion) : anyOfUnion; - } - // Handle oneOf - exclusive union (exactly one must match) - if (schema.oneOf && Array.isArray(schema.oneOf)) { - const options = schema.oneOf.map((s) => convertSchema(s, ctx)); - const oneOfUnion = from_json_schema_z.xor(options); - baseSchema = hasExplicitType ? from_json_schema_z.intersection(baseSchema, oneOfUnion) : oneOfUnion; - } - // Handle allOf - wrap base schema with intersection - if (schema.allOf && Array.isArray(schema.allOf)) { - if (schema.allOf.length === 0) { - baseSchema = hasExplicitType ? baseSchema : from_json_schema_z.any(); - } - else { - let result = hasExplicitType ? baseSchema : convertSchema(schema.allOf[0], ctx); - const startIdx = hasExplicitType ? 0 : 1; - for (let i = startIdx; i < schema.allOf.length; i++) { - result = from_json_schema_z.intersection(result, convertSchema(schema.allOf[i], ctx)); - } - baseSchema = result; - } - } - // Handle nullable (OpenAPI 3.0) - if (schema.nullable === true && ctx.version === "openapi-3.0") { - baseSchema = from_json_schema_z.nullable(baseSchema); - } - // Handle readOnly - if (schema.readOnly === true) { - baseSchema = from_json_schema_z.readonly(baseSchema); - } - return baseSchema; -} -/** - * Converts a JSON Schema to a Zod schema. This function should be considered semi-experimental. It's behavior is liable to change. */ -function fromJSONSchema(schema, params) { - // Handle boolean schemas - if (typeof schema === "boolean") { - return schema ? from_json_schema_z.any() : from_json_schema_z.never(); - } - const version = detectVersion(schema, params?.defaultTarget); - const defs = (schema.$defs || schema.definitions || {}); - const ctx = { - version, - defs, - refs: new Map(), - processing: new Set(), - rootSchema: schema, - }; - return convertSchema(schema, ctx); -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/coerce.js - - -function coerce_string(params) { - return _coercedString(schemas_ZodString, params); -} -function coerce_number(params) { - return _coercedNumber(schemas_ZodNumber, params); -} -function coerce_boolean(params) { - return _coercedBoolean(schemas_ZodBoolean, params); -} -function coerce_bigint(params) { - return _coercedBigint(schemas_ZodBigInt, params); -} -function coerce_date(params) { - return _coercedDate(schemas_ZodDate, params); -} - -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/external.js - - - - - - -// zod-specified - - -config(en()); - - - - -// iso -// must be exported from top-level -// https://github.com/colinhacks/zod/issues/4491 - - - - -;// CONCATENATED MODULE: ./node_modules/zod/v4/classic/index.js - - - -/* harmony default export */ const classic = ((/* unused pure expression or super */ null && (z))); - -;// CONCATENATED MODULE: ./node_modules/zod/v4/index.js - - -/* harmony default export */ const zod_v4 = ((/* unused pure expression or super */ null && (z4))); - -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/tools/index.js - - - - - - - - - - - - - - - - -//#region src/tools/index.ts -var tools_exports = {}; -__export(tools_exports, { - BaseToolkit: () => BaseToolkit, - DynamicStructuredTool: () => tools_DynamicStructuredTool, - DynamicTool: () => tools_DynamicTool, - StructuredTool: () => StructuredTool, - Tool: () => Tool, - ToolInputParsingException: () => ToolInputParsingException, - isLangChainTool: () => isLangChainTool, - isRunnableToolLike: () => isRunnableToolLike, - isStructuredTool: () => isStructuredTool, - isStructuredToolParams: () => isStructuredToolParams, - tool: () => tool -}); -/** -* Base class for Tools that accept input of any shape defined by a Zod schema. -*/ -var StructuredTool = class extends BaseLangChain { - /** - * Optional provider-specific extra fields for the tool. - * - * This is used to pass provider-specific configuration that doesn't fit into - * standard tool fields. - */ - extras; - /** - * Whether to return the tool's output directly. - * - * Setting this to true means that after the tool is called, - * an agent should stop looping. - */ - returnDirect = false; - verboseParsingErrors = false; - get lc_namespace() { - return ["langchain", "tools"]; - } - /** - * The tool response format. - * - * If "content" then the output of the tool is interpreted as the contents of a - * ToolMessage. If "content_and_artifact" then the output is expected to be a - * two-tuple corresponding to the (content, artifact) of a ToolMessage. - * - * @default "content" - */ - responseFormat = "content"; - /** - * Default config object for the tool runnable. - */ - defaultConfig; - constructor(fields) { - super(fields ?? {}); - this.verboseParsingErrors = fields?.verboseParsingErrors ?? this.verboseParsingErrors; - this.responseFormat = fields?.responseFormat ?? this.responseFormat; - this.defaultConfig = fields?.defaultConfig ?? this.defaultConfig; - this.metadata = fields?.metadata ?? this.metadata; - this.extras = fields?.extras ?? this.extras; - } - /** - * Invokes the tool with the provided input and configuration. - * @param input The input for the tool. - * @param config Optional configuration for the tool. - * @returns A Promise that resolves with the tool's output. - */ - async invoke(input, config) { - let toolInput; - let enrichedConfig = ensureConfig(mergeConfigs(this.defaultConfig, config)); - if (_isToolCall(input)) { - toolInput = input.args; - enrichedConfig = { - ...enrichedConfig, - toolCall: input - }; - } else toolInput = input; - return this.call(toolInput, enrichedConfig); - } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.3.0. - * - * Calls the tool with the provided argument, configuration, and tags. It - * parses the input according to the schema, handles any errors, and - * manages callbacks. - * @param arg The input argument for the tool. - * @param configArg Optional configuration or callbacks for the tool. - * @param tags Optional tags for the tool. - * @returns A Promise that resolves with a string. - */ - async call(arg, configArg, tags) { - const inputForValidation = _isToolCall(arg) ? arg.args : arg; - let parsed; - if (isInteropZodSchema(this.schema)) try { - parsed = await interopParseAsync(this.schema, inputForValidation); - } catch (e) { - let message = `Received tool input did not match expected schema`; - if (this.verboseParsingErrors) message = `${message}\nDetails: ${e.message}`; - if (isInteropZodError(e)) message = `${message}\n\n${prettifyError(e)}`; - throw new ToolInputParsingException(message, JSON.stringify(arg)); - } - else { - const result$1 = validate_validate(inputForValidation, this.schema); - if (!result$1.valid) { - let message = `Received tool input did not match expected schema`; - if (this.verboseParsingErrors) message = `${message}\nDetails: ${result$1.errors.map((e) => `${e.keywordLocation}: ${e.error}`).join("\n")}`; - throw new ToolInputParsingException(message, JSON.stringify(arg)); - } - parsed = inputForValidation; - } - const config = parseCallbackConfigArg(configArg); - const callbackManager_ = CallbackManager.configure(config.callbacks, this.callbacks, config.tags || tags, this.tags, config.metadata, this.metadata, { verbose: this.verbose }); - const runManager = await callbackManager_?.handleToolStart(this.toJSON(), typeof arg === "string" ? arg : JSON.stringify(arg), config.runId, void 0, void 0, void 0, config.runName); - delete config.runId; - let result; - try { - result = await this._call(parsed, runManager, config); - } catch (e) { - await runManager?.handleToolError(e); - throw e; - } - let content; - let artifact; - if (this.responseFormat === "content_and_artifact") if (Array.isArray(result) && result.length === 2) [content, artifact] = result; - else throw new Error(`Tool response format is "content_and_artifact" but the output was not a two-tuple.\nResult: ${JSON.stringify(result)}`); - else content = result; - let toolCallId; - if (_isToolCall(arg)) toolCallId = arg.id; - if (!toolCallId && _configHasToolCallId(config)) toolCallId = config.toolCall.id; - const formattedOutput = _formatToolOutput({ - content, - artifact, - toolCallId, - name: this.name, - metadata: this.metadata - }); - await runManager?.handleToolEnd(formattedOutput); - return formattedOutput; - } -}; -/** -* Base class for Tools that accept input as a string. -*/ -var Tool = class extends StructuredTool { - schema = objectType({ input: stringType().optional() }).transform((obj) => obj.input); - constructor(fields) { - super(fields); - } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.3.0. - * - * Calls the tool with the provided argument and callbacks. It handles - * string inputs specifically. - * @param arg The input argument for the tool, which can be a string, undefined, or an input of the tool's schema. - * @param callbacks Optional callbacks for the tool. - * @returns A Promise that resolves with a string. - */ - call(arg, callbacks) { - const structuredArg = typeof arg === "string" || arg == null ? { input: arg } : arg; - return super.call(structuredArg, callbacks); - } -}; -/** -* A tool that can be created dynamically from a function, name, and description. -*/ -var tools_DynamicTool = class extends Tool { - static lc_name() { - return "DynamicTool"; - } - name; - description; - func; - constructor(fields) { - super(fields); - this.name = fields.name; - this.description = fields.description; - this.func = fields.func; - this.returnDirect = fields.returnDirect ?? this.returnDirect; - } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.3.0. - */ - async call(arg, configArg) { - const config = parseCallbackConfigArg(configArg); - if (config.runName === void 0) config.runName = this.name; - return super.call(arg, config); - } - /** @ignore */ - async _call(input, runManager, parentConfig) { - return this.func(input, runManager, parentConfig); - } -}; -/** -* A tool that can be created dynamically from a function, name, and -* description, designed to work with structured data. It extends the -* StructuredTool class and overrides the _call method to execute the -* provided function when the tool is called. -* -* Schema can be passed as Zod or JSON schema. The tool will not validate -* input if JSON schema is passed. -*/ -var tools_DynamicStructuredTool = class extends StructuredTool { - static lc_name() { - return "DynamicStructuredTool"; - } - name; - description; - func; - schema; - constructor(fields) { - super(fields); - this.name = fields.name; - this.description = fields.description; - this.func = fields.func; - this.returnDirect = fields.returnDirect ?? this.returnDirect; - this.schema = fields.schema; - } - /** - * @deprecated Use .invoke() instead. Will be removed in 0.3.0. - */ - async call(arg, configArg, tags) { - const config = parseCallbackConfigArg(configArg); - if (config.runName === void 0) config.runName = this.name; - return super.call(arg, config, tags); - } - _call(arg, runManager, parentConfig) { - return this.func(arg, runManager, parentConfig); - } -}; -/** -* Abstract base class for toolkits in LangChain. Toolkits are collections -* of tools that agents can use. Subclasses must implement the `tools` -* property to provide the specific tools for the toolkit. -*/ -var BaseToolkit = class { - getTools() { - return this.tools; - } -}; -function tool(func, fields) { - const isSimpleStringSchema = isSimpleStringZodSchema(fields.schema); - const isStringJSONSchema = validatesOnlyStrings(fields.schema); - if (!fields.schema || isSimpleStringSchema || isStringJSONSchema) return new tools_DynamicTool({ - ...fields, - description: fields.description ?? fields.schema?.description ?? `${fields.name} tool`, - func: async (input, runManager, config) => { - return new Promise((resolve, reject) => { - const childConfig = config_patchConfig(config, { callbacks: runManager?.getChild() }); - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { - try { - resolve(func(input, childConfig)); - } catch (e) { - reject(e); - } - }); - }); - } - }); - const schema = fields.schema; - const description = fields.description ?? fields.schema.description ?? `${fields.name} tool`; - return new tools_DynamicStructuredTool({ - ...fields, - description, - schema, - func: async (input, runManager, config) => { - return new Promise((resolve, reject) => { - let listener; - const cleanup = () => { - if (config?.signal && listener) config.signal.removeEventListener("abort", listener); - }; - if (config?.signal) { - listener = () => { - cleanup(); - reject(getAbortSignalError(config.signal)); - }; - config.signal.addEventListener("abort", listener); - } - const childConfig = config_patchConfig(config, { callbacks: runManager?.getChild() }); - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(config_pickRunnableConfigKeys(childConfig), async () => { - try { - const result = await func(input, childConfig); - /** - * If the signal is aborted, we don't want to resolve the promise - * as the promise is already rejected. - */ - if (config?.signal?.aborted) { - cleanup(); - return; - } - cleanup(); - resolve(result); - } catch (e) { - cleanup(); - reject(e); - } - }); - }); - } - }); -} -function _formatToolOutput(params) { - const { content, artifact, toolCallId, metadata } = params; - if (toolCallId && !isDirectToolOutput(content)) if (typeof content === "string" || Array.isArray(content) && content.every((item) => typeof item === "object")) return new ToolMessage({ - status: "success", - content, - artifact, - tool_call_id: toolCallId, - name: params.name, - metadata - }); - else return new ToolMessage({ - status: "success", - content: tools_stringify(content), - artifact, - tool_call_id: toolCallId, - name: params.name, - metadata - }); - else return content; -} -function tools_stringify(content) { - try { - return JSON.stringify(content, null, 2) ?? ""; - } catch (_noOp) { - return `${content}`; - } -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/chat_models.js - - - - - - - -//#region src/utils/testing/chat_models.ts -var FakeChatModel = class extends BaseChatModel { - _combineLLMOutput() { - return []; - } - _llmType() { - return "fake"; - } - async _generate(messages, options, runManager) { - if (options?.stop?.length) return { generations: [{ - message: new AIMessage(options.stop[0]), - text: options.stop[0] - }] }; - const text = messages.map((m) => { - if (typeof m.content === "string") return m.content; - return JSON.stringify(m.content, null, 2); - }).join("\n"); - await runManager?.handleLLMNewToken(text); - return { - generations: [{ - message: new AIMessage(text), - text - }], - llmOutput: {} - }; - } -}; -var FakeStreamingChatModel = class FakeStreamingChatModel extends BaseChatModel { - sleep = 50; - responses = []; - chunks = []; - toolStyle = "openai"; - thrownErrorString; - tools = []; - constructor({ sleep = 50, responses = [], chunks = [], toolStyle = "openai", thrownErrorString,...rest }) { - super(rest); - this.sleep = sleep; - this.responses = responses; - this.chunks = chunks; - this.toolStyle = toolStyle; - this.thrownErrorString = thrownErrorString; - } - _llmType() { - return "fake"; - } - bindTools(tools) { - const merged = [...this.tools, ...tools]; - const toolDicts = merged.map((t) => { - switch (this.toolStyle) { - case "openai": return { - type: "function", - function: { - name: t.name, - description: t.description, - parameters: toJsonSchema(t.schema) - } - }; - case "anthropic": return { - name: t.name, - description: t.description, - input_schema: toJsonSchema(t.schema) - }; - case "bedrock": return { toolSpec: { - name: t.name, - description: t.description, - inputSchema: toJsonSchema(t.schema) - } }; - case "google": return { - name: t.name, - description: t.description, - parameters: toJsonSchema(t.schema) - }; - default: throw new Error(`Unsupported tool style: ${this.toolStyle}`); - } - }); - const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts; - const next = new FakeStreamingChatModel({ - sleep: this.sleep, - responses: this.responses, - chunks: this.chunks, - toolStyle: this.toolStyle, - thrownErrorString: this.thrownErrorString - }); - next.tools = merged; - return next.withConfig({ tools: wrapped }); - } - async _generate(messages, _options, _runManager) { - if (this.thrownErrorString) throw new Error(this.thrownErrorString); - const content = this.responses?.[0]?.content ?? messages[0].content ?? ""; - const generation = { generations: [{ - text: "", - message: new AIMessage({ - content, - tool_calls: this.chunks?.[0]?.tool_calls - }) - }] }; - return generation; - } - async *_streamResponseChunks(_messages, options, runManager) { - if (this.thrownErrorString) throw new Error(this.thrownErrorString); - if (this.chunks?.length) { - for (const msgChunk of this.chunks) { - const cg = new ChatGenerationChunk({ - message: new AIMessageChunk({ - content: msgChunk.content, - tool_calls: msgChunk.tool_calls, - additional_kwargs: msgChunk.additional_kwargs ?? {} - }), - text: msgChunk.content?.toString() ?? "" - }); - if (options.signal?.aborted) break; - yield cg; - await runManager?.handleLLMNewToken(msgChunk.content, void 0, void 0, void 0, void 0, { chunk: cg }); - } - return; - } - const fallback = this.responses?.[0] ?? new AIMessage(typeof _messages[0].content === "string" ? _messages[0].content : ""); - const text = typeof fallback.content === "string" ? fallback.content : ""; - for (const ch of text) { - await new Promise((r) => setTimeout(r, this.sleep)); - const cg = new ChatGenerationChunk({ - message: new AIMessageChunk({ content: ch }), - text: ch - }); - if (options.signal?.aborted) break; - yield cg; - await runManager?.handleLLMNewToken(ch, void 0, void 0, void 0, void 0, { chunk: cg }); - } - } -}; -/** -* A fake Chat Model that returns a predefined list of responses. It can be used -* for testing purposes. -* @example -* ```typescript -* const chat = new FakeListChatModel({ -* responses: ["I'll callback later.", "You 'console' them!"] -* }); -* -* const firstMessage = new HumanMessage("You want to hear a JavaScript joke?"); -* const secondMessage = new HumanMessage("How do you cheer up a JavaScript developer?"); -* -* // Call the chat model with a message and log the response -* const firstResponse = await chat.call([firstMessage]); -* console.log({ firstResponse }); -* -* const secondResponse = await chat.call([secondMessage]); -* console.log({ secondResponse }); -* ``` -*/ -var FakeListChatModel = class FakeListChatModel extends BaseChatModel { - static lc_name() { - return "FakeListChatModel"; - } - lc_serializable = true; - responses; - i = 0; - sleep; - emitCustomEvent = false; - generationInfo; - tools = []; - toolStyle = "openai"; - constructor(params) { - super(params); - const { responses, sleep, emitCustomEvent, generationInfo } = params; - this.responses = responses; - this.sleep = sleep; - this.emitCustomEvent = emitCustomEvent ?? this.emitCustomEvent; - this.generationInfo = generationInfo; - } - _combineLLMOutput() { - return []; - } - _llmType() { - return "fake-list"; - } - async _generate(_messages, options, runManager) { - await this._sleepIfRequested(); - if (options?.thrownErrorString) throw new Error(options.thrownErrorString); - if (this.emitCustomEvent) await runManager?.handleCustomEvent("some_test_event", { someval: true }); - if (options?.stop?.length) return { generations: [this._formatGeneration(options.stop[0])] }; - else { - const response = this._currentResponse(); - this._incrementResponse(); - return { - generations: [this._formatGeneration(response)], - llmOutput: {} - }; - } - } - _formatGeneration(text) { - return { - message: new AIMessage(text), - text - }; - } - async *_streamResponseChunks(_messages, options, runManager) { - const response = this._currentResponse(); - this._incrementResponse(); - if (this.emitCustomEvent) await runManager?.handleCustomEvent("some_test_event", { someval: true }); - const responseChars = [...response]; - for (let i = 0; i < responseChars.length; i++) { - const text = responseChars[i]; - const isLastChunk = i === responseChars.length - 1; - await this._sleepIfRequested(); - if (options?.thrownErrorString) throw new Error(options.thrownErrorString); - const chunk = this._createResponseChunk(text, isLastChunk ? this.generationInfo : void 0); - if (options.signal?.aborted) break; - yield chunk; - runManager?.handleLLMNewToken(text); - } - } - async _sleepIfRequested() { - if (this.sleep !== void 0) await this._sleep(); - } - async _sleep() { - return new Promise((resolve) => { - setTimeout(() => resolve(), this.sleep); - }); - } - _createResponseChunk(text, generationInfo) { - return new ChatGenerationChunk({ - message: new AIMessageChunk({ content: text }), - text, - generationInfo - }); - } - _currentResponse() { - return this.responses[this.i]; - } - _incrementResponse() { - if (this.i < this.responses.length - 1) this.i += 1; - else this.i = 0; - } - bindTools(tools) { - const merged = [...this.tools, ...tools]; - const toolDicts = merged.map((t) => { - switch (this.toolStyle) { - case "openai": return { - type: "function", - function: { - name: t.name, - description: t.description, - parameters: toJsonSchema(t.schema) - } - }; - case "anthropic": return { - name: t.name, - description: t.description, - input_schema: toJsonSchema(t.schema) - }; - case "bedrock": return { toolSpec: { - name: t.name, - description: t.description, - inputSchema: toJsonSchema(t.schema) - } }; - case "google": return { - name: t.name, - description: t.description, - parameters: toJsonSchema(t.schema) - }; - default: throw new Error(`Unsupported tool style: ${this.toolStyle}`); - } - }); - const wrapped = this.toolStyle === "google" ? [{ functionDeclarations: toolDicts }] : toolDicts; - const next = new FakeListChatModel({ - responses: this.responses, - sleep: this.sleep, - emitCustomEvent: this.emitCustomEvent, - generationInfo: this.generationInfo - }); - next.tools = merged; - next.toolStyle = this.toolStyle; - next.i = this.i; - return next.withConfig({ tools: wrapped }); - } - withStructuredOutput(_params, _config) { - return RunnableLambda.from(async (input) => { - const message = await this.invoke(input); - if (message.tool_calls?.[0]?.args) return message.tool_calls[0].args; - if (typeof message.content === "string") return JSON.parse(message.content); - throw new Error("No structured output found"); - }); - } -}; - -//#endregion - -//# sourceMappingURL=chat_models.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/embeddings.js - - -//#region src/utils/testing/embeddings.ts -/** -* A class that provides synthetic embeddings by overriding the -* embedDocuments and embedQuery methods to generate embeddings based on -* the input documents. The embeddings are generated by converting each -* document into chunks, calculating a numerical value for each chunk, and -* returning an array of these values as the embedding. -*/ -var SyntheticEmbeddings = class extends Embeddings { - vectorSize; - constructor(params) { - super(params ?? {}); - this.vectorSize = params?.vectorSize ?? 4; - } - /** - * Generates synthetic embeddings for a list of documents. - * @param documents List of documents to generate embeddings for. - * @returns A promise that resolves with a list of synthetic embeddings for each document. - */ - async embedDocuments(documents) { - return Promise.all(documents.map((doc) => this.embedQuery(doc))); - } - /** - * Generates a synthetic embedding for a document. The document is - * converted into chunks, a numerical value is calculated for each chunk, - * and an array of these values is returned as the embedding. - * @param document The document to generate an embedding for. - * @returns A promise that resolves with a synthetic embedding for the document. - */ - async embedQuery(document) { - let doc = document; - doc = doc.toLowerCase().replaceAll(/[^a-z ]/g, ""); - const padMod = doc.length % this.vectorSize; - const padGapSize = padMod === 0 ? 0 : this.vectorSize - padMod; - const padSize = doc.length + padGapSize; - doc = doc.padEnd(padSize, " "); - const chunkSize = doc.length / this.vectorSize; - const docChunk = []; - for (let co = 0; co < doc.length; co += chunkSize) docChunk.push(doc.slice(co, co + chunkSize)); - const ret = docChunk.map((s) => { - let sum = 0; - for (let co = 0; co < s.length; co += 1) sum += s === " " ? 0 : s.charCodeAt(co); - const ret$1 = sum % 26 / 26; - return ret$1; - }); - return ret; - } -}; -/** -* A class that provides fake embeddings by overriding the embedDocuments -* and embedQuery methods to return fixed values. -*/ -var FakeEmbeddings = class extends Embeddings { - constructor(params) { - super(params ?? {}); - } - /** - * Generates fixed embeddings for a list of documents. - * @param documents List of documents to generate embeddings for. - * @returns A promise that resolves with a list of fixed embeddings for each document. - */ - embedDocuments(documents) { - return Promise.resolve(documents.map(() => [ - .1, - .2, - .3, - .4 - ])); - } - /** - * Generates a fixed embedding for a query. - * @param _ The query to generate an embedding for. - * @returns A promise that resolves with a fixed embedding for the query. - */ - embedQuery(_) { - return Promise.resolve([ - .1, - .2, - .3, - .4 - ]); - } -}; - -//#endregion - -//# sourceMappingURL=embeddings.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/llms.js - - -//#region src/utils/testing/llms.ts -var FakeLLM = class extends LLM { - response; - thrownErrorString; - constructor(fields) { - super(fields); - this.response = fields.response; - this.thrownErrorString = fields.thrownErrorString; - } - _llmType() { - return "fake"; - } - async _call(prompt, _options, runManager) { - if (this.thrownErrorString) throw new Error(this.thrownErrorString); - const response = this.response ?? prompt; - await runManager?.handleLLMNewToken(response); - return response; - } -}; -var FakeStreamingLLM = class extends LLM { - sleep = 50; - responses; - thrownErrorString; - constructor(fields) { - super(fields); - this.sleep = fields.sleep ?? this.sleep; - this.responses = fields.responses; - this.thrownErrorString = fields.thrownErrorString; - } - _llmType() { - return "fake"; - } - async _call(prompt) { - if (this.thrownErrorString) throw new Error(this.thrownErrorString); - const response = this.responses?.[0]; - this.responses = this.responses?.slice(1); - return response ?? prompt; - } - async *_streamResponseChunks(input, _options, runManager) { - if (this.thrownErrorString) throw new Error(this.thrownErrorString); - const response = this.responses?.[0]; - this.responses = this.responses?.slice(1); - for (const c of response ?? input) { - await new Promise((resolve) => setTimeout(resolve, this.sleep)); - yield { - text: c, - generationInfo: {} - }; - await runManager?.handleLLMNewToken(c); - } - } -}; - -//#endregion - -//# sourceMappingURL=llms.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/message_history.js - - - - - - -//#region src/utils/testing/message_history.ts -var FakeChatMessageHistory = class extends BaseChatMessageHistory { - lc_namespace = [ - "langchain_core", - "message", - "fake" - ]; - messages = []; - constructor() { - super(); - } - async getMessages() { - return this.messages; - } - async addMessage(message) { - this.messages.push(message); - } - async addUserMessage(message) { - this.messages.push(new HumanMessage(message)); - } - async addAIMessage(message) { - this.messages.push(new AIMessage(message)); - } - async clear() { - this.messages = []; - } -}; -var FakeListChatMessageHistory = class extends BaseListChatMessageHistory { - lc_namespace = [ - "langchain_core", - "message", - "fake" - ]; - messages = []; - constructor() { - super(); - } - async addMessage(message) { - this.messages.push(message); - } - async getMessages() { - return this.messages; - } -}; -var FakeTracer = class extends BaseTracer { - name = "fake_tracer"; - runs = []; - constructor() { - super(); - } - persistRun(run) { - this.runs.push(run); - return Promise.resolve(); - } -}; - -//#endregion - -//# sourceMappingURL=message_history.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/output_parsers.js - - -//#region src/utils/testing/output_parsers.ts -/** -* Parser for comma-separated values. It splits the input text by commas -* and trims the resulting values. -*/ -var FakeSplitIntoListParser = class extends BaseOutputParser { - lc_namespace = ["tests", "fake"]; - getFormatInstructions() { - return ""; - } - async parse(text) { - return text.split(",").map((value) => value.trim()); - } -}; - -//#endregion - -//# sourceMappingURL=output_parsers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/retrievers.js - - - -//#region src/utils/testing/retrievers.ts -var FakeRetriever = class extends BaseRetriever { - lc_namespace = ["test", "fake"]; - output = [new Document({ pageContent: "foo" }), new Document({ pageContent: "bar" })]; - constructor(fields) { - super(); - this.output = fields?.output ?? this.output; - } - async _getRelevantDocuments(_query) { - return this.output; - } -}; - -//#endregion - -//# sourceMappingURL=retrievers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/runnables.js - - -//#region src/utils/testing/runnables.ts -var FakeRunnable = class extends Runnable { - lc_namespace = ["tests", "fake"]; - returnOptions; - constructor(fields) { - super(fields); - this.returnOptions = fields.returnOptions; - } - async invoke(input, options) { - if (this.returnOptions) return options ?? {}; - return { input }; - } -}; - -//#endregion - -//# sourceMappingURL=runnables.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/tools.js - - -//#region src/utils/testing/tools.ts -var FakeTool = class extends StructuredTool { - name; - description; - schema; - constructor(fields) { - super(fields); - this.name = fields.name; - this.description = fields.description; - this.schema = fields.schema; - } - async _call(arg, _runManager) { - return JSON.stringify(arg); - } -}; - -//#endregion - -//# sourceMappingURL=tools.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/tracers.js - - -//#region src/utils/testing/tracers.ts -var SingleRunExtractor = class extends BaseTracer { - runPromiseResolver; - runPromise; - /** The name of the callback handler. */ - name = "single_run_extractor"; - constructor() { - super(); - this.runPromise = new Promise((extract) => { - this.runPromiseResolver = extract; - }); - } - async persistRun(run) { - this.runPromiseResolver(run); - } - async extract() { - return this.runPromise; - } -}; - -//#endregion - -//# sourceMappingURL=tracers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/ml-distance/similarities.js -//#region src/utils/ml-distance/similarities.ts -/** -* Returns the average of cosine distances between vectors a and b -* @param a - first vector -* @param b - second vector -* -*/ -function cosine(a, b) { - let p = 0; - let p2 = 0; - let q2 = 0; - for (let i = 0; i < a.length; i++) { - p += a[i] * b[i]; - p2 += a[i] * a[i]; - q2 += b[i] * b[i]; - } - return p / (Math.sqrt(p2) * Math.sqrt(q2)); -} - -//#endregion - -//# sourceMappingURL=similarities.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/vectorstores.js - - - - -//#region src/utils/testing/vectorstores.ts -/** -* Class that extends `VectorStore` to store vectors in memory. Provides -* methods for adding documents, performing similarity searches, and -* creating instances from texts, documents, or an existing index. -*/ -var FakeVectorStore = class FakeVectorStore extends VectorStore { - memoryVectors = []; - similarity; - _vectorstoreType() { - return "memory"; - } - constructor(embeddings, { similarity,...rest } = {}) { - super(embeddings, rest); - this.similarity = similarity ?? cosine; - } - /** - * Method to add documents to the memory vector store. It extracts the - * text from each document, generates embeddings for them, and adds the - * resulting vectors to the store. - * @param documents Array of `Document` instances to be added to the store. - * @returns Promise that resolves when all documents have been added. - */ - async addDocuments(documents) { - const texts = documents.map(({ pageContent }) => pageContent); - return this.addVectors(await this.embeddings.embedDocuments(texts), documents); - } - /** - * Method to add vectors to the memory vector store. It creates - * `MemoryVector` instances for each vector and document pair and adds - * them to the store. - * @param vectors Array of vectors to be added to the store. - * @param documents Array of `Document` instances corresponding to the vectors. - * @returns Promise that resolves when all vectors have been added. - */ - async addVectors(vectors, documents) { - const memoryVectors = vectors.map((embedding, idx) => ({ - content: documents[idx].pageContent, - embedding, - metadata: documents[idx].metadata - })); - this.memoryVectors = this.memoryVectors.concat(memoryVectors); - } - /** - * Method to perform a similarity search in the memory vector store. It - * calculates the similarity between the query vector and each vector in - * the store, sorts the results by similarity, and returns the top `k` - * results along with their scores. - * @param query Query vector to compare against the vectors in the store. - * @param k Number of top results to return. - * @param filter Optional filter function to apply to the vectors before performing the search. - * @returns Promise that resolves with an array of tuples, each containing a `Document` and its similarity score. - */ - async similaritySearchVectorWithScore(query, k, filter) { - const filterFunction = (memoryVector) => { - if (!filter) return true; - const doc = new Document({ - metadata: memoryVector.metadata, - pageContent: memoryVector.content - }); - return filter(doc); - }; - const filteredMemoryVectors = this.memoryVectors.filter(filterFunction); - const searches = filteredMemoryVectors.map((vector, index) => ({ - similarity: this.similarity(query, vector.embedding), - index - })).sort((a, b) => a.similarity > b.similarity ? -1 : 0).slice(0, k); - const result = searches.map((search) => [new Document({ - metadata: filteredMemoryVectors[search.index].metadata, - pageContent: filteredMemoryVectors[search.index].content - }), search.similarity]); - return result; - } - /** - * Static method to create a `FakeVectorStore` instance from an array of - * texts. It creates a `Document` for each text and metadata pair, and - * adds them to the store. - * @param texts Array of texts to be added to the store. - * @param metadatas Array or single object of metadata corresponding to the texts. - * @param embeddings `Embeddings` instance used to generate embeddings for the texts. - * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. - * @returns Promise that resolves with a new `FakeVectorStore` instance. - */ - static async fromTexts(texts, metadatas, embeddings, dbConfig) { - const docs = []; - for (let i = 0; i < texts.length; i += 1) { - const metadata = Array.isArray(metadatas) ? metadatas[i] : metadatas; - const newDoc = new Document({ - pageContent: texts[i], - metadata - }); - docs.push(newDoc); - } - return FakeVectorStore.fromDocuments(docs, embeddings, dbConfig); - } - /** - * Static method to create a `FakeVectorStore` instance from an array of - * `Document` instances. It adds the documents to the store. - * @param docs Array of `Document` instances to be added to the store. - * @param embeddings `Embeddings` instance used to generate embeddings for the documents. - * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. - * @returns Promise that resolves with a new `FakeVectorStore` instance. - */ - static async fromDocuments(docs, embeddings, dbConfig) { - const instance = new this(embeddings, dbConfig); - await instance.addDocuments(docs); - return instance; - } - /** - * Static method to create a `FakeVectorStore` instance from an existing - * index. It creates a new `FakeVectorStore` instance without adding any - * documents or vectors. - * @param embeddings `Embeddings` instance used to generate embeddings for the documents. - * @param dbConfig Optional `FakeVectorStoreArgs` to configure the `FakeVectorStore` instance. - * @returns Promise that resolves with a new `FakeVectorStore` instance. - */ - static async fromExistingIndex(embeddings, dbConfig) { - const instance = new this(embeddings, dbConfig); - return instance; - } -}; - -//#endregion - -//# sourceMappingURL=vectorstores.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/testing/index.js - - - - - - - - - - - - -//#region src/utils/testing/index.ts -var testing_exports = {}; -__export(testing_exports, { - FakeChatMessageHistory: () => FakeChatMessageHistory, - FakeChatModel: () => FakeChatModel, - FakeEmbeddings: () => FakeEmbeddings, - FakeLLM: () => FakeLLM, - FakeListChatMessageHistory: () => FakeListChatMessageHistory, - FakeListChatModel: () => FakeListChatModel, - FakeRetriever: () => FakeRetriever, - FakeRunnable: () => FakeRunnable, - FakeSplitIntoListParser: () => FakeSplitIntoListParser, - FakeStreamingChatModel: () => FakeStreamingChatModel, - FakeStreamingLLM: () => FakeStreamingLLM, - FakeTool: () => FakeTool, - FakeTracer: () => FakeTracer, - FakeVectorStore: () => FakeVectorStore, - SingleRunExtractor: () => SingleRunExtractor, - SyntheticEmbeddings: () => SyntheticEmbeddings -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/types/index.js - - - -//#region src/utils/types/index.ts -var types_exports = {}; -__export(types_exports, { - extendInteropZodObject: () => extendInteropZodObject, - getInteropZodDefaultGetter: () => getInteropZodDefaultGetter, - getInteropZodObjectShape: () => getInteropZodObjectShape, - getSchemaDescription: () => getSchemaDescription, - interopParse: () => interopParse, - interopParseAsync: () => interopParseAsync, - interopSafeParse: () => interopSafeParse, - interopSafeParseAsync: () => interopSafeParseAsync, - interopZodObjectMakeFieldsOptional: () => interopZodObjectMakeFieldsOptional, - interopZodObjectPartial: () => interopZodObjectPartial, - interopZodObjectPassthrough: () => interopZodObjectPassthrough, - interopZodObjectStrict: () => interopZodObjectStrict, - interopZodTransformInputSchema: () => interopZodTransformInputSchema, - isInteropZodError: () => isInteropZodError, - isInteropZodLiteral: () => isInteropZodLiteral, - isInteropZodObject: () => isInteropZodObject, - isInteropZodSchema: () => isInteropZodSchema, - isShapelessZodSchema: () => isShapelessZodSchema, - isSimpleStringZodSchema: () => isSimpleStringZodSchema, - isZodArrayV4: () => isZodArrayV4, - isZodLiteralV3: () => isZodLiteralV3, - isZodLiteralV4: () => isZodLiteralV4, - isZodNullableV4: () => isZodNullableV4, - isZodObjectV3: () => isZodObjectV3, - isZodObjectV4: () => isZodObjectV4, - isZodOptionalV4: () => isZodOptionalV4, - isZodSchema: () => isZodSchema, - isZodSchemaV3: () => isZodSchemaV3, - isZodSchemaV4: () => isZodSchemaV4 -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/event_source_parse.js - - - -//#region src/utils/event_source_parse.ts -var event_source_parse_exports = {}; -__export(event_source_parse_exports, { - EventStreamContentType: () => EventStreamContentType, - convertEventStreamToIterableReadableDataStream: () => convertEventStreamToIterableReadableDataStream, - getBytes: () => getBytes, - getLines: () => getLines, - getMessages: () => getMessages -}); -const EventStreamContentType = "text/event-stream"; -/** -* Converts a ReadableStream into a callback pattern. -* @param stream The input ReadableStream. -* @param onChunk A function that will be called on each new byte chunk in the stream. -* @returns {Promise} A promise that will be resolved when the stream closes. -*/ -async function getBytes(stream, onChunk) { - if (stream instanceof ReadableStream) { - const reader = stream.getReader(); - while (true) { - const result = await reader.read(); - if (result.done) { - onChunk(new Uint8Array(), true); - break; - } - onChunk(result.value); - } - } else try { - for await (const chunk of stream) onChunk(new Uint8Array(chunk)); - onChunk(new Uint8Array(), true); - } catch (e) { - throw new Error([ - "Parsing event source stream failed.", - "Ensure your implementation of fetch returns a web or Node readable stream.", - `Error: ${e.message}` - ].join("\n")); - } -} -var ControlChars = /* @__PURE__ */ function(ControlChars$1) { - ControlChars$1[ControlChars$1["NewLine"] = 10] = "NewLine"; - ControlChars$1[ControlChars$1["CarriageReturn"] = 13] = "CarriageReturn"; - ControlChars$1[ControlChars$1["Space"] = 32] = "Space"; - ControlChars$1[ControlChars$1["Colon"] = 58] = "Colon"; - return ControlChars$1; -}(ControlChars || {}); -/** -* Parses arbitary byte chunks into EventSource line buffers. -* Each line should be of the format "field: value" and ends with \r, \n, or \r\n. -* @param onLine A function that will be called on each new EventSource line. -* @returns A function that should be called for each incoming byte chunk. -*/ -function getLines(onLine) { - let buffer; - let position; - let fieldLength; - let discardTrailingNewline = false; - return function onChunk(arr, flush) { - if (flush) { - onLine(arr, 0, true); - return; - } - if (buffer === void 0) { - buffer = arr; - position = 0; - fieldLength = -1; - } else buffer = event_source_parse_concat(buffer, arr); - const bufLength = buffer.length; - let lineStart = 0; - while (position < bufLength) { - if (discardTrailingNewline) { - if (buffer[position] === ControlChars.NewLine) lineStart = ++position; - discardTrailingNewline = false; - } - let lineEnd = -1; - for (; position < bufLength && lineEnd === -1; ++position) switch (buffer[position]) { - case ControlChars.Colon: - if (fieldLength === -1) fieldLength = position - lineStart; - break; - case ControlChars.CarriageReturn: discardTrailingNewline = true; - case ControlChars.NewLine: - lineEnd = position; - break; - } - if (lineEnd === -1) break; - onLine(buffer.subarray(lineStart, lineEnd), fieldLength); - lineStart = position; - fieldLength = -1; - } - if (lineStart === bufLength) buffer = void 0; - else if (lineStart !== 0) { - buffer = buffer.subarray(lineStart); - position -= lineStart; - } - }; -} -/** -* Parses line buffers into EventSourceMessages. -* @param onId A function that will be called on each `id` field. -* @param onRetry A function that will be called on each `retry` field. -* @param onMessage A function that will be called on each message. -* @returns A function that should be called for each incoming line buffer. -*/ -function getMessages(onMessage, onId, onRetry) { - let message = newMessage(); - const decoder = new TextDecoder(); - return function onLine(line, fieldLength, flush) { - if (flush) { - if (!isEmpty(message)) { - onMessage?.(message); - message = newMessage(); - } - return; - } - if (line.length === 0) { - onMessage?.(message); - message = newMessage(); - } else if (fieldLength > 0) { - const field = decoder.decode(line.subarray(0, fieldLength)); - const valueOffset = fieldLength + (line[fieldLength + 1] === ControlChars.Space ? 2 : 1); - const value = decoder.decode(line.subarray(valueOffset)); - switch (field) { - case "data": - message.data = message.data ? message.data + "\n" + value : value; - break; - case "event": - message.event = value; - break; - case "id": - onId?.(message.id = value); - break; - case "retry": { - const retry = parseInt(value, 10); - if (!Number.isNaN(retry)) onRetry?.(message.retry = retry); - break; - } - } - } - }; -} -function event_source_parse_concat(a, b) { - const res = new Uint8Array(a.length + b.length); - res.set(a); - res.set(b, a.length); - return res; -} -function newMessage() { - return { - data: "", - event: "", - id: "", - retry: void 0 - }; -} -function convertEventStreamToIterableReadableDataStream(stream, onMetadataEvent) { - const dataStream = new ReadableStream({ async start(controller) { - const enqueueLine = getMessages((msg) => { - if (msg.event === "error") throw new Error(msg.data ?? "Unspecified event streaming error."); - else if (msg.event === "metadata") onMetadataEvent?.(msg); - else if (msg.data) controller.enqueue(msg.data); - }); - const onLine = (line, fieldLength, flush) => { - enqueueLine(line, fieldLength, flush); - if (flush) controller.close(); - }; - await getBytes(stream, getLines(onLine)); - } }); - return IterableReadableStream.fromReadableStream(dataStream); -} -function isEmpty(message) { - return message.data === "" && message.event === "" && message.id === "" && message.retry === void 0; -} - -//#endregion - -//# sourceMappingURL=event_source_parse.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/bytes.js - - -//#region src/output_parsers/bytes.ts -/** -* OutputParser that parses LLMResult into the top likely string and -* encodes it into bytes. -*/ -var BytesOutputParser = class extends BaseTransformOutputParser { - static lc_name() { - return "BytesOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "bytes" - ]; - lc_serializable = true; - textEncoder = new TextEncoder(); - parse(text) { - return Promise.resolve(this.textEncoder.encode(text)); - } - getFormatInstructions() { - return ""; - } -}; - -//#endregion - -//# sourceMappingURL=bytes.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/list.js - - - -//#region src/output_parsers/list.ts -/** -* Class to parse the output of an LLM call to a list. -* @augments BaseOutputParser -*/ -var ListOutputParser = class extends BaseTransformOutputParser { - re; - async *_transform(inputGenerator) { - let buffer = ""; - for await (const input of inputGenerator) { - if (typeof input === "string") buffer += input; - else buffer += input.content; - if (!this.re) { - const parts = await this.parse(buffer); - if (parts.length > 1) { - for (const part of parts.slice(0, -1)) yield [part]; - buffer = parts[parts.length - 1]; - } - } else { - const matches = [...buffer.matchAll(this.re)]; - if (matches.length > 1) { - let doneIdx = 0; - for (const match of matches.slice(0, -1)) { - yield [match[1]]; - doneIdx += (match.index ?? 0) + match[0].length; - } - buffer = buffer.slice(doneIdx); - } - } - } - for (const part of await this.parse(buffer)) yield [part]; - } -}; -/** -* Class to parse the output of an LLM call as a comma-separated list. -* @augments ListOutputParser -*/ -var CommaSeparatedListOutputParser = class extends ListOutputParser { - static lc_name() { - return "CommaSeparatedListOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - lc_serializable = true; - /** - * Parses the given text into an array of strings, using a comma as the - * separator. If the parsing fails, throws an OutputParserException. - * @param text The text to parse. - * @returns An array of strings obtained by splitting the input text at each comma. - */ - async parse(text) { - try { - return text.trim().split(",").map((s) => s.trim()); - } catch { - throw new OutputParserException(`Could not parse output: ${text}`, text); - } - } - /** - * Provides instructions on the expected format of the response for the - * CommaSeparatedListOutputParser. - * @returns A string containing instructions on the expected format of the response. - */ - getFormatInstructions() { - return `Your response should be a list of comma separated values, eg: \`foo, bar, baz\``; - } -}; -/** -* Class to parse the output of an LLM call to a list with a specific length and separator. -* @augments ListOutputParser -*/ -var CustomListOutputParser = class extends ListOutputParser { - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - length; - separator; - constructor({ length, separator }) { - super(...arguments); - this.length = length; - this.separator = separator || ","; - } - /** - * Parses the given text into an array of strings, using the specified - * separator. If the parsing fails or the number of items in the list - * doesn't match the expected length, throws an OutputParserException. - * @param text The text to parse. - * @returns An array of strings obtained by splitting the input text at each occurrence of the specified separator. - */ - async parse(text) { - try { - const items = text.trim().split(this.separator).map((s) => s.trim()); - if (this.length !== void 0 && items.length !== this.length) throw new OutputParserException(`Incorrect number of items. Expected ${this.length}, got ${items.length}.`); - return items; - } catch (e) { - if (Object.getPrototypeOf(e) === OutputParserException.prototype) throw e; - throw new OutputParserException(`Could not parse output: ${text}`); - } - } - /** - * Provides instructions on the expected format of the response for the - * CustomListOutputParser, including the number of items and the - * separator. - * @returns A string containing instructions on the expected format of the response. - */ - getFormatInstructions() { - return `Your response should be a list of ${this.length === void 0 ? "" : `${this.length} `}items separated by "${this.separator}" (eg: \`foo${this.separator} bar${this.separator} baz\`)`; - } -}; -var NumberedListOutputParser = class extends ListOutputParser { - static lc_name() { - return "NumberedListOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - lc_serializable = true; - getFormatInstructions() { - return `Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz`; - } - re = /\d+\.\s([^\n]+)/g; - async parse(text) { - return [...text.matchAll(this.re) ?? []].map((m) => m[1]); - } -}; -var MarkdownListOutputParser = class extends ListOutputParser { - static lc_name() { - return "NumberedListOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "list" - ]; - lc_serializable = true; - getFormatInstructions() { - return `Your response should be a numbered list with each item on a new line. For example: \n\n1. foo\n\n2. bar\n\n3. baz`; - } - re = /^\s*[-*]\s([^\n]+)$/gm; - async parse(text) { - return [...text.matchAll(this.re) ?? []].map((m) => m[1]); - } -}; - -//#endregion - -//# sourceMappingURL=list.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/string.js - - -//#region src/output_parsers/string.ts -/** -* OutputParser that parses LLMResult into the top likely string. -* @example -* ```typescript -* const promptTemplate = PromptTemplate.fromTemplate( -* "Tell me a joke about {topic}", -* ); -* -* const chain = RunnableSequence.from([ -* promptTemplate, -* new ChatOpenAI({ model: "gpt-4o-mini" }), -* new StringOutputParser(), -* ]); -* -* const result = await chain.invoke({ topic: "bears" }); -* console.log("What do you call a bear with no teeth? A gummy bear!"); -* ``` -*/ -var StringOutputParser = class extends BaseTransformOutputParser { - static lc_name() { - return "StrOutputParser"; - } - lc_namespace = [ - "langchain_core", - "output_parsers", - "string" - ]; - lc_serializable = true; - /** - * Parses a string output from an LLM call. This method is meant to be - * implemented by subclasses to define how a string output from an LLM - * should be parsed. - * @param text The string output from an LLM call. - * @param callbacks Optional callbacks. - * @returns A promise of the parsed output. - */ - parse(text) { - return Promise.resolve(text); - } - getFormatInstructions() { - return ""; - } - _textContentToString(content) { - return content.text; - } - _imageUrlContentToString(_content) { - throw new Error(`Cannot coerce a multimodal "image_url" message part into a string.`); - } - _messageContentToString(content) { - switch (content.type) { - case "text": - case "text_delta": - if ("text" in content) return this._textContentToString(content); - break; - case "image_url": - if ("image_url" in content) return this._imageUrlContentToString(content); - break; - default: throw new Error(`Cannot coerce "${content.type}" message part into a string.`); - } - throw new Error(`Invalid content type: ${content.type}`); - } - _baseMessageContentToString(content) { - return content.reduce((acc, item) => acc + this._messageContentToString(item), ""); - } -}; - -//#endregion - -//# sourceMappingURL=string.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/structured.js - - - - - -//#region src/output_parsers/structured.ts -var StructuredOutputParser = class extends BaseOutputParser { - static lc_name() { - return "StructuredOutputParser"; - } - lc_namespace = [ - "langchain", - "output_parsers", - "structured" - ]; - toJSON() { - return this.toJSONNotImplemented(); - } - constructor(schema) { - super(schema); - this.schema = schema; - } - /** - * Creates a new StructuredOutputParser from a Zod schema. - * @param schema The Zod schema which the output should match - * @returns A new instance of StructuredOutputParser. - */ - static fromZodSchema(schema) { - return new this(schema); - } - /** - * Creates a new StructuredOutputParser from a set of names and - * descriptions. - * @param schemas An object where each key is a name and each value is a description - * @returns A new instance of StructuredOutputParser. - */ - static fromNamesAndDescriptions(schemas) { - const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); - return new this(zodSchema); - } - /** - * Returns a markdown code snippet with a JSON object formatted according - * to the schema. - * @param options Optional. The options for formatting the instructions - * @returns A markdown code snippet with a JSON object formatted according to the schema. - */ - getFormatInstructions() { - return `You must format your output as a JSON value that adheres to a given "JSON Schema" instance. - -"JSON Schema" is a declarative language that allows you to annotate and validate JSON documents. - -For example, the example "JSON Schema" instance {{"properties": {{"foo": {{"description": "a list of test words", "type": "array", "items": {{"type": "string"}}}}}}, "required": ["foo"]}} -would match an object with one required property, "foo". The "type" property specifies "foo" must be an "array", and the "description" property semantically describes it as "a list of test words". The items within "foo" must be strings. -Thus, the object {{"foo": ["bar", "baz"]}} is a well-formatted instance of this example "JSON Schema". The object {{"properties": {{"foo": ["bar", "baz"]}}}} is not well-formatted. - -Your output will be parsed and type-checked according to the provided schema instance, so make sure all fields in your output match the schema exactly and there are no trailing commas! - -Here is the JSON Schema instance your output must adhere to. Include the enclosing markdown codeblock: -\`\`\`json -${JSON.stringify(toJsonSchema(this.schema))} -\`\`\` -`; - } - /** - * Parses the given text according to the schema. - * @param text The text to parse - * @returns The parsed output. - */ - async parse(text) { - try { - const trimmedText = text.trim(); - const json = trimmedText.match(/^```(?:json)?\s*([\s\S]*?)```/)?.[1] || trimmedText.match(/```json\s*([\s\S]*?)```/)?.[1] || trimmedText; - const escapedJson = json.replace(/"([^"\\]*(\\.[^"\\]*)*)"/g, (_match, capturedGroup) => { - const escapedInsideQuotes = capturedGroup.replace(/\n/g, "\\n"); - return `"${escapedInsideQuotes}"`; - }).replace(/\n/g, ""); - return await interopParseAsync(this.schema, JSON.parse(escapedJson)); - } catch (e) { - throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); - } - } -}; -/** -* A specific type of `StructuredOutputParser` that parses JSON data -* formatted as a markdown code snippet. -*/ -var JsonMarkdownStructuredOutputParser = class extends StructuredOutputParser { - static lc_name() { - return "JsonMarkdownStructuredOutputParser"; - } - getFormatInstructions(options) { - const interpolationDepth = options?.interpolationDepth ?? 1; - if (interpolationDepth < 1) throw new Error("f string interpolation depth must be at least 1"); - return `Return a markdown code snippet with a JSON object formatted to look like:\n\`\`\`json\n${this._schemaToInstruction(toJsonSchema(this.schema)).replaceAll("{", "{".repeat(interpolationDepth)).replaceAll("}", "}".repeat(interpolationDepth))}\n\`\`\``; - } - _schemaToInstruction(schemaInput, indent = 2) { - const schema = schemaInput; - if ("type" in schema) { - let nullable = false; - let type; - if (Array.isArray(schema.type)) { - const nullIdx = schema.type.findIndex((type$1) => type$1 === "null"); - if (nullIdx !== -1) { - nullable = true; - schema.type.splice(nullIdx, 1); - } - type = schema.type.join(" | "); - } else type = schema.type; - if (schema.type === "object" && schema.properties) { - const description$1 = schema.description ? ` // ${schema.description}` : ""; - const properties = Object.entries(schema.properties).map(([key, value]) => { - const isOptional = schema.required?.includes(key) ? "" : " (optional)"; - return `${" ".repeat(indent)}"${key}": ${this._schemaToInstruction(value, indent + 2)}${isOptional}`; - }).join("\n"); - return `{\n${properties}\n${" ".repeat(indent - 2)}}${description$1}`; - } - if (schema.type === "array" && schema.items) { - const description$1 = schema.description ? ` // ${schema.description}` : ""; - return `array[\n${" ".repeat(indent)}${this._schemaToInstruction(schema.items, indent + 2)}\n${" ".repeat(indent - 2)}] ${description$1}`; - } - const isNullable = nullable ? " (nullable)" : ""; - const description = schema.description ? ` // ${schema.description}` : ""; - return `${type}${description}${isNullable}`; - } - if ("anyOf" in schema) return schema.anyOf.map((s) => this._schemaToInstruction(s, indent)).join(`\n${" ".repeat(indent - 2)}`); - throw new Error("unsupported schema type"); - } - static fromZodSchema(schema) { - return new this(schema); - } - static fromNamesAndDescriptions(schemas) { - const zodSchema = objectType(Object.fromEntries(Object.entries(schemas).map(([name, description]) => [name, stringType().describe(description)]))); - return new this(zodSchema); - } -}; -/** -* A type of `StructuredOutputParser` that handles asymmetric input and -* output schemas. -*/ -var AsymmetricStructuredOutputParser = class extends BaseOutputParser { - structuredInputParser; - constructor({ inputSchema }) { - super(...arguments); - this.structuredInputParser = new JsonMarkdownStructuredOutputParser(inputSchema); - } - async parse(text) { - let parsedInput; - try { - parsedInput = await this.structuredInputParser.parse(text); - } catch (e) { - throw new OutputParserException(`Failed to parse. Text: "${text}". Error: ${e}`, text); - } - return this.outputProcessor(parsedInput); - } - getFormatInstructions() { - return this.structuredInputParser.getFormatInstructions(); - } -}; - -//#endregion - -//# sourceMappingURL=structured.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/sax-js/sax.js -//#region src/utils/sax-js/sax.ts -const initializeSax = function() { - const sax$1 = {}; - sax$1.parser = function(strict, opt) { - return new SAXParser(strict, opt); - }; - sax$1.SAXParser = SAXParser; - sax$1.SAXStream = SAXStream; - sax$1.createStream = createStream; - sax$1.MAX_BUFFER_LENGTH = 64 * 1024; - const buffers = [ - "comment", - "sgmlDecl", - "textNode", - "tagName", - "doctype", - "procInstName", - "procInstBody", - "entity", - "attribName", - "attribValue", - "cdata", - "script" - ]; - sax$1.EVENTS = [ - "text", - "processinginstruction", - "sgmldeclaration", - "doctype", - "comment", - "opentagstart", - "attribute", - "opentag", - "closetag", - "opencdata", - "cdata", - "closecdata", - "error", - "end", - "ready", - "script", - "opennamespace", - "closenamespace" - ]; - function SAXParser(strict, opt) { - if (!(this instanceof SAXParser)) return new SAXParser(strict, opt); - var parser = this; - clearBuffers(parser); - parser.q = parser.c = ""; - parser.bufferCheckPosition = sax$1.MAX_BUFFER_LENGTH; - parser.opt = opt || {}; - parser.opt.lowercase = parser.opt.lowercase || parser.opt.lowercasetags; - parser.looseCase = parser.opt.lowercase ? "toLowerCase" : "toUpperCase"; - parser.tags = []; - parser.closed = parser.closedRoot = parser.sawRoot = false; - parser.tag = parser.error = null; - parser.strict = !!strict; - parser.noscript = !!(strict || parser.opt.noscript); - parser.state = S.BEGIN; - parser.strictEntities = parser.opt.strictEntities; - parser.ENTITIES = parser.strictEntities ? Object.create(sax$1.XML_ENTITIES) : Object.create(sax$1.ENTITIES); - parser.attribList = []; - if (parser.opt.xmlns) parser.ns = Object.create(rootNS); - parser.trackPosition = parser.opt.position !== false; - if (parser.trackPosition) parser.position = parser.line = parser.column = 0; - emit(parser, "onready"); - } - if (!Object.create) Object.create = function(o) { - function F() {} - F.prototype = o; - var newf = new F(); - return newf; - }; - if (!Object.keys) Object.keys = function(o) { - var a = []; - for (var i in o) if (o.hasOwnProperty(i)) a.push(i); - return a; - }; - function checkBufferLength(parser) { - var maxAllowed = Math.max(sax$1.MAX_BUFFER_LENGTH, 10); - var maxActual = 0; - for (var i = 0, l = buffers.length; i < l; i++) { - var len = parser[buffers[i]].length; - if (len > maxAllowed) switch (buffers[i]) { - case "textNode": - closeText(parser); - break; - case "cdata": - emitNode(parser, "oncdata", parser.cdata); - parser.cdata = ""; - break; - case "script": - emitNode(parser, "onscript", parser.script); - parser.script = ""; - break; - default: error(parser, "Max buffer length exceeded: " + buffers[i]); - } - maxActual = Math.max(maxActual, len); - } - var m = sax$1.MAX_BUFFER_LENGTH - maxActual; - parser.bufferCheckPosition = m + parser.position; - } - function clearBuffers(parser) { - for (var i = 0, l = buffers.length; i < l; i++) parser[buffers[i]] = ""; - } - function flushBuffers(parser) { - closeText(parser); - if (parser.cdata !== "") { - emitNode(parser, "oncdata", parser.cdata); - parser.cdata = ""; - } - if (parser.script !== "") { - emitNode(parser, "onscript", parser.script); - parser.script = ""; - } - } - SAXParser.prototype = { - end: function() { - end(this); - }, - write, - resume: function() { - this.error = null; - return this; - }, - close: function() { - return this.write(null); - }, - flush: function() { - flushBuffers(this); - } - }; - var Stream = ReadableStream; - if (!Stream) Stream = function() {}; - var streamWraps = sax$1.EVENTS.filter(function(ev) { - return ev !== "error" && ev !== "end"; - }); - function createStream(strict, opt) { - return new SAXStream(strict, opt); - } - function SAXStream(strict, opt) { - if (!(this instanceof SAXStream)) return new SAXStream(strict, opt); - Stream.apply(this); - this._parser = new SAXParser(strict, opt); - this.writable = true; - this.readable = true; - var me = this; - this._parser.onend = function() { - me.emit("end"); - }; - this._parser.onerror = function(er) { - me.emit("error", er); - me._parser.error = null; - }; - this._decoder = null; - streamWraps.forEach(function(ev) { - Object.defineProperty(me, "on" + ev, { - get: function() { - return me._parser["on" + ev]; - }, - set: function(h) { - if (!h) { - me.removeAllListeners(ev); - me._parser["on" + ev] = h; - return h; - } - me.on(ev, h); - }, - enumerable: true, - configurable: false - }); - }); - } - SAXStream.prototype = Object.create(Stream.prototype, { constructor: { value: SAXStream } }); - SAXStream.prototype.write = function(data) { - this._parser.write(data.toString()); - this.emit("data", data); - return true; - }; - SAXStream.prototype.end = function(chunk) { - if (chunk && chunk.length) this.write(chunk); - this._parser.end(); - return true; - }; - SAXStream.prototype.on = function(ev, handler) { - var me = this; - if (!me._parser["on" + ev] && streamWraps.indexOf(ev) !== -1) me._parser["on" + ev] = function() { - var args = arguments.length === 1 ? [arguments[0]] : Array.apply(null, arguments); - args.splice(0, 0, ev); - me.emit.apply(me, args); - }; - return Stream.prototype.on.call(me, ev, handler); - }; - var CDATA = "[CDATA["; - var DOCTYPE = "DOCTYPE"; - var XML_NAMESPACE = "http://www.w3.org/XML/1998/namespace"; - var XMLNS_NAMESPACE = "http://www.w3.org/2000/xmlns/"; - var rootNS = { - xml: XML_NAMESPACE, - xmlns: XMLNS_NAMESPACE - }; - var nameStart = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; - var nameBody = /[:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; - var entityStart = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD]/; - var entityBody = /[#:_A-Za-z\u00C0-\u00D6\u00D8-\u00F6\u00F8-\u02FF\u0370-\u037D\u037F-\u1FFF\u200C-\u200D\u2070-\u218F\u2C00-\u2FEF\u3001-\uD7FF\uF900-\uFDCF\uFDF0-\uFFFD\u00B7\u0300-\u036F\u203F-\u2040.\d-]/; - function isWhitespace(c) { - return c === " " || c === "\n" || c === "\r" || c === " "; - } - function isQuote(c) { - return c === "\"" || c === "'"; - } - function isAttribEnd(c) { - return c === ">" || isWhitespace(c); - } - function isMatch(regex, c) { - return regex.test(c); - } - function notMatch(regex, c) { - return !isMatch(regex, c); - } - var S = 0; - sax$1.STATE = { - BEGIN: S++, - BEGIN_WHITESPACE: S++, - TEXT: S++, - TEXT_ENTITY: S++, - OPEN_WAKA: S++, - SGML_DECL: S++, - SGML_DECL_QUOTED: S++, - DOCTYPE: S++, - DOCTYPE_QUOTED: S++, - DOCTYPE_DTD: S++, - DOCTYPE_DTD_QUOTED: S++, - COMMENT_STARTING: S++, - COMMENT: S++, - COMMENT_ENDING: S++, - COMMENT_ENDED: S++, - CDATA: S++, - CDATA_ENDING: S++, - CDATA_ENDING_2: S++, - PROC_INST: S++, - PROC_INST_BODY: S++, - PROC_INST_ENDING: S++, - OPEN_TAG: S++, - OPEN_TAG_SLASH: S++, - ATTRIB: S++, - ATTRIB_NAME: S++, - ATTRIB_NAME_SAW_WHITE: S++, - ATTRIB_VALUE: S++, - ATTRIB_VALUE_QUOTED: S++, - ATTRIB_VALUE_CLOSED: S++, - ATTRIB_VALUE_UNQUOTED: S++, - ATTRIB_VALUE_ENTITY_Q: S++, - ATTRIB_VALUE_ENTITY_U: S++, - CLOSE_TAG: S++, - CLOSE_TAG_SAW_WHITE: S++, - SCRIPT: S++, - SCRIPT_ENDING: S++ - }; - sax$1.XML_ENTITIES = { - amp: "&", - gt: ">", - lt: "<", - quot: "\"", - apos: "'" - }; - sax$1.ENTITIES = { - amp: "&", - gt: ">", - lt: "<", - quot: "\"", - apos: "'", - AElig: 198, - Aacute: 193, - Acirc: 194, - Agrave: 192, - Aring: 197, - Atilde: 195, - Auml: 196, - Ccedil: 199, - ETH: 208, - Eacute: 201, - Ecirc: 202, - Egrave: 200, - Euml: 203, - Iacute: 205, - Icirc: 206, - Igrave: 204, - Iuml: 207, - Ntilde: 209, - Oacute: 211, - Ocirc: 212, - Ograve: 210, - Oslash: 216, - Otilde: 213, - Ouml: 214, - THORN: 222, - Uacute: 218, - Ucirc: 219, - Ugrave: 217, - Uuml: 220, - Yacute: 221, - aacute: 225, - acirc: 226, - aelig: 230, - agrave: 224, - aring: 229, - atilde: 227, - auml: 228, - ccedil: 231, - eacute: 233, - ecirc: 234, - egrave: 232, - eth: 240, - euml: 235, - iacute: 237, - icirc: 238, - igrave: 236, - iuml: 239, - ntilde: 241, - oacute: 243, - ocirc: 244, - ograve: 242, - oslash: 248, - otilde: 245, - ouml: 246, - szlig: 223, - thorn: 254, - uacute: 250, - ucirc: 251, - ugrave: 249, - uuml: 252, - yacute: 253, - yuml: 255, - copy: 169, - reg: 174, - nbsp: 160, - iexcl: 161, - cent: 162, - pound: 163, - curren: 164, - yen: 165, - brvbar: 166, - sect: 167, - uml: 168, - ordf: 170, - laquo: 171, - not: 172, - shy: 173, - macr: 175, - deg: 176, - plusmn: 177, - sup1: 185, - sup2: 178, - sup3: 179, - acute: 180, - micro: 181, - para: 182, - middot: 183, - cedil: 184, - ordm: 186, - raquo: 187, - frac14: 188, - frac12: 189, - frac34: 190, - iquest: 191, - times: 215, - divide: 247, - OElig: 338, - oelig: 339, - Scaron: 352, - scaron: 353, - Yuml: 376, - fnof: 402, - circ: 710, - tilde: 732, - Alpha: 913, - Beta: 914, - Gamma: 915, - Delta: 916, - Epsilon: 917, - Zeta: 918, - Eta: 919, - Theta: 920, - Iota: 921, - Kappa: 922, - Lambda: 923, - Mu: 924, - Nu: 925, - Xi: 926, - Omicron: 927, - Pi: 928, - Rho: 929, - Sigma: 931, - Tau: 932, - Upsilon: 933, - Phi: 934, - Chi: 935, - Psi: 936, - Omega: 937, - alpha: 945, - beta: 946, - gamma: 947, - delta: 948, - epsilon: 949, - zeta: 950, - eta: 951, - theta: 952, - iota: 953, - kappa: 954, - lambda: 955, - mu: 956, - nu: 957, - xi: 958, - omicron: 959, - pi: 960, - rho: 961, - sigmaf: 962, - sigma: 963, - tau: 964, - upsilon: 965, - phi: 966, - chi: 967, - psi: 968, - omega: 969, - thetasym: 977, - upsih: 978, - piv: 982, - ensp: 8194, - emsp: 8195, - thinsp: 8201, - zwnj: 8204, - zwj: 8205, - lrm: 8206, - rlm: 8207, - ndash: 8211, - mdash: 8212, - lsquo: 8216, - rsquo: 8217, - sbquo: 8218, - ldquo: 8220, - rdquo: 8221, - bdquo: 8222, - dagger: 8224, - Dagger: 8225, - bull: 8226, - hellip: 8230, - permil: 8240, - prime: 8242, - Prime: 8243, - lsaquo: 8249, - rsaquo: 8250, - oline: 8254, - frasl: 8260, - euro: 8364, - image: 8465, - weierp: 8472, - real: 8476, - trade: 8482, - alefsym: 8501, - larr: 8592, - uarr: 8593, - rarr: 8594, - darr: 8595, - harr: 8596, - crarr: 8629, - lArr: 8656, - uArr: 8657, - rArr: 8658, - dArr: 8659, - hArr: 8660, - forall: 8704, - part: 8706, - exist: 8707, - empty: 8709, - nabla: 8711, - isin: 8712, - notin: 8713, - ni: 8715, - prod: 8719, - sum: 8721, - minus: 8722, - lowast: 8727, - radic: 8730, - prop: 8733, - infin: 8734, - ang: 8736, - and: 8743, - or: 8744, - cap: 8745, - cup: 8746, - int: 8747, - there4: 8756, - sim: 8764, - cong: 8773, - asymp: 8776, - ne: 8800, - equiv: 8801, - le: 8804, - ge: 8805, - sub: 8834, - sup: 8835, - nsub: 8836, - sube: 8838, - supe: 8839, - oplus: 8853, - otimes: 8855, - perp: 8869, - sdot: 8901, - lceil: 8968, - rceil: 8969, - lfloor: 8970, - rfloor: 8971, - lang: 9001, - rang: 9002, - loz: 9674, - spades: 9824, - clubs: 9827, - hearts: 9829, - diams: 9830 - }; - Object.keys(sax$1.ENTITIES).forEach(function(key) { - var e = sax$1.ENTITIES[key]; - var s$1 = typeof e === "number" ? String.fromCharCode(e) : e; - sax$1.ENTITIES[key] = s$1; - }); - for (var s in sax$1.STATE) sax$1.STATE[sax$1.STATE[s]] = s; - S = sax$1.STATE; - function emit(parser, event, data) { - parser[event] && parser[event](data); - } - function emitNode(parser, nodeType, data) { - if (parser.textNode) closeText(parser); - emit(parser, nodeType, data); - } - function closeText(parser) { - parser.textNode = textopts(parser.opt, parser.textNode); - if (parser.textNode) emit(parser, "ontext", parser.textNode); - parser.textNode = ""; - } - function textopts(opt, text) { - if (opt.trim) text = text.trim(); - if (opt.normalize) text = text.replace(/\s+/g, " "); - return text; - } - function error(parser, er) { - closeText(parser); - if (parser.trackPosition) er += "\nLine: " + parser.line + "\nColumn: " + parser.column + "\nChar: " + parser.c; - er = new Error(er); - parser.error = er; - emit(parser, "onerror", er); - return parser; - } - function end(parser) { - if (parser.sawRoot && !parser.closedRoot) strictFail(parser, "Unclosed root tag"); - if (parser.state !== S.BEGIN && parser.state !== S.BEGIN_WHITESPACE && parser.state !== S.TEXT) error(parser, "Unexpected end"); - closeText(parser); - parser.c = ""; - parser.closed = true; - emit(parser, "onend"); - SAXParser.call(parser, parser.strict, parser.opt); - return parser; - } - function strictFail(parser, message) { - if (typeof parser !== "object" || !(parser instanceof SAXParser)) throw new Error("bad call to strictFail"); - if (parser.strict) error(parser, message); - } - function newTag(parser) { - if (!parser.strict) parser.tagName = parser.tagName[parser.looseCase](); - var parent = parser.tags[parser.tags.length - 1] || parser; - var tag = parser.tag = { - name: parser.tagName, - attributes: {} - }; - if (parser.opt.xmlns) tag.ns = parent.ns; - parser.attribList.length = 0; - emitNode(parser, "onopentagstart", tag); - } - function qname(name, attribute) { - var i = name.indexOf(":"); - var qualName = i < 0 ? ["", name] : name.split(":"); - var prefix = qualName[0]; - var local = qualName[1]; - if (attribute && name === "xmlns") { - prefix = "xmlns"; - local = ""; - } - return { - prefix, - local - }; - } - function attrib(parser) { - if (!parser.strict) parser.attribName = parser.attribName[parser.looseCase](); - if (parser.attribList.indexOf(parser.attribName) !== -1 || parser.tag.attributes.hasOwnProperty(parser.attribName)) { - parser.attribName = parser.attribValue = ""; - return; - } - if (parser.opt.xmlns) { - var qn = qname(parser.attribName, true); - var prefix = qn.prefix; - var local = qn.local; - if (prefix === "xmlns") if (local === "xml" && parser.attribValue !== XML_NAMESPACE) strictFail(parser, "xml: prefix must be bound to " + XML_NAMESPACE + "\nActual: " + parser.attribValue); - else if (local === "xmlns" && parser.attribValue !== XMLNS_NAMESPACE) strictFail(parser, "xmlns: prefix must be bound to " + XMLNS_NAMESPACE + "\nActual: " + parser.attribValue); - else { - var tag = parser.tag; - var parent = parser.tags[parser.tags.length - 1] || parser; - if (tag.ns === parent.ns) tag.ns = Object.create(parent.ns); - tag.ns[local] = parser.attribValue; - } - parser.attribList.push([parser.attribName, parser.attribValue]); - } else { - parser.tag.attributes[parser.attribName] = parser.attribValue; - emitNode(parser, "onattribute", { - name: parser.attribName, - value: parser.attribValue - }); - } - parser.attribName = parser.attribValue = ""; - } - function openTag(parser, selfClosing) { - if (parser.opt.xmlns) { - var tag = parser.tag; - var qn = qname(parser.tagName); - tag.prefix = qn.prefix; - tag.local = qn.local; - tag.uri = tag.ns[qn.prefix] || ""; - if (tag.prefix && !tag.uri) { - strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(parser.tagName)); - tag.uri = qn.prefix; - } - var parent = parser.tags[parser.tags.length - 1] || parser; - if (tag.ns && parent.ns !== tag.ns) Object.keys(tag.ns).forEach(function(p) { - emitNode(parser, "onopennamespace", { - prefix: p, - uri: tag.ns[p] - }); - }); - for (var i = 0, l = parser.attribList.length; i < l; i++) { - var nv = parser.attribList[i]; - var name = nv[0]; - var value = nv[1]; - var qualName = qname(name, true); - var prefix = qualName.prefix; - var local = qualName.local; - var uri = prefix === "" ? "" : tag.ns[prefix] || ""; - var a = { - name, - value, - prefix, - local, - uri - }; - if (prefix && prefix !== "xmlns" && !uri) { - strictFail(parser, "Unbound namespace prefix: " + JSON.stringify(prefix)); - a.uri = prefix; - } - parser.tag.attributes[name] = a; - emitNode(parser, "onattribute", a); - } - parser.attribList.length = 0; - } - parser.tag.isSelfClosing = !!selfClosing; - parser.sawRoot = true; - parser.tags.push(parser.tag); - emitNode(parser, "onopentag", parser.tag); - if (!selfClosing) { - if (!parser.noscript && parser.tagName.toLowerCase() === "script") parser.state = S.SCRIPT; - else parser.state = S.TEXT; - parser.tag = null; - parser.tagName = ""; - } - parser.attribName = parser.attribValue = ""; - parser.attribList.length = 0; - } - function closeTag(parser) { - if (!parser.tagName) { - strictFail(parser, "Weird empty close tag."); - parser.textNode += ""; - parser.state = S.TEXT; - return; - } - if (parser.script) { - if (parser.tagName !== "script") { - parser.script += ""; - parser.tagName = ""; - parser.state = S.SCRIPT; - return; - } - emitNode(parser, "onscript", parser.script); - parser.script = ""; - } - var t = parser.tags.length; - var tagName = parser.tagName; - if (!parser.strict) tagName = tagName[parser.looseCase](); - var closeTo = tagName; - while (t--) { - var close = parser.tags[t]; - if (close.name !== closeTo) strictFail(parser, "Unexpected close tag"); - else break; - } - if (t < 0) { - strictFail(parser, "Unmatched closing tag: " + parser.tagName); - parser.textNode += ""; - parser.state = S.TEXT; - return; - } - parser.tagName = tagName; - var s$1 = parser.tags.length; - while (s$1-- > t) { - var tag = parser.tag = parser.tags.pop(); - parser.tagName = parser.tag.name; - emitNode(parser, "onclosetag", parser.tagName); - var x = {}; - for (var i in tag.ns) x[i] = tag.ns[i]; - var parent = parser.tags[parser.tags.length - 1] || parser; - if (parser.opt.xmlns && tag.ns !== parent.ns) Object.keys(tag.ns).forEach(function(p) { - var n = tag.ns[p]; - emitNode(parser, "onclosenamespace", { - prefix: p, - uri: n - }); - }); - } - if (t === 0) parser.closedRoot = true; - parser.tagName = parser.attribValue = parser.attribName = ""; - parser.attribList.length = 0; - parser.state = S.TEXT; - } - function parseEntity(parser) { - var entity = parser.entity; - var entityLC = entity.toLowerCase(); - var num; - var numStr = ""; - if (parser.ENTITIES[entity]) return parser.ENTITIES[entity]; - if (parser.ENTITIES[entityLC]) return parser.ENTITIES[entityLC]; - entity = entityLC; - if (entity.charAt(0) === "#") if (entity.charAt(1) === "x") { - entity = entity.slice(2); - num = parseInt(entity, 16); - numStr = num.toString(16); - } else { - entity = entity.slice(1); - num = parseInt(entity, 10); - numStr = num.toString(10); - } - entity = entity.replace(/^0+/, ""); - if (isNaN(num) || numStr.toLowerCase() !== entity) { - strictFail(parser, "Invalid character entity"); - return "&" + parser.entity + ";"; - } - return String.fromCodePoint(num); - } - function beginWhiteSpace(parser, c) { - if (c === "<") { - parser.state = S.OPEN_WAKA; - parser.startTagPosition = parser.position; - } else if (!isWhitespace(c)) { - strictFail(parser, "Non-whitespace before first tag."); - parser.textNode = c; - parser.state = S.TEXT; - } - } - function charAt(chunk, i) { - var result = ""; - if (i < chunk.length) result = chunk.charAt(i); - return result; - } - function write(chunk) { - var parser = this; - if (this.error) throw this.error; - if (parser.closed) return error(parser, "Cannot write after close. Assign an onready handler."); - if (chunk === null) return end(parser); - if (typeof chunk === "object") chunk = chunk.toString(); - var i = 0; - var c = ""; - while (true) { - c = charAt(chunk, i++); - parser.c = c; - if (!c) break; - if (parser.trackPosition) { - parser.position++; - if (c === "\n") { - parser.line++; - parser.column = 0; - } else parser.column++; - } - switch (parser.state) { - case S.BEGIN: - parser.state = S.BEGIN_WHITESPACE; - if (c === "") continue; - beginWhiteSpace(parser, c); - continue; - case S.BEGIN_WHITESPACE: - beginWhiteSpace(parser, c); - continue; - case S.TEXT: - if (parser.sawRoot && !parser.closedRoot) { - var starti = i - 1; - while (c && c !== "<" && c !== "&") { - c = charAt(chunk, i++); - if (c && parser.trackPosition) { - parser.position++; - if (c === "\n") { - parser.line++; - parser.column = 0; - } else parser.column++; - } - } - parser.textNode += chunk.substring(starti, i - 1); - } - if (c === "<" && !(parser.sawRoot && parser.closedRoot && !parser.strict)) { - parser.state = S.OPEN_WAKA; - parser.startTagPosition = parser.position; - } else { - if (!isWhitespace(c) && (!parser.sawRoot || parser.closedRoot)) strictFail(parser, "Text data outside of root node."); - if (c === "&") parser.state = S.TEXT_ENTITY; - else parser.textNode += c; - } - continue; - case S.SCRIPT: - if (c === "<") parser.state = S.SCRIPT_ENDING; - else parser.script += c; - continue; - case S.SCRIPT_ENDING: - if (c === "/") parser.state = S.CLOSE_TAG; - else { - parser.script += "<" + c; - parser.state = S.SCRIPT; - } - continue; - case S.OPEN_WAKA: - if (c === "!") { - parser.state = S.SGML_DECL; - parser.sgmlDecl = ""; - } else if (isWhitespace(c)) {} else if (isMatch(nameStart, c)) { - parser.state = S.OPEN_TAG; - parser.tagName = c; - } else if (c === "/") { - parser.state = S.CLOSE_TAG; - parser.tagName = ""; - } else if (c === "?") { - parser.state = S.PROC_INST; - parser.procInstName = parser.procInstBody = ""; - } else { - strictFail(parser, "Unencoded <"); - if (parser.startTagPosition + 1 < parser.position) { - var pad = parser.position - parser.startTagPosition; - c = new Array(pad).join(" ") + c; - } - parser.textNode += "<" + c; - parser.state = S.TEXT; - } - continue; - case S.SGML_DECL: - if ((parser.sgmlDecl + c).toUpperCase() === CDATA) { - emitNode(parser, "onopencdata"); - parser.state = S.CDATA; - parser.sgmlDecl = ""; - parser.cdata = ""; - } else if (parser.sgmlDecl + c === "--") { - parser.state = S.COMMENT; - parser.comment = ""; - parser.sgmlDecl = ""; - } else if ((parser.sgmlDecl + c).toUpperCase() === DOCTYPE) { - parser.state = S.DOCTYPE; - if (parser.doctype || parser.sawRoot) strictFail(parser, "Inappropriately located doctype declaration"); - parser.doctype = ""; - parser.sgmlDecl = ""; - } else if (c === ">") { - emitNode(parser, "onsgmldeclaration", parser.sgmlDecl); - parser.sgmlDecl = ""; - parser.state = S.TEXT; - } else if (isQuote(c)) { - parser.state = S.SGML_DECL_QUOTED; - parser.sgmlDecl += c; - } else parser.sgmlDecl += c; - continue; - case S.SGML_DECL_QUOTED: - if (c === parser.q) { - parser.state = S.SGML_DECL; - parser.q = ""; - } - parser.sgmlDecl += c; - continue; - case S.DOCTYPE: - if (c === ">") { - parser.state = S.TEXT; - emitNode(parser, "ondoctype", parser.doctype); - parser.doctype = true; - } else { - parser.doctype += c; - if (c === "[") parser.state = S.DOCTYPE_DTD; - else if (isQuote(c)) { - parser.state = S.DOCTYPE_QUOTED; - parser.q = c; - } - } - continue; - case S.DOCTYPE_QUOTED: - parser.doctype += c; - if (c === parser.q) { - parser.q = ""; - parser.state = S.DOCTYPE; - } - continue; - case S.DOCTYPE_DTD: - parser.doctype += c; - if (c === "]") parser.state = S.DOCTYPE; - else if (isQuote(c)) { - parser.state = S.DOCTYPE_DTD_QUOTED; - parser.q = c; - } - continue; - case S.DOCTYPE_DTD_QUOTED: - parser.doctype += c; - if (c === parser.q) { - parser.state = S.DOCTYPE_DTD; - parser.q = ""; - } - continue; - case S.COMMENT: - if (c === "-") parser.state = S.COMMENT_ENDING; - else parser.comment += c; - continue; - case S.COMMENT_ENDING: - if (c === "-") { - parser.state = S.COMMENT_ENDED; - parser.comment = textopts(parser.opt, parser.comment); - if (parser.comment) emitNode(parser, "oncomment", parser.comment); - parser.comment = ""; - } else { - parser.comment += "-" + c; - parser.state = S.COMMENT; - } - continue; - case S.COMMENT_ENDED: - if (c !== ">") { - strictFail(parser, "Malformed comment"); - parser.comment += "--" + c; - parser.state = S.COMMENT; - } else parser.state = S.TEXT; - continue; - case S.CDATA: - if (c === "]") parser.state = S.CDATA_ENDING; - else parser.cdata += c; - continue; - case S.CDATA_ENDING: - if (c === "]") parser.state = S.CDATA_ENDING_2; - else { - parser.cdata += "]" + c; - parser.state = S.CDATA; - } - continue; - case S.CDATA_ENDING_2: - if (c === ">") { - if (parser.cdata) emitNode(parser, "oncdata", parser.cdata); - emitNode(parser, "onclosecdata"); - parser.cdata = ""; - parser.state = S.TEXT; - } else if (c === "]") parser.cdata += "]"; - else { - parser.cdata += "]]" + c; - parser.state = S.CDATA; - } - continue; - case S.PROC_INST: - if (c === "?") parser.state = S.PROC_INST_ENDING; - else if (isWhitespace(c)) parser.state = S.PROC_INST_BODY; - else parser.procInstName += c; - continue; - case S.PROC_INST_BODY: - if (!parser.procInstBody && isWhitespace(c)) continue; - else if (c === "?") parser.state = S.PROC_INST_ENDING; - else parser.procInstBody += c; - continue; - case S.PROC_INST_ENDING: - if (c === ">") { - emitNode(parser, "onprocessinginstruction", { - name: parser.procInstName, - body: parser.procInstBody - }); - parser.procInstName = parser.procInstBody = ""; - parser.state = S.TEXT; - } else { - parser.procInstBody += "?" + c; - parser.state = S.PROC_INST_BODY; - } - continue; - case S.OPEN_TAG: - if (isMatch(nameBody, c)) parser.tagName += c; - else { - newTag(parser); - if (c === ">") openTag(parser); - else if (c === "/") parser.state = S.OPEN_TAG_SLASH; - else { - if (!isWhitespace(c)) strictFail(parser, "Invalid character in tag name"); - parser.state = S.ATTRIB; - } - } - continue; - case S.OPEN_TAG_SLASH: - if (c === ">") { - openTag(parser, true); - closeTag(parser); - } else { - strictFail(parser, "Forward-slash in opening tag not followed by >"); - parser.state = S.ATTRIB; - } - continue; - case S.ATTRIB: - if (isWhitespace(c)) continue; - else if (c === ">") openTag(parser); - else if (c === "/") parser.state = S.OPEN_TAG_SLASH; - else if (isMatch(nameStart, c)) { - parser.attribName = c; - parser.attribValue = ""; - parser.state = S.ATTRIB_NAME; - } else strictFail(parser, "Invalid attribute name"); - continue; - case S.ATTRIB_NAME: - if (c === "=") parser.state = S.ATTRIB_VALUE; - else if (c === ">") { - strictFail(parser, "Attribute without value"); - parser.attribValue = parser.attribName; - attrib(parser); - openTag(parser); - } else if (isWhitespace(c)) parser.state = S.ATTRIB_NAME_SAW_WHITE; - else if (isMatch(nameBody, c)) parser.attribName += c; - else strictFail(parser, "Invalid attribute name"); - continue; - case S.ATTRIB_NAME_SAW_WHITE: - if (c === "=") parser.state = S.ATTRIB_VALUE; - else if (isWhitespace(c)) continue; - else { - strictFail(parser, "Attribute without value"); - parser.tag.attributes[parser.attribName] = ""; - parser.attribValue = ""; - emitNode(parser, "onattribute", { - name: parser.attribName, - value: "" - }); - parser.attribName = ""; - if (c === ">") openTag(parser); - else if (isMatch(nameStart, c)) { - parser.attribName = c; - parser.state = S.ATTRIB_NAME; - } else { - strictFail(parser, "Invalid attribute name"); - parser.state = S.ATTRIB; - } - } - continue; - case S.ATTRIB_VALUE: - if (isWhitespace(c)) continue; - else if (isQuote(c)) { - parser.q = c; - parser.state = S.ATTRIB_VALUE_QUOTED; - } else { - strictFail(parser, "Unquoted attribute value"); - parser.state = S.ATTRIB_VALUE_UNQUOTED; - parser.attribValue = c; - } - continue; - case S.ATTRIB_VALUE_QUOTED: - if (c !== parser.q) { - if (c === "&") parser.state = S.ATTRIB_VALUE_ENTITY_Q; - else parser.attribValue += c; - continue; - } - attrib(parser); - parser.q = ""; - parser.state = S.ATTRIB_VALUE_CLOSED; - continue; - case S.ATTRIB_VALUE_CLOSED: - if (isWhitespace(c)) parser.state = S.ATTRIB; - else if (c === ">") openTag(parser); - else if (c === "/") parser.state = S.OPEN_TAG_SLASH; - else if (isMatch(nameStart, c)) { - strictFail(parser, "No whitespace between attributes"); - parser.attribName = c; - parser.attribValue = ""; - parser.state = S.ATTRIB_NAME; - } else strictFail(parser, "Invalid attribute name"); - continue; - case S.ATTRIB_VALUE_UNQUOTED: - if (!isAttribEnd(c)) { - if (c === "&") parser.state = S.ATTRIB_VALUE_ENTITY_U; - else parser.attribValue += c; - continue; - } - attrib(parser); - if (c === ">") openTag(parser); - else parser.state = S.ATTRIB; - continue; - case S.CLOSE_TAG: - if (!parser.tagName) if (isWhitespace(c)) continue; - else if (notMatch(nameStart, c)) if (parser.script) { - parser.script += "") closeTag(parser); - else if (isMatch(nameBody, c)) parser.tagName += c; - else if (parser.script) { - parser.script += "") closeTag(parser); - else strictFail(parser, "Invalid characters in closing tag"); - continue; - case S.TEXT_ENTITY: - case S.ATTRIB_VALUE_ENTITY_Q: - case S.ATTRIB_VALUE_ENTITY_U: - var returnState; - var buffer; - switch (parser.state) { - case S.TEXT_ENTITY: - returnState = S.TEXT; - buffer = "textNode"; - break; - case S.ATTRIB_VALUE_ENTITY_Q: - returnState = S.ATTRIB_VALUE_QUOTED; - buffer = "attribValue"; - break; - case S.ATTRIB_VALUE_ENTITY_U: - returnState = S.ATTRIB_VALUE_UNQUOTED; - buffer = "attribValue"; - break; - } - if (c === ";") if (parser.opt.unparsedEntities) { - var parsedEntity = parseEntity(parser); - parser.entity = ""; - parser.state = returnState; - parser.write(parsedEntity); - } else { - parser[buffer] += parseEntity(parser); - parser.entity = ""; - parser.state = returnState; - } - else if (isMatch(parser.entity.length ? entityBody : entityStart, c)) parser.entity += c; - else { - strictFail(parser, "Invalid character in entity name"); - parser[buffer] += "&" + parser.entity + c; - parser.entity = ""; - parser.state = returnState; - } - continue; - default: throw new Error(parser, "Unknown state: " + parser.state); - } - } - if (parser.position >= parser.bufferCheckPosition) checkBufferLength(parser); - return parser; - } - /*! http://mths.be/fromcodepoint v0.1.0 by @mathias */ - /* istanbul ignore next */ - if (!String.fromCodePoint) (function() { - var stringFromCharCode = String.fromCharCode; - var floor = Math.floor; - var fromCodePoint = function() { - var MAX_SIZE = 16384; - var codeUnits = []; - var highSurrogate; - var lowSurrogate; - var index = -1; - var length = arguments.length; - if (!length) return ""; - var result = ""; - while (++index < length) { - var codePoint = Number(arguments[index]); - if (!isFinite(codePoint) || codePoint < 0 || codePoint > 1114111 || floor(codePoint) !== codePoint) throw RangeError("Invalid code point: " + codePoint); - if (codePoint <= 65535) codeUnits.push(codePoint); - else { - codePoint -= 65536; - highSurrogate = (codePoint >> 10) + 55296; - lowSurrogate = codePoint % 1024 + 56320; - codeUnits.push(highSurrogate, lowSurrogate); - } - if (index + 1 === length || codeUnits.length > MAX_SIZE) { - result += stringFromCharCode.apply(null, codeUnits); - codeUnits.length = 0; - } - } - return result; - }; - /* istanbul ignore next */ - if (Object.defineProperty) Object.defineProperty(String, "fromCodePoint", { - value: fromCodePoint, - configurable: true, - writable: true - }); - else String.fromCodePoint = fromCodePoint; - })(); - return sax$1; -}; -const sax = initializeSax(); - -//#endregion - -//# sourceMappingURL=sax.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/xml.js - - - - - -//#region src/output_parsers/xml.ts -const XML_FORMAT_INSTRUCTIONS = `The output should be formatted as a XML file. -1. Output should conform to the tags below. -2. If tags are not given, make them on your own. -3. Remember to always open and close all the tags. - -As an example, for the tags ["foo", "bar", "baz"]: -1. String "\n \n \n \n" is a well-formatted instance of the schema. -2. String "\n \n " is a badly-formatted instance. -3. String "\n \n \n" is a badly-formatted instance. - -Here are the output tags: -\`\`\` -{tags} -\`\`\``; -var XMLOutputParser = class extends BaseCumulativeTransformOutputParser { - tags; - constructor(fields) { - super(fields); - this.tags = fields?.tags; - } - static lc_name() { - return "XMLOutputParser"; - } - lc_namespace = ["langchain_core", "output_parsers"]; - lc_serializable = true; - _diff(prev, next) { - if (!next) return void 0; - if (!prev) return [{ - op: "replace", - path: "", - value: next - }]; - return compare(prev, next); - } - async parsePartialResult(generations) { - return parseXMLMarkdown(generations[0].text); - } - async parse(text) { - return parseXMLMarkdown(text); - } - getFormatInstructions() { - const withTags = !!(this.tags && this.tags.length > 0); - return withTags ? XML_FORMAT_INSTRUCTIONS.replace("{tags}", this.tags?.join(", ") ?? "") : XML_FORMAT_INSTRUCTIONS; - } -}; -const strip = (text) => text.split("\n").map((line) => line.replace(/^\s+/, "")).join("\n").trim(); -const parseParsedResult = (input) => { - if (Object.keys(input).length === 0) return {}; - const result = {}; - if (input.children.length > 0) { - result[input.name] = input.children.map(parseParsedResult); - return result; - } else { - result[input.name] = input.text ?? void 0; - return result; - } -}; -function parseXMLMarkdown(s) { - const cleanedString = strip(s); - const parser = sax.parser(true); - let parsedResult = {}; - const elementStack = []; - parser.onopentag = (node) => { - const element = { - name: node.name, - attributes: node.attributes, - children: [], - text: "", - isSelfClosing: node.isSelfClosing - }; - if (elementStack.length > 0) { - const parentElement = elementStack[elementStack.length - 1]; - parentElement.children.push(element); - } else parsedResult = element; - if (!node.isSelfClosing) elementStack.push(element); - }; - parser.onclosetag = () => { - if (elementStack.length > 0) { - const lastElement = elementStack.pop(); - if (elementStack.length === 0 && lastElement) parsedResult = lastElement; - } - }; - parser.ontext = (text) => { - if (elementStack.length > 0) { - const currentElement = elementStack[elementStack.length - 1]; - currentElement.text += text; - } - }; - parser.onattribute = (attr) => { - if (elementStack.length > 0) { - const currentElement = elementStack[elementStack.length - 1]; - currentElement.attributes[attr.name] = attr.value; - } - }; - const match = /```(xml)?(.*)```/s.exec(cleanedString); - const xmlString = match ? match[2] : cleanedString; - parser.write(xmlString).close(); - if (parsedResult && parsedResult.name === "?xml") parsedResult = parsedResult.children[0]; - return parseParsedResult(parsedResult); -} - -//#endregion - -//# sourceMappingURL=xml.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/output_parsers/index.js - - - - - - - - - - - -//#region src/output_parsers/index.ts -var output_parsers_exports = {}; -__export(output_parsers_exports, { - AsymmetricStructuredOutputParser: () => AsymmetricStructuredOutputParser, - BaseCumulativeTransformOutputParser: () => BaseCumulativeTransformOutputParser, - BaseLLMOutputParser: () => BaseLLMOutputParser, - BaseOutputParser: () => BaseOutputParser, - BaseTransformOutputParser: () => BaseTransformOutputParser, - BytesOutputParser: () => BytesOutputParser, - CommaSeparatedListOutputParser: () => CommaSeparatedListOutputParser, - CustomListOutputParser: () => CustomListOutputParser, - JsonMarkdownStructuredOutputParser: () => JsonMarkdownStructuredOutputParser, - JsonOutputParser: () => JsonOutputParser, - ListOutputParser: () => ListOutputParser, - MarkdownListOutputParser: () => MarkdownListOutputParser, - NumberedListOutputParser: () => NumberedListOutputParser, - OutputParserException: () => OutputParserException, - StringOutputParser: () => StringOutputParser, - StructuredOutputParser: () => StructuredOutputParser, - XMLOutputParser: () => XMLOutputParser, - XML_FORMAT_INSTRUCTIONS: () => XML_FORMAT_INSTRUCTIONS, - parseJsonMarkdown: () => parseJsonMarkdown, - parsePartialJson: () => parsePartialJson, - parseXMLMarkdown: () => parseXMLMarkdown -}); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/format.js -//#region src/utils/format.ts -var format_exports = {}; - -//#endregion - -//# sourceMappingURL=format.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/ml-distance/distances.js -//#region src/utils/ml-distance/distances.ts -/** -*Returns the Inner Product similarity between vectors a and b -* @link [Inner Product Similarity algorithm](https://www.naun.org/main/NAUN/ijmmas/mmmas-49.pdf) -* @param a - first vector -* @param b - second vector -* -*/ -function innerProduct(a, b) { - let ans = 0; - for (let i = 0; i < a.length; i++) ans += a[i] * b[i]; - return ans; -} - -//#endregion - -//# sourceMappingURL=distances.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/ml-distance-euclidean/euclidean.js -//#region src/utils/ml-distance-euclidean/euclidean.ts -function squaredEuclidean(p, q) { - let d = 0; - for (let i = 0; i < p.length; i++) d += (p[i] - q[i]) * (p[i] - q[i]); - return d; -} -function euclidean(p, q) { - return Math.sqrt(squaredEuclidean(p, q)); -} - -//#endregion - -//# sourceMappingURL=euclidean.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/utils/math.js - - - - - -//#region src/utils/math.ts -var math_exports = {}; -__export(math_exports, { - cosineSimilarity: () => cosineSimilarity, - euclideanDistance: () => euclideanDistance, - innerProduct: () => innerProduct$1, - matrixFunc: () => matrixFunc, - maximalMarginalRelevance: () => maximalMarginalRelevance, - normalize: () => normalize -}); -/** -* Apply a row-wise function between two matrices with the same number of columns. -* -* @param {number[][]} X - The first matrix. -* @param {number[][]} Y - The second matrix. -* @param {VectorFunction} func - The function to apply. -* -* @throws {Error} If the number of columns in X and Y are not the same. -* -* @returns {number[][] | [[]]} A matrix where each row represents the result of applying the function between the corresponding rows of X and Y. -*/ -function matrixFunc(X, Y, func) { - if (X.length === 0 || X[0].length === 0 || Y.length === 0 || Y[0].length === 0) return [[]]; - if (X[0].length !== Y[0].length) throw new Error(`Number of columns in X and Y must be the same. X has shape ${[X.length, X[0].length]} and Y has shape ${[Y.length, Y[0].length]}.`); - return X.map((xVector) => Y.map((yVector) => func(xVector, yVector)).map((similarity) => Number.isNaN(similarity) ? 0 : similarity)); -} -function normalize(M, similarity = false) { - const max = matrixMaxVal(M); - return M.map((row) => row.map((val) => similarity ? 1 - val / max : val / max)); -} -/** -* This function calculates the row-wise cosine similarity between two matrices with the same number of columns. -* -* @param {number[][]} X - The first matrix. -* @param {number[][]} Y - The second matrix. -* -* @throws {Error} If the number of columns in X and Y are not the same. -* -* @returns {number[][] | [[]]} A matrix where each row represents the cosine similarity values between the corresponding rows of X and Y. -*/ -function cosineSimilarity(X, Y) { - return matrixFunc(X, Y, cosine); -} -function innerProduct$1(X, Y) { - return matrixFunc(X, Y, innerProduct); -} -function euclideanDistance(X, Y) { - return matrixFunc(X, Y, euclidean); -} -/** -* This function implements the Maximal Marginal Relevance algorithm -* to select a set of embeddings that maximizes the diversity and relevance to a query embedding. -* -* @param {number[]|number[][]} queryEmbedding - The query embedding. -* @param {number[][]} embeddingList - The list of embeddings to select from. -* @param {number} [lambda=0.5] - The trade-off parameter between relevance and diversity. -* @param {number} [k=4] - The maximum number of embeddings to select. -* -* @returns {number[]} The indexes of the selected embeddings in the embeddingList. -*/ -function maximalMarginalRelevance(queryEmbedding, embeddingList, lambda = .5, k = 4) { - if (Math.min(k, embeddingList.length) <= 0) return []; - const queryEmbeddingExpanded = Array.isArray(queryEmbedding[0]) ? queryEmbedding : [queryEmbedding]; - const similarityToQuery = cosineSimilarity(queryEmbeddingExpanded, embeddingList)[0]; - const mostSimilarEmbeddingIndex = argMax(similarityToQuery).maxIndex; - const selectedEmbeddings = [embeddingList[mostSimilarEmbeddingIndex]]; - const selectedEmbeddingsIndexes = [mostSimilarEmbeddingIndex]; - while (selectedEmbeddingsIndexes.length < Math.min(k, embeddingList.length)) { - let bestScore = -Infinity; - let bestIndex = -1; - const similarityToSelected = cosineSimilarity(embeddingList, selectedEmbeddings); - similarityToQuery.forEach((queryScore, queryScoreIndex) => { - if (selectedEmbeddingsIndexes.includes(queryScoreIndex)) return; - const maxSimilarityToSelected = Math.max(...similarityToSelected[queryScoreIndex]); - const score = lambda * queryScore - (1 - lambda) * maxSimilarityToSelected; - if (score > bestScore) { - bestScore = score; - bestIndex = queryScoreIndex; - } - }); - selectedEmbeddings.push(embeddingList[bestIndex]); - selectedEmbeddingsIndexes.push(bestIndex); - } - return selectedEmbeddingsIndexes; -} -/** -* Finds the index of the maximum value in the given array. -* @param {number[]} array - The input array. -* -* @returns {number} The index of the maximum value in the array. If the array is empty, returns -1. -*/ -function argMax(array) { - if (array.length === 0) return { - maxIndex: -1, - maxValue: NaN - }; - let maxValue = array[0]; - let maxIndex = 0; - for (let i = 1; i < array.length; i += 1) if (array[i] > maxValue) { - maxIndex = i; - maxValue = array[i]; - } - return { - maxIndex, - maxValue - }; -} -function matrixMaxVal(arrays) { - return arrays.reduce((acc, array) => Math.max(acc, argMax(array).maxValue), 0); -} - -//#endregion - -//# sourceMappingURL=math.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/import_map.js - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -//#region src/load/import_map.ts -var import_map_exports = {}; -__export(import_map_exports, { - agents: () => agents_exports, - caches: () => caches_exports, - callbacks__base: () => base_exports, - callbacks__manager: () => manager_exports, - callbacks__promises: () => promises_exports, - chat_history: () => chat_history_exports, - document_loaders__base: () => document_loaders_base_base_exports, - document_loaders__langsmith: () => langsmith_exports, - documents: () => documents_exports, - embeddings: () => embeddings_exports, - example_selectors: () => example_selectors_exports, - index: () => src_exports, - indexing: () => indexing_exports, - language_models__base: () => language_models_base_base_exports, - language_models__chat_models: () => chat_models_exports, - language_models__llms: () => llms_exports, - language_models__profile: () => profile_exports, - load__serializable: () => serializable_exports, - memory: () => memory_exports, - messages: () => messages_exports, - messages__tool: () => tool_exports, - output_parsers: () => output_parsers_exports, - output_parsers__openai_functions: () => openai_functions_exports, - output_parsers__openai_tools: () => openai_tools_exports, - outputs: () => outputs_exports, - prompt_values: () => prompt_values_exports, - prompts: () => prompts_exports, - retrievers: () => retrievers_exports, - retrievers__document_compressors: () => document_compressors_exports, - runnables: () => runnables_exports, - runnables__graph: () => graph_exports, - singletons: () => singletons_exports, - stores: () => stores_exports, - structured_query: () => structured_query_exports, - tools: () => tools_exports, - tracers__base: () => base_base_exports, - tracers__console: () => console_exports, - tracers__log_stream: () => log_stream_exports, - tracers__run_collector: () => run_collector_exports, - tracers__tracer_langchain: () => tracer_langchain_exports, - types__stream: () => stream_stream_exports, - utils__async_caller: () => async_caller_exports, - utils__chunk_array: () => chunk_array_exports, - utils__context: () => context_exports, - utils__env: () => env_exports, - utils__event_source_parse: () => event_source_parse_exports, - utils__format: () => format_exports, - utils__function_calling: () => function_calling_exports, - utils__hash: () => hash_exports, - utils__json_patch: () => json_patch_exports, - utils__json_schema: () => json_schema_exports, - utils__math: () => math_exports, - utils__stream: () => stream_exports, - utils__testing: () => testing_exports, - utils__tiktoken: () => tiktoken_exports, - utils__types: () => types_exports, - vectorstores: () => vectorstores_exports -}); - -//#endregion - -//# sourceMappingURL=import_map.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/core/dist/load/index.js - - - - - - - -//#region src/load/index.ts -/** -* Default maximum recursion depth for deserialization. -* This provides protection against DoS attacks via deeply nested structures. -*/ -const DEFAULT_MAX_DEPTH = 50; -function combineAliasesAndInvert(constructor) { - const aliases = {}; - for (let current = constructor; current && current.prototype; current = Object.getPrototypeOf(current)) Object.assign(aliases, Reflect.get(current.prototype, "lc_aliases")); - return Object.entries(aliases).reduce((acc, [key, value]) => { - acc[value] = key; - return acc; - }, {}); -} -/** -* Recursively revive a value, handling escape markers and LC objects. -* -* This function handles: -* 1. Escaped dicts - unwrapped and returned as plain objects -* 2. LC secret objects - resolved from secretsMap or env -* 3. LC constructor objects - instantiated -* 4. Regular objects/arrays - recursed into -*/ -async function reviver(value) { - const { optionalImportsMap, optionalImportEntrypoints: optionalImportEntrypoints$1, importMap, secretsMap, secretsFromEnv, path, depth, maxDepth } = this; - const pathStr = path.join("."); - if (depth > maxDepth) throw new Error(`Maximum recursion depth (${maxDepth}) exceeded during deserialization. This may indicate a malicious payload or you may need to increase maxDepth.`); - if (typeof value !== "object" || value == null) return value; - if (Array.isArray(value)) return Promise.all(value.map((v, i) => reviver.call({ - ...this, - path: [...path, `${i}`], - depth: depth + 1 - }, v))); - const record = value; - if (isEscapedObject(record)) return unescapeValue(record); - if ("lc" in record && "type" in record && "id" in record && record.lc === 1 && record.type === "secret") { - const serialized = record; - const [key] = serialized.id; - if (key in secretsMap) return secretsMap[key]; - else if (secretsFromEnv) { - const secretValueInEnv = getEnvironmentVariable(key); - if (secretValueInEnv) return secretValueInEnv; - } - throw new Error(`Missing secret "${key}" at ${pathStr}`); - } - if ("lc" in record && "type" in record && "id" in record && record.lc === 1 && record.type === "not_implemented") { - const serialized = record; - const str = JSON.stringify(serialized); - throw new Error(`Trying to load an object that doesn't implement serialization: ${pathStr} -> ${str}`); - } - if ("lc" in record && "type" in record && "id" in record && "kwargs" in record && record.lc === 1 && record.type === "constructor") { - const serialized = record; - const str = JSON.stringify(serialized); - const [name, ...namespaceReverse] = serialized.id.slice().reverse(); - const namespace = namespaceReverse.reverse(); - const importMaps = { - langchain_core: import_map_exports, - langchain: importMap - }; - let module = null; - const optionalImportNamespaceAliases = [namespace.join("/")]; - if (namespace[0] === "langchain_community") optionalImportNamespaceAliases.push(["langchain", ...namespace.slice(1)].join("/")); - const matchingNamespaceAlias = optionalImportNamespaceAliases.find((alias) => alias in optionalImportsMap); - if (optionalImportEntrypoints.concat(optionalImportEntrypoints$1).includes(namespace.join("/")) || matchingNamespaceAlias) if (matchingNamespaceAlias !== void 0) module = await optionalImportsMap[matchingNamespaceAlias]; - else throw new Error(`Missing key "${namespace.join("/")}" for ${pathStr} in load(optionalImportsMap={})`); - else { - let finalImportMap; - if (namespace[0] === "langchain" || namespace[0] === "langchain_core") { - finalImportMap = importMaps[namespace[0]]; - namespace.shift(); - } else throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); - if (namespace.length === 0) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); - let importMapKey; - do { - importMapKey = namespace.join("__"); - if (importMapKey in finalImportMap) break; - else namespace.pop(); - } while (namespace.length > 0); - if (importMapKey in finalImportMap) module = finalImportMap[importMapKey]; - } - if (typeof module !== "object" || module === null) throw new Error(`Invalid namespace: ${pathStr} -> ${str}`); - const builder = module[name] ?? Object.values(module).find((v) => typeof v === "function" && get_lc_unique_name(v) === name); - if (typeof builder !== "function") throw new Error(`Invalid identifer: ${pathStr} -> ${str}`); - const kwargs = await reviver.call({ - ...this, - path: [...path, "kwargs"], - depth: depth + 1 - }, serialized.kwargs); - const instance = new builder(mapKeys(kwargs, keyFromJson, combineAliasesAndInvert(builder))); - Object.defineProperty(instance.constructor, "name", { value: name }); - return instance; - } - const result = {}; - for (const [key, val] of Object.entries(record)) result[key] = await reviver.call({ - ...this, - path: [...path, key], - depth: depth + 1 - }, val); - return result; -} -/** -* Load a LangChain object from a JSON string. -* -* @param text - The JSON string to parse and load. -* @param options - Options for loading. -* @returns The loaded LangChain object. -* -* @example -* ```typescript -* import { load } from "@langchain/core/load"; -* import { AIMessage } from "@langchain/core/messages"; -* -* // Basic usage - secrets must be provided explicitly -* const msg = await load(jsonString); -* -* // With secrets from a map -* const msg = await load(jsonString, { -* secretsMap: { OPENAI_API_KEY: "sk-..." } -* }); -* -* // Allow loading secrets from environment (use with caution) -* const msg = await load(jsonString, { -* secretsFromEnv: true -* }); -* ``` -*/ -async function load(text, options) { - const json = JSON.parse(text); - const context = { - optionalImportsMap: options?.optionalImportsMap ?? {}, - optionalImportEntrypoints: options?.optionalImportEntrypoints ?? [], - secretsMap: options?.secretsMap ?? {}, - secretsFromEnv: options?.secretsFromEnv ?? false, - importMap: options?.importMap ?? {}, - path: ["$"], - depth: 0, - maxDepth: options?.maxDepth ?? DEFAULT_MAX_DEPTH - }; - return reviver.call(context, json); -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/serde/jsonplus.js - - - -//#region src/serde/jsonplus.ts -function isLangChainSerializedObject(value) { - return value !== null && value.lc === 1 && value.type === "constructor" && Array.isArray(value.id); -} -/** -* The replacer in stringify does not allow delegation to built-in LangChain -* serialization methods, and instead immediately calls `.toJSON()` and -* continues to stringify subfields. -* -* We therefore must start from the most nested elements in the input and -* deserialize upwards rather than top-down. -*/ -async function _reviver(value) { - if (value && typeof value === "object") if (Array.isArray(value)) { - const revivedArray = await Promise.all(value.map((item) => _reviver(item))); - return revivedArray; - } else { - const revivedObj = {}; - for (const [k, v] of Object.entries(value)) revivedObj[k] = await _reviver(v); - if (revivedObj.lc === 2 && revivedObj.type === "undefined") return void 0; - else if (revivedObj.lc === 2 && revivedObj.type === "constructor" && Array.isArray(revivedObj.id)) try { - const constructorName = revivedObj.id[revivedObj.id.length - 1]; - let constructor; - switch (constructorName) { - case "Set": - constructor = Set; - break; - case "Map": - constructor = Map; - break; - case "RegExp": - constructor = RegExp; - break; - case "Error": - constructor = Error; - break; - default: return revivedObj; - } - if (revivedObj.method) return constructor[revivedObj.method](...revivedObj.args || []); - else return new constructor(...revivedObj.args || []); - } catch (error) { - return revivedObj; - } - else if (isLangChainSerializedObject(revivedObj)) return load(JSON.stringify(revivedObj)); - return revivedObj; - } - return value; -} -function _encodeConstructorArgs(constructor, method, args, kwargs) { - return { - lc: 2, - type: "constructor", - id: [constructor.name], - method: method ?? null, - args: args ?? [], - kwargs: kwargs ?? {} - }; -} -function jsonplus_default(obj) { - if (obj === void 0) return { - lc: 2, - type: "undefined" - }; - else if (obj instanceof Set || obj instanceof Map) return _encodeConstructorArgs(obj.constructor, void 0, [Array.from(obj)]); - else if (obj instanceof RegExp) return _encodeConstructorArgs(RegExp, void 0, [obj.source, obj.flags]); - else if (obj instanceof Error) return _encodeConstructorArgs(obj.constructor, void 0, [obj.message]); - else if (obj?.lg_name === "Send") return { - node: obj.node, - args: obj.args - }; - else return obj; -} -var JsonPlusSerializer = class { - _dumps(obj) { - const encoder = new TextEncoder(); - return encoder.encode(fast_safe_stringify_stringify(obj, (_, value) => { - return jsonplus_default(value); - })); - } - async dumpsTyped(obj) { - if (obj instanceof Uint8Array) return ["bytes", obj]; - else return ["json", this._dumps(obj)]; - } - async _loads(data) { - const parsed = JSON.parse(data); - return _reviver(parsed); - } - async loadsTyped(type, data) { - if (type === "bytes") return typeof data === "string" ? new TextEncoder().encode(data) : data; - else if (type === "json") return this._loads(typeof data === "string" ? data : new TextDecoder().decode(data)); - else throw new Error(`Unknown serialization type: ${type}`); - } -}; - -//#endregion - -//# sourceMappingURL=jsonplus.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/base.js - - - - -//#region src/base.ts -function deepCopy(obj) { - if (typeof obj !== "object" || obj === null) return obj; - const newObj = Array.isArray(obj) ? [] : {}; - for (const key in obj) if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = deepCopy(obj[key]); - return newObj; -} -/** @hidden */ -function emptyCheckpoint() { - return { - v: 4, - id: uuid6(-2), - ts: (/* @__PURE__ */ new Date()).toISOString(), - channel_values: {}, - channel_versions: {}, - versions_seen: {} - }; -} -/** @hidden */ -function copyCheckpoint(checkpoint) { - return { - v: checkpoint.v, - id: checkpoint.id, - ts: checkpoint.ts, - channel_values: { ...checkpoint.channel_values }, - channel_versions: { ...checkpoint.channel_versions }, - versions_seen: deepCopy(checkpoint.versions_seen) - }; -} -var BaseCheckpointSaver = class { - serde = new JsonPlusSerializer(); - constructor(serde) { - this.serde = serde || this.serde; - } - async get(config) { - const value = await this.getTuple(config); - return value ? value.checkpoint : void 0; - } - /** - * Generate the next version ID for a channel. - * - * Default is to use integer versions, incrementing by 1. If you override, you can use str/int/float versions, - * as long as they are monotonically increasing. - */ - getNextVersion(current) { - if (typeof current === "string") throw new Error("Please override this method to use string versions."); - return current !== void 0 && typeof current === "number" ? current + 1 : 1; - } -}; -function compareChannelVersions(a, b) { - if (typeof a === "number" && typeof b === "number") return Math.sign(a - b); - return String(a).localeCompare(String(b)); -} -function maxChannelVersion(...versions) { - return versions.reduce((max, version, idx) => { - if (idx === 0) return version; - return compareChannelVersions(max, version) >= 0 ? max : version; - }); -} -/** -* Mapping from error type to error index. -* Regular writes just map to their index in the list of writes being saved. -* Special writes (e.g. errors) map to negative indices, to avoid those writes from -* conflicting with regular writes. -* Each Checkpointer implementation should use this mapping in put_writes. -*/ -const WRITES_IDX_MAP = { - [types_ERROR]: -1, - [SCHEDULED]: -2, - [INTERRUPT]: -3, - [RESUME]: -4 -}; -function getCheckpointId(config) { - return config.configurable?.checkpoint_id || config.configurable?.thread_ts || ""; -} - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/memory.js - - - -//#region src/memory.ts -function _generateKey(threadId, checkpointNamespace, checkpointId) { - return JSON.stringify([ - threadId, - checkpointNamespace, - checkpointId - ]); -} -function _parseKey(key) { - const [threadId, checkpointNamespace, checkpointId] = JSON.parse(key); - return { - threadId, - checkpointNamespace, - checkpointId - }; -} -var MemorySaver = class extends BaseCheckpointSaver { - storage = {}; - writes = {}; - constructor(serde) { - super(serde); - } - /** @internal */ - async _migratePendingSends(mutableCheckpoint, threadId, checkpointNs, parentCheckpointId) { - const deseriablizableCheckpoint = mutableCheckpoint; - const parentKey = _generateKey(threadId, checkpointNs, parentCheckpointId); - const pendingSends = await Promise.all(Object.values(this.writes[parentKey] ?? {}).filter(([_taskId, channel]) => channel === TASKS).map(async ([_taskId, _channel, writes]) => await this.serde.loadsTyped("json", writes))); - deseriablizableCheckpoint.channel_values ??= {}; - deseriablizableCheckpoint.channel_values[TASKS] = pendingSends; - deseriablizableCheckpoint.channel_versions ??= {}; - deseriablizableCheckpoint.channel_versions[TASKS] = Object.keys(deseriablizableCheckpoint.channel_versions).length > 0 ? maxChannelVersion(...Object.values(deseriablizableCheckpoint.channel_versions)) : this.getNextVersion(void 0); - } - async getTuple(config) { - const thread_id = config.configurable?.thread_id; - const checkpoint_ns = config.configurable?.checkpoint_ns ?? ""; - let checkpoint_id = getCheckpointId(config); - if (checkpoint_id) { - const saved = this.storage[thread_id]?.[checkpoint_ns]?.[checkpoint_id]; - if (saved !== void 0) { - const [checkpoint, metadata, parentCheckpointId] = saved; - const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id); - const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); - if (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId); - const pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => { - return [ - taskId, - channel, - await this.serde.loadsTyped("json", value) - ]; - })); - const checkpointTuple = { - config, - checkpoint: deserializedCheckpoint, - metadata: await this.serde.loadsTyped("json", metadata), - pendingWrites - }; - if (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: { - thread_id, - checkpoint_ns, - checkpoint_id: parentCheckpointId - } }; - return checkpointTuple; - } - } else { - const checkpoints = this.storage[thread_id]?.[checkpoint_ns]; - if (checkpoints !== void 0) { - checkpoint_id = Object.keys(checkpoints).sort((a, b) => b.localeCompare(a))[0]; - const saved = checkpoints[checkpoint_id]; - const [checkpoint, metadata, parentCheckpointId] = saved; - const key = _generateKey(thread_id, checkpoint_ns, checkpoint_id); - const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); - if (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, thread_id, checkpoint_ns, parentCheckpointId); - const pendingWrites = await Promise.all(Object.values(this.writes[key] || {}).map(async ([taskId, channel, value]) => { - return [ - taskId, - channel, - await this.serde.loadsTyped("json", value) - ]; - })); - const checkpointTuple = { - config: { configurable: { - thread_id, - checkpoint_id, - checkpoint_ns - } }, - checkpoint: deserializedCheckpoint, - metadata: await this.serde.loadsTyped("json", metadata), - pendingWrites - }; - if (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: { - thread_id, - checkpoint_ns, - checkpoint_id: parentCheckpointId - } }; - return checkpointTuple; - } - } - return void 0; - } - async *list(config, options) { - let { before, limit, filter } = options ?? {}; - const threadIds = config.configurable?.thread_id ? [config.configurable?.thread_id] : Object.keys(this.storage); - const configCheckpointNamespace = config.configurable?.checkpoint_ns; - const configCheckpointId = config.configurable?.checkpoint_id; - for (const threadId of threadIds) for (const checkpointNamespace of Object.keys(this.storage[threadId] ?? {})) { - if (configCheckpointNamespace !== void 0 && checkpointNamespace !== configCheckpointNamespace) continue; - const checkpoints = this.storage[threadId]?.[checkpointNamespace] ?? {}; - const sortedCheckpoints = Object.entries(checkpoints).sort((a, b) => b[0].localeCompare(a[0])); - for (const [checkpointId, [checkpoint, metadataStr, parentCheckpointId]] of sortedCheckpoints) { - if (configCheckpointId && checkpointId !== configCheckpointId) continue; - if (before && before.configurable?.checkpoint_id && checkpointId >= before.configurable.checkpoint_id) continue; - const metadata = await this.serde.loadsTyped("json", metadataStr); - if (filter && !Object.entries(filter).every(([key$1, value]) => metadata[key$1] === value)) continue; - if (limit !== void 0) { - if (limit <= 0) break; - limit -= 1; - } - const key = _generateKey(threadId, checkpointNamespace, checkpointId); - const writes = Object.values(this.writes[key] || {}); - const pendingWrites = await Promise.all(writes.map(async ([taskId, channel, value]) => { - return [ - taskId, - channel, - await this.serde.loadsTyped("json", value) - ]; - })); - const deserializedCheckpoint = await this.serde.loadsTyped("json", checkpoint); - if (deserializedCheckpoint.v < 4 && parentCheckpointId !== void 0) await this._migratePendingSends(deserializedCheckpoint, threadId, checkpointNamespace, parentCheckpointId); - const checkpointTuple = { - config: { configurable: { - thread_id: threadId, - checkpoint_ns: checkpointNamespace, - checkpoint_id: checkpointId - } }, - checkpoint: deserializedCheckpoint, - metadata, - pendingWrites - }; - if (parentCheckpointId !== void 0) checkpointTuple.parentConfig = { configurable: { - thread_id: threadId, - checkpoint_ns: checkpointNamespace, - checkpoint_id: parentCheckpointId - } }; - yield checkpointTuple; - } - } - } - async put(config, checkpoint, metadata) { - const preparedCheckpoint = copyCheckpoint(checkpoint); - const threadId = config.configurable?.thread_id; - const checkpointNamespace = config.configurable?.checkpoint_ns ?? ""; - if (threadId === void 0) throw new Error(`Failed to put checkpoint. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property.`); - if (!this.storage[threadId]) this.storage[threadId] = {}; - if (!this.storage[threadId][checkpointNamespace]) this.storage[threadId][checkpointNamespace] = {}; - const [[, serializedCheckpoint], [, serializedMetadata]] = await Promise.all([this.serde.dumpsTyped(preparedCheckpoint), this.serde.dumpsTyped(metadata)]); - this.storage[threadId][checkpointNamespace][checkpoint.id] = [ - serializedCheckpoint, - serializedMetadata, - config.configurable?.checkpoint_id - ]; - return { configurable: { - thread_id: threadId, - checkpoint_ns: checkpointNamespace, - checkpoint_id: checkpoint.id - } }; - } - async putWrites(config, writes, taskId) { - const threadId = config.configurable?.thread_id; - const checkpointNamespace = config.configurable?.checkpoint_ns; - const checkpointId = config.configurable?.checkpoint_id; - if (threadId === void 0) throw new Error(`Failed to put writes. The passed RunnableConfig is missing a required "thread_id" field in its "configurable" property`); - if (checkpointId === void 0) throw new Error(`Failed to put writes. The passed RunnableConfig is missing a required "checkpoint_id" field in its "configurable" property.`); - const outerKey = _generateKey(threadId, checkpointNamespace, checkpointId); - const outerWrites_ = this.writes[outerKey]; - if (this.writes[outerKey] === void 0) this.writes[outerKey] = {}; - await Promise.all(writes.map(async ([channel, value], idx) => { - const [, serializedValue] = await this.serde.dumpsTyped(value); - const innerKey = [taskId, WRITES_IDX_MAP[channel] || idx]; - const innerKeyStr = `${innerKey[0]},${innerKey[1]}`; - if (innerKey[1] >= 0 && outerWrites_ && innerKeyStr in outerWrites_) return; - this.writes[outerKey][innerKeyStr] = [ - taskId, - channel, - serializedValue - ]; - })); - } - async deleteThread(threadId) { - delete this.storage[threadId]; - for (const key of Object.keys(this.writes)) if (_parseKey(key).threadId === threadId) delete this.writes[key]; - } -}; - -//#endregion - -//# sourceMappingURL=memory.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/base.js -//#region src/store/base.ts -/** -* Error thrown when an invalid namespace is provided. -*/ -var InvalidNamespaceError = class extends Error { - constructor(message) { - super(message); - this.name = "InvalidNamespaceError"; - } -}; -/** -* Validates the provided namespace. -* @param namespace The namespace to validate. -* @throws {InvalidNamespaceError} If the namespace is invalid. -*/ -function validateNamespace(namespace) { - if (namespace.length === 0) throw new InvalidNamespaceError("Namespace cannot be empty."); - for (const label of namespace) { - if (typeof label !== "string") throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels must be strings, but got ${typeof label}.`); - if (label.includes(".")) throw new InvalidNamespaceError(`Invalid namespace label '${label}' found in ${namespace}. Namespace labels cannot contain periods ('.').`); - if (label === "") throw new InvalidNamespaceError(`Namespace labels cannot be empty strings. Got ${label} in ${namespace}`); - } - if (namespace[0] === "langgraph") throw new InvalidNamespaceError(`Root label for namespace cannot be "langgraph". Got: ${namespace}`); -} -/** -* Utility function to get text at a specific JSON path -*/ -function getTextAtPath(obj, path) { - const parts = path.split("."); - let current = obj; - for (const part of parts) { - if (part.includes("[")) { - const [arrayName, indexStr] = part.split("["); - const index = indexStr.replace("]", ""); - if (!current[arrayName]) return []; - if (index === "*") { - const results = []; - for (const item of current[arrayName]) if (typeof item === "string") results.push(item); - return results; - } - const idx = parseInt(index, 10); - if (Number.isNaN(idx)) return []; - current = current[arrayName][idx]; - } else current = current[part]; - if (current === void 0) return []; - } - return typeof current === "string" ? [current] : []; -} -/** -* Tokenizes a JSON path into parts -*/ -function tokenizePath(path) { - return path.split("."); -} -/** -* Abstract base class for persistent key-value stores. -* -* Stores enable persistence and memory that can be shared across threads, -* scoped to user IDs, assistant IDs, or other arbitrary namespaces. -* -* Features: -* - Hierarchical namespaces for organization -* - Key-value storage with metadata -* - Vector similarity search (if configured) -* - Filtering and pagination -*/ -var base_BaseStore = class { - /** - * Retrieve a single item by its namespace and key. - * - * @param namespace Hierarchical path for the item - * @param key Unique identifier within the namespace - * @returns Promise resolving to the item or null if not found - */ - async get(namespace, key) { - return (await this.batch([{ - namespace, - key - }]))[0]; - } - /** - * Search for items within a namespace prefix. - * Supports both metadata filtering and vector similarity search. - * - * @param namespacePrefix Hierarchical path prefix to search within - * @param options Search options for filtering and pagination - * @returns Promise resolving to list of matching items with relevance scores - * - * @example - * // Search with filters - * await store.search(["documents"], { - * filter: { type: "report", status: "active" }, - * limit: 5, - * offset: 10 - * }); - * - * // Vector similarity search - * await store.search(["users", "content"], { - * query: "technical documentation about APIs", - * limit: 20 - * }); - */ - async search(namespacePrefix, options = {}) { - const { filter, limit = 10, offset = 0, query } = options; - return (await this.batch([{ - namespacePrefix, - filter, - limit, - offset, - query - }]))[0]; - } - /** - * Store or update an item. - * - * @param namespace Hierarchical path for the item - * @param key Unique identifier within the namespace - * @param value Object containing the item's data - * @param index Optional indexing configuration - * - * @example - * // Simple storage - * await store.put(["docs"], "report", { title: "Annual Report" }); - * - * // With specific field indexing - * await store.put( - * ["docs"], - * "report", - * { - * title: "Q4 Report", - * chapters: [{ content: "..." }, { content: "..." }] - * }, - * ["title", "chapters[*].content"] - * ); - */ - async put(namespace, key, value, index) { - validateNamespace(namespace); - await this.batch([{ - namespace, - key, - value, - index - }]); - } - /** - * Delete an item from the store. - * - * @param namespace Hierarchical path for the item - * @param key Unique identifier within the namespace - */ - async delete(namespace, key) { - await this.batch([{ - namespace, - key, - value: null - }]); - } - /** - * List and filter namespaces in the store. - * Used to explore data organization and navigate the namespace hierarchy. - * - * @param options Options for listing namespaces - * @returns Promise resolving to list of namespace paths - * - * @example - * // List all namespaces under "documents" - * await store.listNamespaces({ - * prefix: ["documents"], - * maxDepth: 2 - * }); - * - * // List namespaces ending with "v1" - * await store.listNamespaces({ - * suffix: ["v1"], - * limit: 50 - * }); - */ - async listNamespaces(options = {}) { - const { prefix, suffix, maxDepth, limit = 100, offset = 0 } = options; - const matchConditions = []; - if (prefix) matchConditions.push({ - matchType: "prefix", - path: prefix - }); - if (suffix) matchConditions.push({ - matchType: "suffix", - path: suffix - }); - return (await this.batch([{ - matchConditions: matchConditions.length ? matchConditions : void 0, - maxDepth, - limit, - offset - }]))[0]; - } - /** - * Start the store. Override if initialization is needed. - */ - start() {} - /** - * Stop the store. Override if cleanup is needed. - */ - stop() {} -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/batch.js - - -//#region src/store/batch.ts -/** -* Extracts and returns the underlying store from an `AsyncBatchedStore`, -* or returns the input if it is not an `AsyncBatchedStore`. -*/ -const extractStore = (input) => { - if ("lg_name" in input && input.lg_name === "AsyncBatchedStore") return input.store; - return input; -}; -var AsyncBatchedStore = class extends base_BaseStore { - lg_name = "AsyncBatchedStore"; - store; - queue = /* @__PURE__ */ new Map(); - nextKey = 0; - running = false; - processingTask = null; - constructor(store) { - super(); - this.store = extractStore(store); - } - get isRunning() { - return this.running; - } - /** - * @ignore - * Batch is not implemented here as we're only extending `BaseStore` - * to allow it to be passed where `BaseStore` is expected, and implement - * the convenience methods (get, search, put, delete). - */ - async batch(_operations) { - throw new Error("The `batch` method is not implemented on `AsyncBatchedStore`.\n Instead, it calls the `batch` method on the wrapped store.\n If you are seeing this error, something is wrong."); - } - async get(namespace, key) { - return this.enqueueOperation({ - namespace, - key - }); - } - async search(namespacePrefix, options) { - const { filter, limit = 10, offset = 0, query } = options || {}; - return this.enqueueOperation({ - namespacePrefix, - filter, - limit, - offset, - query - }); - } - async put(namespace, key, value) { - return this.enqueueOperation({ - namespace, - key, - value - }); - } - async delete(namespace, key) { - return this.enqueueOperation({ - namespace, - key, - value: null - }); - } - start() { - if (!this.running) { - this.running = true; - this.processingTask = this.processBatchQueue(); - } - } - async stop() { - this.running = false; - if (this.processingTask) await this.processingTask; - } - enqueueOperation(operation) { - return new Promise((resolve, reject) => { - const key = this.nextKey; - this.nextKey += 1; - this.queue.set(key, { - operation, - resolve, - reject - }); - }); - } - async processBatchQueue() { - while (this.running) { - await new Promise((resolve) => { - setTimeout(resolve, 0); - }); - if (this.queue.size === 0) continue; - const batch = new Map(this.queue); - this.queue.clear(); - try { - const operations = Array.from(batch.values()).map(({ operation }) => operation); - const results = await this.store.batch(operations); - batch.forEach(({ resolve }, key) => { - const index = Array.from(batch.keys()).indexOf(key); - resolve(results[index]); - }); - } catch (e) { - batch.forEach(({ reject }) => { - reject(e); - }); - } - } - } - toJSON() { - return { - queue: this.queue, - nextKey: this.nextKey, - running: this.running, - store: "[LangGraphStore]" - }; - } -}; - -//#endregion - -//# sourceMappingURL=batch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/utils.js -//#region src/store/utils.ts -/** -* Tokenize a JSON path into parts. -* @example -* tokenizePath("metadata.title") // -> ["metadata", "title"] -* tokenizePath("chapters[*].content") // -> ["chapters[*]", "content"] -*/ -function utils_tokenizePath(path) { - if (!path) return []; - const tokens = []; - let current = []; - let i = 0; - while (i < path.length) { - const char = path[i]; - if (char === "[") { - if (current.length) { - tokens.push(current.join("")); - current = []; - } - let bracketCount = 1; - const indexChars = ["["]; - i += 1; - while (i < path.length && bracketCount > 0) { - if (path[i] === "[") bracketCount += 1; - else if (path[i] === "]") bracketCount -= 1; - indexChars.push(path[i]); - i += 1; - } - tokens.push(indexChars.join("")); - continue; - } else if (char === "{") { - if (current.length) { - tokens.push(current.join("")); - current = []; - } - let braceCount = 1; - const fieldChars = ["{"]; - i += 1; - while (i < path.length && braceCount > 0) { - if (path[i] === "{") braceCount += 1; - else if (path[i] === "}") braceCount -= 1; - fieldChars.push(path[i]); - i += 1; - } - tokens.push(fieldChars.join("")); - continue; - } else if (char === ".") { - if (current.length) { - tokens.push(current.join("")); - current = []; - } - } else current.push(char); - i += 1; - } - if (current.length) tokens.push(current.join("")); - return tokens; -} -/** -* Type guard to check if an object is a FilterOperators -*/ -function isFilterOperators(obj) { - return typeof obj === "object" && obj !== null && Object.keys(obj).every((key) => key === "$eq" || key === "$ne" || key === "$gt" || key === "$gte" || key === "$lt" || key === "$lte" || key === "$in" || key === "$nin"); -} -/** -* Compare values for filtering, supporting operator-based comparisons. -*/ -function compareValues(itemValue, filterValue) { - if (isFilterOperators(filterValue)) { - const operators = Object.keys(filterValue).filter((k) => k.startsWith("$")); - return operators.every((op) => { - const value = filterValue[op]; - switch (op) { - case "$eq": return itemValue === value; - case "$ne": return itemValue !== value; - case "$gt": return Number(itemValue) > Number(value); - case "$gte": return Number(itemValue) >= Number(value); - case "$lt": return Number(itemValue) < Number(value); - case "$lte": return Number(itemValue) <= Number(value); - case "$in": return Array.isArray(value) ? value.includes(itemValue) : false; - case "$nin": return Array.isArray(value) ? !value.includes(itemValue) : true; - default: return false; - } - }); - } - return itemValue === filterValue; -} -/** -* Extract text from a value at a specific JSON path. -* -* Supports: -* - Simple paths: "field1.field2" -* - Array indexing: "[0]", "[*]", "[-1]" -* - Wildcards: "*" -* - Multi-field selection: "{field1,field2}" -* - Nested paths in multi-field: "{field1,nested.field2}" -*/ -function utils_getTextAtPath(obj, path) { - if (!path || path === "$") return [JSON.stringify(obj, null, 2)]; - const tokens = Array.isArray(path) ? path : utils_tokenizePath(path); - function extractFromObj(obj$1, tokens$1, pos) { - if (pos >= tokens$1.length) { - if (typeof obj$1 === "string" || typeof obj$1 === "number" || typeof obj$1 === "boolean") return [String(obj$1)]; - if (obj$1 === null || obj$1 === void 0) return []; - if (Array.isArray(obj$1) || typeof obj$1 === "object") return [JSON.stringify(obj$1, null, 2)]; - return []; - } - const token = tokens$1[pos]; - const results = []; - if (pos === 0 && token === "$") results.push(JSON.stringify(obj$1, null, 2)); - if (token.startsWith("[") && token.endsWith("]")) { - if (!Array.isArray(obj$1)) return []; - const index = token.slice(1, -1); - if (index === "*") for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1)); - else try { - let idx = parseInt(index, 10); - if (idx < 0) idx = obj$1.length + idx; - if (idx >= 0 && idx < obj$1.length) results.push(...extractFromObj(obj$1[idx], tokens$1, pos + 1)); - } catch { - return []; - } - } else if (token.startsWith("{") && token.endsWith("}")) { - if (typeof obj$1 !== "object" || obj$1 === null) return []; - const fields = token.slice(1, -1).split(",").map((f) => f.trim()); - for (const field of fields) { - const nestedTokens = utils_tokenizePath(field); - if (nestedTokens.length) { - let currentObj = obj$1; - for (const nestedToken of nestedTokens) if (currentObj && typeof currentObj === "object" && nestedToken in currentObj) currentObj = currentObj[nestedToken]; - else { - currentObj = void 0; - break; - } - if (currentObj !== void 0) { - if (typeof currentObj === "string" || typeof currentObj === "number" || typeof currentObj === "boolean") results.push(String(currentObj)); - else if (Array.isArray(currentObj) || typeof currentObj === "object") results.push(JSON.stringify(currentObj, null, 2)); - } - } - } - } else if (token === "*") { - if (Array.isArray(obj$1)) for (const item of obj$1) results.push(...extractFromObj(item, tokens$1, pos + 1)); - else if (typeof obj$1 === "object" && obj$1 !== null) for (const value of Object.values(obj$1)) results.push(...extractFromObj(value, tokens$1, pos + 1)); - } else if (typeof obj$1 === "object" && obj$1 !== null && token in obj$1) results.push(...extractFromObj(obj$1[token], tokens$1, pos + 1)); - return results; - } - return extractFromObj(obj, tokens, 0); -} - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/store/memory.js - - - -//#region src/store/memory.ts -/** -* In-memory key-value store with optional vector search. -* -* A lightweight store implementation using JavaScript Maps. Supports basic -* key-value operations and vector search when configured with embeddings. -* -* @example -* ```typescript -* // Basic key-value storage -* const store = new InMemoryStore(); -* await store.put(["users", "123"], "prefs", { theme: "dark" }); -* const item = await store.get(["users", "123"], "prefs"); -* -* // Vector search with embeddings -* import { OpenAIEmbeddings } from "@langchain/openai"; -* const store = new InMemoryStore({ -* index: { -* dims: 1536, -* embeddings: new OpenAIEmbeddings({ modelName: "text-embedding-3-small" }), -* } -* }); -* -* // Store documents -* await store.put(["docs"], "doc1", { text: "Python tutorial" }); -* await store.put(["docs"], "doc2", { text: "TypeScript guide" }); -* -* // Search by similarity -* const results = await store.search(["docs"], { query: "python programming" }); -* ``` -* -* **Warning**: This store keeps all data in memory. Data is lost when the process exits. -* For persistence, use a database-backed store. -*/ -var memory_InMemoryStore = class extends base_BaseStore { - data = /* @__PURE__ */ new Map(); - vectors = /* @__PURE__ */ new Map(); - _indexConfig; - constructor(options) { - super(); - if (options?.index) this._indexConfig = { - ...options.index, - __tokenizedFields: (options.index.fields ?? ["$"]).map((p) => [p, p === "$" ? [p] : utils_tokenizePath(p)]) - }; - } - async batch(operations) { - const results = []; - const putOps = /* @__PURE__ */ new Map(); - const searchOps = /* @__PURE__ */ new Map(); - for (let i = 0; i < operations.length; i += 1) { - const op = operations[i]; - if ("key" in op && "namespace" in op && !("value" in op)) results.push(this.getOperation(op)); - else if ("namespacePrefix" in op) { - const candidates = this.filterItems(op); - searchOps.set(i, [op, candidates]); - results.push(null); - } else if ("value" in op) { - const key = `${op.namespace.join(":")}:${op.key}`; - putOps.set(key, op); - results.push(null); - } else if ("matchConditions" in op) results.push(this.listNamespacesOperation(op)); - } - if (searchOps.size > 0) if (this._indexConfig?.embeddings) { - const queries = /* @__PURE__ */ new Set(); - for (const [op] of searchOps.values()) if (op.query) queries.add(op.query); - const queryEmbeddings = queries.size > 0 ? await Promise.all(Array.from(queries).map((q) => this._indexConfig.embeddings.embedQuery(q))) : []; - const queryVectors = Object.fromEntries(Array.from(queries).map((q, i) => [q, queryEmbeddings[i]])); - for (const [i, [op, candidates]] of searchOps.entries()) if (op.query && queryVectors[op.query]) { - const queryVector = queryVectors[op.query]; - const scoredResults = this.scoreResults(candidates, queryVector, op.offset ?? 0, op.limit ?? 10); - results[i] = scoredResults; - } else results[i] = this.paginateResults(candidates.map((item) => ({ - ...item, - score: void 0 - })), op.offset ?? 0, op.limit ?? 10); - } else for (const [i, [op, candidates]] of searchOps.entries()) results[i] = this.paginateResults(candidates.map((item) => ({ - ...item, - score: void 0 - })), op.offset ?? 0, op.limit ?? 10); - if (putOps.size > 0 && this._indexConfig?.embeddings) { - const toEmbed = this.extractTexts(Array.from(putOps.values())); - if (Object.keys(toEmbed).length > 0) { - const embeddings = await this._indexConfig.embeddings.embedDocuments(Object.keys(toEmbed)); - this.insertVectors(toEmbed, embeddings); - } - } - for (const op of putOps.values()) this.putOperation(op); - return results; - } - getOperation(op) { - const namespaceKey = op.namespace.join(":"); - const item = this.data.get(namespaceKey)?.get(op.key); - return item ?? null; - } - putOperation(op) { - const namespaceKey = op.namespace.join(":"); - if (!this.data.has(namespaceKey)) this.data.set(namespaceKey, /* @__PURE__ */ new Map()); - const namespaceMap = this.data.get(namespaceKey); - if (op.value === null) namespaceMap.delete(op.key); - else { - const now = /* @__PURE__ */ new Date(); - if (namespaceMap.has(op.key)) { - const item = namespaceMap.get(op.key); - item.value = op.value; - item.updatedAt = now; - } else namespaceMap.set(op.key, { - value: op.value, - key: op.key, - namespace: op.namespace, - createdAt: now, - updatedAt: now - }); - } - } - listNamespacesOperation(op) { - const allNamespaces = Array.from(this.data.keys()).map((ns) => ns.split(":")); - let namespaces = allNamespaces; - if (op.matchConditions && op.matchConditions.length > 0) namespaces = namespaces.filter((ns) => op.matchConditions.every((condition) => this.doesMatch(condition, ns))); - if (op.maxDepth !== void 0) namespaces = Array.from(new Set(namespaces.map((ns) => ns.slice(0, op.maxDepth).join(":")))).map((ns) => ns.split(":")); - namespaces.sort((a, b) => a.join(":").localeCompare(b.join(":"))); - return namespaces.slice(op.offset ?? 0, (op.offset ?? 0) + (op.limit ?? namespaces.length)); - } - doesMatch(matchCondition, key) { - const { matchType, path } = matchCondition; - if (matchType === "prefix") { - if (path.length > key.length) return false; - return path.every((pElem, index) => { - const kElem = key[index]; - return pElem === "*" || kElem === pElem; - }); - } else if (matchType === "suffix") { - if (path.length > key.length) return false; - return path.every((pElem, index) => { - const kElem = key[key.length - path.length + index]; - return pElem === "*" || kElem === pElem; - }); - } - throw new Error(`Unsupported match type: ${matchType}`); - } - filterItems(op) { - const candidates = []; - for (const [namespace, items] of this.data.entries()) if (namespace.startsWith(op.namespacePrefix.join(":"))) candidates.push(...items.values()); - let filteredCandidates = candidates; - if (op.filter) filteredCandidates = candidates.filter((item) => Object.entries(op.filter).every(([key, value]) => compareValues(item.value[key], value))); - return filteredCandidates; - } - scoreResults(candidates, queryVector, offset = 0, limit = 10) { - const flatItems = []; - const flatVectors = []; - const scoreless = []; - for (const item of candidates) { - const vectors = this.getVectors(item); - if (vectors.length) for (const vector of vectors) { - flatItems.push(item); - flatVectors.push(vector); - } - else scoreless.push(item); - } - const scores = this.cosineSimilarity(queryVector, flatVectors); - const sortedResults = scores.map((score, i) => [score, flatItems[i]]).sort((a, b) => b[0] - a[0]); - const seen = /* @__PURE__ */ new Set(); - const kept = []; - for (const [score, item] of sortedResults) { - const key = `${item.namespace.join(":")}:${item.key}`; - if (seen.has(key)) continue; - const ix = seen.size; - if (ix >= offset + limit) break; - if (ix < offset) { - seen.add(key); - continue; - } - seen.add(key); - kept.push([score, item]); - } - if (scoreless.length && kept.length < limit) for (const item of scoreless.slice(0, limit - kept.length)) { - const key = `${item.namespace.join(":")}:${item.key}`; - if (!seen.has(key)) { - seen.add(key); - kept.push([void 0, item]); - } - } - return kept.map(([score, item]) => ({ - ...item, - score - })); - } - paginateResults(results, offset, limit) { - return results.slice(offset, offset + limit); - } - extractTexts(ops) { - if (!ops.length || !this._indexConfig) return {}; - const toEmbed = {}; - for (const op of ops) if (op.value !== null && op.index !== false) { - const paths = op.index === null || op.index === void 0 ? this._indexConfig.__tokenizedFields ?? [] : op.index.map((ix) => [ix, utils_tokenizePath(ix)]); - for (const [path, field] of paths) { - const texts = utils_getTextAtPath(op.value, field); - if (texts.length) if (texts.length > 1) texts.forEach((text, i) => { - if (!toEmbed[text]) toEmbed[text] = []; - toEmbed[text].push([ - op.namespace, - op.key, - `${path}.${i}` - ]); - }); - else { - if (!toEmbed[texts[0]]) toEmbed[texts[0]] = []; - toEmbed[texts[0]].push([ - op.namespace, - op.key, - path - ]); - } - } - } - return toEmbed; - } - insertVectors(texts, embeddings) { - for (const [text, metadata] of Object.entries(texts)) { - const embedding = embeddings.shift(); - if (!embedding) throw new Error(`No embedding found for text: ${text}`); - for (const [namespace, key, field] of metadata) { - const namespaceKey = namespace.join(":"); - if (!this.vectors.has(namespaceKey)) this.vectors.set(namespaceKey, /* @__PURE__ */ new Map()); - const namespaceMap = this.vectors.get(namespaceKey); - if (!namespaceMap.has(key)) namespaceMap.set(key, /* @__PURE__ */ new Map()); - const itemMap = namespaceMap.get(key); - itemMap.set(field, embedding); - } - } - } - getVectors(item) { - const namespaceKey = item.namespace.join(":"); - const itemKey = item.key; - if (!this.vectors.has(namespaceKey)) return []; - const namespaceMap = this.vectors.get(namespaceKey); - if (!namespaceMap.has(itemKey)) return []; - const itemMap = namespaceMap.get(itemKey); - const vectors = Array.from(itemMap.values()); - if (!vectors.length) return []; - return vectors; - } - cosineSimilarity(X, Y) { - if (!Y.length) return []; - const dotProducts = Y.map((vector) => vector.reduce((acc, val, i) => acc + val * X[i], 0)); - const magnitude1 = Math.sqrt(X.reduce((acc, val) => acc + val * val, 0)); - const magnitudes2 = Y.map((vector) => Math.sqrt(vector.reduce((acc, val) => acc + val * val, 0))); - return dotProducts.map((dot, i) => { - const magnitude2 = magnitudes2[i]; - return magnitude1 && magnitude2 ? dot / (magnitude1 * magnitude2) : 0; - }); - } - get indexConfig() { - return this._indexConfig; - } -}; -/** @deprecated Alias for InMemoryStore */ -var MemoryStore = class extends (/* unused pure expression or super */ null && (memory_InMemoryStore)) {}; - -//#endregion - -//# sourceMappingURL=memory.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/cache/base.js - - -//#region src/cache/base.ts -var base_BaseCache = class { - serde = new JsonPlusSerializer(); - /** - * Initialize the cache with a serializer. - * - * @param serde - The serializer to use. - */ - constructor(serde) { - this.serde = serde || this.serde; - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/cache/memory.js - - -//#region src/cache/memory.ts -var memory_InMemoryCache = class extends (/* unused pure expression or super */ null && (BaseCache)) { - cache = {}; - async get(keys) { - if (!keys.length) return []; - const now = Date.now(); - return (await Promise.all(keys.map(async (fullKey) => { - const [namespace, key] = fullKey; - const strNamespace = namespace.join(","); - if (strNamespace in this.cache && key in this.cache[strNamespace]) { - const cached = this.cache[strNamespace][key]; - if (cached.exp == null || now < cached.exp) { - const value = await this.serde.loadsTyped(cached.enc, cached.val); - return [{ - key: fullKey, - value - }]; - } else delete this.cache[strNamespace][key]; - } - return []; - }))).flat(); - } - async set(pairs) { - const now = Date.now(); - for (const { key: fullKey, value, ttl } of pairs) { - const [namespace, key] = fullKey; - const strNamespace = namespace.join(","); - const [enc, val] = await this.serde.dumpsTyped(value); - const exp = ttl != null ? ttl * 1e3 + now : null; - this.cache[strNamespace] ??= {}; - this.cache[strNamespace][key] = { - enc, - val, - exp - }; - } - } - async clear(namespaces) { - if (!namespaces.length) { - this.cache = {}; - return; - } - for (const namespace of namespaces) { - const strNamespace = namespace.join(","); - if (strNamespace in this.cache) delete this.cache[strNamespace]; - } - } -}; - -//#endregion - -//# sourceMappingURL=memory.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/cache/index.js - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph-checkpoint/dist/index.js - - - - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/base.js - - - -//#region src/channels/base.ts -function isBaseChannel(obj) { - return obj != null && obj.lg_is_channel === true; -} -/** @internal */ -var BaseChannel = class { - ValueType; - UpdateType; - /** @ignore */ - lg_is_channel = true; - /** - * Mark the current value of the channel as consumed. By default, no-op. - * A channel can use this method to modify its state, preventing the value - * from being consumed again. - * - * Returns True if the channel was updated, False otherwise. - */ - consume() { - return false; - } - /** - * Notify the channel that the Pregel run is finishing. By default, no-op. - * A channel can use this method to modify its state, preventing finish. - * - * Returns True if the channel was updated, False otherwise. - */ - finish() { - return false; - } - /** - * Return True if the channel is available (not empty), False otherwise. - * Subclasses should override this method to provide a more efficient - * implementation than calling get() and catching EmptyChannelError. - */ - isAvailable() { - try { - this.get(); - return true; - } catch (error) { - if (error.name === EmptyChannelError.unminifiable_name) return false; - throw error; - } - } -}; -const IS_ONLY_BASE_CHANNEL = Symbol.for("LG_IS_ONLY_BASE_CHANNEL"); -function getOnlyChannels(channels) { - if (channels[IS_ONLY_BASE_CHANNEL] === true) return channels; - const newChannels = {}; - for (const k in channels) { - if (!Object.prototype.hasOwnProperty.call(channels, k)) continue; - const value = channels[k]; - if (isBaseChannel(value)) newChannels[k] = value; - } - Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); - return newChannels; -} -function emptyChannels(channels, checkpoint) { - const filteredChannels = getOnlyChannels(channels); - const newChannels = {}; - for (const k in filteredChannels) { - if (!Object.prototype.hasOwnProperty.call(filteredChannels, k)) continue; - const channelValue = checkpoint.channel_values[k]; - newChannels[k] = filteredChannels[k].fromCheckpoint(channelValue); - } - Object.assign(newChannels, { [IS_ONLY_BASE_CHANNEL]: true }); - return newChannels; -} -function createCheckpoint(checkpoint, channels, step, options) { - let values; - if (channels === void 0) values = checkpoint.channel_values; - else { - values = {}; - for (const k in channels) { - if (!Object.prototype.hasOwnProperty.call(channels, k)) continue; - try { - values[k] = channels[k].checkpoint(); - } catch (error) { - if (error.name === EmptyChannelError.unminifiable_name) {} else throw error; - } - } - } - return { - v: 4, - id: options?.id ?? uuid6(step), - ts: (/* @__PURE__ */ new Date()).toISOString(), - channel_values: values, - channel_versions: checkpoint.channel_versions, - versions_seen: checkpoint.versions_seen - }; -} - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/binop.js - - - -//#region src/channels/binop.ts -/** -* Stores the result of applying a binary operator to the current value and each new value. -*/ -var BinaryOperatorAggregate = class BinaryOperatorAggregate extends BaseChannel { - lc_graph_name = "BinaryOperatorAggregate"; - value; - operator; - initialValueFactory; - constructor(operator, initialValueFactory) { - super(); - this.operator = operator; - this.initialValueFactory = initialValueFactory; - this.value = initialValueFactory?.(); - } - fromCheckpoint(checkpoint) { - const empty = new BinaryOperatorAggregate(this.operator, this.initialValueFactory); - if (typeof checkpoint !== "undefined") empty.value = checkpoint; - return empty; - } - update(values) { - let newValues = values; - if (!newValues.length) return false; - if (this.value === void 0) { - [this.value] = newValues; - newValues = newValues.slice(1); - } - for (const value of newValues) if (this.value !== void 0) this.value = this.operator(this.value, value); - return true; - } - get() { - if (this.value === void 0) throw new EmptyChannelError(); - return this.value; - } - checkpoint() { - if (this.value === void 0) throw new EmptyChannelError(); - return this.value; - } - isAvailable() { - return this.value !== void 0; - } -}; - -//#endregion - -//# sourceMappingURL=binop.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/last_value.js - - - -//#region src/channels/last_value.ts -/** -* Stores the last value received, can receive at most one value per step. -* -* Since `update` is only called once per step and value can only be of length 1, -* LastValue always stores the last value of a single node. If multiple nodes attempt to -* write to this channel in a single step, an error will be thrown. -* @internal -*/ -var LastValue = class LastValue extends BaseChannel { - lc_graph_name = "LastValue"; - value = []; - constructor(initialValueFactory) { - super(); - this.initialValueFactory = initialValueFactory; - if (initialValueFactory) this.value = [initialValueFactory()]; - } - fromCheckpoint(checkpoint) { - const empty = new LastValue(this.initialValueFactory); - if (typeof checkpoint !== "undefined") empty.value = [checkpoint]; - return empty; - } - update(values) { - if (values.length === 0) return false; - if (values.length !== 1) throw new InvalidUpdateError("LastValue can only receive one value per step.", { lc_error_code: "INVALID_CONCURRENT_GRAPH_UPDATE" }); - this.value = [values[values.length - 1]]; - return true; - } - get() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - checkpoint() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - isAvailable() { - return this.value.length !== 0; - } -}; -/** -* Stores the last value received, but only made available after finish(). -* Once made available, clears the value. -*/ -var LastValueAfterFinish = class LastValueAfterFinish extends BaseChannel { - lc_graph_name = "LastValueAfterFinish"; - value = []; - finished = false; - fromCheckpoint(checkpoint) { - const empty = new LastValueAfterFinish(); - if (typeof checkpoint !== "undefined") { - const [value, finished] = checkpoint; - empty.value = [value]; - empty.finished = finished; - } - return empty; - } - update(values) { - if (values.length === 0) return false; - this.finished = false; - this.value = [values[values.length - 1]]; - return true; - } - get() { - if (this.value.length === 0 || !this.finished) throw new EmptyChannelError(); - return this.value[0]; - } - checkpoint() { - if (this.value.length === 0) return void 0; - return [this.value[0], this.finished]; - } - consume() { - if (this.finished) { - this.finished = false; - this.value = []; - return true; - } - return false; - } - finish() { - if (!this.finished && this.value.length > 0) { - this.finished = true; - return true; - } - return false; - } - isAvailable() { - return this.value.length !== 0 && this.finished; - } -}; - -//#endregion - -//# sourceMappingURL=last_value.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/annotation.js - - - -//#region src/graph/annotation.ts -/** -* Should not be instantiated directly. See {@link Annotation}. -*/ -var AnnotationRoot = class { - lc_graph_name = "AnnotationRoot"; - spec; - constructor(s) { - this.spec = s; - } -}; -/** -* Helper that instantiates channels within a StateGraph state. -* -* Can be used as a field in an {@link Annotation.Root} wrapper in one of two ways: -* 1. **Directly**: Creates a channel that stores the most recent value returned from a node. -* 2. **With a reducer**: Creates a channel that applies the reducer on a node's return value. -* -* @example -* ```ts -* import { StateGraph, Annotation } from "@langchain/langgraph"; -* -* // Define a state with a single string key named "currentOutput" -* const SimpleAnnotation = Annotation.Root({ -* currentOutput: Annotation, -* }); -* -* const graphBuilder = new StateGraph(SimpleAnnotation); -* -* // A node in the graph that returns an object with a "currentOutput" key -* // replaces the value in the state. You can get the state type as shown below: -* const myNode = (state: typeof SimpleAnnotation.State) => { -* return { -* currentOutput: "some_new_value", -* }; -* } -* -* const graph = graphBuilder -* .addNode("myNode", myNode) -* ... -* .compile(); -* ``` -* -* @example -* ```ts -* import { type BaseMessage, AIMessage } from "@langchain/core/messages"; -* import { StateGraph, Annotation } from "@langchain/langgraph"; -* -* // Define a state with a single key named "messages" that will -* // combine a returned BaseMessage or arrays of BaseMessages -* const AnnotationWithReducer = Annotation.Root({ -* messages: Annotation({ -* // Different types are allowed for updates -* reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => { -* if (Array.isArray(right)) { -* return left.concat(right); -* } -* return left.concat([right]); -* }, -* default: () => [], -* }), -* }); -* -* const graphBuilder = new StateGraph(AnnotationWithReducer); -* -* // A node in the graph that returns an object with a "messages" key -* // will update the state by combining the existing value with the returned one. -* const myNode = (state: typeof AnnotationWithReducer.State) => { -* return { -* messages: [new AIMessage("Some new response")], -* }; -* }; -* -* const graph = graphBuilder -* .addNode("myNode", myNode) -* ... -* .compile(); -* ``` -* @namespace -* @property Root -* Helper function that instantiates a StateGraph state. See {@link Annotation} for usage. -*/ -const Annotation = function(annotation) { - if (annotation) return getChannel(annotation); - else return new LastValue(); -}; -Annotation.Root = (sd) => new AnnotationRoot(sd); -function getChannel(reducer) { - if (typeof reducer === "object" && reducer && "reducer" in reducer && reducer.reducer) return new BinaryOperatorAggregate(reducer.reducer, reducer.default); - if (typeof reducer === "object" && reducer && "value" in reducer && reducer.value) return new BinaryOperatorAggregate(reducer.value, reducer.default); - return new LastValue(); -} - -//#endregion - -//# sourceMappingURL=annotation.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/constants.js -//#region src/constants.ts -/** Special reserved node name denoting the start of a graph. */ -const START = "__start__"; -/** Special reserved node name denoting the end of a graph. */ -const END = "__end__"; -const INPUT = "__input__"; -const COPY = "__copy__"; -const constants_ERROR = "__error__"; -/** Special reserved cache namespaces */ -const CACHE_NS_WRITES = "__pregel_ns_writes"; -const CONFIG_KEY_SEND = "__pregel_send"; -/** config key containing function used to call a node (push task) */ -const constants_CONFIG_KEY_CALL = "__pregel_call"; -const CONFIG_KEY_READ = "__pregel_read"; -const CONFIG_KEY_CHECKPOINTER = "__pregel_checkpointer"; -const CONFIG_KEY_RESUMING = "__pregel_resuming"; -const CONFIG_KEY_TASK_ID = "__pregel_task_id"; -const CONFIG_KEY_STREAM = "__pregel_stream"; -const CONFIG_KEY_RESUME_VALUE = "__pregel_resume_value"; -const CONFIG_KEY_RESUME_MAP = "__pregel_resume_map"; -const constants_CONFIG_KEY_SCRATCHPAD = "__pregel_scratchpad"; -/** config key containing state from previous invocation of graph for the given thread */ -const constants_CONFIG_KEY_PREVIOUS_STATE = "__pregel_previous"; -const CONFIG_KEY_DURABILITY = "__pregel_durability"; -const CONFIG_KEY_CHECKPOINT_ID = "checkpoint_id"; -const CONFIG_KEY_CHECKPOINT_NS = "checkpoint_ns"; -const CONFIG_KEY_NODE_FINISHED = "__pregel_node_finished"; -const CONFIG_KEY_CHECKPOINT_MAP = "checkpoint_map"; -const CONFIG_KEY_ABORT_SIGNALS = "__pregel_abort_signals"; -/** Special channel reserved for graph interrupts */ -const constants_INTERRUPT = "__interrupt__"; -/** Special channel reserved for graph resume */ -const constants_RESUME = "__resume__"; -/** Special channel reserved for cases when a task exits without any writes */ -const NO_WRITES = "__no_writes__"; -/** Special channel reserved for graph return */ -const RETURN = "__return__"; -/** Special channel reserved for graph previous state */ -const PREVIOUS = "__previous__"; -const TAG_HIDDEN = "langsmith:hidden"; -const TAG_NOSTREAM = "langsmith:nostream"; -const SELF = "__self__"; -const constants_TASKS = "__pregel_tasks"; -const PUSH = "__pregel_push"; -const PULL = "__pregel_pull"; -const NULL_TASK_ID = "00000000-0000-0000-0000-000000000000"; -const RESERVED = [ - TAG_HIDDEN, - INPUT, - constants_INTERRUPT, - constants_RESUME, - constants_ERROR, - NO_WRITES, - CONFIG_KEY_SEND, - CONFIG_KEY_READ, - CONFIG_KEY_CHECKPOINTER, - CONFIG_KEY_DURABILITY, - CONFIG_KEY_STREAM, - CONFIG_KEY_RESUMING, - CONFIG_KEY_TASK_ID, - constants_CONFIG_KEY_CALL, - CONFIG_KEY_RESUME_VALUE, - constants_CONFIG_KEY_SCRATCHPAD, - constants_CONFIG_KEY_PREVIOUS_STATE, - CONFIG_KEY_CHECKPOINT_MAP, - CONFIG_KEY_CHECKPOINT_NS, - CONFIG_KEY_CHECKPOINT_ID -]; -const CHECKPOINT_NAMESPACE_SEPARATOR = "|"; -const CHECKPOINT_NAMESPACE_END = ":"; -/** @internal */ -const COMMAND_SYMBOL = Symbol.for("langgraph.command"); -/** -* Instance of a {@link Command} class. -* -* This is used to avoid IntelliSense suggesting public fields -* of {@link Command} class when a plain object is expected. -* -* @see {@link Command} -* @internal -*/ -var CommandInstance = class { - [COMMAND_SYMBOL]; - constructor(args) { - this[COMMAND_SYMBOL] = args; - } -}; -function _isSendInterface(x) { - const operation = x; - return operation !== null && operation !== void 0 && typeof operation.node === "string" && operation.args !== void 0; -} -/** -* -* A message or packet to send to a specific node in the graph. -* -* The `Send` class is used within a `StateGraph`'s conditional edges to -* dynamically invoke a node with a custom state at the next step. -* -* Importantly, the sent state can differ from the core graph's state, -* allowing for flexible and dynamic workflow management. -* -* One such example is a "map-reduce" workflow where your graph invokes -* the same node multiple times in parallel with different states, -* before aggregating the results back into the main graph's state. -* -* @example -* ```typescript -* import { Annotation, Send, StateGraph } from "@langchain/langgraph"; -* -* const ChainState = Annotation.Root({ -* subjects: Annotation, -* jokes: Annotation({ -* reducer: (a, b) => a.concat(b), -* }), -* }); -* -* const continueToJokes = async (state: typeof ChainState.State) => { -* return state.subjects.map((subject) => { -* return new Send("generate_joke", { subjects: [subject] }); -* }); -* }; -* -* const graph = new StateGraph(ChainState) -* .addNode("generate_joke", (state) => ({ -* jokes: [`Joke about ${state.subjects}`], -* })) -* .addConditionalEdges("__start__", continueToJokes) -* .addEdge("generate_joke", "__end__") -* .compile(); -* -* const res = await graph.invoke({ subjects: ["cats", "dogs"] }); -* console.log(res); -* -* // Invoking with two subjects results in a generated joke for each -* // { subjects: ["cats", "dogs"], jokes: [`Joke about cats`, `Joke about dogs`] } -* ``` -*/ -var Send = class { - lg_name = "Send"; - node; - args; - constructor(node, args) { - this.node = node; - this.args = _deserializeCommandSendObjectGraph(args); - } - toJSON() { - return { - lg_name: this.lg_name, - node: this.node, - args: this.args - }; - } -}; -function _isSend(x) { - return x instanceof Send; -} -/** -* Checks if the given graph invoke / stream chunk contains interrupt. -* -* @example -* ```ts -* import { INTERRUPT, isInterrupted } from "@langchain/langgraph"; -* -* const values = await graph.invoke({ foo: "bar" }); -* if (isInterrupted(values)) { -* const interrupt = values[INTERRUPT][0].value; -* } -* ``` -* -* @param values - The values to check. -* @returns `true` if the values contain an interrupt, `false` otherwise. -*/ -function isInterrupted(values) { - if (!values || typeof values !== "object") return false; - if (!(constants_INTERRUPT in values)) return false; - return Array.isArray(values[constants_INTERRUPT]); -} -/** -* One or more commands to update the graph's state and send messages to nodes. -* Can be used to combine routing logic with state updates in lieu of conditional edges -* -* @example -* ```ts -* import { Annotation, Command } from "@langchain/langgraph"; -* -* // Define graph state -* const StateAnnotation = Annotation.Root({ -* foo: Annotation, -* }); -* -* // Define the nodes -* const nodeA = async (_state: typeof StateAnnotation.State) => { -* console.log("Called A"); -* // this is a replacement for a real conditional edge function -* const goto = Math.random() > .5 ? "nodeB" : "nodeC"; -* // note how Command allows you to BOTH update the graph state AND route to the next node -* return new Command({ -* // this is the state update -* update: { -* foo: "a", -* }, -* // this is a replacement for an edge -* goto, -* }); -* }; -* -* // Nodes B and C are unchanged -* const nodeB = async (state: typeof StateAnnotation.State) => { -* console.log("Called B"); -* return { -* foo: state.foo + "|b", -* }; -* } -* -* const nodeC = async (state: typeof StateAnnotation.State) => { -* console.log("Called C"); -* return { -* foo: state.foo + "|c", -* }; -* } -* -* import { StateGraph } from "@langchain/langgraph"; - -* // NOTE: there are no edges between nodes A, B and C! -* const graph = new StateGraph(StateAnnotation) -* .addNode("nodeA", nodeA, { -* ends: ["nodeB", "nodeC"], -* }) -* .addNode("nodeB", nodeB) -* .addNode("nodeC", nodeC) -* .addEdge("__start__", "nodeA") -* .compile(); -* -* await graph.invoke({ foo: "" }); -* -* // Randomly oscillates between -* // { foo: 'a|c' } and { foo: 'a|b' } -* ``` -*/ -var Command = class extends CommandInstance { - lg_name = "Command"; - lc_direct_tool_output = true; - /** - * Graph to send the command to. Supported values are: - * - None: the current graph (default) - * - The specific name of the graph to send the command to - * - {@link Command.PARENT}: closest parent graph (only supported when returned from a node in a subgraph) - */ - graph; - /** - * Update to apply to the graph's state as a result of executing the node that is returning the command. - * Written to the state as if the node had simply returned this value instead of the Command object. - */ - update; - /** - * Value to resume execution with. To be used together with {@link interrupt}. - */ - resume; - /** - * Can be one of the following: - * - name of the node to navigate to next (any node that belongs to the specified `graph`) - * - sequence of node names to navigate to next - * - {@link Send} object (to execute a node with the exact input provided in the {@link Send} object) - * - sequence of {@link Send} objects - */ - goto = []; - static PARENT = "__parent__"; - constructor(args) { - super(args); - this.resume = args.resume; - this.graph = args.graph; - this.update = args.update; - if (args.goto) this.goto = Array.isArray(args.goto) ? _deserializeCommandSendObjectGraph(args.goto) : [_deserializeCommandSendObjectGraph(args.goto)]; - } - /** - * Convert the update field to a list of {@link PendingWrite} tuples - * @returns List of {@link PendingWrite} tuples of the form `[channelKey, value]`. - * @internal - */ - _updateAsTuples() { - if (this.update && typeof this.update === "object" && !Array.isArray(this.update)) return Object.entries(this.update); - else if (Array.isArray(this.update) && this.update.every((t) => Array.isArray(t) && t.length === 2 && typeof t[0] === "string")) return this.update; - else return [["__root__", this.update]]; - } - toJSON() { - let serializedGoto; - if (typeof this.goto === "string") serializedGoto = this.goto; - else if (_isSend(this.goto)) serializedGoto = this.goto.toJSON(); - else serializedGoto = this.goto?.map((innerGoto) => { - if (typeof innerGoto === "string") return innerGoto; - else return innerGoto.toJSON(); - }); - return { - lg_name: this.lg_name, - update: this.update, - resume: this.resume, - goto: serializedGoto - }; - } -}; -/** -* A type guard to check if the given value is a {@link Command}. -* -* Useful for type narrowing when working with the {@link Command} object. -* -* @param x - The value to check. -* @returns `true` if the value is a {@link Command}, `false` otherwise. -*/ -function isCommand(x) { - if (typeof x !== "object") return false; - if (x === null || x === void 0) return false; - if ("lg_name" in x && x.lg_name === "Command") return true; - return false; -} -/** -* Reconstructs Command and Send objects from a deeply nested tree of anonymous objects -* matching their interfaces. -* -* This is only exported for testing purposes. It is NOT intended to be used outside of -* the Command and Send classes. -* -* @internal -* -* @param x - The command send tree to convert. -* @param seen - A map of seen objects to avoid infinite loops. -* @returns The converted command send tree. -*/ -function _deserializeCommandSendObjectGraph(x, seen = /* @__PURE__ */ new Map()) { - if (x !== void 0 && x !== null && typeof x === "object") { - if (seen.has(x)) return seen.get(x); - let result; - if (Array.isArray(x)) { - result = []; - seen.set(x, result); - x.forEach((item, index) => { - result[index] = _deserializeCommandSendObjectGraph(item, seen); - }); - } else if (isCommand(x) && !(x instanceof Command)) { - result = new Command(x); - seen.set(x, result); - } else if (_isSendInterface(x) && !(x instanceof Send)) { - result = new Send(x.node, x.args); - seen.set(x, result); - } else if (isCommand(x) || _isSend(x)) { - result = x; - seen.set(x, result); - } else if ("lc_serializable" in x && x.lc_serializable) { - result = x; - seen.set(x, result); - } else { - result = {}; - seen.set(x, result); - for (const [key, value] of Object.entries(x)) result[key] = _deserializeCommandSendObjectGraph(value, seen); - } - return result; - } - return x; -} - -//#endregion - -//# sourceMappingURL=constants.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/utils/config.js - - - -//#region src/pregel/utils/config.ts -const COPIABLE_KEYS = [ - "tags", - "metadata", - "callbacks", - "configurable" -]; -const CONFIG_KEYS = [ - "tags", - "metadata", - "callbacks", - "runName", - "maxConcurrency", - "recursionLimit", - "configurable", - "runId", - "outputKeys", - "streamMode", - "store", - "writer", - "interrupt", - "context", - "interruptBefore", - "interruptAfter", - "checkpointDuring", - "durability", - "signal" -]; -const config_DEFAULT_RECURSION_LIMIT = 25; -function config_ensureLangGraphConfig(...configs) { - const empty = { - tags: [], - metadata: {}, - callbacks: void 0, - recursionLimit: config_DEFAULT_RECURSION_LIMIT, - configurable: {} - }; - const implicitConfig = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (implicitConfig !== void 0) { - for (const [k, v] of Object.entries(implicitConfig)) if (v !== void 0) if (COPIABLE_KEYS.includes(k)) { - let copiedValue; - if (Array.isArray(v)) copiedValue = [...v]; - else if (typeof v === "object") if (k === "callbacks" && "copy" in v && typeof v.copy === "function") copiedValue = v.copy(); - else copiedValue = { ...v }; - else copiedValue = v; - empty[k] = copiedValue; - } else empty[k] = v; - } - for (const config of configs) { - if (config === void 0) continue; - for (const [k, v] of Object.entries(config)) if (v !== void 0 && CONFIG_KEYS.includes(k)) empty[k] = v; - } - for (const [key, value] of Object.entries(empty.configurable)) { - empty.metadata = empty.metadata ?? {}; - if (!key.startsWith("__") && (typeof value === "string" || typeof value === "number" || typeof value === "boolean") && !(key in empty.metadata)) empty.metadata[key] = value; - } - return empty; -} -/** -* A helper utility function that returns the {@link BaseStore} that was set when the graph was initialized -* -* @returns a reference to the {@link BaseStore} that was set when the graph was initialized -*/ -function getStore(config) { - const runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (runConfig === void 0) throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getStore` in such environment, pass the `config` from the node function directly."].join("\n")); - return runConfig?.store; -} -/** -* A helper utility function that returns the {@link LangGraphRunnableConfig#writer} if "custom" stream mode is enabled, otherwise undefined. -* -* @returns a reference to the {@link LangGraphRunnableConfig#writer} if "custom" stream mode is enabled, otherwise undefined -*/ -function getWriter(config) { - const runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (runConfig === void 0) throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getWriter` in such environment, pass the `config` from the node function directly."].join("\n")); - return runConfig?.writer || runConfig?.configurable?.writer; -} -/** -* A helper utility function that returns the {@link LangGraphRunnableConfig} that was set when the graph was initialized. -* -* Note: This only works when running in an environment that supports node:async_hooks and AsyncLocalStorage. If you're running this in a -* web environment, access the LangGraphRunnableConfig from the node function directly. -* -* @returns the {@link LangGraphRunnableConfig} that was set when the graph was initialized -*/ -function getConfig() { - return async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); -} -/** -* A helper utility function that returns the input for the currently executing task -* -* @returns the input for the currently executing task -*/ -function getCurrentTaskInput(config) { - const runConfig = config ?? AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (runConfig === void 0) throw new Error(["Config not retrievable. This is likely because you are running in an environment without support for AsyncLocalStorage.", "If you're running `getCurrentTaskInput` in such environment, pass the `config` from the node function directly."].join("\n")); - if (runConfig.configurable?.[CONFIG_KEY_SCRATCHPAD]?.currentTaskInput === void 0) throw new Error("BUG: internal scratchpad not initialized."); - return runConfig.configurable[CONFIG_KEY_SCRATCHPAD].currentTaskInput; -} -function recastCheckpointNamespace(namespace) { - return namespace.split(CHECKPOINT_NAMESPACE_SEPARATOR).filter((part) => !part.match(/^\d+$/)).map((part) => part.split(CHECKPOINT_NAMESPACE_END)[0]).join(CHECKPOINT_NAMESPACE_SEPARATOR); -} -function getParentCheckpointNamespace(namespace) { - const parts = namespace.split(CHECKPOINT_NAMESPACE_SEPARATOR); - while (parts.length > 1 && parts[parts.length - 1].match(/^\d+$/)) parts.pop(); - return parts.slice(0, -1).join(CHECKPOINT_NAMESPACE_SEPARATOR); -} - -//#endregion - -//# sourceMappingURL=config.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/hash.js -//#region src/hash.ts -const n = (n$1) => BigInt(n$1); -const view = (data, offset = 0) => new DataView(data.buffer, data.byteOffset + offset, data.byteLength - offset); -const PRIME32_1 = n("0x9E3779B1"); -const PRIME32_2 = n("0x85EBCA77"); -const PRIME32_3 = n("0xC2B2AE3D"); -const PRIME64_1 = n("0x9E3779B185EBCA87"); -const PRIME64_2 = n("0xC2B2AE3D27D4EB4F"); -const PRIME64_3 = n("0x165667B19E3779F9"); -const PRIME64_4 = n("0x85EBCA77C2B2AE63"); -const PRIME64_5 = n("0x27D4EB2F165667C5"); -const PRIME_MX1 = n("0x165667919E3779F9"); -const PRIME_MX2 = n("0x9FB21C651E98DF25"); -const hash_hexToUint8Array = (hex) => { - const strLen = hex.length; - if (strLen % 2 !== 0) throw new Error("String should have an even number of characters"); - const maxLength = strLen / 2; - const bytes = new Uint8Array(maxLength); - let read = 0; - let write = 0; - while (write < maxLength) { - const slice = hex.slice(read, read += 2); - bytes[write] = Number.parseInt(slice, 16); - write += 1; - } - return view(bytes); -}; -const kkey = hash_hexToUint8Array("b8fe6c3923a44bbe7c01812cf721ad1cded46de9839097db7240a4a4b7b3671fcb79e64eccc0e578825ad07dccff7221b8084674f743248ee03590e6813a264c3c2852bb91c300cb88d0658b1b532ea371644897a20df94e3819ef46a9deacd8a8fa763fe39c343ff9dcbbc7c70b4f1d8a51e04bcdb45931c89f7ec9d9787364eac5ac8334d3ebc3c581a0fffa1363eb170ddd51b7f0da49d316552629d4689e2b16be587d47a1fc8ff8b8d17ad031ce45cb3a8f95160428afd7fbcabb4b407e"); -const mask128 = (n(1) << n(128)) - n(1); -const mask64 = (n(1) << n(64)) - n(1); -const mask32 = (n(1) << n(32)) - n(1); -const STRIPE_LEN = 64; -const ACC_NB = STRIPE_LEN / 8; -const _U64 = 8; -const _U32 = 4; -function hash_assert(a) { - if (!a) throw new Error("Assert failed"); -} -function bswap64(a) { - const scratchbuf = /* @__PURE__ */ new DataView(/* @__PURE__ */ new ArrayBuffer(8)); - scratchbuf.setBigUint64(0, a, true); - return scratchbuf.getBigUint64(0, false); -} -function bswap32(input) { - let a = input; - a = (a & n(65535)) << n(16) | (a & n(4294901760)) >> n(16); - a = (a & n(16711935)) << n(8) | (a & n(4278255360)) >> n(8); - return a; -} -function XXH_mult32to64(a, b) { - return (a & mask32) * (b & mask32) & mask64; -} -function rotl32(a, b) { - return (a << b | a >> n(32) - b) & mask32; -} -function XXH3_accumulate_512(acc, dataView, keyView) { - for (let i = 0; i < ACC_NB; i += 1) { - const data_val = dataView.getBigUint64(i * 8, true); - const data_key = data_val ^ keyView.getBigUint64(i * 8, true); - acc[i ^ 1] += data_val; - acc[i] += XXH_mult32to64(data_key, data_key >> n(32)); - } - return acc; -} -function XXH3_accumulate(acc, dataView, keyView, nbStripes) { - for (let n$1 = 0; n$1 < nbStripes; n$1 += 1) XXH3_accumulate_512(acc, view(dataView, n$1 * STRIPE_LEN), view(keyView, n$1 * 8)); - return acc; -} -function XXH3_scrambleAcc(acc, key) { - for (let i = 0; i < ACC_NB; i += 1) { - const key64 = key.getBigUint64(i * 8, true); - let acc64 = acc[i]; - acc64 = xorshift64(acc64, n(47)); - acc64 ^= key64; - acc64 *= PRIME32_1; - acc[i] = acc64 & mask64; - } - return acc; -} -function XXH3_mix2Accs(acc, key) { - return XXH3_mul128_fold64(acc[0] ^ key.getBigUint64(0, true), acc[1] ^ key.getBigUint64(_U64, true)); -} -function XXH3_mergeAccs(acc, key, start) { - let result64 = start; - result64 += XXH3_mix2Accs(acc.slice(0), view(key, 0 * _U32)); - result64 += XXH3_mix2Accs(acc.slice(2), view(key, 4 * _U32)); - result64 += XXH3_mix2Accs(acc.slice(4), view(key, 8 * _U32)); - result64 += XXH3_mix2Accs(acc.slice(6), view(key, 12 * _U32)); - return XXH3_avalanche(result64 & mask64); -} -function XXH3_hashLong(input, data, secret, f_acc, f_scramble) { - let acc = input; - const nbStripesPerBlock = Math.floor((secret.byteLength - STRIPE_LEN) / 8); - const block_len = STRIPE_LEN * nbStripesPerBlock; - const nb_blocks = Math.floor((data.byteLength - 1) / block_len); - for (let n$1 = 0; n$1 < nb_blocks; n$1 += 1) { - acc = XXH3_accumulate(acc, view(data, n$1 * block_len), secret, nbStripesPerBlock); - acc = f_scramble(acc, view(secret, secret.byteLength - STRIPE_LEN)); - } - { - const nbStripes = Math.floor((data.byteLength - 1 - block_len * nb_blocks) / STRIPE_LEN); - acc = XXH3_accumulate(acc, view(data, nb_blocks * block_len), secret, nbStripes); - acc = f_acc(acc, view(data, data.byteLength - STRIPE_LEN), view(secret, secret.byteLength - STRIPE_LEN - 7)); - } - return acc; -} -function XXH3_hashLong_128b(data, secret) { - let acc = new BigUint64Array([ - PRIME32_3, - PRIME64_1, - PRIME64_2, - PRIME64_3, - PRIME64_4, - PRIME32_2, - PRIME64_5, - PRIME32_1 - ]); - hash_assert(data.byteLength > 128); - acc = XXH3_hashLong(acc, data, secret, XXH3_accumulate_512, XXH3_scrambleAcc); - hash_assert(acc.length * 8 === 64); - { - const low64 = XXH3_mergeAccs(acc, view(secret, 11), n(data.byteLength) * PRIME64_1 & mask64); - const high64 = XXH3_mergeAccs(acc, view(secret, secret.byteLength - STRIPE_LEN - 11), ~(n(data.byteLength) * PRIME64_2) & mask64); - return high64 << n(64) | low64; - } -} -function XXH3_mul128_fold64(a, b) { - const lll = a * b & mask128; - return lll & mask64 ^ lll >> n(64); -} -function XXH3_mix16B(dataView, keyView, seed) { - return XXH3_mul128_fold64((dataView.getBigUint64(0, true) ^ keyView.getBigUint64(0, true) + seed) & mask64, (dataView.getBigUint64(8, true) ^ keyView.getBigUint64(8, true) - seed) & mask64); -} -function XXH3_mix32B(acc, data1, data2, key, seed) { - let accl = acc & mask64; - let acch = acc >> n(64) & mask64; - accl += XXH3_mix16B(data1, key, seed); - accl ^= data2.getBigUint64(0, true) + data2.getBigUint64(8, true); - accl &= mask64; - acch += XXH3_mix16B(data2, view(key, 16), seed); - acch ^= data1.getBigUint64(0, true) + data1.getBigUint64(8, true); - acch &= mask64; - return acch << n(64) | accl; -} -function XXH3_avalanche(input) { - let h64 = input; - h64 ^= h64 >> n(37); - h64 *= PRIME_MX1; - h64 &= mask64; - h64 ^= h64 >> n(32); - return h64; -} -function XXH3_avalanche64(input) { - let h64 = input; - h64 ^= h64 >> n(33); - h64 *= PRIME64_2; - h64 &= mask64; - h64 ^= h64 >> n(29); - h64 *= PRIME64_3; - h64 &= mask64; - h64 ^= h64 >> n(32); - return h64; -} -function XXH3_len_1to3_128b(data, key32, seed) { - const len = data.byteLength; - hash_assert(len > 0 && len <= 3); - const combined = n(data.getUint8(len - 1)) | n(len << 8) | n(data.getUint8(0) << 16) | n(data.getUint8(len >> 1) << 24); - const blow = (n(key32.getUint32(0, true)) ^ n(key32.getUint32(4, true))) + seed; - const low = (combined ^ blow) & mask64; - const bhigh = (n(key32.getUint32(8, true)) ^ n(key32.getUint32(12, true))) - seed; - const high = (rotl32(bswap32(combined), n(13)) ^ bhigh) & mask64; - return (XXH3_avalanche64(high) & mask64) << n(64) | XXH3_avalanche64(low); -} -function xorshift64(b, shift) { - return b ^ b >> shift; -} -function XXH3_len_4to8_128b(data, key32, seed) { - const len = data.byteLength; - hash_assert(len >= 4 && len <= 8); - { - const l1 = data.getUint32(0, true); - const l2 = data.getUint32(len - 4, true); - const l64 = n(l1) | n(l2) << n(32); - const bitflip = (key32.getBigUint64(16, true) ^ key32.getBigUint64(24, true)) + seed & mask64; - const keyed = l64 ^ bitflip; - let m128 = keyed * (PRIME64_1 + (n(len) << n(2))) & mask128; - m128 += (m128 & mask64) << n(65); - m128 &= mask128; - m128 ^= m128 >> n(67); - return xorshift64(xorshift64(m128 & mask64, n(35)) * PRIME_MX2 & mask64, n(28)) | XXH3_avalanche(m128 >> n(64)) << n(64); - } -} -function XXH3_len_9to16_128b(data, key64, seed) { - const len = data.byteLength; - hash_assert(len >= 9 && len <= 16); - { - const bitflipl = (key64.getBigUint64(32, true) ^ key64.getBigUint64(40, true)) + seed & mask64; - const bitfliph = (key64.getBigUint64(48, true) ^ key64.getBigUint64(56, true)) - seed & mask64; - const ll1 = data.getBigUint64(0, true); - let ll2 = data.getBigUint64(len - 8, true); - let m128 = (ll1 ^ ll2 ^ bitflipl) * PRIME64_1; - const m128_l = (m128 & mask64) + (n(len - 1) << n(54)); - m128 = m128 & (mask128 ^ mask64) | m128_l; - ll2 ^= bitfliph; - m128 += ll2 + (ll2 & mask32) * (PRIME32_2 - n(1)) << n(64); - m128 &= mask128; - m128 ^= bswap64(m128 >> n(64)); - let h128 = (m128 & mask64) * PRIME64_2; - h128 += (m128 >> n(64)) * PRIME64_2 << n(64); - h128 &= mask128; - return XXH3_avalanche(h128 & mask64) | XXH3_avalanche(h128 >> n(64)) << n(64); - } -} -function XXH3_len_0to16_128b(data, seed) { - const len = data.byteLength; - hash_assert(len <= 16); - if (len > 8) return XXH3_len_9to16_128b(data, kkey, seed); - if (len >= 4) return XXH3_len_4to8_128b(data, kkey, seed); - if (len > 0) return XXH3_len_1to3_128b(data, kkey, seed); - return XXH3_avalanche64(seed ^ kkey.getBigUint64(64, true) ^ kkey.getBigUint64(72, true)) | XXH3_avalanche64(seed ^ kkey.getBigUint64(80, true) ^ kkey.getBigUint64(88, true)) << n(64); -} -function inv64(x) { - return ~x + n(1) & mask64; -} -function XXH3_len_17to128_128b(data, secret, seed) { - let acc = n(data.byteLength) * PRIME64_1 & mask64; - let i = n(data.byteLength - 1) / n(32); - while (i >= 0) { - const ni = Number(i); - acc = XXH3_mix32B(acc, view(data, 16 * ni), view(data, data.byteLength - 16 * (ni + 1)), view(secret, 32 * ni), seed); - i -= n(1); - } - let h128l = acc + (acc >> n(64)) & mask64; - h128l = XXH3_avalanche(h128l); - let h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2; - h128h &= mask64; - h128h = inv64(XXH3_avalanche(h128h)); - return h128l | h128h << n(64); -} -function XXH3_len_129to240_128b(data, secret, seed) { - let acc = n(data.byteLength) * PRIME64_1 & mask64; - for (let i = 32; i < 160; i += 32) acc = XXH3_mix32B(acc, view(data, i - 32), view(data, i - 16), view(secret, i - 32), seed); - acc = XXH3_avalanche(acc & mask64) | XXH3_avalanche(acc >> n(64)) << n(64); - for (let i = 160; i <= data.byteLength; i += 32) acc = XXH3_mix32B(acc, view(data, i - 32), view(data, i - 16), view(secret, 3 + i - 160), seed); - acc = XXH3_mix32B(acc, view(data, data.byteLength - 16), view(data, data.byteLength - 32), view(secret, 103), inv64(seed)); - let h128l = acc + (acc >> n(64)) & mask64; - h128l = XXH3_avalanche(h128l); - let h128h = (acc & mask64) * PRIME64_1 + (acc >> n(64)) * PRIME64_4 + (n(data.byteLength) - seed & mask64) * PRIME64_2; - h128h &= mask64; - h128h = inv64(XXH3_avalanche(h128h)); - return h128l | h128h << n(64); -} -function XXH3(input, seed = n(0)) { - const encoder = new TextEncoder(); - const data = view(typeof input === "string" ? encoder.encode(input) : input); - const len = data.byteLength; - const hexDigest = (data$1) => data$1.toString(16).padStart(32, "0"); - if (len <= 16) return hexDigest(XXH3_len_0to16_128b(data, seed)); - if (len <= 128) return hexDigest(XXH3_len_17to128_128b(data, kkey, seed)); - if (len <= 240) return hexDigest(XXH3_len_129to240_128b(data, kkey, seed)); - return hexDigest(XXH3_hashLong_128b(data, kkey)); -} -function isXXH3(value) { - return /^[0-9a-f]{32}$/.test(value); -} - -//#endregion - -//# sourceMappingURL=hash.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/interrupt.js - - - - - -//#region src/interrupt.ts -/** -* Interrupts the execution of a graph node. -* This function can be used to pause execution of a node, and return the value of the `resume` -* input when the graph is re-invoked using `Command`. -* Multiple interrupts can be called within a single node, and each will be handled sequentially. -* -* When an interrupt is called: -* 1. If there's a `resume` value available (from a previous `Command`), it returns that value. -* 2. Otherwise, it throws a `GraphInterrupt` with the provided value -* 3. The graph can be resumed by passing a `Command` with a `resume` value -* -* Because the `interrupt` function propagates by throwing a special `GraphInterrupt` error, -* you should avoid using `try/catch` blocks around the `interrupt` function, -* or if you do, ensure that the `GraphInterrupt` error is thrown again within your `catch` block. -* -* @param value - The value to include in the interrupt. This will be available in task.interrupts[].value -* @returns The `resume` value provided when the graph is re-invoked with a Command -* -* @example -* ```typescript -* // Define a node that uses multiple interrupts -* const nodeWithInterrupts = () => { -* // First interrupt - will pause execution and include {value: 1} in task values -* const answer1 = interrupt({ value: 1 }); -* -* // Second interrupt - only called after first interrupt is resumed -* const answer2 = interrupt({ value: 2 }); -* -* // Use the resume values -* return { myKey: answer1 + " " + answer2 }; -* }; -* -* // Resume the graph after first interrupt -* await graph.stream(new Command({ resume: "answer 1" })); -* -* // Resume the graph after second interrupt -* await graph.stream(new Command({ resume: "answer 2" })); -* // Final result: { myKey: "answer 1 answer 2" } -* ``` -* -* @throws {Error} If called outside the context of a graph -* @throws {GraphInterrupt} When no resume value is available -*/ -function interrupt(value) { - const config = async_local_storage_AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (!config) throw new Error("Called interrupt() outside the context of a graph."); - const conf = config.configurable; - if (!conf) throw new Error("No configurable found in config"); - const checkpointer = conf[CONFIG_KEY_CHECKPOINTER]; - if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const scratchpad = conf[constants_CONFIG_KEY_SCRATCHPAD]; - scratchpad.interruptCounter += 1; - const idx = scratchpad.interruptCounter; - if (scratchpad.resume.length > 0 && idx < scratchpad.resume.length) { - conf[CONFIG_KEY_SEND]?.([[constants_RESUME, scratchpad.resume]]); - return scratchpad.resume[idx]; - } - if (scratchpad.nullResume !== void 0) { - if (scratchpad.resume.length !== idx) throw new Error(`Resume length mismatch: ${scratchpad.resume.length} !== ${idx}`); - const v = scratchpad.consumeNullResume(); - scratchpad.resume.push(v); - conf[CONFIG_KEY_SEND]?.([[constants_RESUME, scratchpad.resume]]); - return v; - } - const ns = conf[CONFIG_KEY_CHECKPOINT_NS]?.split(CHECKPOINT_NAMESPACE_SEPARATOR); - const id = ns ? XXH3(ns.join(CHECKPOINT_NAMESPACE_SEPARATOR)) : void 0; - throw new GraphInterrupt([{ - id, - value - }]); -} - -//#endregion - -//# sourceMappingURL=interrupt.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/utils.js - - - - -//#region src/utils.ts -var RunnableCallable = class extends Runnable { - lc_namespace = ["langgraph"]; - func; - tags; - config; - trace = true; - recurse = true; - constructor(fields) { - super(); - this.name = fields.name ?? fields.func.name; - this.func = fields.func; - this.config = fields.tags ? { tags: fields.tags } : void 0; - this.trace = fields.trace ?? this.trace; - this.recurse = fields.recurse ?? this.recurse; - } - async _tracedInvoke(input, config, runManager) { - return new Promise((resolve, reject) => { - const childConfig = config_patchConfig(config, { callbacks: runManager?.getChild() }); - async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(childConfig, async () => { - try { - const output = await this.func(input, childConfig); - resolve(output); - } catch (e) { - reject(e); - } - }); - }); - } - async invoke(input, options) { - let returnValue; - const config = config_ensureLangGraphConfig(options); - const mergedConfig = mergeConfigs(this.config, config); - if (this.trace) returnValue = await this._callWithConfig(this._tracedInvoke, input, mergedConfig); - else returnValue = await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => this.func(input, mergedConfig)); - if (Runnable.isRunnable(returnValue) && this.recurse) return await async_local_storage_AsyncLocalStorageProviderSingleton.runWithConfig(mergedConfig, async () => returnValue.invoke(input, mergedConfig)); - return returnValue; - } -}; -function* prefixGenerator(generator, prefix) { - if (prefix === void 0) yield* generator; - else for (const value of generator) yield [prefix, value]; -} -async function gatherIterator(i) { - const out = []; - for await (const item of await i) out.push(item); - return out; -} -function gatherIteratorSync(i) { - const out = []; - for (const item of i) out.push(item); - return out; -} -function patchConfigurable(config, patch) { - if (!config) return { configurable: patch }; - else if (!("configurable" in config)) return { - ...config, - configurable: patch - }; - else return { - ...config, - configurable: { - ...config.configurable, - ...patch - } - }; -} -function utils_isAsyncGeneratorFunction(val) { - return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(async function* () {}).constructor; -} -function utils_isGeneratorFunction(val) { - return val != null && typeof val === "function" && val instanceof Object.getPrototypeOf(function* () {}).constructor; -} - -//#endregion - -//# sourceMappingURL=utils.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/write.js - - - - - -//#region src/pregel/write.ts -const SKIP_WRITE = { [Symbol.for("LG_SKIP_WRITE")]: true }; -function _isSkipWrite(x) { - return typeof x === "object" && x?.[Symbol.for("LG_SKIP_WRITE")] !== void 0; -} -const PASSTHROUGH = { [Symbol.for("LG_PASSTHROUGH")]: true }; -function _isPassthrough(x) { - return typeof x === "object" && x?.[Symbol.for("LG_PASSTHROUGH")] !== void 0; -} -const IS_WRITER = Symbol("IS_WRITER"); -/** -* Mapping of write channels to Runnables that return the value to be written, -* or None to skip writing. -*/ -var ChannelWrite = class ChannelWrite extends RunnableCallable { - writes; - constructor(writes, tags) { - const name = `ChannelWrite<${writes.map((packet) => { - if (_isSend(packet)) return packet.node; - else if ("channel" in packet) return packet.channel; - return "..."; - }).join(",")}>`; - super({ - writes, - name, - tags, - func: async (input, config) => { - return this._write(input, config ?? {}); - } - }); - this.writes = writes; - } - async _write(input, config) { - const writes = this.writes.map((write) => { - if (_isChannelWriteTupleEntry(write) && _isPassthrough(write.value)) return { - mapper: write.mapper, - value: input - }; - else if (_isChannelWriteEntry(write) && _isPassthrough(write.value)) return { - channel: write.channel, - value: input, - skipNone: write.skipNone, - mapper: write.mapper - }; - else return write; - }); - await ChannelWrite.doWrite(config, writes); - return input; - } - static async doWrite(config, writes) { - for (const w of writes) { - if (_isChannelWriteEntry(w)) { - if (w.channel === constants_TASKS) throw new InvalidUpdateError("Cannot write to the reserved channel TASKS"); - if (_isPassthrough(w.value)) throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); - } - if (_isChannelWriteTupleEntry(w)) { - if (_isPassthrough(w.value)) throw new InvalidUpdateError("PASSTHROUGH value must be replaced"); - } - } - const writeEntries = []; - for (const w of writes) if (_isSend(w)) writeEntries.push([constants_TASKS, w]); - else if (_isChannelWriteTupleEntry(w)) { - const mappedResult = await w.mapper.invoke(w.value, config); - if (mappedResult != null && mappedResult.length > 0) writeEntries.push(...mappedResult); - } else if (_isChannelWriteEntry(w)) { - const mappedValue = w.mapper !== void 0 ? await w.mapper.invoke(w.value, config) : w.value; - if (_isSkipWrite(mappedValue)) continue; - if (w.skipNone && mappedValue === void 0) continue; - writeEntries.push([w.channel, mappedValue]); - } else throw new Error(`Invalid write entry: ${JSON.stringify(w)}`); - const write = config.configurable?.[CONFIG_KEY_SEND]; - write(writeEntries); - } - static isWriter(runnable) { - return runnable instanceof ChannelWrite || IS_WRITER in runnable && !!runnable[IS_WRITER]; - } - static registerWriter(runnable) { - return Object.defineProperty(runnable, IS_WRITER, { value: true }); - } -}; -function _isChannelWriteEntry(x) { - return x !== void 0 && typeof x.channel === "string"; -} -function _isChannelWriteTupleEntry(x) { - return x !== void 0 && !_isChannelWriteEntry(x) && Runnable.isRunnable(x.mapper); -} - -//#endregion - -//# sourceMappingURL=write.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/read.js - - - - - -//#region src/pregel/read.ts -var ChannelRead = class ChannelRead extends RunnableCallable { - lc_graph_name = "ChannelRead"; - channel; - fresh = false; - mapper; - constructor(channel, mapper, fresh = false) { - super({ func: (_, config) => ChannelRead.doRead(config, this.channel, this.fresh, this.mapper) }); - this.fresh = fresh; - this.mapper = mapper; - this.channel = channel; - this.name = Array.isArray(channel) ? `ChannelRead<${channel.join(",")}>` : `ChannelRead<${channel}>`; - } - static doRead(config, channel, fresh, mapper) { - const read = config.configurable?.[CONFIG_KEY_READ]; - if (!read) throw new Error("Runnable is not configured with a read function. Make sure to call in the context of a Pregel process"); - if (mapper) return mapper(read(channel, fresh)); - else return read(channel, fresh); - } -}; -const defaultRunnableBound = /* @__PURE__ */ new RunnablePassthrough(); -var PregelNode = class PregelNode extends RunnableBinding { - lc_graph_name = "PregelNode"; - channels; - triggers = []; - mapper; - writers = []; - bound = defaultRunnableBound; - kwargs = {}; - metadata = {}; - tags = []; - retryPolicy; - cachePolicy; - subgraphs; - ends; - constructor(fields) { - const { channels, triggers, mapper, writers, bound, kwargs, metadata, retryPolicy, cachePolicy, tags, subgraphs, ends } = fields; - const mergedTags = [...fields.config?.tags ? fields.config.tags : [], ...tags ?? []]; - super({ - ...fields, - bound: fields.bound ?? defaultRunnableBound, - config: { - ...fields.config ? fields.config : {}, - tags: mergedTags - } - }); - this.channels = channels; - this.triggers = triggers; - this.mapper = mapper; - this.writers = writers ?? this.writers; - this.bound = bound ?? this.bound; - this.kwargs = kwargs ?? this.kwargs; - this.metadata = metadata ?? this.metadata; - this.tags = mergedTags; - this.retryPolicy = retryPolicy; - this.cachePolicy = cachePolicy; - this.subgraphs = subgraphs; - this.ends = ends; - } - getWriters() { - const newWriters = [...this.writers]; - while (newWriters.length > 1 && newWriters[newWriters.length - 1] instanceof ChannelWrite && newWriters[newWriters.length - 2] instanceof ChannelWrite) { - const endWriters = newWriters.slice(-2); - const combinedWrites = endWriters[0].writes.concat(endWriters[1].writes); - newWriters[newWriters.length - 2] = new ChannelWrite(combinedWrites, endWriters[0].config?.tags); - newWriters.pop(); - } - return newWriters; - } - getNode() { - const writers = this.getWriters(); - if (this.bound === defaultRunnableBound && writers.length === 0) return void 0; - else if (this.bound === defaultRunnableBound && writers.length === 1) return writers[0]; - else if (this.bound === defaultRunnableBound) return new RunnableSequence({ - first: writers[0], - middle: writers.slice(1, writers.length - 1), - last: writers[writers.length - 1], - omitSequenceTags: true - }); - else if (writers.length > 0) return new RunnableSequence({ - first: this.bound, - middle: writers.slice(0, writers.length - 1), - last: writers[writers.length - 1], - omitSequenceTags: true - }); - else return this.bound; - } - join(channels) { - if (!Array.isArray(channels)) throw new Error("channels must be a list"); - if (typeof this.channels !== "object") throw new Error("all channels must be named when using .join()"); - return new PregelNode({ - channels: { - ...this.channels, - ...Object.fromEntries(channels.map((chan) => [chan, chan])) - }, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: this.bound, - kwargs: this.kwargs, - config: this.config, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - } - pipe(coerceable) { - if (ChannelWrite.isWriter(coerceable)) return new PregelNode({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: [...this.writers, coerceable], - bound: this.bound, - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - else if (this.bound === defaultRunnableBound) return new PregelNode({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: _coerceToRunnable(coerceable), - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - else return new PregelNode({ - channels: this.channels, - triggers: this.triggers, - mapper: this.mapper, - writers: this.writers, - bound: this.bound.pipe(coerceable), - config: this.config, - kwargs: this.kwargs, - retryPolicy: this.retryPolicy, - cachePolicy: this.cachePolicy - }); - } -}; - -//#endregion - -//# sourceMappingURL=read.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/utils/subgraph.js -//#region src/pregel/utils/subgraph.ts -function isRunnableSequence(x) { - return "steps" in x && Array.isArray(x.steps); -} -function isPregelLike(x) { - return "lg_is_pregel" in x && x.lg_is_pregel === true; -} -function findSubgraphPregel(candidate) { - const candidates = [candidate]; - for (const candidate$1 of candidates) if (isPregelLike(candidate$1)) return candidate$1; - else if (isRunnableSequence(candidate$1)) candidates.push(...candidate$1.steps); - return void 0; -} - -//#endregion - -//# sourceMappingURL=subgraph.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/io.js - - - - -//#region src/pregel/io.ts -function readChannel(channels, chan, catchErrors = true, returnException = false) { - try { - return channels[chan].get(); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) { - if (returnException) return e; - else if (catchErrors) return null; - } - throw e; - } -} -function readChannels(channels, select, skipEmpty = true) { - if (Array.isArray(select)) { - const values = {}; - for (const k of select) try { - values[k] = readChannel(channels, k, !skipEmpty); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) continue; - } - return values; - } else return readChannel(channels, select); -} -/** -* Map input chunk to a sequence of pending writes in the form (channel, value). -*/ -function* mapCommand(cmd, pendingWrites) { - if (cmd.graph === Command.PARENT) throw new InvalidUpdateError("There is no parent graph."); - if (cmd.goto) { - let sends; - if (Array.isArray(cmd.goto)) sends = cmd.goto; - else sends = [cmd.goto]; - for (const send of sends) if (_isSend(send)) yield [ - NULL_TASK_ID, - constants_TASKS, - send - ]; - else if (typeof send === "string") yield [ - NULL_TASK_ID, - `branch:to:${send}`, - "__start__" - ]; - else throw new Error(`In Command.send, expected Send or string, got ${typeof send}`); - } - if (cmd.resume) if (typeof cmd.resume === "object" && Object.keys(cmd.resume).length && Object.keys(cmd.resume).every(isXXH3)) for (const [tid, resume] of Object.entries(cmd.resume)) { - const existing = pendingWrites.filter((w) => w[0] === tid && w[1] === constants_RESUME).map((w) => w[2]).slice(0, 1) ?? []; - existing.push(resume); - yield [ - tid, - constants_RESUME, - existing - ]; - } - else yield [ - NULL_TASK_ID, - constants_RESUME, - cmd.resume - ]; - if (cmd.update) { - if (typeof cmd.update !== "object" || !cmd.update) throw new Error("Expected cmd.update to be a dict mapping channel names to update values"); - if (Array.isArray(cmd.update)) for (const [k, v] of cmd.update) yield [ - NULL_TASK_ID, - k, - v - ]; - else for (const [k, v] of Object.entries(cmd.update)) yield [ - NULL_TASK_ID, - k, - v - ]; - } -} -/** -* Map input chunk to a sequence of pending writes in the form [channel, value]. -*/ -function* mapInput(inputChannels, chunk) { - if (chunk !== void 0 && chunk !== null) if (Array.isArray(inputChannels) && typeof chunk === "object" && !Array.isArray(chunk)) { - for (const k in chunk) if (inputChannels.includes(k)) yield [k, chunk[k]]; - } else if (Array.isArray(inputChannels)) throw new Error(`Input chunk must be an object when "inputChannels" is an array`); - else yield [inputChannels, chunk]; -} -/** -* Map pending writes (a sequence of tuples (channel, value)) to output chunk. -*/ -function* mapOutputValues(outputChannels, pendingWrites, channels) { - if (Array.isArray(outputChannels)) { - if (pendingWrites === true || pendingWrites.find(([chan, _]) => outputChannels.includes(chan))) yield readChannels(channels, outputChannels); - } else if (pendingWrites === true || pendingWrites.some(([chan, _]) => chan === outputChannels)) yield readChannel(channels, outputChannels); -} -/** -* Map pending writes (a sequence of tuples (channel, value)) to output chunk. -* @internal -* -* @param outputChannels - The channels to output. -* @param tasks - The tasks to output. -* @param cached - Whether the output is cached. -* -* @returns A generator that yields the output chunk (if any). -*/ -function* mapOutputUpdates(outputChannels, tasks, cached) { - const outputTasks = tasks.filter(([task, ww]) => { - return (task.config === void 0 || !task.config.tags?.includes(TAG_HIDDEN)) && ww[0][0] !== constants_ERROR && ww[0][0] !== constants_INTERRUPT; - }); - if (!outputTasks.length) return; - let updated; - if (outputTasks.some(([task]) => task.writes.some(([chan, _]) => chan === RETURN))) updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === RETURN).map(([_, value]) => [task.name, value])); - else if (!Array.isArray(outputChannels)) updated = outputTasks.flatMap(([task]) => task.writes.filter(([chan, _]) => chan === outputChannels).map(([_, value]) => [task.name, value])); - else updated = outputTasks.flatMap(([task]) => { - const { writes } = task; - const counts = {}; - for (const [chan] of writes) if (outputChannels.includes(chan)) counts[chan] = (counts[chan] || 0) + 1; - if (Object.values(counts).some((count) => count > 1)) return writes.filter(([chan]) => outputChannels.includes(chan)).map(([chan, value]) => [task.name, { [chan]: value }]); - else return [[task.name, Object.fromEntries(writes.filter(([chan]) => outputChannels.includes(chan)))]]; - }); - const grouped = {}; - for (const [node, value] of updated) { - if (!(node in grouped)) grouped[node] = []; - grouped[node].push(value); - } - const flattened = {}; - for (const node in grouped) if (grouped[node].length === 1) { - const [write] = grouped[node]; - flattened[node] = write; - } else flattened[node] = grouped[node]; - if (cached) flattened["__metadata__"] = { cached }; - yield flattened; -} - -//#endregion - -//# sourceMappingURL=io.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/utils/index.js - - -//#region src/pregel/utils/index.ts -function getNullChannelVersion(currentVersions) { - const startVersion = typeof currentVersions[START]; - if (startVersion === "number") return 0; - if (startVersion === "string") return ""; - for (const key in currentVersions) { - if (!Object.prototype.hasOwnProperty.call(currentVersions, key)) continue; - const versionType = typeof currentVersions[key]; - if (versionType === "number") return 0; - if (versionType === "string") return ""; - break; - } - return void 0; -} -function getNewChannelVersions(previousVersions, currentVersions) { - if (Object.keys(previousVersions).length > 0) { - const nullVersion = getNullChannelVersion(currentVersions); - return Object.fromEntries(Object.entries(currentVersions).filter(([k, v]) => v > (previousVersions[k] ?? nullVersion))); - } else return currentVersions; -} -function utils_coerceToDict(value, defaultKey) { - return value && !Array.isArray(value) && !(value instanceof Date) && typeof value === "object" ? value : { [defaultKey]: value }; -} -function utils_patchConfigurable(config, patch) { - if (config === null) return { configurable: patch }; - else if (config?.configurable === void 0) return { - ...config, - configurable: patch - }; - else return { - ...config, - configurable: { - ...config.configurable, - ...patch - } - }; -} -function patchCheckpointMap(config, metadata) { - const parents = metadata?.parents ?? {}; - if (Object.keys(parents).length > 0) return utils_patchConfigurable(config, { [CONFIG_KEY_CHECKPOINT_MAP]: { - ...parents, - [config.configurable?.checkpoint_ns ?? ""]: config.configurable?.checkpoint_id - } }); - else return config; -} -/** -* Combine multiple abort signals into a single abort signal. -* @param signals - The abort signals to combine. -* @returns A combined abort signal and a dispose function to remove the abort listener if unused. -*/ -function combineAbortSignals(...x) { - const signals = [...new Set(x.filter(Boolean))]; - if (signals.length === 0) return { - signal: void 0, - dispose: void 0 - }; - if (signals.length === 1) return { - signal: signals[0], - dispose: void 0 - }; - const combinedController = new AbortController(); - const listener = () => { - const reason = signals.find((s) => s.aborted)?.reason; - combinedController.abort(reason); - signals.forEach((s) => s.removeEventListener("abort", listener)); - }; - signals.forEach((s) => s.addEventListener("abort", listener, { once: true })); - const hasAlreadyAbortedSignal = signals.find((s) => s.aborted); - if (hasAlreadyAbortedSignal) combinedController.abort(hasAlreadyAbortedSignal.reason); - return { - signal: combinedController.signal, - dispose: () => { - signals.forEach((s) => s.removeEventListener("abort", listener)); - } - }; -} -/** -* Combine multiple callbacks into a single callback. -* @param callback1 - The first callback to combine. -* @param callback2 - The second callback to combine. -* @returns A single callback that is a combination of the input callbacks. -*/ -const combineCallbacks = (callback1, callback2) => { - if (!callback1 && !callback2) return void 0; - if (!callback1) return callback2; - if (!callback2) return callback1; - if (Array.isArray(callback1) && Array.isArray(callback2)) return [...callback1, ...callback2]; - if (Array.isArray(callback1)) return [...callback1, callback2]; - if (Array.isArray(callback2)) return [callback1, ...callback2]; - return [callback1, callback2]; -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/types.js -//#region src/pregel/types.ts -var Call = class { - func; - name; - input; - retry; - cache; - callbacks; - __lg_type = "call"; - constructor({ func, name, input, retry, cache, callbacks }) { - this.func = func; - this.name = name; - this.input = input; - this.retry = retry; - this.cache = cache; - this.callbacks = callbacks; - } -}; -function isCall(value) { - return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "call"; -} - -//#endregion - -//# sourceMappingURL=types.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/call.js - - - - - - -//#region src/pregel/call.ts -/** -* Wraps a user function in a Runnable that writes the returned value to the RETURN channel. -*/ -function getRunnableForFunc(name, func) { - const run = new RunnableCallable({ - func: (input) => func(...input), - name, - trace: false, - recurse: false - }); - return new RunnableSequence({ - name, - first: run, - last: new ChannelWrite([{ - channel: RETURN, - value: PASSTHROUGH - }], [TAG_HIDDEN]) - }); -} -function getRunnableForEntrypoint(name, func) { - const run = new RunnableCallable({ - func: (input, config) => { - return func(input, config); - }, - name, - trace: false, - recurse: false - }); - return run; -} -function call_call({ func, name, cache, retry }, ...args) { - const config = AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (typeof config.configurable?.[CONFIG_KEY_CALL] === "function") return config.configurable[CONFIG_KEY_CALL](func, name, args, { - retry, - cache, - callbacks: config.callbacks - }); - throw new Error("Async local storage not initialized. Please call initializeAsyncLocalStorageSingleton() before using this function."); -} - -//#endregion - -//# sourceMappingURL=call.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/algo.js - - - - - - - - - - - -//#region src/pregel/algo.ts -const increment = (current) => { - return current !== void 0 ? current + 1 : 1; -}; -function triggersNextStep(updatedChannels, triggerToNodes) { - if (triggerToNodes == null) return false; - for (const chan of updatedChannels) if (triggerToNodes[chan]) return true; - return false; -} -function maxChannelMapVersion(channelVersions) { - let maxVersion; - for (const chan in channelVersions) { - if (!Object.prototype.hasOwnProperty.call(channelVersions, chan)) continue; - if (maxVersion == null) maxVersion = channelVersions[chan]; - else maxVersion = maxChannelVersion(maxVersion, channelVersions[chan]); - } - return maxVersion; -} -function shouldInterrupt(checkpoint, interruptNodes, tasks) { - const nullVersion = getNullChannelVersion(checkpoint.channel_versions); - const seen = checkpoint.versions_seen[constants_INTERRUPT] ?? {}; - let anyChannelUpdated = false; - if ((checkpoint.channel_versions[START] ?? nullVersion) > (seen[START] ?? nullVersion)) anyChannelUpdated = true; - else for (const chan in checkpoint.channel_versions) { - if (!Object.prototype.hasOwnProperty.call(checkpoint.channel_versions, chan)) continue; - if (checkpoint.channel_versions[chan] > (seen[chan] ?? nullVersion)) { - anyChannelUpdated = true; - break; - } - } - const anyTriggeredNodeInInterruptNodes = tasks.some((task) => interruptNodes === "*" ? !task.config?.tags?.includes(TAG_HIDDEN) : interruptNodes.includes(task.name)); - return anyChannelUpdated && anyTriggeredNodeInInterruptNodes; -} -function _localRead(checkpoint, channels, task, select, fresh = false) { - let updated = /* @__PURE__ */ new Set(); - if (!Array.isArray(select)) { - for (const [c] of task.writes) if (c === select) { - updated = new Set([c]); - break; - } - updated = updated || /* @__PURE__ */ new Set(); - } else updated = new Set(select.filter((c) => task.writes.some(([key, _]) => key === c))); - let values; - if (fresh && updated.size > 0) { - const localChannels = Object.fromEntries(Object.entries(channels).filter(([k, _]) => updated.has(k))); - const newCheckpoint = createCheckpoint(checkpoint, localChannels, -1); - const newChannels = emptyChannels(localChannels, newCheckpoint); - _applyWrites(copyCheckpoint(newCheckpoint), newChannels, [task], void 0, void 0); - values = readChannels({ - ...channels, - ...newChannels - }, select); - } else values = readChannels(channels, select); - return values; -} -function _localWrite(commit, processes, writes) { - for (const [chan, value] of writes) if ([PUSH, constants_TASKS].includes(chan) && value != null) { - if (!_isSend(value)) throw new InvalidUpdateError(`Invalid packet type, expected SendProtocol, got ${JSON.stringify(value)}`); - if (!(value.node in processes)) throw new InvalidUpdateError(`Invalid node name "${value.node}" in Send packet`); - } - commit(writes); -} -const IGNORE = new Set([ - NO_WRITES, - PUSH, - constants_RESUME, - constants_INTERRUPT, - RETURN, - constants_ERROR -]); -function _applyWrites(checkpoint, channels, tasks, getNextVersion, triggerToNodes) { - tasks.sort((a, b) => { - const aPath = a.path?.slice(0, 3) || []; - const bPath = b.path?.slice(0, 3) || []; - for (let i = 0; i < Math.min(aPath.length, bPath.length); i += 1) { - if (aPath[i] < bPath[i]) return -1; - if (aPath[i] > bPath[i]) return 1; - } - return aPath.length - bPath.length; - }); - const bumpStep = tasks.some((task) => task.triggers.length > 0); - const onlyChannels = getOnlyChannels(channels); - for (const task of tasks) { - checkpoint.versions_seen[task.name] ??= {}; - for (const chan of task.triggers) if (chan in checkpoint.channel_versions) checkpoint.versions_seen[task.name][chan] = checkpoint.channel_versions[chan]; - } - let maxVersion = maxChannelMapVersion(checkpoint.channel_versions); - const channelsToConsume = new Set(tasks.flatMap((task) => task.triggers).filter((chan) => !RESERVED.includes(chan))); - let usedNewVersion = false; - for (const chan of channelsToConsume) if (chan in onlyChannels && onlyChannels[chan].consume()) { - if (getNextVersion !== void 0) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - usedNewVersion = true; - } - } - const pendingWritesByChannel = {}; - for (const task of tasks) for (const [chan, val] of task.writes) if (IGNORE.has(chan)) {} else if (chan in onlyChannels) { - pendingWritesByChannel[chan] ??= []; - pendingWritesByChannel[chan].push(val); - } - if (maxVersion != null && getNextVersion != null) maxVersion = usedNewVersion ? getNextVersion(maxVersion) : maxVersion; - const updatedChannels = /* @__PURE__ */ new Set(); - for (const [chan, vals] of Object.entries(pendingWritesByChannel)) if (chan in onlyChannels) { - const channel = onlyChannels[chan]; - let updated; - try { - updated = channel.update(vals); - } catch (e) { - if (e.name === InvalidUpdateError.unminifiable_name) { - const wrappedError = new InvalidUpdateError(`Invalid update for channel "${chan}" with values ${JSON.stringify(vals)}: ${e.message}`); - wrappedError.lc_error_code = e.lc_error_code; - throw wrappedError; - } else throw e; - } - if (updated && getNextVersion !== void 0) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) updatedChannels.add(chan); - } - } - if (bumpStep) for (const chan in onlyChannels) { - if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue; - const channel = onlyChannels[chan]; - if (channel.isAvailable() && !updatedChannels.has(chan)) { - const updated = channel.update([]); - if (updated && getNextVersion !== void 0) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) updatedChannels.add(chan); - } - } - } - if (bumpStep && !triggersNextStep(updatedChannels, triggerToNodes)) for (const chan in onlyChannels) { - if (!Object.prototype.hasOwnProperty.call(onlyChannels, chan)) continue; - const channel = onlyChannels[chan]; - if (channel.finish() && getNextVersion !== void 0) { - checkpoint.channel_versions[chan] = getNextVersion(maxVersion); - if (channel.isAvailable()) updatedChannels.add(chan); - } - } - return updatedChannels; -} -function* candidateNodes(checkpoint, processes, extra) { - if (extra.updatedChannels != null && extra.triggerToNodes != null) { - const triggeredNodes = /* @__PURE__ */ new Set(); - for (const channel of extra.updatedChannels) { - const nodeIds = extra.triggerToNodes[channel]; - for (const id of nodeIds ?? []) triggeredNodes.add(id); - } - yield* [...triggeredNodes].sort(); - return; - } - const isEmptyChannelVersions = (() => { - for (const chan in checkpoint.channel_versions) if (checkpoint.channel_versions[chan] !== null) return false; - return true; - })(); - if (isEmptyChannelVersions) return; - for (const name in processes) { - if (!Object.prototype.hasOwnProperty.call(processes, name)) continue; - yield name; - } -} -/** -* Prepare the set of tasks that will make up the next Pregel step. -* This is the union of all PUSH tasks (Sends) and PULL tasks (nodes triggered -* by edges). -*/ -function _prepareNextTasks(checkpoint, pendingWrites, processes, channels, config, forExecution, extra) { - const tasks = {}; - const tasksChannel = channels[constants_TASKS]; - if (tasksChannel?.isAvailable()) { - const len = tasksChannel.get().length; - for (let i = 0; i < len; i += 1) { - const task = _prepareSingleTask([PUSH, i], checkpoint, pendingWrites, processes, channels, config, forExecution, extra); - if (task !== void 0) tasks[task.id] = task; - } - } - for (const name of candidateNodes(checkpoint, processes, extra)) { - const task = _prepareSingleTask([PULL, name], checkpoint, pendingWrites, processes, channels, config, forExecution, extra); - if (task !== void 0) tasks[task.id] = task; - } - return tasks; -} -/** -* Prepares a single task for the next Pregel step, given a task path, which -* uniquely identifies a PUSH or PULL task within the graph. -*/ -function _prepareSingleTask(taskPath, checkpoint, pendingWrites, processes, channels, config, forExecution, extra) { - const { step, checkpointer, manager } = extra; - const configurable = config.configurable ?? {}; - const parentNamespace = configurable.checkpoint_ns ?? ""; - if (taskPath[0] === PUSH && isCall(taskPath[taskPath.length - 1])) { - const call = taskPath[taskPath.length - 1]; - const proc = getRunnableForFunc(call.name, call.func); - const triggers = [PUSH]; - const checkpointNamespace = parentNamespace === "" ? call.name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${call.name}`; - const id = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - call.name, - PUSH, - taskPath[1], - taskPath[2] - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${id}`; - const outputTaskPath = [...taskPath.slice(0, 3), true]; - const metadata = { - langgraph_step: step, - langgraph_node: call.name, - langgraph_triggers: triggers, - langgraph_path: outputTaskPath, - langgraph_checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const writes = []; - const task = { - name: call.name, - input: call.input, - proc, - writes, - config: config_patchConfig(mergeConfigs(config, { - metadata, - store: extra.store ?? config.store - }), { - runName: call.name, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID]: id, - [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { - name: call.name, - writes, - triggers, - path: outputTaskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER], - [CONFIG_KEY_CHECKPOINT_MAP]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP], - [parentNamespace]: checkpoint.id - }, - [constants_CONFIG_KEY_SCRATCHPAD]: _scratchpad({ - pendingWrites: pendingWrites ?? [], - taskId: id, - currentTaskInput: call.input, - resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], - namespaceHash: XXH3(taskCheckpointNamespace) - }), - [constants_CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], - checkpoint_id: void 0, - checkpoint_ns: taskCheckpointNamespace - } - }), - triggers, - retry_policy: call.retry, - cache_key: call.cache ? { - key: XXH3((call.cache.keyFunc ?? JSON.stringify)([call.input])), - ns: [CACHE_NS_WRITES, call.name ?? "__dynamic__"], - ttl: call.cache.ttl - } : void 0, - id, - path: outputTaskPath, - writers: [] - }; - return task; - } else return { - id, - name: call.name, - interrupts: [], - path: outputTaskPath - }; - } else if (taskPath[0] === PUSH) { - const index = typeof taskPath[1] === "number" ? taskPath[1] : parseInt(taskPath[1], 10); - if (!channels[constants_TASKS]?.isAvailable()) return void 0; - const sends = channels[constants_TASKS].get(); - if (index < 0 || index >= sends.length) return void 0; - const packet = _isSendInterface(sends[index]) && !_isSend(sends[index]) ? new Send(sends[index].node, sends[index].args) : sends[index]; - if (!_isSendInterface(packet)) { - console.warn(`Ignoring invalid packet ${JSON.stringify(packet)} in pending sends.`); - return void 0; - } - if (!(packet.node in processes)) { - console.warn(`Ignoring unknown node name ${packet.node} in pending sends.`); - return void 0; - } - const triggers = [PUSH]; - const checkpointNamespace = parentNamespace === "" ? packet.node : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${packet.node}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - packet.node, - PUSH, - index.toString() - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${taskId}`; - let metadata = { - langgraph_step: step, - langgraph_node: packet.node, - langgraph_triggers: triggers, - langgraph_path: taskPath.slice(0, 3), - langgraph_checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const proc = processes[packet.node]; - const node = proc.getNode(); - if (node !== void 0) { - if (proc.metadata !== void 0) metadata = { - ...metadata, - ...proc.metadata - }; - const writes = []; - return { - name: packet.node, - input: packet.args, - proc: node, - subgraphs: proc.subgraphs, - writes, - config: config_patchConfig(mergeConfigs(config, { - metadata, - tags: proc.tags, - store: extra.store ?? config.store - }), { - runName: packet.node, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID]: taskId, - [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => writes.push(...items), processes, writes_), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { - name: packet.node, - writes, - triggers, - path: taskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER], - [CONFIG_KEY_CHECKPOINT_MAP]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP], - [parentNamespace]: checkpoint.id - }, - [constants_CONFIG_KEY_SCRATCHPAD]: _scratchpad({ - pendingWrites: pendingWrites ?? [], - taskId, - currentTaskInput: packet.args, - resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], - namespaceHash: XXH3(taskCheckpointNamespace) - }), - [constants_CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], - checkpoint_id: void 0, - checkpoint_ns: taskCheckpointNamespace - } - }), - triggers, - retry_policy: proc.retryPolicy, - cache_key: proc.cachePolicy ? { - key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([packet.args])), - ns: [ - CACHE_NS_WRITES, - proc.name ?? "__dynamic__", - packet.node - ], - ttl: proc.cachePolicy.ttl - } : void 0, - id: taskId, - path: taskPath, - writers: proc.getWriters() - }; - } - } else return { - id: taskId, - name: packet.node, - interrupts: [], - path: taskPath - }; - } else if (taskPath[0] === PULL) { - const name = taskPath[1].toString(); - const proc = processes[name]; - if (proc === void 0) return void 0; - if (pendingWrites?.length) { - const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${name}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - name, - PULL, - name - ]), checkpoint.id); - const hasSuccessfulWrites = pendingWrites.some((w) => w[0] === taskId && w[1] !== constants_ERROR); - if (hasSuccessfulWrites) return void 0; - } - const nullVersion = getNullChannelVersion(checkpoint.channel_versions); - if (nullVersion === void 0) return void 0; - const seen = checkpoint.versions_seen[name] ?? {}; - const trigger = proc.triggers.find((chan) => { - if (!channels[chan].isAvailable()) return false; - return (checkpoint.channel_versions[chan] ?? nullVersion) > (seen[chan] ?? nullVersion); - }); - if (trigger !== void 0) { - const val = _procInput(proc, channels, forExecution); - if (val === void 0) return void 0; - const checkpointNamespace = parentNamespace === "" ? name : `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${name}`; - const taskId = uuid5(JSON.stringify([ - checkpointNamespace, - step.toString(), - name, - PULL, - [trigger] - ]), checkpoint.id); - const taskCheckpointNamespace = `${checkpointNamespace}${CHECKPOINT_NAMESPACE_END}${taskId}`; - let metadata = { - langgraph_step: step, - langgraph_node: name, - langgraph_triggers: [trigger], - langgraph_path: taskPath, - langgraph_checkpoint_ns: taskCheckpointNamespace - }; - if (forExecution) { - const node = proc.getNode(); - if (node !== void 0) { - if (proc.metadata !== void 0) metadata = { - ...metadata, - ...proc.metadata - }; - const writes = []; - return { - name, - input: val, - proc: node, - subgraphs: proc.subgraphs, - writes, - config: config_patchConfig(mergeConfigs(config, { - metadata, - tags: proc.tags, - store: extra.store ?? config.store - }), { - runName: name, - callbacks: manager?.getChild(`graph:step:${step}`), - configurable: { - [CONFIG_KEY_TASK_ID]: taskId, - [CONFIG_KEY_SEND]: (writes_) => _localWrite((items) => { - writes.push(...items); - }, processes, writes_), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, { - name, - writes, - triggers: [trigger], - path: taskPath - }, select_, fresh_), - [CONFIG_KEY_CHECKPOINTER]: checkpointer ?? configurable[CONFIG_KEY_CHECKPOINTER], - [CONFIG_KEY_CHECKPOINT_MAP]: { - ...configurable[CONFIG_KEY_CHECKPOINT_MAP], - [parentNamespace]: checkpoint.id - }, - [constants_CONFIG_KEY_SCRATCHPAD]: _scratchpad({ - pendingWrites: pendingWrites ?? [], - taskId, - currentTaskInput: val, - resumeMap: config.configurable?.[CONFIG_KEY_RESUME_MAP], - namespaceHash: XXH3(taskCheckpointNamespace) - }), - [constants_CONFIG_KEY_PREVIOUS_STATE]: checkpoint.channel_values[PREVIOUS], - checkpoint_id: void 0, - checkpoint_ns: taskCheckpointNamespace - } - }), - triggers: [trigger], - retry_policy: proc.retryPolicy, - cache_key: proc.cachePolicy ? { - key: XXH3((proc.cachePolicy.keyFunc ?? JSON.stringify)([val])), - ns: [ - CACHE_NS_WRITES, - proc.name ?? "__dynamic__", - name - ], - ttl: proc.cachePolicy.ttl - } : void 0, - id: taskId, - path: taskPath, - writers: proc.getWriters() - }; - } - } else return { - id: taskId, - name, - interrupts: [], - path: taskPath - }; - } - } - return void 0; -} -/** -* Function injected under CONFIG_KEY_READ in task config, to read current state. -* Used by conditional edges to read a copy of the state with reflecting the writes -* from that node only. -* -* @internal -*/ -function _procInput(proc, channels, forExecution) { - let val; - if (typeof proc.channels === "object" && !Array.isArray(proc.channels)) { - val = {}; - for (const [k, chan] of Object.entries(proc.channels)) if (proc.triggers.includes(chan)) try { - val[k] = readChannel(channels, chan, false); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) return void 0; - else throw e; - } - else if (chan in channels) try { - val[k] = readChannel(channels, chan, false); - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) continue; - else throw e; - } - } else if (Array.isArray(proc.channels)) { - let successfulRead = false; - for (const chan of proc.channels) try { - val = readChannel(channels, chan, false); - successfulRead = true; - break; - } catch (e) { - if (e.name === EmptyChannelError.unminifiable_name) continue; - else throw e; - } - if (!successfulRead) return void 0; - } else throw new Error(`Invalid channels type, expected list or dict, got ${proc.channels}`); - if (forExecution && proc.mapper !== void 0) val = proc.mapper(val); - return val; -} -function _scratchpad({ pendingWrites, taskId, currentTaskInput, resumeMap, namespaceHash }) { - const nullResume = pendingWrites.find(([writeTaskId, chan]) => writeTaskId === NULL_TASK_ID && chan === constants_RESUME)?.[2]; - const resume = (() => { - const result = pendingWrites.filter(([writeTaskId, chan]) => writeTaskId === taskId && chan === constants_RESUME).flatMap(([_writeTaskId, _chan, resume$1]) => resume$1); - if (resumeMap != null && namespaceHash in resumeMap) { - const mappedResume = resumeMap[namespaceHash]; - result.push(mappedResume); - } - return result; - })(); - const scratchpad = { - callCounter: 0, - interruptCounter: -1, - resume, - nullResume, - subgraphCounter: 0, - currentTaskInput, - consumeNullResume: () => { - if (scratchpad.nullResume) { - delete scratchpad.nullResume; - pendingWrites.splice(pendingWrites.findIndex(([writeTaskId, chan]) => writeTaskId === NULL_TASK_ID && chan === constants_RESUME), 1); - return nullResume; - } - return void 0; - } - }; - return scratchpad; -} - -//#endregion - -//# sourceMappingURL=algo.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/debug.js - - - - -//#region src/pregel/debug.ts -const COLORS_MAP = { - blue: { - start: "\x1B[34m", - end: "\x1B[0m" - }, - green: { - start: "\x1B[32m", - end: "\x1B[0m" - }, - yellow: { - start: "\x1B[33;1m", - end: "\x1B[0m" - } -}; -/** -* Wrap some text in a color for printing to the console. -*/ -const debug_wrap = (color, text) => `${color.start}${text}${color.end}`; -function* mapDebugTasks(tasks) { - for (const { id, name, input, config, triggers, writes } of tasks) { - if (config?.tags?.includes(TAG_HIDDEN)) continue; - const interrupts = writes.filter(([writeId, n]) => { - return writeId === id && n === constants_INTERRUPT; - }).map(([, v]) => { - return v; - }); - yield { - id, - name, - input, - triggers, - interrupts - }; - } -} -function isMultipleChannelWrite(value) { - if (typeof value !== "object" || value === null) return false; - return "$writes" in value && Array.isArray(value.$writes); -} -function mapTaskResultWrites(writes) { - const result = {}; - for (const [channel, value] of writes) { - const strChannel = String(channel); - if (strChannel in result) { - const channelWrites = isMultipleChannelWrite(result[strChannel]) ? result[strChannel].$writes : [result[strChannel]]; - channelWrites.push(value); - result[strChannel] = { $writes: channelWrites }; - } else result[strChannel] = value; - } - return result; -} -function* mapDebugTaskResults(tasks, streamChannels) { - for (const [{ id, name, config }, writes] of tasks) { - if (config?.tags?.includes(TAG_HIDDEN)) continue; - yield { - id, - name, - result: mapTaskResultWrites(writes.filter(([channel]) => { - return Array.isArray(streamChannels) ? streamChannels.includes(channel) : channel === streamChannels; - })), - interrupts: writes.filter((w) => w[0] === constants_INTERRUPT).map((w) => w[1]) - }; - } -} -function* mapDebugCheckpoint(config, channels, streamChannels, metadata, tasks, pendingWrites, parentConfig, outputKeys) { - function formatConfig(config$1) { - const pyConfig = {}; - if (config$1.callbacks != null) pyConfig.callbacks = config$1.callbacks; - if (config$1.configurable != null) pyConfig.configurable = config$1.configurable; - if (config$1.maxConcurrency != null) pyConfig.max_concurrency = config$1.maxConcurrency; - if (config$1.metadata != null) pyConfig.metadata = config$1.metadata; - if (config$1.recursionLimit != null) pyConfig.recursion_limit = config$1.recursionLimit; - if (config$1.runId != null) pyConfig.run_id = config$1.runId; - if (config$1.runName != null) pyConfig.run_name = config$1.runName; - if (config$1.tags != null) pyConfig.tags = config$1.tags; - return pyConfig; - } - const parentNs = config.configurable?.checkpoint_ns; - const taskStates = {}; - for (const task of tasks) { - const candidates = task.subgraphs?.length ? task.subgraphs : [task.proc]; - if (!candidates.find(findSubgraphPregel)) continue; - let taskNs = `${task.name}:${task.id}`; - if (parentNs) taskNs = `${parentNs}|${taskNs}`; - taskStates[task.id] = { configurable: { - thread_id: config.configurable?.thread_id, - checkpoint_ns: taskNs - } }; - } - yield { - config: formatConfig(config), - values: readChannels(channels, streamChannels), - metadata, - next: tasks.map((task) => task.name), - tasks: tasksWithWrites(tasks, pendingWrites, taskStates, outputKeys), - parentConfig: parentConfig ? formatConfig(parentConfig) : void 0 - }; -} -function tasksWithWrites(tasks, pendingWrites, states, outputKeys) { - return tasks.map((task) => { - const error = pendingWrites.find(([id, n]) => id === task.id && n === constants_ERROR)?.[2]; - const interrupts = pendingWrites.filter(([id, n]) => id === task.id && n === constants_INTERRUPT).map(([, , v]) => v); - const result = (() => { - if (error || interrupts.length || !pendingWrites.length) return void 0; - const idx = pendingWrites.findIndex(([tid, n]) => tid === task.id && n === RETURN); - if (idx >= 0) return pendingWrites[idx][2]; - if (typeof outputKeys === "string") return pendingWrites.find(([tid, n]) => tid === task.id && n === outputKeys)?.[2]; - if (Array.isArray(outputKeys)) { - const results = pendingWrites.filter(([tid, n]) => tid === task.id && outputKeys.includes(n)).map(([, n, v]) => [n, v]); - if (!results.length) return void 0; - return mapTaskResultWrites(results); - } - return void 0; - })(); - if (error) return { - id: task.id, - name: task.name, - path: task.path, - error, - interrupts, - result - }; - const taskState = states?.[task.id]; - return { - id: task.id, - name: task.name, - path: task.path, - interrupts, - ...taskState !== void 0 ? { state: taskState } : {}, - result - }; - }); -} -function printStepCheckpoint(step, channels, whitelist) { - console.log([ - `${debug_wrap(COLORS_MAP.blue, `[${step}:checkpoint]`)}`, - `\x1b[1m State at the end of step ${step}:\x1b[0m\n`, - JSON.stringify(readChannels(channels, whitelist), null, 2) - ].join("")); -} -function printStepTasks(step, nextTasks) { - const nTasks = nextTasks.length; - console.log([ - `${debug_wrap(COLORS_MAP.blue, `[${step}:tasks]`)}`, - `\x1b[1m Starting step ${step} with ${nTasks} task${nTasks === 1 ? "" : "s"}:\x1b[0m\n`, - nextTasks.map((task) => `- ${debug_wrap(COLORS_MAP.green, String(task.name))} -> ${JSON.stringify(task.input, null, 2)}`).join("\n") - ].join("")); -} -function printStepWrites(step, writes, whitelist) { - const byChannel = {}; - for (const [channel, value] of writes) if (whitelist.includes(channel)) { - if (!byChannel[channel]) byChannel[channel] = []; - byChannel[channel].push(value); - } - console.log([ - `${debug_wrap(COLORS_MAP.blue, `[${step}:writes]`)}`, - `\x1b[1m Finished step ${step} with writes to ${Object.keys(byChannel).length} channel${Object.keys(byChannel).length !== 1 ? "s" : ""}:\x1b[0m\n`, - Object.entries(byChannel).map(([name, vals]) => `- ${debug_wrap(COLORS_MAP.yellow, name)} -> ${vals.map((v) => JSON.stringify(v)).join(", ")}`).join("\n") - ].join("")); -} - -//#endregion - -//# sourceMappingURL=debug.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/stream.js - - -//#region src/pregel/stream.ts -/** -* A wrapper around an IterableReadableStream that allows for aborting the stream when -* {@link cancel} is called. -*/ -var IterableReadableStreamWithAbortSignal = class extends IterableReadableStream { - _abortController; - _innerReader; - /** - * @param readableStream - The stream to wrap. - * @param abortController - The abort controller to use. Optional. One will be created if not provided. - */ - constructor(readableStream, abortController) { - const reader = readableStream.getReader(); - const ac = abortController ?? new AbortController(); - super({ start(controller) { - return pump(); - function pump() { - return reader.read().then(({ done, value }) => { - if (done) { - controller.close(); - return; - } - controller.enqueue(value); - return pump(); - }); - } - } }); - this._abortController = ac; - this._innerReader = reader; - } - /** - * Aborts the stream, abandoning any pending operations in progress. Calling this triggers an - * {@link AbortSignal} that is propagated to the tasks that are producing the data for this stream. - * @param reason - The reason for aborting the stream. Optional. - */ - async cancel(reason) { - this._abortController.abort(reason); - this._innerReader.releaseLock(); - } - /** - * The {@link AbortSignal} for the stream. Aborted when {@link cancel} is called. - */ - get signal() { - return this._abortController.signal; - } -}; -var IterableReadableWritableStream = class extends IterableReadableStream { - modes; - controller; - passthroughFn; - _closed = false; - get closed() { - return this._closed; - } - constructor(params) { - let streamControllerPromiseResolver; - const streamControllerPromise = new Promise((resolve) => { - streamControllerPromiseResolver = resolve; - }); - super({ start: (controller) => { - streamControllerPromiseResolver(controller); - } }); - streamControllerPromise.then((controller) => { - this.controller = controller; - }); - this.passthroughFn = params.passthroughFn; - this.modes = params.modes; - } - push(chunk) { - this.passthroughFn?.(chunk); - this.controller.enqueue(chunk); - } - close() { - try { - this.controller.close(); - } catch (e) {} finally { - this._closed = true; - } - } - error(e) { - this.controller.error(e); - } -}; -function _stringifyAsDict(obj) { - return JSON.stringify(obj, function(key, value) { - const rawValue = this[key]; - if (rawValue != null && typeof rawValue === "object" && "toDict" in rawValue && typeof rawValue.toDict === "function") { - const { type, data } = rawValue.toDict(); - return { - ...data, - type - }; - } - return value; - }); -} -function _serializeError(error) { - if (error instanceof Error) return { - error: error.name, - message: error.message - }; - return { - error: "Error", - message: JSON.stringify(error) - }; -} -function _isRunnableConfig(config) { - if (typeof config !== "object" || config == null) return false; - return "configurable" in config && typeof config.configurable === "object" && config.configurable != null; -} -function _extractCheckpointFromConfig(config) { - if (!_isRunnableConfig(config) || !config.configurable.thread_id) return null; - return { - thread_id: config.configurable.thread_id, - checkpoint_ns: config.configurable.checkpoint_ns || "", - checkpoint_id: config.configurable.checkpoint_id || null, - checkpoint_map: config.configurable.checkpoint_map || null - }; -} -function _serializeConfig(config) { - if (_isRunnableConfig(config)) { - const configurable = Object.fromEntries(Object.entries(config.configurable).filter(([key]) => !key.startsWith("__"))); - const newConfig = { - ...config, - configurable - }; - delete newConfig.callbacks; - return newConfig; - } - return config; -} -function _serializeCheckpoint(payload) { - const result = { - ...payload, - checkpoint: _extractCheckpointFromConfig(payload.config), - parent_checkpoint: _extractCheckpointFromConfig(payload.parentConfig), - config: _serializeConfig(payload.config), - parent_config: _serializeConfig(payload.parentConfig), - tasks: payload.tasks.map((task) => { - if (_isRunnableConfig(task.state)) { - const checkpoint = _extractCheckpointFromConfig(task.state); - if (checkpoint != null) { - const cloneTask = { - ...task, - checkpoint - }; - delete cloneTask.state; - return cloneTask; - } - } - return task; - }) - }; - delete result.parentConfig; - return result; -} -function toEventStream(stream) { - const encoder = new TextEncoder(); - return new ReadableStream({ async start(controller) { - const enqueueChunk = (sse) => { - controller.enqueue(encoder.encode(`event: ${sse.event}\ndata: ${_stringifyAsDict(sse.data)}\n\n`)); - }; - try { - for await (const payload of stream) { - const [ns, mode, chunk] = payload; - let data = chunk; - if (mode === "debug") { - const debugChunk = chunk; - if (debugChunk.type === "checkpoint") data = { - ...debugChunk, - payload: _serializeCheckpoint(debugChunk.payload) - }; - } - if (mode === "checkpoints") data = _serializeCheckpoint(chunk); - const event = ns?.length ? `${mode}|${ns.join("|")}` : mode; - enqueueChunk({ - event, - data - }); - } - } catch (error) { - enqueueChunk({ - event: "error", - data: _serializeError(error) - }); - } - controller.close(); - } }); -} - -//#endregion - -//# sourceMappingURL=stream.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/loop.js - - - - - - - - - - - - -//#region src/pregel/loop.ts -const INPUT_DONE = Symbol.for("INPUT_DONE"); -const INPUT_RESUMING = Symbol.for("INPUT_RESUMING"); -const DEFAULT_LOOP_LIMIT = 25; -function createDuplexStream(...streams) { - return new IterableReadableWritableStream({ - passthroughFn: (value) => { - for (const stream of streams) if (stream.modes.has(value[1])) stream.push(value); - }, - modes: new Set(streams.flatMap((s) => Array.from(s.modes))) - }); -} -var AsyncBatchedCache = class extends base_BaseCache { - cache; - queue = Promise.resolve(); - constructor(cache) { - super(); - this.cache = cache; - } - async get(keys) { - return this.enqueueOperation("get", keys); - } - async set(pairs) { - return this.enqueueOperation("set", pairs); - } - async clear(namespaces) { - return this.enqueueOperation("clear", namespaces); - } - async stop() { - await this.queue; - } - enqueueOperation(type, ...args) { - const newPromise = this.queue.then(() => { - return this.cache[type](...args); - }); - this.queue = newPromise.then(() => void 0, () => void 0); - return newPromise; - } -}; -var PregelLoop = class PregelLoop { - input; - output; - config; - checkpointer; - checkpointerGetNextVersion; - channels; - checkpoint; - checkpointIdSaved; - checkpointConfig; - checkpointMetadata; - checkpointNamespace; - checkpointPendingWrites = []; - checkpointPreviousVersions; - step; - stop; - durability; - outputKeys; - streamKeys; - nodes; - skipDoneTasks; - prevCheckpointConfig; - updatedChannels; - status = "pending"; - tasks = {}; - stream; - checkpointerPromises = []; - isNested; - _checkpointerChainedPromise = Promise.resolve(); - store; - cache; - manager; - interruptAfter; - interruptBefore; - toInterrupt = []; - debug = false; - triggerToNodes; - get isResuming() { - let hasChannelVersions = false; - if (START in this.checkpoint.channel_versions) hasChannelVersions = true; - else for (const chan in this.checkpoint.channel_versions) if (Object.prototype.hasOwnProperty.call(this.checkpoint.channel_versions, chan)) { - hasChannelVersions = true; - break; - } - const configHasResumingFlag = this.config.configurable?.[CONFIG_KEY_RESUMING] !== void 0; - const configIsResuming = configHasResumingFlag && this.config.configurable?.[CONFIG_KEY_RESUMING]; - const inputIsNullOrUndefined = this.input === null || this.input === void 0; - const inputIsCommandResuming = isCommand(this.input) && this.input.resume != null; - const inputIsResuming = this.input === INPUT_RESUMING; - const runIdMatchesPrevious = !this.isNested && this.config.metadata?.run_id !== void 0 && this.checkpointMetadata?.run_id !== void 0 && this.config.metadata.run_id === this.checkpointMetadata?.run_id; - return hasChannelVersions && (configIsResuming || inputIsNullOrUndefined || inputIsCommandResuming || inputIsResuming || runIdMatchesPrevious); - } - constructor(params) { - this.input = params.input; - this.checkpointer = params.checkpointer; - if (this.checkpointer !== void 0) this.checkpointerGetNextVersion = this.checkpointer.getNextVersion.bind(this.checkpointer); - else this.checkpointerGetNextVersion = increment; - this.checkpoint = params.checkpoint; - this.checkpointMetadata = params.checkpointMetadata; - this.checkpointPreviousVersions = params.checkpointPreviousVersions; - this.channels = params.channels; - this.checkpointPendingWrites = params.checkpointPendingWrites; - this.step = params.step; - this.stop = params.stop; - this.config = params.config; - this.checkpointConfig = params.checkpointConfig; - this.isNested = params.isNested; - this.manager = params.manager; - this.outputKeys = params.outputKeys; - this.streamKeys = params.streamKeys; - this.nodes = params.nodes; - this.skipDoneTasks = params.skipDoneTasks; - this.store = params.store; - this.cache = params.cache ? new AsyncBatchedCache(params.cache) : void 0; - this.stream = params.stream; - this.checkpointNamespace = params.checkpointNamespace; - this.prevCheckpointConfig = params.prevCheckpointConfig; - this.interruptAfter = params.interruptAfter; - this.interruptBefore = params.interruptBefore; - this.durability = params.durability; - this.debug = params.debug; - this.triggerToNodes = params.triggerToNodes; - } - static async initialize(params) { - let { config, stream } = params; - if (stream !== void 0 && config.configurable?.[CONFIG_KEY_STREAM] !== void 0) stream = createDuplexStream(stream, config.configurable[CONFIG_KEY_STREAM]); - const skipDoneTasks = config.configurable ? !("checkpoint_id" in config.configurable) : true; - const scratchpad = config.configurable?.[constants_CONFIG_KEY_SCRATCHPAD]; - if (config.configurable && scratchpad) { - if (scratchpad.subgraphCounter > 0) config = utils_patchConfigurable(config, { [CONFIG_KEY_CHECKPOINT_NS]: [config.configurable[CONFIG_KEY_CHECKPOINT_NS], scratchpad.subgraphCounter.toString()].join(CHECKPOINT_NAMESPACE_SEPARATOR) }); - scratchpad.subgraphCounter += 1; - } - const isNested = CONFIG_KEY_READ in (config.configurable ?? {}); - if (!isNested && config.configurable?.checkpoint_ns !== void 0 && config.configurable?.checkpoint_ns !== "") config = utils_patchConfigurable(config, { - checkpoint_ns: "", - checkpoint_id: void 0 - }); - let checkpointConfig = config; - if (config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP] !== void 0 && config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP]?.[config.configurable?.checkpoint_ns]) checkpointConfig = utils_patchConfigurable(config, { checkpoint_id: config.configurable[CONFIG_KEY_CHECKPOINT_MAP][config.configurable?.checkpoint_ns] }); - const checkpointNamespace = config.configurable?.checkpoint_ns?.split(CHECKPOINT_NAMESPACE_SEPARATOR) ?? []; - const saved = await params.checkpointer?.getTuple(checkpointConfig) ?? { - config, - checkpoint: emptyCheckpoint(), - metadata: { - source: "input", - step: -2, - parents: {} - }, - pendingWrites: [] - }; - checkpointConfig = { - ...config, - ...saved.config, - configurable: { - checkpoint_ns: "", - ...config.configurable, - ...saved.config.configurable - } - }; - const prevCheckpointConfig = saved.parentConfig; - const checkpoint = copyCheckpoint(saved.checkpoint); - const checkpointMetadata = { ...saved.metadata }; - const checkpointPendingWrites = saved.pendingWrites ?? []; - const channels = emptyChannels(params.channelSpecs, checkpoint); - const step = (checkpointMetadata.step ?? 0) + 1; - const stop = step + (config.recursionLimit ?? DEFAULT_LOOP_LIMIT) + 1; - const checkpointPreviousVersions = { ...checkpoint.channel_versions }; - const store = params.store ? new AsyncBatchedStore(params.store) : void 0; - if (store) await store.start(); - return new PregelLoop({ - input: params.input, - config, - checkpointer: params.checkpointer, - checkpoint, - checkpointMetadata, - checkpointConfig, - prevCheckpointConfig, - checkpointNamespace, - channels, - isNested, - manager: params.manager, - skipDoneTasks, - step, - stop, - checkpointPreviousVersions, - checkpointPendingWrites, - outputKeys: params.outputKeys ?? [], - streamKeys: params.streamKeys ?? [], - nodes: params.nodes, - stream, - store, - cache: params.cache, - interruptAfter: params.interruptAfter, - interruptBefore: params.interruptBefore, - durability: params.durability, - debug: params.debug, - triggerToNodes: params.triggerToNodes - }); - } - _checkpointerPutAfterPrevious(input) { - this._checkpointerChainedPromise = this._checkpointerChainedPromise.then(() => { - return this.checkpointer?.put(input.config, input.checkpoint, input.metadata, input.newVersions); - }); - this.checkpointerPromises.push(this._checkpointerChainedPromise); - } - /** - * Put writes for a task, to be read by the next tick. - * @param taskId - * @param writes - */ - putWrites(taskId, writes) { - let writesCopy = writes; - if (writesCopy.length === 0) return; - if (writesCopy.every(([key]) => key in WRITES_IDX_MAP)) writesCopy = Array.from(new Map(writesCopy.map((w) => [w[0], w])).values()); - this.checkpointPendingWrites = this.checkpointPendingWrites.filter((w) => w[0] !== taskId); - for (const [c, v] of writesCopy) this.checkpointPendingWrites.push([ - taskId, - c, - v - ]); - const config = utils_patchConfigurable(this.checkpointConfig, { - [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", - [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id - }); - if (this.durability !== "exit" && this.checkpointer != null) this.checkpointerPromises.push(this.checkpointer.putWrites(config, writesCopy, taskId)); - if (this.tasks) this._outputWrites(taskId, writesCopy); - if (!writes.length || !this.cache || !this.tasks) return; - const task = this.tasks[taskId]; - if (task == null || task.cache_key == null) return; - if (writes[0][0] === constants_ERROR || writes[0][0] === constants_INTERRUPT) return; - this.cache.set([{ - key: [task.cache_key.ns, task.cache_key.key], - value: task.writes, - ttl: task.cache_key.ttl - }]); - } - _outputWrites(taskId, writes, cached = false) { - const task = this.tasks[taskId]; - if (task !== void 0) { - if (task.config !== void 0 && (task.config.tags ?? []).includes(TAG_HIDDEN)) return; - if (writes.length > 0) { - if (writes[0][0] === constants_INTERRUPT) { - if (task.path?.[0] === PUSH && task.path?.at(-1) === true) return; - const interruptWrites = writes.filter((w) => w[0] === constants_INTERRUPT).flatMap((w) => w[1]); - this._emit([["updates", { [constants_INTERRUPT]: interruptWrites }], ["values", { [constants_INTERRUPT]: interruptWrites }]]); - } else if (writes[0][0] !== constants_ERROR) this._emit(gatherIteratorSync(prefixGenerator(mapOutputUpdates(this.outputKeys, [[task, writes]], cached), "updates"))); - } - if (!cached) this._emit(gatherIteratorSync(prefixGenerator(mapDebugTaskResults([[task, writes]], this.streamKeys), "tasks"))); - } - } - async _matchCachedWrites() { - if (!this.cache) return []; - const matched = []; - const serializeKey = ([ns, key]) => { - return `ns:${ns.join(",")}|key:${key}`; - }; - const keys = []; - const keyMap = {}; - for (const task of Object.values(this.tasks)) if (task.cache_key != null && !task.writes.length) { - keys.push([task.cache_key.ns, task.cache_key.key]); - keyMap[serializeKey([task.cache_key.ns, task.cache_key.key])] = task; - } - if (keys.length === 0) return []; - const cache = await this.cache.get(keys); - for (const { key, value } of cache) { - const task = keyMap[serializeKey(key)]; - if (task != null) { - task.writes.push(...value); - matched.push({ - task, - result: value - }); - } - } - return matched; - } - /** - * Execute a single iteration of the Pregel loop. - * Returns true if more iterations are needed. - * @param params - */ - async tick(params) { - if (this.store && !this.store.isRunning) await this.store?.start(); - const { inputKeys = [] } = params; - if (this.status !== "pending") throw new Error(`Cannot tick when status is no longer "pending". Current status: "${this.status}"`); - if (![INPUT_DONE, INPUT_RESUMING].includes(this.input)) await this._first(inputKeys); - else if (this.toInterrupt.length > 0) { - this.status = "interrupt_before"; - throw new GraphInterrupt(); - } else if (Object.values(this.tasks).every((task) => task.writes.length > 0)) { - const writes = Object.values(this.tasks).flatMap((t) => t.writes); - this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); - const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, writes, this.channels), "values")); - this._emit(valuesOutput); - this.checkpointPendingWrites = []; - await this._putCheckpoint({ source: "loop" }); - if (shouldInterrupt(this.checkpoint, this.interruptAfter, Object.values(this.tasks))) { - this.status = "interrupt_after"; - throw new GraphInterrupt(); - } - if (this.config.configurable?.[CONFIG_KEY_RESUMING] !== void 0) delete this.config.configurable?.[CONFIG_KEY_RESUMING]; - } else return false; - if (this.step > this.stop) { - this.status = "out_of_steps"; - return false; - } - const nextTasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { - step: this.step, - checkpointer: this.checkpointer, - isResuming: this.isResuming, - manager: this.manager, - store: this.store, - stream: this.stream, - triggerToNodes: this.triggerToNodes, - updatedChannels: this.updatedChannels - }); - this.tasks = nextTasks; - if (this.checkpointer) this._emit(await gatherIterator(prefixGenerator(mapDebugCheckpoint(this.checkpointConfig, this.channels, this.streamKeys, this.checkpointMetadata, Object.values(this.tasks), this.checkpointPendingWrites, this.prevCheckpointConfig, this.outputKeys), "checkpoints"))); - if (Object.values(this.tasks).length === 0) { - this.status = "done"; - return false; - } - if (this.skipDoneTasks && this.checkpointPendingWrites.length > 0) { - for (const [tid, k, v] of this.checkpointPendingWrites) { - if (k === constants_ERROR || k === constants_INTERRUPT || k === constants_RESUME) continue; - const task = Object.values(this.tasks).find((t) => t.id === tid); - if (task) task.writes.push([k, v]); - } - for (const task of Object.values(this.tasks)) if (task.writes.length > 0) this._outputWrites(task.id, task.writes, true); - } - if (Object.values(this.tasks).every((task) => task.writes.length > 0)) return this.tick({ inputKeys }); - if (shouldInterrupt(this.checkpoint, this.interruptBefore, Object.values(this.tasks))) { - this.status = "interrupt_before"; - throw new GraphInterrupt(); - } - const debugOutput = await gatherIterator(prefixGenerator(mapDebugTasks(Object.values(this.tasks)), "tasks")); - this._emit(debugOutput); - return true; - } - async finishAndHandleError(error) { - if (this.durability === "exit" && (!this.isNested || typeof error !== "undefined" || this.checkpointNamespace.every((part) => !part.includes(CHECKPOINT_NAMESPACE_END)))) { - this._putCheckpoint(this.checkpointMetadata); - this._flushPendingWrites(); - } - const suppress = this._suppressInterrupt(error); - if (suppress || error === void 0) this.output = readChannels(this.channels, this.outputKeys); - if (suppress) { - if (this.tasks !== void 0 && this.checkpointPendingWrites.length > 0 && Object.values(this.tasks).some((task) => task.writes.length > 0)) { - this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(this.tasks), this.checkpointerGetNextVersion, this.triggerToNodes); - this._emit(gatherIteratorSync(prefixGenerator(mapOutputValues(this.outputKeys, Object.values(this.tasks).flatMap((t) => t.writes), this.channels), "values"))); - } - if (isGraphInterrupt(error) && !error.interrupts.length) this._emit([["updates", { [constants_INTERRUPT]: [] }], ["values", { [constants_INTERRUPT]: [] }]]); - } - return suppress; - } - async acceptPush(task, writeIdx, call) { - if (this.interruptAfter?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptAfter, [task])) { - this.toInterrupt.push(task); - return; - } - const pushed = _prepareSingleTask([ - PUSH, - task.path ?? [], - writeIdx, - task.id, - call - ], this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, task.config ?? {}, true, { - step: this.step, - checkpointer: this.checkpointer, - manager: this.manager, - store: this.store, - stream: this.stream - }); - if (!pushed) return; - if (this.interruptBefore?.length > 0 && shouldInterrupt(this.checkpoint, this.interruptBefore, [pushed])) { - this.toInterrupt.push(pushed); - return; - } - this._emit(gatherIteratorSync(prefixGenerator(mapDebugTasks([pushed]), "tasks"))); - if (this.debug) printStepTasks(this.step, [pushed]); - this.tasks[pushed.id] = pushed; - if (this.skipDoneTasks) this._matchWrites({ [pushed.id]: pushed }); - const tasks = await this._matchCachedWrites(); - for (const { task: task$1 } of tasks) this._outputWrites(task$1.id, task$1.writes, true); - return pushed; - } - _suppressInterrupt(e) { - return isGraphInterrupt(e) && !this.isNested; - } - async _first(inputKeys) { - const { configurable } = this.config; - const scratchpad = configurable?.[constants_CONFIG_KEY_SCRATCHPAD]; - if (scratchpad && scratchpad.nullResume !== void 0) this.putWrites(NULL_TASK_ID, [[constants_RESUME, scratchpad.nullResume]]); - if (isCommand(this.input)) { - const hasResume = this.input.resume != null; - if (this.input.resume != null && typeof this.input.resume === "object" && Object.keys(this.input.resume).every(isXXH3)) { - this.config.configurable ??= {}; - this.config.configurable[CONFIG_KEY_RESUME_MAP] = this.input.resume; - } - if (hasResume && this.checkpointer == null) throw new Error("Cannot use Command(resume=...) without checkpointer"); - const writes = {}; - for (const [tid, key, value] of mapCommand(this.input, this.checkpointPendingWrites)) { - writes[tid] ??= []; - writes[tid].push([key, value]); - } - if (Object.keys(writes).length === 0) throw new EmptyInputError("Received empty Command input"); - for (const [tid, ws] of Object.entries(writes)) this.putWrites(tid, ws); - } - const nullWrites = (this.checkpointPendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); - if (nullWrites.length > 0) _applyWrites(this.checkpoint, this.channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], this.checkpointerGetNextVersion, this.triggerToNodes); - const isCommandUpdateOrGoto = isCommand(this.input) && nullWrites.length > 0; - if (this.isResuming || isCommandUpdateOrGoto) { - for (const channelName in this.channels) { - if (!Object.prototype.hasOwnProperty.call(this.channels, channelName)) continue; - if (this.checkpoint.channel_versions[channelName] !== void 0) { - const version = this.checkpoint.channel_versions[channelName]; - this.checkpoint.versions_seen[constants_INTERRUPT] = { - ...this.checkpoint.versions_seen[constants_INTERRUPT], - [channelName]: version - }; - } - } - const valuesOutput = await gatherIterator(prefixGenerator(mapOutputValues(this.outputKeys, true, this.channels), "values")); - this._emit(valuesOutput); - } - if (this.isResuming) this.input = INPUT_RESUMING; - else if (isCommandUpdateOrGoto) { - await this._putCheckpoint({ source: "input" }); - this.input = INPUT_DONE; - } else { - const inputWrites = await gatherIterator(mapInput(inputKeys, this.input)); - if (inputWrites.length > 0) { - const discardTasks = _prepareNextTasks(this.checkpoint, this.checkpointPendingWrites, this.nodes, this.channels, this.config, true, { step: this.step }); - this.updatedChannels = _applyWrites(this.checkpoint, this.channels, Object.values(discardTasks).concat([{ - name: INPUT, - writes: inputWrites, - triggers: [] - }]), this.checkpointerGetNextVersion, this.triggerToNodes); - await this._putCheckpoint({ source: "input" }); - this.input = INPUT_DONE; - } else if (!(CONFIG_KEY_RESUMING in (this.config.configurable ?? {}))) throw new EmptyInputError(`Received no input writes for ${JSON.stringify(inputKeys, null, 2)}`); - else this.input = INPUT_DONE; - } - if (!this.isNested) this.config = utils_patchConfigurable(this.config, { [CONFIG_KEY_RESUMING]: this.isResuming }); - } - _emit(values) { - for (const [mode, payload] of values) { - if (this.stream.modes.has(mode)) this.stream.push([ - this.checkpointNamespace, - mode, - payload - ]); - if ((mode === "checkpoints" || mode === "tasks") && this.stream.modes.has("debug")) { - const step = mode === "checkpoints" ? this.step - 1 : this.step; - const timestamp = (/* @__PURE__ */ new Date()).toISOString(); - const type = (() => { - if (mode === "checkpoints") return "checkpoint"; - else if (typeof payload === "object" && payload != null && "result" in payload) return "task_result"; - else return "task"; - })(); - this.stream.push([ - this.checkpointNamespace, - "debug", - { - step, - type, - timestamp, - payload - } - ]); - } - } - } - _putCheckpoint(inputMetadata) { - const exiting = this.checkpointMetadata === inputMetadata; - const doCheckpoint = this.checkpointer != null && (this.durability !== "exit" || exiting); - const storeCheckpoint = (checkpoint) => { - this.prevCheckpointConfig = this.checkpointConfig?.configurable?.checkpoint_id ? this.checkpointConfig : void 0; - this.checkpointConfig = utils_patchConfigurable(this.checkpointConfig, { [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "" }); - const channelVersions = { ...this.checkpoint.channel_versions }; - const newVersions = getNewChannelVersions(this.checkpointPreviousVersions, channelVersions); - this.checkpointPreviousVersions = channelVersions; - this._checkpointerPutAfterPrevious({ - config: { ...this.checkpointConfig }, - checkpoint: copyCheckpoint(checkpoint), - metadata: { ...this.checkpointMetadata }, - newVersions - }); - this.checkpointConfig = { - ...this.checkpointConfig, - configurable: { - ...this.checkpointConfig.configurable, - checkpoint_id: this.checkpoint.id - } - }; - }; - if (!exiting) this.checkpointMetadata = { - ...inputMetadata, - step: this.step, - parents: this.config.configurable?.[CONFIG_KEY_CHECKPOINT_MAP] ?? {} - }; - this.checkpoint = createCheckpoint(this.checkpoint, doCheckpoint ? this.channels : void 0, this.step, exiting ? { id: this.checkpoint.id } : void 0); - if (doCheckpoint) storeCheckpoint(this.checkpoint); - if (!exiting) this.step += 1; - } - _flushPendingWrites() { - if (this.checkpointer == null) return; - if (this.checkpointPendingWrites.length === 0) return; - const config = utils_patchConfigurable(this.checkpointConfig, { - [CONFIG_KEY_CHECKPOINT_NS]: this.config.configurable?.checkpoint_ns ?? "", - [CONFIG_KEY_CHECKPOINT_ID]: this.checkpoint.id - }); - const byTask = {}; - for (const [tid, key, value] of this.checkpointPendingWrites) { - byTask[tid] ??= []; - byTask[tid].push([key, value]); - } - for (const [tid, ws] of Object.entries(byTask)) this.checkpointerPromises.push(this.checkpointer.putWrites(config, ws, tid)); - } - _matchWrites(tasks) { - for (const [tid, k, v] of this.checkpointPendingWrites) { - if (k === constants_ERROR || k === constants_INTERRUPT || k === constants_RESUME) continue; - const task = Object.values(tasks).find((t) => t.id === tid); - if (task) task.writes.push([k, v]); - } - for (const task of Object.values(tasks)) if (task.writes.length > 0) this._outputWrites(task.id, task.writes, true); - } -}; - -//#endregion - -//# sourceMappingURL=loop.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/messages.js - - - - -//#region src/pregel/messages.ts -function messages_isChatGenerationChunk(x) { - return isBaseMessage(x?.message); -} -/** -* A callback handler that implements stream_mode=messages. -* Collects messages from (1) chat model stream events and (2) node outputs. -*/ -var StreamMessagesHandler = class extends BaseCallbackHandler { - name = "StreamMessagesHandler"; - streamFn; - metadatas = {}; - seen = {}; - emittedChatModelRunIds = {}; - stableMessageIdMap = {}; - lc_prefer_streaming = true; - constructor(streamFn) { - super(); - this.streamFn = streamFn; - } - _emit(meta, message, runId, dedupe = false) { - if (dedupe && message.id !== void 0 && this.seen[message.id] !== void 0) return; - let messageId = message.id; - if (runId != null) if (isToolMessage(message)) messageId ??= `run-${runId}-tool-${message.tool_call_id}`; - else { - if (messageId == null || messageId === `run-${runId}`) messageId = this.stableMessageIdMap[runId] ?? messageId ?? `run-${runId}`; - this.stableMessageIdMap[runId] ??= messageId; - } - if (messageId !== message.id) { - message.id = messageId; - message.lc_kwargs.id = messageId; - } - if (message.id != null) this.seen[message.id] = message; - this.streamFn([ - meta[0], - "messages", - [message, meta[1]] - ]); - } - handleChatModelStart(_llm, _messages, runId, _parentRunId, _extraParams, tags, metadata, name) { - if (metadata && (!tags || !tags.includes(TAG_NOSTREAM) && !tags.includes("nostream"))) this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { - tags, - name, - ...metadata - }]; - } - handleLLMNewToken(token, _idx, runId, _parentRunId, _tags, fields) { - const chunk = fields?.chunk; - this.emittedChatModelRunIds[runId] = true; - if (this.metadatas[runId] !== void 0) if (messages_isChatGenerationChunk(chunk)) this._emit(this.metadatas[runId], chunk.message, runId); - else this._emit(this.metadatas[runId], new AIMessageChunk({ content: token }), runId); - } - handleLLMEnd(output, runId) { - if (this.metadatas[runId] === void 0) return; - if (!this.emittedChatModelRunIds[runId]) { - const chatGeneration = output.generations?.[0]?.[0]; - if (isBaseMessage(chatGeneration?.message)) this._emit(this.metadatas[runId], chatGeneration?.message, runId, true); - delete this.emittedChatModelRunIds[runId]; - } - delete this.metadatas[runId]; - delete this.stableMessageIdMap[runId]; - } - handleLLMError(_err, runId) { - delete this.metadatas[runId]; - } - handleChainStart(_chain, inputs, runId, _parentRunId, tags, metadata, _runType, name) { - if (metadata !== void 0 && name === metadata.langgraph_node && (tags === void 0 || !tags.includes(TAG_HIDDEN))) { - this.metadatas[runId] = [metadata.langgraph_checkpoint_ns.split("|"), { - tags, - name, - ...metadata - }]; - if (typeof inputs === "object") { - for (const value of Object.values(inputs)) if ((isBaseMessage(value) || isBaseMessageChunk(value)) && value.id !== void 0) this.seen[value.id] = value; - else if (Array.isArray(value)) { - for (const item of value) if ((isBaseMessage(item) || isBaseMessageChunk(item)) && item.id !== void 0) this.seen[item.id] = item; - } - } - } - } - handleChainEnd(outputs, runId) { - const metadata = this.metadatas[runId]; - delete this.metadatas[runId]; - if (metadata !== void 0) { - if (isBaseMessage(outputs)) this._emit(metadata, outputs, runId, true); - else if (Array.isArray(outputs)) { - for (const value of outputs) if (isBaseMessage(value)) this._emit(metadata, value, runId, true); - } else if (outputs != null && typeof outputs === "object") { - for (const value of Object.values(outputs)) if (isBaseMessage(value)) this._emit(metadata, value, runId, true); - else if (Array.isArray(value)) { - for (const item of value) if (isBaseMessage(item)) this._emit(metadata, item, runId, true); - } - } - } - } - handleChainError(_err, runId) { - delete this.metadatas[runId]; - } -}; - -//#endregion - -//# sourceMappingURL=messages.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/retry.js - - - - - -//#region src/pregel/retry.ts -const DEFAULT_INITIAL_INTERVAL = 500; -const DEFAULT_BACKOFF_FACTOR = 2; -const DEFAULT_MAX_INTERVAL = 128e3; -const DEFAULT_MAX_RETRIES = 3; -const DEFAULT_STATUS_NO_RETRY = [ - 400, - 401, - 402, - 403, - 404, - 405, - 406, - 407, - 409 -]; -const DEFAULT_RETRY_ON_HANDLER = (error) => { - if (error.message.startsWith("Cancel") || error.message.startsWith("AbortError") || error.name === "AbortError") return false; - if (error.name === "GraphValueError") return false; - if (error?.code === "ECONNABORTED") return false; - const status = error?.response?.status ?? error?.status; - if (status && DEFAULT_STATUS_NO_RETRY.includes(+status)) return false; - if (error?.error?.code === "insufficient_quota") return false; - return true; -}; -async function _runWithRetry(pregelTask, retryPolicy, configurable, signal) { - const resolvedRetryPolicy = pregelTask.retry_policy ?? retryPolicy; - let interval = resolvedRetryPolicy !== void 0 ? resolvedRetryPolicy.initialInterval ?? DEFAULT_INITIAL_INTERVAL : 0; - let attempts = 0; - let error; - let result; - let { config } = pregelTask; - if (configurable) config = utils_patchConfigurable(config, configurable); - config = { - ...config, - signal - }; - while (true) { - if (signal?.aborted) break; - pregelTask.writes.splice(0, pregelTask.writes.length); - error = void 0; - try { - result = await pregelTask.proc.invoke(pregelTask.input, config); - break; - } catch (e) { - error = e; - error.pregelTaskId = pregelTask.id; - if (isParentCommand(error)) { - const ns = config?.configurable?.checkpoint_ns; - const cmd = error.command; - if (cmd.graph === ns) { - for (const writer of pregelTask.writers) await writer.invoke(cmd, config); - error = void 0; - break; - } else if (cmd.graph === Command.PARENT) { - const parentNs = getParentCheckpointNamespace(ns); - error.command = new Command({ - ...error.command, - graph: parentNs - }); - } - } - if (isGraphBubbleUp(error)) break; - if (resolvedRetryPolicy === void 0) break; - attempts += 1; - if (attempts >= (resolvedRetryPolicy.maxAttempts ?? DEFAULT_MAX_RETRIES)) break; - const retryOn = resolvedRetryPolicy.retryOn ?? DEFAULT_RETRY_ON_HANDLER; - if (!retryOn(error)) break; - interval = Math.min(resolvedRetryPolicy.maxInterval ?? DEFAULT_MAX_INTERVAL, interval * (resolvedRetryPolicy.backoffFactor ?? DEFAULT_BACKOFF_FACTOR)); - const intervalWithJitter = resolvedRetryPolicy.jitter ? Math.floor(interval + Math.random() * 1e3) : interval; - await new Promise((resolve) => setTimeout(resolve, intervalWithJitter)); - const errorName = error.name ?? error.constructor.unminifiable_name ?? error.constructor.name; - if (resolvedRetryPolicy?.logWarning ?? true) console.log(`Retrying task "${String(pregelTask.name)}" after ${interval.toFixed(2)}ms (attempt ${attempts}) after ${errorName}: ${error}`); - config = utils_patchConfigurable(config, { [CONFIG_KEY_RESUMING]: true }); - } - } - return { - task: pregelTask, - result, - error, - signalAborted: signal?.aborted - }; -} - -//#endregion - -//# sourceMappingURL=retry.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/runner.js - - - - - - -//#region src/pregel/runner.ts -const PROMISE_ADDED_SYMBOL = Symbol.for("promiseAdded"); -function createPromiseBarrier() { - const barrier = { - next: () => void 0, - wait: Promise.resolve(PROMISE_ADDED_SYMBOL) - }; - function waitHandler(resolve) { - barrier.next = () => { - barrier.wait = new Promise(waitHandler); - resolve(PROMISE_ADDED_SYMBOL); - }; - } - barrier.wait = new Promise(waitHandler); - return barrier; -} -/** -* Responsible for handling task execution on each tick of the {@link PregelLoop}. -*/ -var PregelRunner = class { - nodeFinished; - loop; - /** - * Construct a new PregelRunner, which executes tasks from the provided PregelLoop. - * @param loop - The PregelLoop that produces tasks for this runner to execute. - */ - constructor({ loop, nodeFinished }) { - this.loop = loop; - this.nodeFinished = nodeFinished; - } - /** - * Execute tasks from the current step of the PregelLoop. - * - * Note: this method does NOT call {@link PregelLoop}#tick. That must be handled externally. - * @param options - Options for the execution. - */ - async tick(options = {}) { - const { timeout, retryPolicy, onStepWrite, maxConcurrency } = options; - const nodeErrors = /* @__PURE__ */ new Set(); - let graphBubbleUp; - const exceptionSignalController = new AbortController(); - const exceptionSignal = exceptionSignalController.signal; - const stepTimeoutSignal = timeout ? AbortSignal.timeout(timeout) : void 0; - const pendingTasks = Object.values(this.loop.tasks).filter((t) => t.writes.length === 0); - const { signals, disposeCombinedSignal } = this._initializeAbortSignals({ - exceptionSignal, - stepTimeoutSignal, - signal: options.signal - }); - const taskStream = this._executeTasksWithRetry(pendingTasks, { - signals, - retryPolicy, - maxConcurrency - }); - for await (const { task, error, signalAborted } of taskStream) { - this._commit(task, error); - if (isGraphInterrupt(error)) graphBubbleUp = error; - else if (isGraphBubbleUp(error) && !isGraphInterrupt(graphBubbleUp)) graphBubbleUp = error; - else if (error && (nodeErrors.size === 0 || !signalAborted)) { - exceptionSignalController.abort(); - nodeErrors.add(error); - } - } - disposeCombinedSignal?.(); - onStepWrite?.(this.loop.step, Object.values(this.loop.tasks).map((task) => task.writes).flat()); - if (nodeErrors.size === 1) throw Array.from(nodeErrors)[0]; - else if (nodeErrors.size > 1) throw new AggregateError(Array.from(nodeErrors), `Multiple errors occurred during superstep ${this.loop.step}. See the "errors" field of this exception for more details.`); - if (isGraphInterrupt(graphBubbleUp)) throw graphBubbleUp; - if (isGraphBubbleUp(graphBubbleUp) && this.loop.isNested) throw graphBubbleUp; - } - /** - * Initializes the current AbortSignals for the PregelRunner, handling the various ways that - * AbortSignals must be chained together so that the PregelLoop can be interrupted if necessary - * while still allowing nodes to gracefully exit. - * - * This method must only be called once per PregelRunner#tick. It has the side effect of updating - * the PregelLoop#config with the new AbortSignals so they may be propagated correctly to future - * ticks and subgraph calls. - * - * @param options - Options for the initialization. - * @returns The current abort signals. - * @internal - */ - _initializeAbortSignals({ exceptionSignal, stepTimeoutSignal, signal }) { - const previousSignals = this.loop.config.configurable?.[CONFIG_KEY_ABORT_SIGNALS] ?? {}; - const externalAbortSignal = previousSignals.externalAbortSignal ?? signal; - const timeoutAbortSignal = stepTimeoutSignal ?? previousSignals.timeoutAbortSignal; - const { signal: composedAbortSignal, dispose: disposeCombinedSignal } = combineAbortSignals(externalAbortSignal, timeoutAbortSignal, exceptionSignal); - const signals = { - externalAbortSignal, - timeoutAbortSignal, - composedAbortSignal - }; - this.loop.config = utils_patchConfigurable(this.loop.config, { [CONFIG_KEY_ABORT_SIGNALS]: signals }); - return { - signals, - disposeCombinedSignal - }; - } - /** - * Concurrently executes tasks with the requested retry policy, yielding a {@link SettledPregelTask} for each task as it completes. - * @param tasks - The tasks to execute. - * @param options - Options for the execution. - */ - async *_executeTasksWithRetry(tasks, options) { - const { retryPolicy, maxConcurrency, signals } = options ?? {}; - const barrier = createPromiseBarrier(); - const executingTasksMap = {}; - const thisCall = { - executingTasksMap, - barrier, - retryPolicy, - scheduleTask: async (task, writeIdx, call$1) => this.loop.acceptPush(task, writeIdx, call$1) - }; - if (signals?.composedAbortSignal?.aborted) throw new Error("Abort"); - let startedTasksCount = 0; - let listener; - const timeoutOrCancelSignal = combineAbortSignals(signals?.externalAbortSignal, signals?.timeoutAbortSignal); - const abortPromise = timeoutOrCancelSignal.signal ? new Promise((_resolve, reject) => { - listener = () => reject(/* @__PURE__ */ new Error("Abort")); - timeoutOrCancelSignal.signal?.addEventListener("abort", listener, { once: true }); - }) : void 0; - while ((startedTasksCount === 0 || Object.keys(executingTasksMap).length > 0) && tasks.length) { - for (; Object.values(executingTasksMap).length < (maxConcurrency ?? tasks.length) && startedTasksCount < tasks.length; startedTasksCount += 1) { - const task = tasks[startedTasksCount]; - executingTasksMap[task.id] = _runWithRetry(task, retryPolicy, { [constants_CONFIG_KEY_CALL]: runner_call?.bind(thisCall, this, task) }, signals?.composedAbortSignal).catch((error) => { - return { - task, - error, - signalAborted: signals?.composedAbortSignal?.aborted - }; - }); - } - const settledTask = await Promise.race([ - ...Object.values(executingTasksMap), - ...abortPromise ? [abortPromise] : [], - barrier.wait - ]); - if (settledTask === PROMISE_ADDED_SYMBOL) continue; - yield settledTask; - if (listener != null) { - timeoutOrCancelSignal.signal?.removeEventListener("abort", listener); - timeoutOrCancelSignal.dispose?.(); - } - delete executingTasksMap[settledTask.task.id]; - } - } - /** - * Determines what writes to apply based on whether the task completed successfully, and what type of error occurred. - * - * Throws an error if the error is a {@link GraphBubbleUp} error and {@link PregelLoop}#isNested is true. - * - * @param task - The task to commit. - * @param error - The error that occurred, if any. - */ - _commit(task, error) { - if (error !== void 0) if (isGraphInterrupt(error)) { - if (error.interrupts.length) { - const interrupts = error.interrupts.map((interrupt) => [constants_INTERRUPT, interrupt]); - const resumes = task.writes.filter((w) => w[0] === constants_RESUME); - if (resumes.length) interrupts.push(...resumes); - this.loop.putWrites(task.id, interrupts); - } - } else if (isGraphBubbleUp(error) && task.writes.length) this.loop.putWrites(task.id, task.writes); - else this.loop.putWrites(task.id, [[constants_ERROR, { - message: error.message, - name: error.name - }]]); - else { - if (this.nodeFinished && (task.config?.tags == null || !task.config.tags.includes(TAG_HIDDEN))) this.nodeFinished(String(task.name)); - if (task.writes.length === 0) task.writes.push([NO_WRITES, null]); - this.loop.putWrites(task.id, task.writes); - } - } -}; -async function runner_call(runner, task, func, name, input, options = {}) { - const scratchpad = task.config?.configurable?.[constants_CONFIG_KEY_SCRATCHPAD]; - if (!scratchpad) throw new Error(`BUG: No scratchpad found on task ${task.name}__${task.id}`); - const cnt = scratchpad.callCounter; - scratchpad.callCounter += 1; - const wcall = new Call({ - func, - name, - input, - cache: options.cache, - retry: options.retry, - callbacks: options.callbacks - }); - const nextTask = await this.scheduleTask(task, cnt, wcall); - if (!nextTask) return void 0; - const existingPromise = this.executingTasksMap[nextTask.id]; - if (existingPromise !== void 0) return existingPromise; - if (nextTask.writes.length > 0) { - const returns = nextTask.writes.filter(([c]) => c === RETURN); - const errors = nextTask.writes.filter(([c]) => c === constants_ERROR); - if (returns.length > 0) { - if (returns.length === 1) return Promise.resolve(returns[0][1]); - throw new Error(`BUG: multiple returns found for task ${nextTask.name}__${nextTask.id}`); - } - if (errors.length > 0) { - if (errors.length === 1) { - const errorValue = errors[0][1]; - const error = errorValue instanceof Error ? errorValue : new Error(String(errorValue)); - return Promise.reject(error); - } - throw new Error(`BUG: multiple errors found for task ${nextTask.name}__${nextTask.id}`); - } - return void 0; - } else { - const prom = _runWithRetry(nextTask, options.retry, { [constants_CONFIG_KEY_CALL]: runner_call.bind(this, runner, nextTask) }); - this.executingTasksMap[nextTask.id] = prom; - this.barrier.next(); - return prom.then(({ result, error }) => { - if (error) return Promise.reject(error); - return result; - }); - } -} - -//#endregion - -//# sourceMappingURL=runner.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/validate.js - - - -//#region src/pregel/validate.ts -var GraphValidationError = class extends Error { - constructor(message) { - super(message); - this.name = "GraphValidationError"; - } -}; -function validateGraph({ nodes, channels, inputChannels, outputChannels, streamChannels, interruptAfterNodes, interruptBeforeNodes }) { - if (!channels) throw new GraphValidationError("Channels not provided"); - const subscribedChannels = /* @__PURE__ */ new Set(); - const allOutputChannels = /* @__PURE__ */ new Set(); - for (const [name, node] of Object.entries(nodes)) { - if (name === constants_INTERRUPT) throw new GraphValidationError(`"Node name ${constants_INTERRUPT} is reserved"`); - if (node.constructor === PregelNode) node.triggers.forEach((trigger) => subscribedChannels.add(trigger)); - else throw new GraphValidationError(`Invalid node type ${typeof node}, expected PregelNode`); - } - for (const chan of subscribedChannels) if (!(chan in channels)) throw new GraphValidationError(`Subscribed channel '${String(chan)}' not in channels`); - if (!Array.isArray(inputChannels)) { - if (!subscribedChannels.has(inputChannels)) throw new GraphValidationError(`Input channel ${String(inputChannels)} is not subscribed to by any node`); - } else if (inputChannels.every((channel) => !subscribedChannels.has(channel))) throw new GraphValidationError(`None of the input channels ${inputChannels} are subscribed to by any node`); - if (!Array.isArray(outputChannels)) allOutputChannels.add(outputChannels); - else outputChannels.forEach((chan) => allOutputChannels.add(chan)); - if (streamChannels && !Array.isArray(streamChannels)) allOutputChannels.add(streamChannels); - else if (Array.isArray(streamChannels)) streamChannels.forEach((chan) => allOutputChannels.add(chan)); - for (const chan of allOutputChannels) if (!(chan in channels)) throw new GraphValidationError(`Output channel '${String(chan)}' not in channels`); - if (interruptAfterNodes && interruptAfterNodes !== "*") { - for (const node of interruptAfterNodes) if (!(node in nodes)) throw new GraphValidationError(`Node ${String(node)} not in nodes`); - } - if (interruptBeforeNodes && interruptBeforeNodes !== "*") { - for (const node of interruptBeforeNodes) if (!(node in nodes)) throw new GraphValidationError(`Node ${String(node)} not in nodes`); - } -} -function validateKeys(keys, channels) { - if (Array.isArray(keys)) { - for (const key of keys) if (!(key in channels)) throw new Error(`Key ${String(key)} not found in channels`); - } else if (!(keys in channels)) throw new Error(`Key ${String(keys)} not found in channels`); -} - -//#endregion - -//# sourceMappingURL=validate.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/topic.js - - - -//#region src/channels/topic.ts -/** -* A configurable PubSub Topic. -*/ -var Topic = class Topic extends BaseChannel { - lc_graph_name = "Topic"; - unique = false; - accumulate = false; - seen; - values; - constructor(fields) { - super(); - this.unique = fields?.unique ?? this.unique; - this.accumulate = fields?.accumulate ?? this.accumulate; - this.seen = /* @__PURE__ */ new Set(); - this.values = []; - } - fromCheckpoint(checkpoint) { - const empty = new Topic({ - unique: this.unique, - accumulate: this.accumulate - }); - if (typeof checkpoint !== "undefined") { - empty.seen = new Set(checkpoint[0]); - empty.values = checkpoint[1]; - } - return empty; - } - update(values) { - let updated = false; - if (!this.accumulate) { - updated = this.values.length > 0; - this.values = []; - } - const flatValues = values.flat(); - if (flatValues.length > 0) if (this.unique) { - for (const value of flatValues) if (!this.seen.has(value)) { - updated = true; - this.seen.add(value); - this.values.push(value); - } - } else { - updated = true; - this.values.push(...flatValues); - } - return updated; - } - get() { - if (this.values.length === 0) throw new EmptyChannelError(); - return this.values; - } - checkpoint() { - return [[...this.seen], this.values]; - } - isAvailable() { - return this.values.length !== 0; - } -}; - -//#endregion - -//# sourceMappingURL=topic.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/pregel/index.js - - - - - - - - - - - - - - - - - - - - - - -//#region src/pregel/index.ts -/** -* Utility class for working with channels in the Pregel system. -* Provides static methods for subscribing to channels and writing to them. -* -* Channels are the communication pathways between nodes in a Pregel graph. -* They enable message passing and state updates between different parts of the graph. -*/ -var Channel = class { - static subscribeTo(channels, options) { - const { key, tags } = { - key: void 0, - tags: void 0, - ...options ?? {} - }; - if (Array.isArray(channels) && key !== void 0) throw new Error("Can't specify a key when subscribing to multiple channels"); - let channelMappingOrArray; - if (typeof channels === "string") if (key) channelMappingOrArray = { [key]: channels }; - else channelMappingOrArray = [channels]; - else channelMappingOrArray = Object.fromEntries(channels.map((chan) => [chan, chan])); - const triggers = Array.isArray(channels) ? channels : [channels]; - return new PregelNode({ - channels: channelMappingOrArray, - triggers, - tags - }); - } - /** - * Creates a ChannelWrite that specifies how to write values to channels. - * This is used to define how nodes send output to channels. - * - * @example - * ```typescript - * // Write to multiple channels - * const write = Channel.writeTo(["output", "state"]); - * - * // Write with specific values - * const write = Channel.writeTo(["output"], { - * state: "completed", - * result: calculateResult() - * }); - * - * // Write with a transformation function - * const write = Channel.writeTo(["output"], { - * result: (x) => processResult(x) - * }); - * ``` - * - * @param channels - Array of channel names to write to - * @param writes - Optional map of channel names to values or transformations - * @returns A ChannelWrite object that can be used to write to the specified channels - */ - static writeTo(channels, writes) { - const channelWriteEntries = []; - for (const channel of channels) channelWriteEntries.push({ - channel, - value: PASSTHROUGH, - skipNone: false - }); - for (const [key, value] of Object.entries(writes ?? {})) if (Runnable.isRunnable(value) || typeof value === "function") channelWriteEntries.push({ - channel: key, - value: PASSTHROUGH, - skipNone: true, - mapper: _coerceToRunnable(value) - }); - else channelWriteEntries.push({ - channel: key, - value, - skipNone: false - }); - return new ChannelWrite(channelWriteEntries); - } -}; -var PartialRunnable = class extends Runnable { - lc_namespace = ["langgraph", "pregel"]; - invoke(_input, _options) { - throw new Error("Not implemented"); - } - withConfig(_config) { - return super.withConfig(_config); - } - stream(input, options) { - return super.stream(input, options); - } -}; -/** -* The Pregel class is the core runtime engine of LangGraph, implementing a message-passing graph computation model -* inspired by [Google's Pregel system](https://research.google/pubs/pregel-a-system-for-large-scale-graph-processing/). -* It provides the foundation for building reliable, controllable agent workflows that can evolve state over time. -* -* Key features: -* - Message passing between nodes in discrete "supersteps" -* - Built-in persistence layer through checkpointers -* - First-class streaming support for values, updates, and events -* - Human-in-the-loop capabilities via interrupts -* - Support for parallel node execution within supersteps -* -* The Pregel class is not intended to be instantiated directly by consumers. Instead, use the following higher-level APIs: -* - {@link StateGraph}: The main graph class for building agent workflows -* - Compiling a {@link StateGraph} will return a {@link CompiledGraph} instance, which extends `Pregel` -* - Functional API: A declarative approach using tasks and entrypoints -* - A `Pregel` instance is returned by the {@link entrypoint} function -* -* @example -* ```typescript -* // Using StateGraph API -* const graph = new StateGraph(annotation) -* .addNode("nodeA", myNodeFunction) -* .addEdge("nodeA", "nodeB") -* .compile(); -* -* // The compiled graph is a Pregel instance -* const result = await graph.invoke(input); -* ``` -* -* @example -* ```typescript -* // Using Functional API -* import { task, entrypoint } from "@langchain/langgraph"; -* import { MemorySaver } from "@langchain/langgraph-checkpoint"; -* -* // Define tasks that can be composed -* const addOne = task("add", async (x: number) => x + 1); -* -* // Create a workflow using the entrypoint function -* const workflow = entrypoint({ -* name: "workflow", -* checkpointer: new MemorySaver() -* }, async (numbers: number[]) => { -* // Tasks can be run in parallel -* const results = await Promise.all(numbers.map(n => addOne(n))); -* return results; -* }); -* -* // The workflow is a Pregel instance -* const result = await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4] -* ``` -* -* @typeParam Nodes - Mapping of node names to their {@link PregelNode} implementations -* @typeParam Channels - Mapping of channel names to their {@link BaseChannel} or {@link ManagedValueSpec} implementations -* @typeParam ContextType - Type of context that can be passed to the graph -* @typeParam InputType - Type of input values accepted by the graph -* @typeParam OutputType - Type of output values produced by the graph -*/ -var Pregel = class extends PartialRunnable { - /** - * Name of the class when serialized - * @internal - */ - static lc_name() { - return "LangGraph"; - } - /** @internal LangChain namespace for serialization necessary because Pregel extends Runnable */ - lc_namespace = ["langgraph", "pregel"]; - /** @internal Flag indicating this is a Pregel instance - necessary for serialization */ - lg_is_pregel = true; - /** The nodes in the graph, mapping node names to their PregelNode instances */ - nodes; - /** The channels in the graph, mapping channel names to their BaseChannel or ManagedValueSpec instances */ - channels; - /** - * The input channels for the graph. These channels receive the initial input when the graph is invoked. - * Can be a single channel key or an array of channel keys. - */ - inputChannels; - /** - * The output channels for the graph. These channels contain the final output when the graph completes. - * Can be a single channel key or an array of channel keys. - */ - outputChannels; - /** Whether to automatically validate the graph structure when it is compiled. Defaults to true. */ - autoValidate = true; - /** - * The streaming modes enabled for this graph. Defaults to ["values"]. - * Supported modes: - * - "values": Streams the full state after each step - * - "updates": Streams state updates after each step - * - "messages": Streams messages from within nodes - * - "custom": Streams custom events from within nodes - * - "debug": Streams events related to the execution of the graph - useful for tracing & debugging graph execution - */ - streamMode = ["values"]; - /** - * Optional channels to stream. If not specified, all channels will be streamed. - * Can be a single channel key or an array of channel keys. - */ - streamChannels; - /** - * Optional array of node names or "all" to interrupt after executing these nodes. - * Used for implementing human-in-the-loop workflows. - */ - interruptAfter; - /** - * Optional array of node names or "all" to interrupt before executing these nodes. - * Used for implementing human-in-the-loop workflows. - */ - interruptBefore; - /** Optional timeout in milliseconds for the execution of each superstep */ - stepTimeout; - /** Whether to enable debug logging. Defaults to false. */ - debug = false; - /** - * Optional checkpointer for persisting graph state. - * When provided, saves a checkpoint of the graph state at every superstep. - * When false or undefined, checkpointing is disabled, and the graph will not be able to save or restore state. - */ - checkpointer; - /** Optional retry policy for handling failures in node execution */ - retryPolicy; - /** The default configuration for graph execution, can be overridden on a per-invocation basis */ - config; - /** - * Optional long-term memory store for the graph, allows for persistence & retrieval of data across threads - */ - store; - /** - * Optional cache for the graph, useful for caching tasks. - */ - cache; - /** - * Optional interrupt helper function. - * @internal - */ - userInterrupt; - /** - * The trigger to node mapping for the graph run. - * @internal - */ - triggerToNodes = {}; - /** - * Constructor for Pregel - meant for internal use only. - * - * @internal - */ - constructor(fields) { - super(fields); - let { streamMode } = fields; - if (streamMode != null && !Array.isArray(streamMode)) streamMode = [streamMode]; - this.nodes = fields.nodes; - this.channels = fields.channels; - if (constants_TASKS in this.channels && "lc_graph_name" in this.channels[constants_TASKS] && this.channels[constants_TASKS].lc_graph_name !== "Topic") throw new Error(`Channel '${constants_TASKS}' is reserved and cannot be used in the graph.`); - else this.channels[constants_TASKS] = new Topic({ accumulate: false }); - this.autoValidate = fields.autoValidate ?? this.autoValidate; - this.streamMode = streamMode ?? this.streamMode; - this.inputChannels = fields.inputChannels; - this.outputChannels = fields.outputChannels; - this.streamChannels = fields.streamChannels ?? this.streamChannels; - this.interruptAfter = fields.interruptAfter; - this.interruptBefore = fields.interruptBefore; - this.stepTimeout = fields.stepTimeout ?? this.stepTimeout; - this.debug = fields.debug ?? this.debug; - this.checkpointer = fields.checkpointer; - this.retryPolicy = fields.retryPolicy; - this.config = fields.config; - this.store = fields.store; - this.cache = fields.cache; - this.name = fields.name; - this.triggerToNodes = fields.triggerToNodes ?? this.triggerToNodes; - this.userInterrupt = fields.userInterrupt; - if (this.autoValidate) this.validate(); - } - /** - * Creates a new instance of the Pregel graph with updated configuration. - * This method follows the immutable pattern - instead of modifying the current instance, - * it returns a new instance with the merged configuration. - * - * @example - * ```typescript - * // Create a new instance with debug enabled - * const debugGraph = graph.withConfig({ debug: true }); - * - * // Create a new instance with a specific thread ID - * const threadGraph = graph.withConfig({ - * configurable: { thread_id: "123" } - * }); - * ``` - * - * @param config - The configuration to merge with the current configuration - * @returns A new Pregel instance with the merged configuration - */ - withConfig(config) { - const mergedConfig = mergeConfigs(this.config, config); - return new this.constructor({ - ...this, - config: mergedConfig - }); - } - /** - * Validates the graph structure to ensure it is well-formed. - * Checks for: - * - No orphaned nodes - * - Valid input/output channel configurations - * - Valid interrupt configurations - * - * @returns this - The Pregel instance for method chaining - * @throws {GraphValidationError} If the graph structure is invalid - */ - validate() { - validateGraph({ - nodes: this.nodes, - channels: this.channels, - outputChannels: this.outputChannels, - inputChannels: this.inputChannels, - streamChannels: this.streamChannels, - interruptAfterNodes: this.interruptAfter, - interruptBeforeNodes: this.interruptBefore - }); - for (const [name, node] of Object.entries(this.nodes)) for (const trigger of node.triggers) { - this.triggerToNodes[trigger] ??= []; - this.triggerToNodes[trigger].push(name); - } - return this; - } - /** - * Gets a list of all channels that should be streamed. - * If streamChannels is specified, returns those channels. - * Otherwise, returns all channels in the graph. - * - * @returns Array of channel keys to stream - */ - get streamChannelsList() { - if (Array.isArray(this.streamChannels)) return this.streamChannels; - else if (this.streamChannels) return [this.streamChannels]; - else return Object.keys(this.channels); - } - /** - * Gets the channels to stream in their original format. - * If streamChannels is specified, returns it as-is (either single key or array). - * Otherwise, returns all channels in the graph as an array. - * - * @returns Channel keys to stream, either as a single key or array - */ - get streamChannelsAsIs() { - if (this.streamChannels) return this.streamChannels; - else return Object.keys(this.channels); - } - /** - * Gets a drawable representation of the graph structure. - * This is an async version of getGraph() and is the preferred method to use. - * - * @param config - Configuration for generating the graph visualization - * @returns A representation of the graph that can be visualized - */ - async getGraphAsync(config) { - return this.getGraph(config); - } - /** - * Gets all subgraphs within this graph. - * A subgraph is a Pregel instance that is nested within a node of this graph. - * - * @deprecated Use getSubgraphsAsync instead. The async method will become the default in the next minor release. - * @param namespace - Optional namespace to filter subgraphs - * @param recurse - Whether to recursively get subgraphs of subgraphs - * @returns Generator yielding tuples of [name, subgraph] - */ - *getSubgraphs(namespace, recurse) { - for (const [name, node] of Object.entries(this.nodes)) { - if (namespace !== void 0) { - if (!namespace.startsWith(name)) continue; - } - const candidates = node.subgraphs?.length ? node.subgraphs : [node.bound]; - for (const candidate of candidates) { - const graph = findSubgraphPregel(candidate); - if (graph !== void 0) { - if (name === namespace) { - yield [name, graph]; - return; - } - if (namespace === void 0) yield [name, graph]; - if (recurse) { - let newNamespace = namespace; - if (namespace !== void 0) newNamespace = namespace.slice(name.length + 1); - for (const [subgraphName, subgraph] of graph.getSubgraphs(newNamespace, recurse)) yield [`${name}${CHECKPOINT_NAMESPACE_SEPARATOR}${subgraphName}`, subgraph]; - } - } - } - } - } - /** - * Gets all subgraphs within this graph asynchronously. - * A subgraph is a Pregel instance that is nested within a node of this graph. - * - * @param namespace - Optional namespace to filter subgraphs - * @param recurse - Whether to recursively get subgraphs of subgraphs - * @returns AsyncGenerator yielding tuples of [name, subgraph] - */ - async *getSubgraphsAsync(namespace, recurse) { - yield* this.getSubgraphs(namespace, recurse); - } - /** - * Prepares a state snapshot from saved checkpoint data. - * This is an internal method used by getState and getStateHistory. - * - * @param config - Configuration for preparing the snapshot - * @param saved - Optional saved checkpoint data - * @param subgraphCheckpointer - Optional checkpointer for subgraphs - * @param applyPendingWrites - Whether to apply pending writes to tasks and then to channels - * @returns A snapshot of the graph state - * @internal - */ - async _prepareStateSnapshot({ config, saved, subgraphCheckpointer, applyPendingWrites = false }) { - if (saved === void 0) return { - values: {}, - next: [], - config, - tasks: [] - }; - const channels = emptyChannels(this.channels, saved.checkpoint); - if (saved.pendingWrites?.length) { - const nullWrites = saved.pendingWrites.filter(([taskId, _]) => taskId === NULL_TASK_ID).map(([_, channel, value]) => [String(channel), value]); - if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], void 0, this.triggerToNodes); - } - const nextTasks = Object.values(_prepareNextTasks(saved.checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { - step: (saved.metadata?.step ?? -1) + 1, - store: this.store - })); - const subgraphs = await gatherIterator(this.getSubgraphsAsync()); - const parentNamespace = saved.config.configurable?.checkpoint_ns ?? ""; - const taskStates = {}; - for (const task of nextTasks) { - const matchingSubgraph = subgraphs.find(([name]) => name === task.name); - if (!matchingSubgraph) continue; - let taskNs = `${String(task.name)}${CHECKPOINT_NAMESPACE_END}${task.id}`; - if (parentNamespace) taskNs = `${parentNamespace}${CHECKPOINT_NAMESPACE_SEPARATOR}${taskNs}`; - if (subgraphCheckpointer === void 0) { - const config$1 = { configurable: { - thread_id: saved.config.configurable?.thread_id, - checkpoint_ns: taskNs - } }; - taskStates[task.id] = config$1; - } else { - const subgraphConfig = { configurable: { - [CONFIG_KEY_CHECKPOINTER]: subgraphCheckpointer, - thread_id: saved.config.configurable?.thread_id, - checkpoint_ns: taskNs - } }; - const pregel = matchingSubgraph[1]; - taskStates[task.id] = await pregel.getState(subgraphConfig, { subgraphs: true }); - } - } - if (applyPendingWrites && saved.pendingWrites?.length) { - const nextTaskById = Object.fromEntries(nextTasks.map((task) => [task.id, task])); - for (const [taskId, channel, value] of saved.pendingWrites) { - if ([ - constants_ERROR, - constants_INTERRUPT, - SCHEDULED - ].includes(channel)) continue; - if (!(taskId in nextTaskById)) continue; - nextTaskById[taskId].writes.push([String(channel), value]); - } - const tasksWithWrites$1 = nextTasks.filter((task) => task.writes.length > 0); - if (tasksWithWrites$1.length > 0) _applyWrites(saved.checkpoint, channels, tasksWithWrites$1, void 0, this.triggerToNodes); - } - let metadata = saved?.metadata; - if (metadata && saved?.config?.configurable?.thread_id) metadata = { - ...metadata, - thread_id: saved.config.configurable.thread_id - }; - const nextList = nextTasks.filter((task) => task.writes.length === 0).map((task) => task.name); - return { - values: readChannels(channels, this.streamChannelsAsIs), - next: nextList, - tasks: tasksWithWrites(nextTasks, saved?.pendingWrites ?? [], taskStates, this.streamChannelsAsIs), - metadata, - config: patchCheckpointMap(saved.config, saved.metadata), - createdAt: saved.checkpoint.ts, - parentConfig: saved.parentConfig - }; - } - /** - * Gets the current state of the graph. - * Requires a checkpointer to be configured. - * - * @param config - Configuration for retrieving the state - * @param options - Additional options - * @returns A snapshot of the current graph state - * @throws {GraphValueError} If no checkpointer is configured - */ - async getState(config, options) { - const checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer; - if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const checkpointNamespace = config.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) { - const recastNamespace = recastCheckpointNamespace(checkpointNamespace); - for await (const [name, subgraph] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) return await subgraph.getState(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), { subgraphs: options?.subgraphs }); - throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`); - } - const mergedConfig = mergeConfigs(this.config, config); - const saved = await checkpointer.getTuple(config); - const snapshot = await this._prepareStateSnapshot({ - config: mergedConfig, - saved, - subgraphCheckpointer: options?.subgraphs ? checkpointer : void 0, - applyPendingWrites: !config.configurable?.checkpoint_id - }); - return snapshot; - } - /** - * Gets the history of graph states. - * Requires a checkpointer to be configured. - * Useful for: - * - Debugging execution history - * - Implementing time travel - * - Analyzing graph behavior - * - * @param config - Configuration for retrieving the history - * @param options - Options for filtering the history - * @returns An async iterator of state snapshots - * @throws {Error} If no checkpointer is configured - */ - async *getStateHistory(config, options) { - const checkpointer = config.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer; - if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - const checkpointNamespace = config.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && config.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) { - const recastNamespace = recastCheckpointNamespace(checkpointNamespace); - for await (const [name, pregel] of this.getSubgraphsAsync(recastNamespace, true)) if (name === recastNamespace) { - yield* pregel.getStateHistory(patchConfigurable(config, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), options); - return; - } - throw new Error(`Subgraph with namespace "${recastNamespace}" not found.`); - } - const mergedConfig = mergeConfigs(this.config, config, { configurable: { checkpoint_ns: checkpointNamespace } }); - for await (const checkpointTuple of checkpointer.list(mergedConfig, options)) yield this._prepareStateSnapshot({ - config: checkpointTuple.config, - saved: checkpointTuple - }); - } - /** - * Apply updates to the graph state in bulk. - * Requires a checkpointer to be configured. - * - * This method is useful for recreating a thread - * from a list of updates, especially if a checkpoint - * is created as a result of multiple tasks. - * - * @internal The API might change in the future. - * - * @param startConfig - Configuration for the update - * @param updates - The list of updates to apply to graph state - * @returns Updated configuration - * @throws {GraphValueError} If no checkpointer is configured - * @throws {InvalidUpdateError} If the update cannot be attributed to a node or an update can be only applied in sequence. - */ - async bulkUpdateState(startConfig, supersteps) { - const checkpointer = startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] ?? this.checkpointer; - if (!checkpointer) throw new GraphValueError("No checkpointer set", { lc_error_code: "MISSING_CHECKPOINTER" }); - if (supersteps.length === 0) throw new Error("No supersteps provided"); - if (supersteps.some((s) => s.updates.length === 0)) throw new Error("No updates provided"); - const checkpointNamespace = startConfig.configurable?.checkpoint_ns ?? ""; - if (checkpointNamespace !== "" && startConfig.configurable?.[CONFIG_KEY_CHECKPOINTER] === void 0) { - const recastNamespace = recastCheckpointNamespace(checkpointNamespace); - for await (const [, pregel] of this.getSubgraphsAsync(recastNamespace, true)) return await pregel.bulkUpdateState(patchConfigurable(startConfig, { [CONFIG_KEY_CHECKPOINTER]: checkpointer }), supersteps); - throw new Error(`Subgraph "${recastNamespace}" not found`); - } - const updateSuperStep = async (inputConfig, updates) => { - const config = this.config ? mergeConfigs(this.config, inputConfig) : inputConfig; - const saved = await checkpointer.getTuple(config); - const checkpoint = saved !== void 0 ? copyCheckpoint(saved.checkpoint) : emptyCheckpoint(); - const checkpointPreviousVersions = { ...saved?.checkpoint.channel_versions }; - const step = saved?.metadata?.step ?? -1; - let checkpointConfig = patchConfigurable(config, { checkpoint_ns: config.configurable?.checkpoint_ns ?? "" }); - let checkpointMetadata = config.metadata ?? {}; - if (saved?.config.configurable) { - checkpointConfig = patchConfigurable(config, saved.config.configurable); - checkpointMetadata = { - ...saved.metadata, - ...checkpointMetadata - }; - } - const { values, asNode } = updates[0]; - if (values == null && asNode === void 0) { - if (updates.length > 1) throw new InvalidUpdateError(`Cannot create empty checkpoint with multiple updates`); - const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, void 0, step), { - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, {}); - return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0); - } - const channels = emptyChannels(this.channels, checkpoint); - if (values === null && asNode === END) { - if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when clearing state`); - if (saved) { - const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites || [], this.nodes, channels, saved.config, true, { - step: (saved.metadata?.step ?? -1) + 1, - checkpointer, - store: this.store - }); - const nullWrites = (saved.pendingWrites || []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); - if (nullWrites.length > 0) _applyWrites(checkpoint, channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); - for (const [taskId, k, v] of saved.pendingWrites || []) { - if ([ - constants_ERROR, - constants_INTERRUPT, - SCHEDULED - ].includes(k)) continue; - if (!(taskId in nextTasks)) continue; - nextTasks[taskId].writes.push([k, v]); - } - _applyWrites(checkpoint, channels, Object.values(nextTasks), checkpointer.getNextVersion.bind(checkpointer), this.triggerToNodes); - } - const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step), { - ...checkpointMetadata, - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)); - return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0); - } - if (asNode === COPY) { - if (updates.length > 1) throw new InvalidUpdateError(`Cannot copy checkpoint with multiple updates`); - if (saved == null) throw new InvalidUpdateError(`Cannot copy a non-existent checkpoint`); - const isCopyWithUpdates = (values$1) => { - if (!Array.isArray(values$1)) return false; - if (values$1.length === 0) return false; - return values$1.every((v) => Array.isArray(v) && v.length === 2); - }; - const nextCheckpoint = createCheckpoint(checkpoint, void 0, step); - const nextConfig$1 = await checkpointer.put(saved.parentConfig ?? patchConfigurable(saved.config, { checkpoint_id: void 0 }), nextCheckpoint, { - source: "fork", - step: step + 1, - parents: saved.metadata?.parents ?? {} - }, {}); - if (isCopyWithUpdates(values)) { - const nextTasks = _prepareNextTasks(nextCheckpoint, saved.pendingWrites, this.nodes, channels, nextConfig$1, false, { step: step + 2 }); - const tasksGroupBy = Object.values(nextTasks).reduce((acc, { name, id }) => { - acc[name] ??= []; - acc[name].push({ id }); - return acc; - }, {}); - const userGroupBy = values.reduce((acc, item) => { - const [values$1, asNode$1] = item; - acc[asNode$1] ??= []; - const targetIdx = acc[asNode$1].length; - const taskId = tasksGroupBy[asNode$1]?.[targetIdx]?.id; - acc[asNode$1].push({ - values: values$1, - asNode: asNode$1, - taskId - }); - return acc; - }, {}); - return updateSuperStep(patchCheckpointMap(nextConfig$1, saved.metadata), Object.values(userGroupBy).flat()); - } - return patchCheckpointMap(nextConfig$1, saved.metadata); - } - if (asNode === INPUT) { - if (updates.length > 1) throw new InvalidUpdateError(`Cannot apply multiple updates when updating as input`); - const inputWrites = await gatherIterator(mapInput(this.inputChannels, values)); - if (inputWrites.length === 0) throw new InvalidUpdateError(`Received no input writes for ${JSON.stringify(this.inputChannels, null, 2)}`); - _applyWrites(checkpoint, channels, [{ - name: INPUT, - writes: inputWrites, - triggers: [] - }], checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); - const nextStep = saved?.metadata?.step != null ? saved.metadata.step + 1 : -1; - const nextConfig$1 = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, nextStep), { - source: "input", - step: nextStep, - parents: saved?.metadata?.parents ?? {} - }, getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions)); - await checkpointer.putWrites(nextConfig$1, inputWrites, uuid5(INPUT, checkpoint.id)); - return patchCheckpointMap(nextConfig$1, saved ? saved.metadata : void 0); - } - if (config.configurable?.checkpoint_id === void 0 && saved?.pendingWrites !== void 0 && saved.pendingWrites.length > 0) { - const nextTasks = _prepareNextTasks(checkpoint, saved.pendingWrites, this.nodes, channels, saved.config, true, { - store: this.store, - checkpointer: this.checkpointer, - step: (saved.metadata?.step ?? -1) + 1 - }); - const nullWrites = (saved.pendingWrites ?? []).filter((w) => w[0] === NULL_TASK_ID).map((w) => w.slice(1)); - if (nullWrites.length > 0) _applyWrites(saved.checkpoint, channels, [{ - name: INPUT, - writes: nullWrites, - triggers: [] - }], void 0, this.triggerToNodes); - for (const [tid, k, v] of saved.pendingWrites) { - if ([ - constants_ERROR, - constants_INTERRUPT, - SCHEDULED - ].includes(k) || nextTasks[tid] === void 0) continue; - nextTasks[tid].writes.push([k, v]); - } - const tasks$1 = Object.values(nextTasks).filter((task) => { - return task.writes.length > 0; - }); - if (tasks$1.length > 0) _applyWrites(checkpoint, channels, tasks$1, void 0, this.triggerToNodes); - } - const nonNullVersion = Object.values(checkpoint.versions_seen).map((seenVersions) => { - return Object.values(seenVersions); - }).flat().find((v) => !!v); - const validUpdates = []; - if (updates.length === 1) { - let { values: values$1, asNode: asNode$1, taskId } = updates[0]; - if (asNode$1 === void 0 && Object.keys(this.nodes).length === 1) [asNode$1] = Object.keys(this.nodes); - else if (asNode$1 === void 0 && nonNullVersion === void 0) { - if (typeof this.inputChannels === "string" && this.nodes[this.inputChannels] !== void 0) asNode$1 = this.inputChannels; - } else if (asNode$1 === void 0) { - const lastSeenByNode = Object.entries(checkpoint.versions_seen).map(([n, seen]) => { - return Object.values(seen).map((v) => { - return [v, n]; - }); - }).flat().filter(([_, v]) => v !== constants_INTERRUPT).sort(([aNumber], [bNumber]) => compareChannelVersions(aNumber, bNumber)); - if (lastSeenByNode) { - if (lastSeenByNode.length === 1) asNode$1 = lastSeenByNode[0][1]; - else if (lastSeenByNode[lastSeenByNode.length - 1][0] !== lastSeenByNode[lastSeenByNode.length - 2][0]) asNode$1 = lastSeenByNode[lastSeenByNode.length - 1][1]; - } - } - if (asNode$1 === void 0) throw new InvalidUpdateError(`Ambiguous update, specify "asNode"`); - validUpdates.push({ - values: values$1, - asNode: asNode$1, - taskId - }); - } else for (const { asNode: asNode$1, values: values$1, taskId } of updates) { - if (asNode$1 == null) throw new InvalidUpdateError(`"asNode" is required when applying multiple updates`); - validUpdates.push({ - values: values$1, - asNode: asNode$1, - taskId - }); - } - const tasks = []; - for (const { asNode: asNode$1, values: values$1, taskId } of validUpdates) { - if (this.nodes[asNode$1] === void 0) throw new InvalidUpdateError(`Node "${asNode$1.toString()}" does not exist`); - const writers = this.nodes[asNode$1].getWriters(); - if (!writers.length) throw new InvalidUpdateError(`No writers found for node "${asNode$1.toString()}"`); - tasks.push({ - name: asNode$1, - input: values$1, - proc: writers.length > 1 ? RunnableSequence.from(writers, { omitSequenceTags: true }) : writers[0], - writes: [], - triggers: [constants_INTERRUPT], - id: taskId ?? uuid5(constants_INTERRUPT, checkpoint.id), - writers: [] - }); - } - for (const task of tasks) await task.proc.invoke(task.input, config_patchConfig({ - ...config, - store: config?.store ?? this.store - }, { - runName: config.runName ?? `${this.getName()}UpdateState`, - configurable: { - [CONFIG_KEY_SEND]: (items) => task.writes.push(...items), - [CONFIG_KEY_READ]: (select_, fresh_ = false) => _localRead(checkpoint, channels, task, select_, fresh_) - } - })); - for (const task of tasks) { - const channelWrites = task.writes.filter((w) => w[0] !== PUSH); - if (saved !== void 0 && channelWrites.length > 0) await checkpointer.putWrites(checkpointConfig, channelWrites, task.id); - } - _applyWrites(checkpoint, channels, tasks, checkpointer.getNextVersion.bind(this.checkpointer), this.triggerToNodes); - const newVersions = getNewChannelVersions(checkpointPreviousVersions, checkpoint.channel_versions); - const nextConfig = await checkpointer.put(checkpointConfig, createCheckpoint(checkpoint, channels, step + 1), { - source: "update", - step: step + 1, - parents: saved?.metadata?.parents ?? {} - }, newVersions); - for (const task of tasks) { - const pushWrites = task.writes.filter((w) => w[0] === PUSH); - if (pushWrites.length > 0) await checkpointer.putWrites(nextConfig, pushWrites, task.id); - } - return patchCheckpointMap(nextConfig, saved ? saved.metadata : void 0); - }; - let currentConfig = startConfig; - for (const { updates } of supersteps) currentConfig = await updateSuperStep(currentConfig, updates); - return currentConfig; - } - /** - * Updates the state of the graph with new values. - * Requires a checkpointer to be configured. - * - * This method can be used for: - * - Implementing human-in-the-loop workflows - * - Modifying graph state during breakpoints - * - Integrating external inputs into the graph - * - * @param inputConfig - Configuration for the update - * @param values - The values to update the state with - * @param asNode - Optional node name to attribute the update to - * @returns Updated configuration - * @throws {GraphValueError} If no checkpointer is configured - * @throws {InvalidUpdateError} If the update cannot be attributed to a node - */ - async updateState(inputConfig, values, asNode) { - return this.bulkUpdateState(inputConfig, [{ updates: [{ - values, - asNode - }] }]); - } - /** - * Gets the default values for various graph configuration options. - * This is an internal method used to process and normalize configuration options. - * - * @param config - The input configuration options - * @returns A tuple containing normalized values for: - * - debug mode - * - stream modes - * - input keys - * - output keys - * - remaining config - * - interrupt before nodes - * - interrupt after nodes - * - checkpointer - * - store - * - whether stream mode is single - * - node cache - * - whether checkpoint during is enabled - * @internal - */ - _defaults(config) { - const { debug, streamMode, inputKeys, outputKeys, interruptAfter, interruptBefore,...rest } = config; - let streamModeSingle = true; - const defaultDebug = debug !== void 0 ? debug : this.debug; - let defaultOutputKeys = outputKeys; - if (defaultOutputKeys === void 0) defaultOutputKeys = this.streamChannelsAsIs; - else validateKeys(defaultOutputKeys, this.channels); - let defaultInputKeys = inputKeys; - if (defaultInputKeys === void 0) defaultInputKeys = this.inputChannels; - else validateKeys(defaultInputKeys, this.channels); - const defaultInterruptBefore = interruptBefore ?? this.interruptBefore ?? []; - const defaultInterruptAfter = interruptAfter ?? this.interruptAfter ?? []; - let defaultStreamMode; - if (streamMode !== void 0) { - defaultStreamMode = Array.isArray(streamMode) ? streamMode : [streamMode]; - streamModeSingle = typeof streamMode === "string"; - } else { - if (config.configurable?.[CONFIG_KEY_TASK_ID] !== void 0) defaultStreamMode = ["values"]; - else defaultStreamMode = this.streamMode; - streamModeSingle = true; - } - let defaultCheckpointer; - if (this.checkpointer === false) defaultCheckpointer = void 0; - else if (config !== void 0 && config.configurable?.[CONFIG_KEY_CHECKPOINTER] !== void 0) defaultCheckpointer = config.configurable[CONFIG_KEY_CHECKPOINTER]; - else if (this.checkpointer === true) throw new Error("checkpointer: true cannot be used for root graphs."); - else defaultCheckpointer = this.checkpointer; - const defaultStore = config.store ?? this.store; - const defaultCache = config.cache ?? this.cache; - if (config.durability != null && config.checkpointDuring != null) throw new Error("Cannot use both `durability` and `checkpointDuring` at the same time."); - const checkpointDuringDurability = (() => { - if (config.checkpointDuring == null) return void 0; - if (config.checkpointDuring === false) return "exit"; - return "async"; - })(); - const defaultDurability = config.durability ?? checkpointDuringDurability ?? config?.configurable?.[CONFIG_KEY_DURABILITY] ?? "async"; - return [ - defaultDebug, - defaultStreamMode, - defaultInputKeys, - defaultOutputKeys, - rest, - defaultInterruptBefore, - defaultInterruptAfter, - defaultCheckpointer, - defaultStore, - streamModeSingle, - defaultCache, - defaultDurability - ]; - } - /** - * Streams the execution of the graph, emitting state updates as they occur. - * This is the primary method for observing graph execution in real-time. - * - * Stream modes: - * - "values": Emits complete state after each step - * - "updates": Emits only state changes after each step - * - "debug": Emits detailed debug information - * - "messages": Emits messages from within nodes - * - "custom": Emits custom events from within nodes - * - "checkpoints": Emits checkpoints from within nodes - * - "tasks": Emits tasks from within nodes - * - * @param input - The input to start graph execution with - * @param options - Configuration options for streaming - * @returns An async iterable stream of graph state updates - */ - async stream(input, options) { - const abortController = new AbortController(); - const config = { - recursionLimit: this.config?.recursionLimit, - ...options, - signal: combineAbortSignals(options?.signal, abortController.signal).signal - }; - const stream = await super.stream(input, config); - return new IterableReadableStreamWithAbortSignal(options?.encoding === "text/event-stream" ? toEventStream(stream) : stream, abortController); - } - streamEvents(input, options, streamOptions) { - const abortController = new AbortController(); - const config = { - recursionLimit: this.config?.recursionLimit, - ...options, - callbacks: combineCallbacks(this.config?.callbacks, options?.callbacks), - signal: combineAbortSignals(options?.signal, abortController.signal).signal - }; - return new IterableReadableStreamWithAbortSignal(super.streamEvents(input, config, streamOptions), abortController); - } - /** - * Validates the input for the graph. - * @param input - The input to validate - * @returns The validated input - * @internal - */ - async _validateInput(input) { - return input; - } - /** - * Validates the context options for the graph. - * @param context - The context options to validate - * @returns The validated context options - * @internal - */ - async _validateContext(context) { - return context; - } - /** - * Internal iterator used by stream() to generate state updates. - * This method handles the core logic of graph execution and streaming. - * - * @param input - The input to start graph execution with - * @param options - Configuration options for streaming - * @returns AsyncGenerator yielding state updates - * @internal - */ - async *_streamIterator(input, options) { - const streamEncoding = "version" in (options ?? {}) ? void 0 : options?.encoding ?? void 0; - const streamSubgraphs = options?.subgraphs; - const inputConfig = config_ensureLangGraphConfig(this.config, options); - if (inputConfig.recursionLimit === void 0 || inputConfig.recursionLimit < 1) throw new Error(`Passed "recursionLimit" must be at least 1.`); - if (this.checkpointer !== void 0 && this.checkpointer !== false && inputConfig.configurable === void 0) throw new Error(`Checkpointer requires one or more of the following "configurable" keys: "thread_id", "checkpoint_ns", "checkpoint_id"`); - const validInput = await this._validateInput(input); - const { runId,...restConfig } = inputConfig; - const [debug, streamMode, , outputKeys, config, interruptBefore, interruptAfter, checkpointer, store, streamModeSingle, cache, durability] = this._defaults(restConfig); - if (typeof config.context !== "undefined") config.context = await this._validateContext(config.context); - else config.configurable = await this._validateContext(config.configurable); - const stream = new IterableReadableWritableStream({ modes: new Set(streamMode) }); - if (this.checkpointer === true) { - config.configurable ??= {}; - const ns = config.configurable[CONFIG_KEY_CHECKPOINT_NS] ?? ""; - config.configurable[CONFIG_KEY_CHECKPOINT_NS] = ns.split(CHECKPOINT_NAMESPACE_SEPARATOR).map((part) => part.split(CHECKPOINT_NAMESPACE_END)[0]).join(CHECKPOINT_NAMESPACE_SEPARATOR); - } - if (streamMode.includes("messages")) { - const messageStreamer = new StreamMessagesHandler((chunk) => stream.push(chunk)); - const { callbacks } = config; - if (callbacks === void 0) config.callbacks = [messageStreamer]; - else if (Array.isArray(callbacks)) config.callbacks = callbacks.concat(messageStreamer); - else { - const copiedCallbacks = callbacks.copy(); - copiedCallbacks.addHandler(messageStreamer, true); - config.callbacks = copiedCallbacks; - } - } - config.writer ??= (chunk) => { - if (!streamMode.includes("custom")) return; - const ns = (getConfig()?.configurable?.[CONFIG_KEY_CHECKPOINT_NS])?.split(CHECKPOINT_NAMESPACE_SEPARATOR).slice(0, -1); - stream.push([ - ns ?? [], - "custom", - chunk - ]); - }; - config.interrupt ??= this.userInterrupt ?? interrupt; - const callbackManager = await getCallbackManagerForConfig(config); - const runManager = await callbackManager?.handleChainStart(this.toJSON(), utils_coerceToDict(input, "input"), runId, void 0, void 0, void 0, config?.runName ?? this.getName()); - const channelSpecs = getOnlyChannels(this.channels); - let loop; - let loopError; - /** - * The PregelLoop will yield events from concurrent tasks as soon as they are - * generated. Each task can push multiple events onto the stream in any order. - * - * We use a separate background method and stream here in order to yield events - * from the loop to the main stream and therefore back to the user as soon as - * they are available. - */ - const createAndRunLoop = async () => { - try { - loop = await PregelLoop.initialize({ - input: validInput, - config, - checkpointer, - nodes: this.nodes, - channelSpecs, - outputKeys, - streamKeys: this.streamChannelsAsIs, - store, - cache, - stream, - interruptAfter, - interruptBefore, - manager: runManager, - debug: this.debug, - triggerToNodes: this.triggerToNodes, - durability - }); - const runner = new PregelRunner({ - loop, - nodeFinished: config.configurable?.[CONFIG_KEY_NODE_FINISHED] - }); - if (options?.subgraphs) loop.config.configurable = { - ...loop.config.configurable, - [CONFIG_KEY_STREAM]: loop.stream - }; - await this._runLoop({ - loop, - runner, - debug, - config - }); - if (durability === "sync") await Promise.all(loop?.checkpointerPromises ?? []); - } catch (e) { - loopError = e; - } finally { - try { - if (loop) { - await loop.store?.stop(); - await loop.cache?.stop(); - } - await Promise.all(loop?.checkpointerPromises ?? []); - } catch (e) { - loopError = loopError ?? e; - } - if (loopError) stream.error(loopError); - else stream.close(); - } - }; - const runLoopPromise = createAndRunLoop(); - try { - for await (const chunk of stream) { - if (chunk === void 0) throw new Error("Data structure error."); - const [namespace, mode, payload] = chunk; - if (streamMode.includes(mode)) { - if (streamEncoding === "text/event-stream") { - if (streamSubgraphs) yield [ - namespace, - mode, - payload - ]; - else yield [ - null, - mode, - payload - ]; - continue; - } - if (streamSubgraphs && !streamModeSingle) yield [ - namespace, - mode, - payload - ]; - else if (!streamModeSingle) yield [mode, payload]; - else if (streamSubgraphs) yield [namespace, payload]; - else yield payload; - } - } - } catch (e) { - await runManager?.handleChainError(loopError); - throw e; - } finally { - await runLoopPromise; - } - await runManager?.handleChainEnd(loop?.output ?? {}, runId, void 0, void 0, void 0); - } - /** - * Run the graph with a single input and config. - * @param input The input to the graph. - * @param options The configuration to use for the run. - */ - async invoke(input, options) { - const streamMode = options?.streamMode ?? "values"; - const config = { - ...options, - outputKeys: options?.outputKeys ?? this.outputChannels, - streamMode, - encoding: void 0 - }; - const chunks = []; - const stream = await this.stream(input, config); - const interruptChunks = []; - let latest; - for await (const chunk of stream) if (streamMode === "values") if (isInterrupted(chunk)) interruptChunks.push(chunk[constants_INTERRUPT]); - else latest = chunk; - else chunks.push(chunk); - if (streamMode === "values") { - if (interruptChunks.length > 0) { - const interrupts = interruptChunks.flat(1); - if (latest == null) return { [constants_INTERRUPT]: interrupts }; - if (typeof latest === "object") return { - ...latest, - [constants_INTERRUPT]: interrupts - }; - } - return latest; - } - return chunks; - } - async _runLoop(params) { - const { loop, runner, debug, config } = params; - let tickError; - try { - while (await loop.tick({ inputKeys: this.inputChannels })) { - for (const { task } of await loop._matchCachedWrites()) loop._outputWrites(task.id, task.writes, true); - if (debug) printStepCheckpoint(loop.checkpointMetadata.step, loop.channels, this.streamChannelsList); - if (debug) printStepTasks(loop.step, Object.values(loop.tasks)); - await runner.tick({ - timeout: this.stepTimeout, - retryPolicy: this.retryPolicy, - onStepWrite: (step, writes) => { - if (debug) printStepWrites(step, writes, this.streamChannelsList); - }, - maxConcurrency: config.maxConcurrency, - signal: config.signal - }); - } - if (loop.status === "out_of_steps") throw new GraphRecursionError([ - `Recursion limit of ${config.recursionLimit} reached`, - "without hitting a stop condition. You can increase the", - `limit by setting the "recursionLimit" config key.` - ].join(" "), { lc_error_code: "GRAPH_RECURSION_LIMIT" }); - } catch (e) { - tickError = e; - const suppress = await loop.finishAndHandleError(tickError); - if (!suppress) throw e; - } finally { - if (tickError === void 0) await loop.finishAndHandleError(); - } - } - async clearCache() { - await this.cache?.clear([]); - } -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/ephemeral_value.js - - - -//#region src/channels/ephemeral_value.ts -/** -* Stores the value received in the step immediately preceding, clears after. -*/ -var EphemeralValue = class EphemeralValue extends BaseChannel { - lc_graph_name = "EphemeralValue"; - guard; - value = []; - constructor(guard = true) { - super(); - this.guard = guard; - } - fromCheckpoint(checkpoint) { - const empty = new EphemeralValue(this.guard); - if (typeof checkpoint !== "undefined") empty.value = [checkpoint]; - return empty; - } - update(values) { - if (values.length === 0) { - const updated = this.value.length > 0; - this.value = []; - return updated; - } - if (values.length !== 1 && this.guard) throw new InvalidUpdateError("EphemeralValue can only receive one value per step."); - this.value = [values[values.length - 1]]; - return true; - } - get() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - checkpoint() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - isAvailable() { - return this.value.length !== 0; - } -}; - -//#endregion - -//# sourceMappingURL=ephemeral_value.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/graph.js - - - - - - - - - - - - - -//#region src/graph/graph.ts -var Branch = class { - path; - ends; - constructor(options) { - if (Runnable.isRunnable(options.path)) this.path = options.path; - else this.path = _coerceToRunnable(options.path).withConfig({ runName: `Branch` }); - this.ends = Array.isArray(options.pathMap) ? options.pathMap.reduce((acc, n) => { - acc[n] = n; - return acc; - }, {}) : options.pathMap; - } - run(writer, reader) { - return ChannelWrite.registerWriter(new RunnableCallable({ - name: "", - trace: false, - func: async (input, config) => { - try { - return await this._route(input, config, writer, reader); - } catch (e) { - if (e.name === NodeInterrupt.unminifiable_name) console.warn("[WARN]: 'NodeInterrupt' thrown in conditional edge. This is likely a bug in your graph implementation.\nNodeInterrupt should only be thrown inside a node, not in edge conditions."); - throw e; - } - } - })); - } - async _route(input, config, writer, reader) { - let result = await this.path.invoke(reader ? reader(config) : input, config); - if (!Array.isArray(result)) result = [result]; - let destinations; - if (this.ends) destinations = result.map((r) => _isSend(r) ? r : this.ends[r]); - else destinations = result; - if (destinations.some((dest) => !dest)) throw new Error("Branch condition returned unknown or null destination"); - if (destinations.filter(_isSend).some((packet) => packet.node === END)) throw new InvalidUpdateError("Cannot send a packet to the END node"); - const writeResult = await writer(destinations, config); - return writeResult ?? input; - } -}; -var Graph$1 = class { - nodes; - edges; - branches; - entryPoint; - compiled = false; - constructor() { - this.nodes = {}; - this.edges = /* @__PURE__ */ new Set(); - this.branches = {}; - } - warnIfCompiled(message) { - if (this.compiled) console.warn(message); - } - get allEdges() { - return this.edges; - } - addNode(...args) { - function isMutlipleNodes(args$1) { - return args$1.length >= 1 && typeof args$1[0] !== "string"; - } - const nodes = isMutlipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]) : [[ - args[0], - args[1], - args[2] - ]]; - if (nodes.length === 0) throw new Error("No nodes provided in `addNode`"); - for (const [key, action, options] of nodes) { - for (const reservedChar of [CHECKPOINT_NAMESPACE_SEPARATOR, CHECKPOINT_NAMESPACE_END]) if (key.includes(reservedChar)) throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); - this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (key in this.nodes) throw new Error(`Node \`${key}\` already present.`); - if (key === END) throw new Error(`Node \`${key}\` is reserved.`); - const runnable = _coerceToRunnable(action); - this.nodes[key] = { - runnable, - metadata: options?.metadata, - subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, - ends: options?.ends - }; - } - return this; - } - addEdge(startKey, endKey) { - this.warnIfCompiled(`Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (startKey === END) throw new Error("END cannot be a start node"); - if (endKey === START) throw new Error("START cannot be an end node"); - if (Array.from(this.edges).some(([start]) => start === startKey) && !("channels" in this)) throw new Error(`Already found path for ${startKey}. For multiple edges, use StateGraph.`); - this.edges.add([startKey, endKey]); - return this; - } - addConditionalEdges(source, path, pathMap) { - const options = typeof source === "object" ? source : { - source, - path, - pathMap - }; - this.warnIfCompiled("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); - if (!Runnable.isRunnable(options.path)) { - const pathDisplayValues = Array.isArray(options.pathMap) ? options.pathMap.join(",") : Object.keys(options.pathMap ?? {}).join(","); - options.path = _coerceToRunnable(options.path).withConfig({ runName: `Branch<${options.source}${pathDisplayValues !== "" ? `,${pathDisplayValues}` : ""}>`.slice(0, 63) }); - } - const name = options.path.getName() === "RunnableLambda" ? "condition" : options.path.getName(); - if (this.branches[options.source] && this.branches[options.source][name]) throw new Error(`Condition \`${name}\` already present for node \`${source}\``); - this.branches[options.source] ??= {}; - this.branches[options.source][name] = new Branch(options); - return this; - } - /** - * @deprecated use `addEdge(START, key)` instead - */ - setEntryPoint(key) { - this.warnIfCompiled("Setting the entry point of a graph that has already been compiled. This will not be reflected in the compiled graph."); - return this.addEdge(START, key); - } - /** - * @deprecated use `addEdge(key, END)` instead - */ - setFinishPoint(key) { - this.warnIfCompiled("Setting a finish point of a graph that has already been compiled. This will not be reflected in the compiled graph."); - return this.addEdge(key, END); - } - compile({ checkpointer, interruptBefore, interruptAfter, name } = {}) { - this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); - const compiled = new CompiledGraph({ - builder: this, - checkpointer, - interruptAfter, - interruptBefore, - autoValidate: false, - nodes: {}, - channels: { - [START]: new EphemeralValue(), - [END]: new EphemeralValue() - }, - inputChannels: START, - outputChannels: END, - streamChannels: [], - streamMode: "values", - name - }); - for (const [key, node] of Object.entries(this.nodes)) compiled.attachNode(key, node); - for (const [start, end] of this.edges) compiled.attachEdge(start, end); - for (const [start, branches] of Object.entries(this.branches)) for (const [name$1, branch] of Object.entries(branches)) compiled.attachBranch(start, name$1, branch); - return compiled.validate(); - } - validate(interrupt) { - const allSources = new Set([...this.allEdges].map(([src, _]) => src)); - for (const [start] of Object.entries(this.branches)) allSources.add(start); - for (const source of allSources) if (source !== START && !(source in this.nodes)) throw new Error(`Found edge starting at unknown node \`${source}\``); - const allTargets = new Set([...this.allEdges].map(([_, target]) => target)); - for (const [start, branches] of Object.entries(this.branches)) for (const branch of Object.values(branches)) if (branch.ends != null) for (const end of Object.values(branch.ends)) allTargets.add(end); - else { - allTargets.add(END); - for (const node of Object.keys(this.nodes)) if (node !== start) allTargets.add(node); - } - for (const node of Object.values(this.nodes)) for (const target of node.ends ?? []) allTargets.add(target); - for (const node of Object.keys(this.nodes)) if (!allTargets.has(node)) throw new UnreachableNodeError([ - `Node \`${node}\` is not reachable.`, - "", - "If you are returning Command objects from your node,", - "make sure you are passing names of potential destination nodes as an \"ends\" array", - "into \".addNode(..., { ends: [\"node1\", \"node2\"] })\"." - ].join("\n"), { lc_error_code: "UNREACHABLE_NODE" }); - for (const target of allTargets) if (target !== END && !(target in this.nodes)) throw new Error(`Found edge ending at unknown node \`${target}\``); - if (interrupt) { - for (const node of interrupt) if (!(node in this.nodes)) throw new Error(`Interrupt node \`${node}\` is not present`); - } - this.compiled = true; - } -}; -var CompiledGraph = class extends Pregel { - builder; - constructor({ builder,...rest }) { - super(rest); - this.builder = builder; - } - attachNode(key, node) { - this.channels[key] = new EphemeralValue(); - this.nodes[key] = new PregelNode({ - channels: [], - triggers: [], - metadata: node.metadata, - subgraphs: node.subgraphs, - ends: node.ends - }).pipe(node.runnable).pipe(new ChannelWrite([{ - channel: key, - value: PASSTHROUGH - }], [TAG_HIDDEN])); - this.streamChannels.push(key); - } - attachEdge(start, end) { - if (end === END) { - if (start === START) throw new Error("Cannot have an edge from START to END"); - this.nodes[start].writers.push(new ChannelWrite([{ - channel: END, - value: PASSTHROUGH - }], [TAG_HIDDEN])); - } else { - this.nodes[end].triggers.push(start); - this.nodes[end].channels.push(start); - } - } - attachBranch(start, name, branch) { - if (start === START && !this.nodes[START]) this.nodes[START] = Channel.subscribeTo(START, { tags: [TAG_HIDDEN] }); - this.nodes[start].pipe(branch.run((dests) => { - const writes = dests.map((dest) => { - if (_isSend(dest)) return dest; - return { - channel: dest === END ? END : `branch:${start}:${name}:${dest}`, - value: PASSTHROUGH - }; - }); - return new ChannelWrite(writes, [TAG_HIDDEN]); - })); - const ends = branch.ends ? Object.values(branch.ends) : Object.keys(this.nodes); - for (const end of ends) if (end !== END) { - const channelName = `branch:${start}:${name}:${end}`; - this.channels[channelName] = new EphemeralValue(); - this.nodes[end].triggers.push(channelName); - this.nodes[end].channels.push(channelName); - } - } - /** - * Returns a drawable representation of the computation graph. - */ - async getGraphAsync(config) { - const xray = config?.xray; - const graph = new Graph(); - const startNodes = { [START]: graph.addNode({ schema: any() }, START) }; - const endNodes = {}; - let subgraphs = {}; - if (xray) subgraphs = Object.fromEntries((await gatherIterator(this.getSubgraphsAsync())).filter((x) => isCompiledGraph(x[1]))); - function addEdge(start, end, label, conditional = false) { - if (end === END && endNodes[END] === void 0) endNodes[END] = graph.addNode({ schema: any() }, END); - if (startNodes[start] === void 0) return; - if (endNodes[end] === void 0) throw new Error(`End node ${end} not found!`); - return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional); - } - for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { - const displayKey = _escapeMermaidKeywords(key); - const node = nodeSpec.runnable; - const metadata = nodeSpec.metadata ?? {}; - if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) metadata.__interrupt = "before,after"; - else if (this.interruptBefore?.includes(key)) metadata.__interrupt = "before"; - else if (this.interruptAfter?.includes(key)) metadata.__interrupt = "after"; - if (xray) { - const newXrayValue = typeof xray === "number" ? xray - 1 : xray; - const drawableSubgraph = subgraphs[key] !== void 0 ? await subgraphs[key].getGraphAsync({ - ...config, - xray: newXrayValue - }) : node.getGraph(config); - drawableSubgraph.trimFirstNode(); - drawableSubgraph.trimLastNode(); - if (Object.keys(drawableSubgraph.nodes).length > 1) { - const [e, s] = graph.extend(drawableSubgraph, displayKey); - if (e === void 0) throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); - function _isRunnableInterface(thing) { - return thing ? thing.lc_runnable : false; - } - function _nodeDataStr(id, data) { - if (id !== void 0 && !wrapper_validate(id)) return id; - else if (_isRunnableInterface(data)) try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; - return dataStr; - } catch (error) { - return data.getName(); - } - else return data.name ?? "UnknownSchema"; - } - if (s !== void 0) startNodes[displayKey] = { - name: _nodeDataStr(s.id, s.data), - ...s - }; - endNodes[displayKey] = { - name: _nodeDataStr(e.id, e.data), - ...e - }; - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } - const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { - if (a < b) return -1; - else if (b > a) return 1; - else return 0; - }); - for (const [start, end] of sortedEdges) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); - for (const [start, branches] of Object.entries(this.builder.branches)) { - const defaultEnds = { - ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), - [END]: END - }; - for (const branch of Object.values(branches)) { - let ends; - if (branch.ends !== void 0) ends = branch.ends; - else ends = defaultEnds; - for (const [label, end] of Object.entries(ends)) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); - } - } - for (const [key, node] of Object.entries(this.builder.nodes)) if (node.ends !== void 0) for (const end of node.ends) addEdge(_escapeMermaidKeywords(key), _escapeMermaidKeywords(end), void 0, true); - return graph; - } - /** - * Returns a drawable representation of the computation graph. - * - * @deprecated Use getGraphAsync instead. The async method will be the default in the next minor core release. - */ - getGraph(config) { - const xray = config?.xray; - const graph = new Graph(); - const startNodes = { [START]: graph.addNode({ schema: any() }, START) }; - const endNodes = {}; - let subgraphs = {}; - if (xray) subgraphs = Object.fromEntries(gatherIteratorSync(this.getSubgraphs()).filter((x) => isCompiledGraph(x[1]))); - function addEdge(start, end, label, conditional = false) { - if (end === END && endNodes[END] === void 0) endNodes[END] = graph.addNode({ schema: any() }, END); - return graph.addEdge(startNodes[start], endNodes[end], label !== end ? label : void 0, conditional); - } - for (const [key, nodeSpec] of Object.entries(this.builder.nodes)) { - const displayKey = _escapeMermaidKeywords(key); - const node = nodeSpec.runnable; - const metadata = nodeSpec.metadata ?? {}; - if (this.interruptBefore?.includes(key) && this.interruptAfter?.includes(key)) metadata.__interrupt = "before,after"; - else if (this.interruptBefore?.includes(key)) metadata.__interrupt = "before"; - else if (this.interruptAfter?.includes(key)) metadata.__interrupt = "after"; - if (xray) { - const newXrayValue = typeof xray === "number" ? xray - 1 : xray; - const drawableSubgraph = subgraphs[key] !== void 0 ? subgraphs[key].getGraph({ - ...config, - xray: newXrayValue - }) : node.getGraph(config); - drawableSubgraph.trimFirstNode(); - drawableSubgraph.trimLastNode(); - if (Object.keys(drawableSubgraph.nodes).length > 1) { - const [e, s] = graph.extend(drawableSubgraph, displayKey); - if (e === void 0) throw new Error(`Could not extend subgraph "${key}" due to missing entrypoint.`); - function _isRunnableInterface(thing) { - return thing ? thing.lc_runnable : false; - } - function _nodeDataStr(id, data) { - if (id !== void 0 && !wrapper_validate(id)) return id; - else if (_isRunnableInterface(data)) try { - let dataStr = data.getName(); - dataStr = dataStr.startsWith("Runnable") ? dataStr.slice(8) : dataStr; - return dataStr; - } catch (error) { - return data.getName(); - } - else return data.name ?? "UnknownSchema"; - } - if (s !== void 0) startNodes[displayKey] = { - name: _nodeDataStr(s.id, s.data), - ...s - }; - endNodes[displayKey] = { - name: _nodeDataStr(e.id, e.data), - ...e - }; - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } else { - const newNode = graph.addNode(node, displayKey, metadata); - startNodes[displayKey] = newNode; - endNodes[displayKey] = newNode; - } - } - const sortedEdges = [...this.builder.allEdges].sort(([a], [b]) => { - if (a < b) return -1; - else if (b > a) return 1; - else return 0; - }); - for (const [start, end] of sortedEdges) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end)); - for (const [start, branches] of Object.entries(this.builder.branches)) { - const defaultEnds = { - ...Object.fromEntries(Object.keys(this.builder.nodes).filter((k) => k !== start).map((k) => [_escapeMermaidKeywords(k), _escapeMermaidKeywords(k)])), - [END]: END - }; - for (const branch of Object.values(branches)) { - let ends; - if (branch.ends !== void 0) ends = branch.ends; - else ends = defaultEnds; - for (const [label, end] of Object.entries(ends)) addEdge(_escapeMermaidKeywords(start), _escapeMermaidKeywords(end), label, true); - } - } - return graph; - } -}; -function isCompiledGraph(x) { - return typeof x.attachNode === "function" && typeof x.attachEdge === "function"; -} -function _escapeMermaidKeywords(key) { - if (key === "subgraph") return `"${key}"`; - return key; -} - -//#endregion - -//# sourceMappingURL=graph.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/named_barrier_value.js - - - -//#region src/channels/named_barrier_value.ts -const areSetsEqual = (a, b) => a.size === b.size && [...a].every((value) => b.has(value)); -/** -* A channel that waits until all named values are received before making the value available. -* -* This ensures that if node N and node M both write to channel C, the value of C will not be updated -* until N and M have completed updating. -*/ -var NamedBarrierValue = class NamedBarrierValue extends BaseChannel { - lc_graph_name = "NamedBarrierValue"; - names; - seen; - constructor(names) { - super(); - this.names = names; - this.seen = /* @__PURE__ */ new Set(); - } - fromCheckpoint(checkpoint) { - const empty = new NamedBarrierValue(this.names); - if (typeof checkpoint !== "undefined") empty.seen = new Set(checkpoint); - return empty; - } - update(values) { - let updated = false; - for (const nodeName of values) if (this.names.has(nodeName)) { - if (!this.seen.has(nodeName)) { - this.seen.add(nodeName); - updated = true; - } - } else throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); - return updated; - } - get() { - if (!areSetsEqual(this.names, this.seen)) throw new EmptyChannelError(); - return void 0; - } - checkpoint() { - return [...this.seen]; - } - consume() { - if (this.seen && this.names && areSetsEqual(this.seen, this.names)) { - this.seen = /* @__PURE__ */ new Set(); - return true; - } - return false; - } - isAvailable() { - return !!this.names && areSetsEqual(this.names, this.seen); - } -}; -/** -* A channel that waits until all named values are received before making the value ready to be made available. -* It is only made available after finish() is called. -* @internal -*/ -var NamedBarrierValueAfterFinish = class NamedBarrierValueAfterFinish extends BaseChannel { - lc_graph_name = "NamedBarrierValueAfterFinish"; - names; - seen; - finished; - constructor(names) { - super(); - this.names = names; - this.seen = /* @__PURE__ */ new Set(); - this.finished = false; - } - fromCheckpoint(checkpoint) { - const empty = new NamedBarrierValueAfterFinish(this.names); - if (typeof checkpoint !== "undefined") { - const [seen, finished] = checkpoint; - empty.seen = new Set(seen); - empty.finished = finished; - } - return empty; - } - update(values) { - let updated = false; - for (const nodeName of values) if (this.names.has(nodeName) && !this.seen.has(nodeName)) { - this.seen.add(nodeName); - updated = true; - } else if (!this.names.has(nodeName)) throw new InvalidUpdateError(`Value ${JSON.stringify(nodeName)} not in names ${JSON.stringify(this.names)}`); - return updated; - } - get() { - if (!this.finished || !areSetsEqual(this.names, this.seen)) throw new EmptyChannelError(); - return void 0; - } - checkpoint() { - return [[...this.seen], this.finished]; - } - consume() { - if (this.finished && this.seen && this.names && areSetsEqual(this.seen, this.names)) { - this.seen = /* @__PURE__ */ new Set(); - this.finished = false; - return true; - } - return false; - } - finish() { - if (!this.finished && !!this.names && areSetsEqual(this.names, this.seen)) { - this.finished = true; - return true; - } - return false; - } - isAvailable() { - return this.finished && !!this.names && areSetsEqual(this.names, this.seen); - } -}; - -//#endregion - -//# sourceMappingURL=named_barrier_value.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/zod/meta.js - - - - -//#region src/graph/zod/meta.ts -const META_EXTRAS_DESCRIPTION_PREFIX = "lg:"; -/** -* A registry for storing and managing metadata associated with schemas. -* This class provides methods to get, extend, remove, and check metadata for a given schema. -*/ -var SchemaMetaRegistry = class { - /** - * Internal map storing schema metadata. - * @internal - */ - _map = /* @__PURE__ */ new WeakMap(); - /** - * Cache for extended schfemas. - * @internal - */ - _extensionCache = /* @__PURE__ */ new Map(); - /** - * Retrieves the metadata associated with a given schema. - * @template TValue The value type of the schema. - * @template TUpdate The update type of the schema (defaults to TValue). - * @param schema The schema to retrieve metadata for. - * @returns The associated SchemaMeta, or undefined if not present. - */ - get(schema) { - return this._map.get(schema); - } - /** - * Extends or sets the metadata for a given schema. - * @template TValue The value type of the schema. - * @template TUpdate The update type of the schema (defaults to TValue). - * @param schema The schema to extend metadata for. - * @param predicate A function that receives the existing metadata (or undefined) and returns the new metadata. - */ - extend(schema, predicate) { - const existingMeta = this.get(schema); - this._map.set(schema, predicate(existingMeta)); - } - /** - * Removes the metadata associated with a given schema. - * @param schema The schema to remove metadata for. - * @returns The SchemaMetaRegistry instance (for chaining). - */ - remove(schema) { - this._map.delete(schema); - return this; - } - /** - * Checks if metadata exists for a given schema. - * @param schema The schema to check. - * @returns True if metadata exists, false otherwise. - */ - has(schema) { - return this._map.has(schema); - } - /** - * Returns a mapping of channel instances for each property in the schema - * using the associated metadata in the registry. - * - * This is used to create the `channels` object that's passed to the `Graph` constructor. - * - * @template T The shape of the schema. - * @param schema The schema to extract channels from. - * @returns A mapping from property names to channel instances. - */ - getChannelsForSchema(schema) { - const channels = {}; - const shape = getInteropZodObjectShape(schema); - for (const [key, channelSchema] of Object.entries(shape)) { - const meta = this.get(channelSchema); - if (meta?.reducer) channels[key] = new BinaryOperatorAggregate(meta.reducer.fn, meta.default); - else channels[key] = new LastValue(meta?.default); - } - return channels; - } - /** - * Returns a modified schema that introspectively looks at all keys of the provided - * object schema, and applies the augmentations based on meta provided with those keys - * in the registry and the selectors provided in the `effects` parameter. - * - * This assumes that the passed in schema is the "root" schema object for a graph where - * the keys of the schema are the channels of the graph. Because we need to represent - * the input of a graph in a couple of different ways, the `effects` parameter allows - * us to apply those augmentations based on pre determined conditions. - * - * @param schema The root schema object to extend. - * @param effects The effects that are being applied. - * @returns The extended schema. - */ - getExtendedChannelSchemas(schema, effects) { - if (Object.keys(effects).length === 0) return schema; - const cacheKey = Object.entries(effects).filter(([, v]) => v === true).sort(([a], [b]) => a.localeCompare(b)).map(([k, v]) => `${k}:${v}`).join("|"); - const cache = this._extensionCache.get(cacheKey) ?? /* @__PURE__ */ new WeakMap(); - if (cache.has(schema)) return cache.get(schema); - let modifiedSchema = schema; - if (effects.withReducerSchema || effects.withJsonSchemaExtrasAsDescription) { - const newShapeEntries = Object.entries(getInteropZodObjectShape(schema)).map(([key, schema$1]) => { - const meta = this.get(schema$1); - let outputSchema = effects.withReducerSchema ? meta?.reducer?.schema ?? schema$1 : schema$1; - if (effects.withJsonSchemaExtrasAsDescription && meta?.jsonSchemaExtra) { - const description = getSchemaDescription(outputSchema) ?? getSchemaDescription(schema$1); - const strExtras = JSON.stringify({ - ...meta.jsonSchemaExtra, - description - }); - outputSchema = outputSchema.describe(`${META_EXTRAS_DESCRIPTION_PREFIX}${strExtras}`); - } - return [key, outputSchema]; - }); - modifiedSchema = extendInteropZodObject(schema, Object.fromEntries(newShapeEntries)); - if (isZodSchemaV3(modifiedSchema)) modifiedSchema._def.unknownKeys = "strip"; - } - if (effects.asPartial) modifiedSchema = interopZodObjectPartial(modifiedSchema); - cache.set(schema, modifiedSchema); - this._extensionCache.set(cacheKey, cache); - return modifiedSchema; - } -}; -const schemaMetaRegistry = new SchemaMetaRegistry(); -function withLangGraph(schema, meta) { - if (meta.reducer && !meta.default) { - const defaultValueGetter = getInteropZodDefaultGetter(schema); - if (defaultValueGetter != null) meta.default = defaultValueGetter; - } - if (meta.reducer) { - const schemaWithReducer = Object.assign(schema, { lg_reducer_schema: meta.reducer?.schema ?? schema }); - schemaMetaRegistry.extend(schemaWithReducer, () => meta); - return schemaWithReducer; - } else { - schemaMetaRegistry.extend(schema, () => meta); - return schema; - } -} - -//#endregion - -//# sourceMappingURL=meta.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/state.js - - - - - - - - - - - - - - - - -//#region src/graph/state.ts -const state_ROOT = "__root__"; -const PartialStateSchema = Symbol.for("langgraph.state.partial"); -/** -* A graph whose nodes communicate by reading and writing to a shared state. -* Each node takes a defined `State` as input and returns a `Partial`. -* -* Each state key can optionally be annotated with a reducer function that -* will be used to aggregate the values of that key received from multiple nodes. -* The signature of a reducer function is (left: Value, right: UpdateValue) => Value. -* -* See {@link Annotation} for more on defining state. -* -* After adding nodes and edges to your graph, you must call `.compile()` on it before -* you can use it. -* -* @example -* ```ts -* import { -* type BaseMessage, -* AIMessage, -* HumanMessage, -* } from "@langchain/core/messages"; -* import { StateGraph, Annotation } from "@langchain/langgraph"; -* -* // Define a state with a single key named "messages" that will -* // combine a returned BaseMessage or arrays of BaseMessages -* const StateAnnotation = Annotation.Root({ -* sentiment: Annotation, -* messages: Annotation({ -* reducer: (left: BaseMessage[], right: BaseMessage | BaseMessage[]) => { -* if (Array.isArray(right)) { -* return left.concat(right); -* } -* return left.concat([right]); -* }, -* default: () => [], -* }), -* }); -* -* const graphBuilder = new StateGraph(StateAnnotation); -* -* // A node in the graph that returns an object with a "messages" key -* // will update the state by combining the existing value with the returned one. -* const myNode = (state: typeof StateAnnotation.State) => { -* return { -* messages: [new AIMessage("Some new response")], -* sentiment: "positive", -* }; -* }; -* -* const graph = graphBuilder -* .addNode("myNode", myNode) -* .addEdge("__start__", "myNode") -* .addEdge("myNode", "__end__") -* .compile(); -* -* await graph.invoke({ messages: [new HumanMessage("how are you?")] }); -* -* // { -* // messages: [HumanMessage("how are you?"), AIMessage("Some new response")], -* // sentiment: "positive", -* // } -* ``` -*/ -var StateGraph = class extends Graph$1 { - channels = {}; - waitingEdges = /* @__PURE__ */ new Set(); - /** @internal */ - _schemaDefinition; - /** @internal */ - _schemaRuntimeDefinition; - /** @internal */ - _inputDefinition; - /** @internal */ - _inputRuntimeDefinition; - /** @internal */ - _outputDefinition; - /** @internal */ - _outputRuntimeDefinition; - /** - * Map schemas to managed values - * @internal - */ - _schemaDefinitions = /* @__PURE__ */ new Map(); - /** @internal */ - _metaRegistry = schemaMetaRegistry; - /** @internal Used only for typing. */ - _configSchema; - /** @internal */ - _configRuntimeSchema; - /** @internal */ - _interrupt; - /** @internal */ - _writer; - constructor(fields, contextSchema) { - super(); - if (isZodStateGraphArgsWithStateSchema(fields)) { - const stateDef = this._metaRegistry.getChannelsForSchema(fields.state); - const inputDef = fields.input != null ? this._metaRegistry.getChannelsForSchema(fields.input) : stateDef; - const outputDef = fields.output != null ? this._metaRegistry.getChannelsForSchema(fields.output) : stateDef; - this._schemaDefinition = stateDef; - this._schemaRuntimeDefinition = fields.state; - this._inputDefinition = inputDef; - this._inputRuntimeDefinition = fields.input ?? PartialStateSchema; - this._outputDefinition = outputDef; - this._outputRuntimeDefinition = fields.output ?? fields.state; - } else if (isInteropZodObject(fields)) { - const stateDef = this._metaRegistry.getChannelsForSchema(fields); - this._schemaDefinition = stateDef; - this._schemaRuntimeDefinition = fields; - this._inputDefinition = stateDef; - this._inputRuntimeDefinition = PartialStateSchema; - this._outputDefinition = stateDef; - this._outputRuntimeDefinition = fields; - } else if (isStateGraphArgsWithInputOutputSchemas(fields)) { - this._schemaDefinition = fields.input.spec; - this._inputDefinition = fields.input.spec; - this._outputDefinition = fields.output.spec; - } else if (isStateGraphArgsWithStateSchema(fields)) { - this._schemaDefinition = fields.stateSchema.spec; - this._inputDefinition = fields.input?.spec ?? this._schemaDefinition; - this._outputDefinition = fields.output?.spec ?? this._schemaDefinition; - } else if (isStateDefinition(fields) || isAnnotationRoot(fields)) { - const spec = isAnnotationRoot(fields) ? fields.spec : fields; - this._schemaDefinition = spec; - } else if (isStateGraphArgs(fields)) { - const spec = _getChannels(fields.channels); - this._schemaDefinition = spec; - } else throw new Error("Invalid StateGraph input. Make sure to pass a valid Annotation.Root or Zod schema."); - this._inputDefinition ??= this._schemaDefinition; - this._outputDefinition ??= this._schemaDefinition; - this._addSchema(this._schemaDefinition); - this._addSchema(this._inputDefinition); - this._addSchema(this._outputDefinition); - function isOptions(options) { - return typeof options === "object" && options != null && !("spec" in options) && !isInteropZodObject(options); - } - if (isOptions(contextSchema)) { - if (isInteropZodObject(contextSchema.context)) this._configRuntimeSchema = contextSchema.context; - this._interrupt = contextSchema.interrupt; - this._writer = contextSchema.writer; - } else if (isInteropZodObject(contextSchema)) this._configRuntimeSchema = contextSchema; - } - get allEdges() { - return new Set([...this.edges, ...Array.from(this.waitingEdges).flatMap(([starts, end]) => starts.map((start) => [start, end]))]); - } - _addSchema(stateDefinition) { - if (this._schemaDefinitions.has(stateDefinition)) return; - this._schemaDefinitions.set(stateDefinition, stateDefinition); - for (const [key, val] of Object.entries(stateDefinition)) { - let channel; - if (typeof val === "function") channel = val(); - else channel = val; - if (this.channels[key] !== void 0) { - if (this.channels[key] !== channel) { - if (channel.lc_graph_name !== "LastValue") throw new Error(`Channel "${key}" already exists with a different type.`); - } - } else this.channels[key] = channel; - } - } - addNode(...args) { - function isMultipleNodes(args$1) { - return args$1.length >= 1 && typeof args$1[0] !== "string"; - } - const nodes = isMultipleNodes(args) ? Array.isArray(args[0]) ? args[0] : Object.entries(args[0]).map(([key, action]) => [key, action]) : [[ - args[0], - args[1], - args[2] - ]]; - if (nodes.length === 0) throw new Error("No nodes provided in `addNode`"); - for (const [key, action, options] of nodes) { - if (key in this.channels) throw new Error(`${key} is already being used as a state attribute (a.k.a. a channel), cannot also be used as a node name.`); - for (const reservedChar of [CHECKPOINT_NAMESPACE_SEPARATOR, CHECKPOINT_NAMESPACE_END]) if (key.includes(reservedChar)) throw new Error(`"${reservedChar}" is a reserved character and is not allowed in node names.`); - this.warnIfCompiled(`Adding a node to a graph that has already been compiled. This will not be reflected in the compiled graph.`); - if (key in this.nodes) throw new Error(`Node \`${key}\` already present.`); - if (key === END || key === START) throw new Error(`Node \`${key}\` is reserved.`); - let inputSpec = this._schemaDefinition; - if (options?.input !== void 0) { - if (isInteropZodObject(options.input)) inputSpec = this._metaRegistry.getChannelsForSchema(options.input); - else if (options.input.spec !== void 0) inputSpec = options.input.spec; - } - if (inputSpec !== void 0) this._addSchema(inputSpec); - let runnable; - if (Runnable.isRunnable(action)) runnable = action; - else if (typeof action === "function") runnable = new RunnableCallable({ - func: action, - name: key, - trace: false - }); - else runnable = _coerceToRunnable(action); - let cachePolicy = options?.cachePolicy; - if (typeof cachePolicy === "boolean") cachePolicy = cachePolicy ? {} : void 0; - const nodeSpec = { - runnable, - retryPolicy: options?.retryPolicy, - cachePolicy, - metadata: options?.metadata, - input: inputSpec ?? this._schemaDefinition, - subgraphs: isPregelLike(runnable) ? [runnable] : options?.subgraphs, - ends: options?.ends, - defer: options?.defer - }; - this.nodes[key] = nodeSpec; - } - return this; - } - addEdge(startKey, endKey) { - if (typeof startKey === "string") return super.addEdge(startKey, endKey); - if (this.compiled) console.warn("Adding an edge to a graph that has already been compiled. This will not be reflected in the compiled graph."); - for (const start of startKey) { - if (start === END) throw new Error("END cannot be a start node"); - if (!Object.keys(this.nodes).some((node) => node === start)) throw new Error(`Need to add a node named "${start}" first`); - } - if (endKey === END) throw new Error("END cannot be an end node"); - if (!Object.keys(this.nodes).some((node) => node === endKey)) throw new Error(`Need to add a node named "${endKey}" first`); - this.waitingEdges.add([startKey, endKey]); - return this; - } - addSequence(nodes) { - const parsedNodes = Array.isArray(nodes) ? nodes : Object.entries(nodes); - if (parsedNodes.length === 0) throw new Error("Sequence requires at least one node."); - let previousNode; - for (const [key, action, options] of parsedNodes) { - if (key in this.nodes) throw new Error(`Node names must be unique: node with the name "${key}" already exists.`); - const validKey = key; - this.addNode(validKey, action, options); - if (previousNode != null) this.addEdge(previousNode, validKey); - previousNode = validKey; - } - return this; - } - compile({ checkpointer, store, cache, interruptBefore, interruptAfter, name, description } = {}) { - this.validate([...Array.isArray(interruptBefore) ? interruptBefore : [], ...Array.isArray(interruptAfter) ? interruptAfter : []]); - const outputKeys = Object.keys(this._schemaDefinitions.get(this._outputDefinition)); - const outputChannels = outputKeys.length === 1 && outputKeys[0] === state_ROOT ? state_ROOT : outputKeys; - const streamKeys = Object.keys(this.channels); - const streamChannels = streamKeys.length === 1 && streamKeys[0] === state_ROOT ? state_ROOT : streamKeys; - const userInterrupt = this._interrupt; - const compiled = new CompiledStateGraph({ - builder: this, - checkpointer, - interruptAfter, - interruptBefore, - autoValidate: false, - nodes: {}, - channels: { - ...this.channels, - [START]: new EphemeralValue() - }, - inputChannels: START, - outputChannels, - streamChannels, - streamMode: "updates", - store, - cache, - name, - description, - userInterrupt - }); - compiled.attachNode(START); - for (const [key, node] of Object.entries(this.nodes)) compiled.attachNode(key, node); - compiled.attachBranch(START, SELF, _getControlBranch(), { withReader: false }); - for (const [key] of Object.entries(this.nodes)) compiled.attachBranch(key, SELF, _getControlBranch(), { withReader: false }); - for (const [start, end] of this.edges) compiled.attachEdge(start, end); - for (const [starts, end] of this.waitingEdges) compiled.attachEdge(starts, end); - for (const [start, branches] of Object.entries(this.branches)) for (const [name$1, branch] of Object.entries(branches)) compiled.attachBranch(start, name$1, branch); - return compiled.validate(); - } -}; -function _getChannels(schema) { - const channels = {}; - for (const [name, val] of Object.entries(schema)) if (name === state_ROOT) channels[name] = getChannel(val); - else channels[name] = getChannel(val); - return channels; -} -/** -* Final result from building and compiling a {@link StateGraph}. -* Should not be instantiated directly, only using the StateGraph `.compile()` -* instance method. -*/ -var CompiledStateGraph = class extends CompiledGraph { - /** - * The description of the compiled graph. - * This is used by the supervisor agent to describe the handoff to the agent. - */ - description; - /** @internal */ - _metaRegistry = schemaMetaRegistry; - constructor({ description,...rest }) { - super(rest); - this.description = description; - } - attachNode(key, node) { - let outputKeys; - if (key === START) outputKeys = Object.entries(this.builder._schemaDefinitions.get(this.builder._inputDefinition)).map(([k]) => k); - else outputKeys = Object.keys(this.builder.channels); - function _getRoot(input) { - if (isCommand(input)) { - if (input.graph === Command.PARENT) return null; - return input._updateAsTuples(); - } else if (Array.isArray(input) && input.length > 0 && input.some((i) => isCommand(i))) { - const updates = []; - for (const i of input) if (isCommand(i)) { - if (i.graph === Command.PARENT) continue; - updates.push(...i._updateAsTuples()); - } else updates.push([state_ROOT, i]); - return updates; - } else if (input != null) return [[state_ROOT, input]]; - return null; - } - const nodeKey = key; - function _getUpdates(input) { - if (!input) return null; - else if (isCommand(input)) { - if (input.graph === Command.PARENT) return null; - return input._updateAsTuples().filter(([k]) => outputKeys.includes(k)); - } else if (Array.isArray(input) && input.length > 0 && input.some(isCommand)) { - const updates = []; - for (const item of input) if (isCommand(item)) { - if (item.graph === Command.PARENT) continue; - updates.push(...item._updateAsTuples().filter(([k]) => outputKeys.includes(k))); - } else { - const itemUpdates = _getUpdates(item); - if (itemUpdates) updates.push(...itemUpdates ?? []); - } - return updates; - } else if (typeof input === "object" && !Array.isArray(input)) return Object.entries(input).filter(([k]) => outputKeys.includes(k)); - else { - const typeofInput = Array.isArray(input) ? "array" : typeof input; - throw new InvalidUpdateError(`Expected node "${nodeKey.toString()}" to return an object or an array containing at least one Command object, received ${typeofInput}`, { lc_error_code: "INVALID_GRAPH_NODE_RETURN_VALUE" }); - } - } - const stateWriteEntries = [{ - value: PASSTHROUGH, - mapper: new RunnableCallable({ - func: outputKeys.length && outputKeys[0] === state_ROOT ? _getRoot : _getUpdates, - trace: false, - recurse: false - }) - }]; - if (key === START) this.nodes[key] = new PregelNode({ - tags: [TAG_HIDDEN], - triggers: [START], - channels: [START], - writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])] - }); - else { - const inputDefinition = node?.input ?? this.builder._schemaDefinition; - const inputValues = Object.fromEntries(Object.keys(this.builder._schemaDefinitions.get(inputDefinition)).map((k) => [k, k])); - const isSingleInput = Object.keys(inputValues).length === 1 && state_ROOT in inputValues; - const branchChannel = `branch:to:${key}`; - this.channels[branchChannel] = node?.defer ? new LastValueAfterFinish() : new EphemeralValue(false); - this.nodes[key] = new PregelNode({ - triggers: [branchChannel], - channels: isSingleInput ? Object.keys(inputValues) : inputValues, - writers: [new ChannelWrite(stateWriteEntries, [TAG_HIDDEN])], - mapper: isSingleInput ? void 0 : (input) => { - return Object.fromEntries(Object.entries(input).filter(([k]) => k in inputValues)); - }, - bound: node?.runnable, - metadata: node?.metadata, - retryPolicy: node?.retryPolicy, - cachePolicy: node?.cachePolicy, - subgraphs: node?.subgraphs, - ends: node?.ends - }); - } - } - attachEdge(starts, end) { - if (end === END) return; - if (typeof starts === "string") this.nodes[starts].writers.push(new ChannelWrite([{ - channel: `branch:to:${end}`, - value: null - }], [TAG_HIDDEN])); - else if (Array.isArray(starts)) { - const channelName = `join:${starts.join("+")}:${end}`; - this.channels[channelName] = this.builder.nodes[end].defer ? new NamedBarrierValueAfterFinish(new Set(starts)) : new NamedBarrierValue(new Set(starts)); - this.nodes[end].triggers.push(channelName); - for (const start of starts) this.nodes[start].writers.push(new ChannelWrite([{ - channel: channelName, - value: start - }], [TAG_HIDDEN])); - } - } - attachBranch(start, _, branch, options = { withReader: true }) { - const branchWriter = async (packets, config) => { - const filteredPackets = packets.filter((p) => p !== END); - if (!filteredPackets.length) return; - const writes = filteredPackets.map((p) => { - if (_isSend(p)) return p; - return { - channel: p === END ? p : `branch:to:${p}`, - value: start - }; - }); - await ChannelWrite.doWrite({ - ...config, - tags: (config.tags ?? []).concat([TAG_HIDDEN]) - }, writes); - }; - this.nodes[start].writers.push(branch.run(branchWriter, options.withReader ? (config) => ChannelRead.doRead(config, this.streamChannels ?? this.outputChannels, true) : void 0)); - } - async _validateInput(input) { - if (input == null) return input; - const schema = (() => { - const input$1 = this.builder._inputRuntimeDefinition; - const schema$1 = this.builder._schemaRuntimeDefinition; - const apply = (schema$2) => { - if (schema$2 == null) return void 0; - return this._metaRegistry.getExtendedChannelSchemas(schema$2, { withReducerSchema: true }); - }; - if (isInteropZodObject(input$1)) return apply(input$1); - if (input$1 === PartialStateSchema) return interopZodObjectPartial(apply(schema$1)); - return void 0; - })(); - if (isCommand(input)) { - const parsedInput = input; - if (input.update && schema != null) parsedInput.update = interopParse(schema, input.update); - return parsedInput; - } - if (schema != null) return interopParse(schema, input); - return input; - } - isInterrupted(input) { - return isInterrupted(input); - } - async _validateContext(config) { - const configSchema = this.builder._configRuntimeSchema; - if (isInteropZodObject(configSchema)) interopParse(configSchema, config); - return config; - } -}; -function isStateDefinition(obj) { - return typeof obj === "object" && obj !== null && !Array.isArray(obj) && Object.keys(obj).length > 0 && Object.values(obj).every((v) => typeof v === "function" || isBaseChannel(v)); -} -function isAnnotationRoot(obj) { - return typeof obj === "object" && obj !== null && "lc_graph_name" in obj && obj.lc_graph_name === "AnnotationRoot"; -} -function isStateGraphArgs(obj) { - return typeof obj === "object" && obj !== null && obj.channels !== void 0; -} -function isStateGraphArgsWithStateSchema(obj) { - return typeof obj === "object" && obj !== null && obj.stateSchema !== void 0; -} -function isStateGraphArgsWithInputOutputSchemas(obj) { - return typeof obj === "object" && obj !== null && obj.stateSchema === void 0 && obj.input !== void 0 && obj.output !== void 0; -} -function isZodStateGraphArgsWithStateSchema(value) { - if (typeof value !== "object" || value == null) return false; - if (!("state" in value) || !isInteropZodObject(value.state)) return false; - if ("input" in value && !isInteropZodObject(value.input)) return false; - if ("output" in value && !isInteropZodObject(value.output)) return false; - return true; -} -function _controlBranch(value) { - if (_isSend(value)) return [value]; - const commands = []; - if (isCommand(value)) commands.push(value); - else if (Array.isArray(value)) commands.push(...value.filter(isCommand)); - const destinations = []; - for (const command of commands) { - if (command.graph === Command.PARENT) throw new ParentCommand(command); - if (_isSend(command.goto)) destinations.push(command.goto); - else if (typeof command.goto === "string") destinations.push(command.goto); - else if (Array.isArray(command.goto)) destinations.push(...command.goto); - } - return destinations; -} -function _getControlBranch() { - const CONTROL_BRANCH_PATH = new RunnableCallable({ - func: _controlBranch, - tags: [TAG_HIDDEN], - trace: false, - recurse: false, - name: "" - }); - return new Branch({ path: CONTROL_BRANCH_PATH }); -} - -//#endregion - -//# sourceMappingURL=state.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/message.js - - - - - -//#region src/graph/message.ts -const REMOVE_ALL_MESSAGES = "__remove_all__"; -/** -* Prebuilt reducer that combines returned messages. -* Can handle standard messages and special modifiers like {@link RemoveMessage} -* instances. -*/ -function messagesStateReducer(left, right) { - const leftArray = Array.isArray(left) ? left : [left]; - const rightArray = Array.isArray(right) ? right : [right]; - const leftMessages = leftArray.map(utils_coerceMessageLikeToMessage); - const rightMessages = rightArray.map(utils_coerceMessageLikeToMessage); - for (const m of leftMessages) if (m.id === null || m.id === void 0) { - m.id = v4(); - m.lc_kwargs.id = m.id; - } - let removeAllIdx; - for (let i = 0; i < rightMessages.length; i += 1) { - const m = rightMessages[i]; - if (m.id === null || m.id === void 0) { - m.id = v4(); - m.lc_kwargs.id = m.id; - } - if (m.getType() === "remove" && m.id === REMOVE_ALL_MESSAGES) removeAllIdx = i; - } - if (removeAllIdx != null) return rightMessages.slice(removeAllIdx + 1); - const merged = [...leftMessages]; - const mergedById = new Map(merged.map((m, i) => [m.id, i])); - const idsToRemove = /* @__PURE__ */ new Set(); - for (const m of rightMessages) { - const existingIdx = mergedById.get(m.id); - if (existingIdx !== void 0) if (m.getType() === "remove") idsToRemove.add(m.id); - else { - idsToRemove.delete(m.id); - merged[existingIdx] = m; - } - else { - if (m.getType() === "remove") throw new Error(`Attempting to delete a message with an ID that doesn't exist ('${m.id}')`); - mergedById.set(m.id, merged.length); - merged.push(m); - } - } - return merged.filter((m) => !idsToRemove.has(m.id)); -} -/** @ignore */ -var MessageGraph = class extends StateGraph { - constructor() { - super({ channels: { __root__: { - reducer: messagesStateReducer, - default: () => [] - } } }); - } -}; -/** -* Manually push a message to a message stream. -* -* This is useful when you need to push a manually created message before the node -* has finished executing. -* -* When a message is pushed, it will be automatically persisted to the state after the node has finished executing. -* To disable persisting, set `options.stateKey` to `null`. -* -* @param message The message to push. The message must have an ID set, otherwise an error will be thrown. -* @param options RunnableConfig / Runtime coming from node context. -*/ -function pushMessage(message, options) { - const { stateKey: userStateKey,...userConfig } = options ?? {}; - const config = ensureLangGraphConfig(userConfig); - let stateKey = userStateKey ?? "messages"; - if (userStateKey === null) stateKey = void 0; - const validMessage = coerceMessageLikeToMessage(message); - if (!validMessage.id) throw new Error("Message ID is required."); - const callbacks = (() => { - if (Array.isArray(config.callbacks)) return config.callbacks; - if (typeof config.callbacks !== "undefined") return config.callbacks.handlers; - return []; - })(); - const messagesHandler = callbacks.find((cb) => "name" in cb && cb.name === "StreamMessagesHandler"); - if (messagesHandler) { - const metadata = config.metadata ?? {}; - const namespace = (metadata.langgraph_checkpoint_ns ?? "").split("|"); - messagesHandler._emit([namespace, metadata], validMessage, void 0, false); - } - if (stateKey) config.configurable?.__pregel_send?.([[stateKey, validMessage]]); - return validMessage; -} - -//#endregion - -//# sourceMappingURL=message.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/func/index.js - - - - - - - - - - -//#region src/func/index.ts -/** -* Define a LangGraph task using the `task` function. -* -* Tasks can only be called from within an {@link entrypoint} or from within a StateGraph. -* A task can be called like a regular function with the following differences: -* -* - When a checkpointer is enabled, the function inputs and outputs must be serializable. -* - The wrapped function can only be called from within an entrypoint or StateGraph. -* - Calling the function produces a promise. This makes it easy to parallelize tasks. -* -* @typeParam ArgsT - The type of arguments the task function accepts -* @typeParam OutputT - The type of value the task function returns -* @param optionsOrName - Either an {@link TaskOptions} object, or a string for the name of the task -* @param func - The function that executes this task -* @returns A proxy function that accepts the same arguments as the original and always returns the result as a Promise -* -* @example basic example -* ```typescript -* const addOne = task("add", async (a: number) => a + 1); -* -* const workflow = entrypoint("example", async (numbers: number[]) => { -* const promises = numbers.map(n => addOne(n)); -* const results = await Promise.all(promises); -* return results; -* }); -* -* // Call the entrypoint -* await workflow.invoke([1, 2, 3]); // Returns [2, 3, 4] -* ``` -* -* @example using a retry policy -* ```typescript -* const addOne = task({ -* name: "add", -* retry: { maxAttempts: 3 } -* }, -* async (a: number) => a + 1 -* ); -* -* const workflow = entrypoint("example", async (numbers: number[]) => { -* const promises = numbers.map(n => addOne(n)); -* const results = await Promise.all(promises); -* return results; -* }); -* ``` -* @category Functional API -*/ -function task(optionsOrName, func) { - const options = typeof optionsOrName === "string" ? { - name: optionsOrName, - retry: void 0, - cachePolicy: void 0 - } : optionsOrName; - const { name, retry } = options; - if (isAsyncGeneratorFunction(func) || isGeneratorFunction(func)) throw new Error("Generators are disallowed as tasks. For streaming responses, use config.write."); - const cachePolicy = options.cachePolicy ?? ("cache" in options ? options.cache : void 0); - let cache; - if (typeof cachePolicy === "boolean") cache = cachePolicy ? {} : void 0; - else cache = cachePolicy; - return (...args) => { - return call({ - func, - name, - retry, - cache - }, ...args); - }; -} -/** -* Define a LangGraph workflow using the `entrypoint` function. -* -* ### Function signature -* -* The wrapped function must accept at most **two parameters**. The first parameter -* is the input to the function. The second (optional) parameter is a -* {@link LangGraphRunnableConfig} object. If you wish to pass multiple parameters to -* the function, you can pass them as an object. -* -* ### Helper functions -* -* #### Streaming -* To write data to the "custom" stream, use the {@link getWriter} function, or the -* {@link LangGraphRunnableConfig.writer} property. -* -* #### State management -* The {@link getPreviousState} function can be used to access the previous state -* that was returned from the last invocation of the entrypoint on the same thread id. -* -* If you wish to save state other than the return value, you can use the -* {@link entrypoint.final} function. -* -* @typeParam InputT - The type of input the entrypoint accepts -* @typeParam OutputT - The type of output the entrypoint produces -* @param optionsOrName - Either an {@link EntrypointOptions} object, or a string for the name of the entrypoint -* @param func - The function that executes this entrypoint -* @returns A {@link Pregel} instance that can be run to execute the workflow -* -* @example Using entrypoint and tasks -* ```typescript -* import { task, entrypoint } from "@langchain/langgraph"; -* import { MemorySaver } from "@langchain/langgraph-checkpoint"; -* import { interrupt, Command } from "@langchain/langgraph"; -* -* const composeEssay = task("compose", async (topic: string) => { -* await new Promise(r => setTimeout(r, 1000)); // Simulate slow operation -* return `An essay about ${topic}`; -* }); -* -* const reviewWorkflow = entrypoint({ -* name: "review", -* checkpointer: new MemorySaver() -* }, async (topic: string) => { -* const essay = await composeEssay(topic); -* const humanReview = await interrupt({ -* question: "Please provide a review", -* essay -* }); -* return { -* essay, -* review: humanReview -* }; -* }); -* -* // Example configuration for the workflow -* const config = { -* configurable: { -* thread_id: "some_thread" -* } -* }; -* -* // Topic for the essay -* const topic = "cats"; -* -* // Stream the workflow to generate the essay and await human review -* for await (const result of reviewWorkflow.stream(topic, config)) { -* console.log(result); -* } -* -* // Example human review provided after the interrupt -* const humanReview = "This essay is great."; -* -* // Resume the workflow with the provided human review -* for await (const result of reviewWorkflow.stream(new Command({ resume: humanReview }), config)) { -* console.log(result); -* } -* ``` -* -* @example Accessing the previous return value -* ```typescript -* import { entrypoint, getPreviousState } from "@langchain/langgraph"; -* import { MemorySaver } from "@langchain/langgraph-checkpoint"; -* -* const accumulator = entrypoint({ -* name: "accumulator", -* checkpointer: new MemorySaver() -* }, async (input: string) => { -* const previous = getPreviousState(); -* return previous !== undefined ? `${previous } ${input}` : input; -* }); -* -* const config = { -* configurable: { -* thread_id: "some_thread" -* } -* }; -* await accumulator.invoke("hello", config); // returns "hello" -* await accumulator.invoke("world", config); // returns "hello world" -* ``` -* -* @example Using entrypoint.final to save a value -* ```typescript -* import { entrypoint, getPreviousState } from "@langchain/langgraph"; -* import { MemorySaver } from "@langchain/langgraph-checkpoint"; -* -* const myWorkflow = entrypoint({ -* name: "accumulator", -* checkpointer: new MemorySaver() -* }, async (num: number) => { -* const previous = getPreviousState(); -* -* // This will return the previous value to the caller, saving -* // 2 * num to the checkpoint, which will be used in the next invocation -* // for the `previous` parameter. -* return entrypoint.final({ -* value: previous ?? 0, -* save: 2 * num -* }); -* }); -* -* const config = { -* configurable: { -* thread_id: "some_thread" -* } -* }; -* -* await myWorkflow.invoke(3, config); // 0 (previous was undefined) -* await myWorkflow.invoke(1, config); // 6 (previous was 3 * 2 from the previous invocation) -* ``` -* @category Functional API -*/ -const entrypoint = function entrypoint$1(optionsOrName, func) { - const { name, checkpointer, store, cache } = typeof optionsOrName === "string" ? { - name: optionsOrName, - checkpointer: void 0, - store: void 0 - } : optionsOrName; - if (utils_isAsyncGeneratorFunction(func) || utils_isGeneratorFunction(func)) throw new Error("Generators are disallowed as entrypoints. For streaming responses, use config.write."); - const streamMode = "updates"; - const bound = getRunnableForEntrypoint(name, func); - function isEntrypointFinal(value) { - return typeof value === "object" && value !== null && "__lg_type" in value && value.__lg_type === "__pregel_final"; - } - const pluckReturnValue = new RunnableCallable({ - name: "pluckReturnValue", - func: (value) => { - return isEntrypointFinal(value) ? value.value : value; - } - }); - const pluckSaveValue = new RunnableCallable({ - name: "pluckSaveValue", - func: (value) => { - return isEntrypointFinal(value) ? value.save : value; - } - }); - const entrypointNode = new PregelNode({ - bound, - triggers: [START], - channels: [START], - writers: [new ChannelWrite([{ - channel: END, - value: PASSTHROUGH, - mapper: pluckReturnValue - }, { - channel: PREVIOUS, - value: PASSTHROUGH, - mapper: pluckSaveValue - }], [TAG_HIDDEN])] - }); - return new Pregel({ - name, - checkpointer, - nodes: { [name]: entrypointNode }, - channels: { - [START]: new EphemeralValue(), - [END]: new LastValue(), - [PREVIOUS]: new LastValue() - }, - inputChannels: START, - outputChannels: END, - streamChannels: END, - streamMode, - store, - cache - }); -}; -entrypoint.final = function final({ value, save }) { - return { - value, - save, - __lg_type: "__pregel_final" - }; -}; -/** -* A helper utility function for use with the functional API that returns the previous -* state from the checkpoint from the last invocation of the current thread. -* -* This function allows workflows to access state that was saved in previous runs -* using {@link entrypoint.final}. -* -* @typeParam StateT - The type of the state that was previously saved -* @returns The previous saved state from the last invocation of the current thread -* -* @example -* ```typescript -* const previousState = getPreviousState<{ counter: number }>(); -* const newCount = (previousState?.counter ?? 0) + 1; -* ``` -* @category Functional API -*/ -function getPreviousState() { - const config = AsyncLocalStorageProviderSingleton.getRunnableConfig(); - return config.configurable?.[CONFIG_KEY_PREVIOUS_STATE]; -} - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/messages_annotation.js - - - - - -//#region src/graph/messages_annotation.ts -/** -* Prebuilt state annotation that combines returned messages. -* Can handle standard messages and special modifiers like {@link RemoveMessage} -* instances. -* -* Specifically, importing and using the prebuilt MessagesAnnotation like this: -* -* @example -* ```ts -* import { MessagesAnnotation, StateGraph } from "@langchain/langgraph"; -* -* const graph = new StateGraph(MessagesAnnotation) -* .addNode(...) -* ... -* ``` -* -* Is equivalent to initializing your state manually like this: -* -* @example -* ```ts -* import { BaseMessage } from "@langchain/core/messages"; -* import { Annotation, StateGraph, messagesStateReducer } from "@langchain/langgraph"; -* -* export const StateAnnotation = Annotation.Root({ -* messages: Annotation({ -* reducer: messagesStateReducer, -* default: () => [], -* }), -* }); -* -* const graph = new StateGraph(StateAnnotation) -* .addNode(...) -* ... -* ``` -*/ -const MessagesAnnotation = Annotation.Root({ messages: Annotation({ - reducer: messagesStateReducer, - default: () => [] -}) }); -/** -* Prebuilt schema meta for Zod state definition. -* -* @example -* ```ts -* import { z } from "zod/v4-mini"; -* import { MessagesZodState, StateGraph } from "@langchain/langgraph"; -* -* const AgentState = z.object({ -* messages: z.custom().register(registry, MessagesZodMeta), -* }); -* ``` -*/ -const MessagesZodMeta = { - reducer: { fn: messagesStateReducer }, - jsonSchemaExtra: { langgraph_type: "messages" }, - default: () => [] -}; -/** -* Prebuilt state object that uses Zod to combine returned messages. -* This utility is synonymous with the `MessagesAnnotation` annotation, -* but uses Zod as the way to express messages state. -* -* You can use import and use this prebuilt schema like this: -* -* @example -* ```ts -* import { MessagesZodState, StateGraph } from "@langchain/langgraph"; -* -* const graph = new StateGraph(MessagesZodState) -* .addNode(...) -* ... -* ``` -* -* Which is equivalent to initializing the schema object manually like this: -* -* @example -* ```ts -* import { z } from "zod"; -* import type { BaseMessage, BaseMessageLike } from "@langchain/core/messages"; -* import { StateGraph, messagesStateReducer } from "@langchain/langgraph"; -* import "@langchain/langgraph/zod"; -* -* const AgentState = z.object({ -* messages: z -* .custom() -* .default(() => []) -* .langgraph.reducer( -* messagesStateReducer, -* z.custom() -* ), -* }); -* const graph = new StateGraph(AgentState) -* .addNode(...) -* ... -* ``` -*/ -const MessagesZodState = objectType({ messages: withLangGraph(custom(), MessagesZodMeta) }); - -//#endregion - -//# sourceMappingURL=messages_annotation.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/graph/index.js - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/any_value.js - - - -//#region src/channels/any_value.ts -/** -* Stores the last value received, assumes that if multiple values are received, they are all equal. -* -* Note: Unlike 'LastValue' if multiple nodes write to this channel in a single step, the values -* will be continuously overwritten. -*/ -var AnyValue = class AnyValue extends BaseChannel { - lc_graph_name = "AnyValue"; - value = []; - constructor() { - super(); - } - fromCheckpoint(checkpoint) { - const empty = new AnyValue(); - if (typeof checkpoint !== "undefined") empty.value = [checkpoint]; - return empty; - } - update(values) { - if (values.length === 0) { - const updated = this.value.length > 0; - this.value = []; - return updated; - } - this.value = [values[values.length - 1]]; - return false; - } - get() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - checkpoint() { - if (this.value.length === 0) throw new EmptyChannelError(); - return this.value[0]; - } - isAvailable() { - return this.value.length !== 0; - } -}; - -//#endregion - -//# sourceMappingURL=any_value.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/dynamic_barrier_value.js - - - - -//#region src/channels/dynamic_barrier_value.ts -function isWaitForNames(v) { - return v.__names !== void 0; -} -/** -* A channel that switches between two states -* -* - in the "priming" state it can't be read from. -* - if it receives a WaitForNames update, it switches to the "waiting" state. -* - in the "waiting" state it collects named values until all are received. -* - once all named values are received, it can be read once, and it switches -* back to the "priming" state. -*/ -var DynamicBarrierValue = class DynamicBarrierValue extends BaseChannel { - lc_graph_name = "DynamicBarrierValue"; - names; - seen; - constructor() { - super(); - this.names = void 0; - this.seen = /* @__PURE__ */ new Set(); - } - fromCheckpoint(checkpoint) { - const empty = new DynamicBarrierValue(); - if (typeof checkpoint !== "undefined") { - empty.names = new Set(checkpoint[0]); - empty.seen = new Set(checkpoint[1]); - } - return empty; - } - update(values) { - const waitForNames = values.filter(isWaitForNames); - if (waitForNames.length > 0) { - if (waitForNames.length > 1) throw new InvalidUpdateError("Received multiple WaitForNames updates in the same step."); - this.names = new Set(waitForNames[0].__names); - return true; - } else if (this.names !== void 0) { - let updated = false; - for (const value of values) { - if (isWaitForNames(value)) throw new Error("Assertion Error: Received unexpected WaitForNames instance."); - if (this.names.has(value) && !this.seen.has(value)) { - this.seen.add(value); - updated = true; - } - } - return updated; - } - return false; - } - consume() { - if (this.seen && this.names && areSetsEqual(this.seen, this.names)) { - this.seen = /* @__PURE__ */ new Set(); - this.names = void 0; - return true; - } - return false; - } - get() { - if (!this.names || !areSetsEqual(this.names, this.seen)) throw new EmptyChannelError(); - return void 0; - } - checkpoint() { - return [this.names ? [...this.names] : void 0, [...this.seen]]; - } - isAvailable() { - return !!this.names && areSetsEqual(this.names, this.seen); - } -}; - -//#endregion - -//# sourceMappingURL=dynamic_barrier_value.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/channels/index.js - - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/web.js - - - - - - - - - - - - - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/writer.js - - -//#region src/writer.ts -function writer(chunk) { - const config = AsyncLocalStorageProviderSingleton.getRunnableConfig(); - if (!config) throw new Error("Called interrupt() outside the context of a graph."); - const conf = config.configurable; - if (!conf) throw new Error("No configurable found in config"); - return conf.writer?.(chunk); -} - -//#endregion - -//# sourceMappingURL=writer.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/langgraph/dist/index.js - - - - - - - - - - - - - - - - -//#region src/index.ts -initializeAsyncLocalStorageSingleton(); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./src/tools/pr-analysis-tools.ts -/** - * PR Analysis Tools for LangChain Agent - * These tools are used by the agent to analyze different aspects of PR changes - */ - - -/** - * Parse git diff into structured file changes - */ -function parseDiff(diff) { - const files = []; - const lines = diff.split('\n'); - let currentFile = null; - let currentDiff = []; - for (let i = 0; i < lines.length; i++) { - const line = lines[i]; - // New file detected - if (line.startsWith('diff --git')) { - // Save previous file - if (currentFile) { - files.push({ - ...currentFile, - diff: currentDiff.join('\n'), - }); - } - // Parse file path - const match = line.match(/^diff --git a\/(.+?) b\/(.+?)$/); - if (match) { - const filePath = match[2] !== '/dev/null' ? match[2] : match[1]; - currentFile = { - path: filePath, - additions: 0, - deletions: 0, - language: detectLanguage(filePath), - }; - currentDiff = [line]; - } - } - else if (line.startsWith('new file') && currentFile) { - currentFile.status = 'A'; - currentDiff.push(line); - } - else if (line.startsWith('deleted file') && currentFile) { - currentFile.status = 'D'; - currentDiff.push(line); - } - else if (line.startsWith('rename from') && currentFile) { - currentFile.status = 'R'; - const oldPath = line.replace('rename from ', '').trim(); - currentFile.oldPath = oldPath; - currentDiff.push(line); - } - else if (line.startsWith('+') && !line.startsWith('+++') && currentFile) { - currentFile.additions = (currentFile.additions || 0) + 1; - currentDiff.push(line); - } - else if (line.startsWith('-') && !line.startsWith('---') && currentFile) { - currentFile.deletions = (currentFile.deletions || 0) + 1; - currentDiff.push(line); - } - else if (currentFile) { - currentDiff.push(line); - } - } - // Save last file - if (currentFile) { - files.push({ - ...currentFile, - diff: currentDiff.join('\n'), - }); - } - return files; -} -/** - * Detect programming language from file extension - */ -function detectLanguage(filePath) { - const ext = filePath.split('.').pop()?.toLowerCase(); - const languageMap = { - ts: 'typescript', - tsx: 'typescript', - js: 'javascript', - jsx: 'javascript', - py: 'python', - java: 'java', - go: 'go', - rs: 'rust', - rb: 'ruby', - php: 'php', - cs: 'csharp', - cpp: 'cpp', - c: 'c', - swift: 'swift', - kt: 'kotlin', - yaml: 'yaml', - yml: 'yaml', - json: 'json', - md: 'markdown', - }; - return languageMap[ext || ''] || 'unknown'; -} -/** - * Create file analyzer tool - */ -function createFileAnalyzerTool() { - return new tools_DynamicStructuredTool({ - name: 'analyze_file', - description: 'Analyze a specific file from the diff to identify risks, complexity, and provide recommendations', - schema: object({ - filePath: schemas_string().describe('Path of the file to analyze'), - diffContent: schemas_string().describe('The diff content for this file'), - }), - func: async ({ filePath, diffContent }) => { - // Parse the diff to extract changes - const additions = (diffContent.match(/^\+[^+]/gm) || []).length; - const deletions = (diffContent.match(/^-[^-]/gm) || []).length; - const totalChanges = additions + deletions; - // Basic complexity scoring - let complexity = 1; - if (totalChanges > 100) - complexity = 4; - else if (totalChanges > 50) - complexity = 3; - else if (totalChanges > 20) - complexity = 2; - // Detect potential risks - const risks = []; - // Check for security-related patterns - if (/eval\(|exec\(|system\(/i.test(diffContent)) { - risks.push('Potentially dangerous function calls detected (eval, exec, system)'); - } - if (/password|secret|api[_-]?key|token/i.test(diffContent) && /['"]/i.test(diffContent)) { - risks.push('Possible hardcoded credentials or secrets'); - } - if (/TODO|FIXME|XXX|HACK/i.test(diffContent)) { - risks.push('Contains TODO/FIXME comments indicating incomplete work'); - } - if (totalChanges > 200) { - risks.push('Very large change set - difficult to review thoroughly'); - } - // Check for error handling - const hasTryCatch = /try\s*{|catch\s*\(/i.test(diffContent); - const hasThrow = /throw\s+/i.test(diffContent); - if (hasThrow && !hasTryCatch) { - risks.push('Throws errors without apparent error handling'); - } - return JSON.stringify({ - path: filePath, - additions, - deletions, - complexity, - risks, - language: detectLanguage(filePath), - }); - }, - }); -} -/** - * Create risk detector tool - */ -function createRiskDetectorTool() { - return new tools_DynamicStructuredTool({ - name: 'detect_risks', - description: 'Detect security, quality, and breaking change risks in the PR', - schema: object({ - diff: schemas_string().describe('The full diff to analyze for risks'), - context: schemas_string().optional().describe('Additional context about the changes'), - }), - func: async ({ diff, context }) => { - const risks = []; - // Security risks - if (/sql.*=.*\+|SQL.*=.*\+/i.test(diff)) { - risks.push({ - type: 'security', - severity: 'high', - description: 'Potential SQL injection - string concatenation in SQL queries', - }); - } - if (/innerHTML|dangerouslySetInnerHTML/i.test(diff)) { - risks.push({ - type: 'security', - severity: 'medium', - description: 'XSS risk - using innerHTML or dangerouslySetInnerHTML', - }); - } - // Breaking changes - if (/export\s+(interface|type|class|function)\s+\w+/i.test(diff) && /-.*export/i.test(diff)) { - risks.push({ - type: 'breaking', - severity: 'high', - description: 'Potential breaking change - modified or removed export', - }); - } - // Code quality - if ((diff.match(/console\.log/g) || []).length > 3) { - risks.push({ - type: 'quality', - severity: 'low', - description: 'Multiple console.log statements - consider using proper logging', - }); - } - // Performance - if (/for.*for|while.*while/i.test(diff) && /O\(n\^2\)/i.test(diff)) { - risks.push({ - type: 'performance', - severity: 'medium', - description: 'Nested loops detected - potential O(n²) complexity', - }); - } - return JSON.stringify({ - riskCount: risks.length, - risks, - context: context || 'No additional context provided', - }); - }, - }); -} -/** - * Create complexity scorer tool - */ -function createComplexityScorerTool() { - return new tools_DynamicStructuredTool({ - name: 'score_complexity', - description: 'Calculate overall complexity score for the PR (1-5 scale)', - schema: object({ - filesAnalyzed: array(any()).describe('Array of analyzed files'), - totalChanges: schemas_number().describe('Total lines changed'), - }), - func: async ({ filesAnalyzed, totalChanges }) => { - let score = 1; - // Factor 1: Total changes - if (totalChanges > 500) - score = Math.max(score, 5); - else if (totalChanges > 300) - score = Math.max(score, 4); - else if (totalChanges > 150) - score = Math.max(score, 3); - else if (totalChanges > 50) - score = Math.max(score, 2); - // Factor 2: Number of files - const fileCount = filesAnalyzed.length; - if (fileCount > 20) - score = Math.max(score, 5); - else if (fileCount > 10) - score = Math.max(score, 4); - else if (fileCount > 5) - score = Math.max(score, 3); - // Factor 3: File complexity average - const avgFileComplexity = filesAnalyzed.reduce((sum, f) => sum + (f.complexity || 1), 0) / Math.max(fileCount, 1); - if (avgFileComplexity >= 4) - score = Math.max(score, 5); - else if (avgFileComplexity >= 3) - score = Math.max(score, 4); - return JSON.stringify({ - overallComplexity: Math.min(score, 5), - factors: { - totalChanges, - fileCount, - avgFileComplexity: avgFileComplexity.toFixed(1), - }, - recommendation: score >= 4 - ? 'High complexity - consider breaking into smaller PRs' - : score >= 3 - ? 'Moderate complexity - ensure thorough testing' - : 'Low complexity - straightforward changes', - }); - }, - }); -} -/** - * Create summary generator tool - */ -function createSummaryGeneratorTool() { - return new tools_DynamicStructuredTool({ - name: 'generate_summary', - description: 'Generate a concise summary of PR changes', - schema: object({ - files: array(any()).describe('Array of changed files'), - title: schemas_string().optional().describe('PR title'), - }), - func: async ({ files, title }) => { - const filesByType = {}; - let totalAdditions = 0; - let totalDeletions = 0; - files.forEach((file) => { - const lang = file.language || 'other'; - filesByType[lang] = (filesByType[lang] || 0) + 1; - totalAdditions += file.additions || 0; - totalDeletions += file.deletions || 0; - }); - const mainLanguage = Object.entries(filesByType).sort((a, b) => b[1] - a[1])[0]?.[0] || 'unknown'; - return JSON.stringify({ - title: title || 'Untitled PR', - fileCount: files.length, - totalAdditions, - totalDeletions, - netChange: totalAdditions - totalDeletions, - mainLanguage, - filesByType, - summary: `Changes ${files.length} file(s) with ${totalAdditions} additions and ${totalDeletions} deletions. Primary language: ${mainLanguage}.`, - }); - }, - }); -} -/** - * Create code suggestion tool for fixing issues based on reviewer comments - */ -function createCodeSuggestionTool() { - return new DynamicStructuredTool({ - name: 'suggest_code_fix', - description: 'Generate a code fix suggestion based on a reviewer comment and the associated code snippet', - schema: z.object({ - reviewerComment: z.string().describe('The reviewer\'s comment describing the issue'), - codeSnippet: z.string().describe('The original code snippet to be fixed'), - filePath: z.string().describe('Path of the file containing the code'), - prTitle: z.string().optional().describe('PR title for context'), - prContext: z.string().optional().describe('Additional PR context (repo, branch, etc.)'), - }), - func: async ({ reviewerComment, codeSnippet, filePath, prTitle, prContext }) => { - // Build the fix prompt - const prompt = `You are an expert software engineer and code-fixer. You will take a reviewer comment and the associated code snippet and produce the corrected code snippet only. - -Context: -${prContext || '(no additional context)'} -- PR Title: ${prTitle || '(unknown)'} -- File: ${filePath} - -Reviewer comment: -${reviewerComment.trim()} - -Original code snippet: -\`\`\` -${codeSnippet} -\`\`\` - -Task: -1) Apply the reviewer's requested changes to the provided code snippet. -2) Output rules (MUST follow exactly): - - Return only the corrected code snippet (no explanations, no markdown fences, no extra text). - - If only a few lines changed you may return only the updated lines, but prefer returning the full corrected snippet when structural/context changes are required. - - Preserve original code style and indentation. - - If no changes are needed, reply with exactly: NO CHANGE - - Do not include filenames, metadata, or commentary. - -Produce the corrected code now.`; - return JSON.stringify({ - filePath, - originalCode: codeSnippet, - reviewerComment, - prompt, - status: 'ready', - message: 'Code suggestion prompt prepared. The agent will use this to generate the fix.', - }); - }, - }); -} - -// EXTERNAL MODULE: external "fs" -var external_fs_ = __nccwpck_require__(9896); -// EXTERNAL MODULE: external "path" -var external_path_ = __nccwpck_require__(6928); -;// CONCATENATED MODULE: ./src/utils/arch-docs-parser.ts -/** - * Arch-Docs Parser - * Parses .arch-docs markdown files for RAG system - */ - - -/** - * Check if .arch-docs folder exists - */ -function archDocsExists(repoPath = process.cwd()) { - const archDocsPath = external_path_.join(repoPath, '.arch-docs'); - return external_fs_.existsSync(archDocsPath) && external_fs_.statSync(archDocsPath).isDirectory(); -} -/** - * Get all markdown files from .arch-docs folder - */ -function getArchDocsFiles(repoPath = process.cwd()) { - const archDocsPath = external_path_.join(repoPath, '.arch-docs'); - if (!archDocsExists(repoPath)) { - return []; - } - try { - const files = external_fs_.readdirSync(archDocsPath); - return files - .filter(file => file.endsWith('.md')) - .map(file => external_path_.join(archDocsPath, file)); - } - catch (error) { - console.warn('Error reading .arch-docs folder:', error); - return []; - } -} -/** - * Parse a markdown file into structured sections - */ -function parseMarkdownFile(filePath) { - const content = external_fs_.readFileSync(filePath, 'utf-8'); - const filename = external_path_.basename(filePath, '.md'); - const lines = content.split('\n'); - const sections = []; - let currentSection; - let title = filename.charAt(0).toUpperCase() + filename.slice(1).replace(/-/g, ' '); - for (let index = 0; index < lines.length; index++) { - const line = lines[index]; - const headingMatch = line.match(/^(#{1,6})\s+(.+)$/); - if (headingMatch) { - // Save previous section - if (currentSection) { - currentSection.lineEnd = index - 1; - sections.push(currentSection); - } - // Extract title from first heading - if (sections.length === 0 && headingMatch[1].length === 1) { - title = headingMatch[2]; - } - // Start new section - currentSection = { - heading: headingMatch[2], - level: headingMatch[1].length, - content: '', - lineStart: index, - lineEnd: index, - }; - } - else if (currentSection) { - // Add content to current section - currentSection.content += line + '\n'; - } - } - // Save last section - if (currentSection) { - currentSection.lineEnd = lines.length - 1; - sections.push(currentSection); - } - return { - filename, - title, - content, - sections, - }; -} -/** - * Parse all arch-docs files - */ -function parseAllArchDocs(repoPath = process.cwd()) { - const files = getArchDocsFiles(repoPath); - return files.map(file => parseMarkdownFile(file)); -} -/** - * Search arch-docs by keyword (simple text search) - */ -function searchArchDocs(docs, query, maxResults = 5) { - const results = []; - const queryLower = query.toLowerCase(); - const queryWords = queryLower.split(/\s+/).filter(w => w.length > 2); - for (const doc of docs) { - for (const section of doc.sections) { - const sectionText = (section.heading + ' ' + section.content).toLowerCase(); - // Calculate relevance score - let relevance = 0; - // Exact phrase match - if (sectionText.includes(queryLower)) { - relevance += 10; - } - // Word matches - for (const word of queryWords) { - const matches = (sectionText.match(new RegExp(word, 'g')) || []).length; - relevance += matches * 2; - } - // Heading match bonus - if (section.heading.toLowerCase().includes(queryLower)) { - relevance += 5; - } - if (relevance > 0) { - results.push({ doc, section, relevance }); - } - } - } - // Sort by relevance and return top results - return results - .sort((a, b) => b.relevance - a.relevance) - .slice(0, maxResults); -} -/** - * Get specific arch-docs by filename - */ -function getArchDocByFilename(docs, filename) { - return docs.find(doc => doc.filename === filename); -} -/** - * Get arch-docs summary (index.md content if available) - */ -function getArchDocsSummary(docs) { - const indexDoc = getArchDocByFilename(docs, 'index'); - if (indexDoc) { - return indexDoc.content; - } - // Fallback: create summary from available docs - const fileList = docs.map(doc => `- ${doc.title} (${doc.filename}.md)`).join('\n'); - return `Available Architecture Documentation:\n\n${fileList}`; -} - -;// CONCATENATED MODULE: ./src/utils/arch-docs-rag.ts -/** - * Arch-Docs RAG System - * Retrieval Augmented Generation for architecture documentation - */ - -/** - * Build context from arch-docs based on PR analysis needs - */ -function buildArchDocsContext(docs, prContext) { - if (docs.length === 0) { - return { - available: false, - summary: '', - relevantDocs: [], - totalDocs: 0, - }; - } - // Extract keywords from PR context - const keywords = extractKeywords(prContext); - // Search for relevant sections - const relevantResults = new Map(); - // Search for each keyword and aggregate results - for (const keyword of keywords) { - const results = searchArchDocs(docs, keyword, 3); - for (const result of results) { - const key = `${result.doc.filename}:${result.section.heading}`; - const existing = relevantResults.get(key); - if (!existing || result.relevance > existing.relevance) { - relevantResults.set(key, result); - } - } - } - // Also always include key documents - const keyDocs = ['architecture', 'patterns', 'file-structure', 'security']; - for (const keyDoc of keyDocs) { - const doc = docs.find(d => d.filename === keyDoc); - if (doc && doc.sections.length > 0) { - const key = `${doc.filename}:${doc.sections[0].heading}`; - if (!relevantResults.has(key)) { - relevantResults.set(key, { - doc, - section: doc.sections[0], - relevance: 3, // Base relevance for key docs - }); - } - } - } - // Convert to array and sort by relevance - const sortedResults = Array.from(relevantResults.values()) - .sort((a, b) => b.relevance - a.relevance) - .slice(0, 10); // Top 10 most relevant sections - // Build context - const relevantDocs = sortedResults.map(result => ({ - filename: result.doc.filename, - title: result.doc.title, - section: result.section.heading, - content: result.section.content.trim(), - relevance: result.relevance, - })); - // Build summary - const summary = buildContextSummary(docs, relevantDocs); - return { - available: true, - summary, - relevantDocs, - totalDocs: docs.length, - }; -} -/** - * Extract keywords from PR context for semantic search - */ -function extractKeywords(prContext) { - const keywords = new Set(); - // From title - if (prContext.title) { - const titleWords = prContext.title - .toLowerCase() - .split(/\s+/) - .filter(w => w.length > 3 && !isCommonWord(w)); - titleWords.forEach(w => keywords.add(w)); - } - // From file paths - for (const file of prContext.files) { - const pathParts = file.path.split(/[\/\-_\.]/); - for (const part of pathParts) { - if (part.length > 3 && !isCommonWord(part.toLowerCase())) { - keywords.add(part.toLowerCase()); - } - } - // Extract from file extensions and directories - if (file.path.includes('test')) - keywords.add('testing'); - if (file.path.includes('api')) - keywords.add('api'); - if (file.path.includes('auth')) - keywords.add('authentication'); - if (file.path.includes('db') || file.path.includes('database')) - keywords.add('database'); - if (file.path.includes('security')) - keywords.add('security'); - if (file.path.includes('schema')) - keywords.add('schema'); - if (file.path.includes('config')) - keywords.add('configuration'); - if (file.path.includes('migration')) - keywords.add('migration'); - } - // From diff content (look for imports, function names, etc.) - if (prContext.diff) { - // Extract import statements - const importMatches = prContext.diff.matchAll(/import\s+.*?\s+from\s+['"]([^'"]+)['"]/g); - for (const match of importMatches) { - const importPath = match[1]; - const parts = importPath.split(/[\/\-_]/); - for (const part of parts) { - if (part.length > 3 && !isCommonWord(part)) { - keywords.add(part); - } - } - } - // Extract class and function names - const classMatches = prContext.diff.matchAll(/class\s+(\w+)/g); - for (const match of classMatches) { - keywords.add(match[1].toLowerCase()); - } - const functionMatches = prContext.diff.matchAll(/function\s+(\w+)/g); - for (const match of functionMatches) { - if (match[1].length > 3) { - keywords.add(match[1].toLowerCase()); - } - } - } - return Array.from(keywords).slice(0, 20); // Limit to top 20 keywords -} -/** - * Check if a word is too common to be useful - */ -function isCommonWord(word) { - const commonWords = new Set([ - 'the', 'and', 'for', 'that', 'this', 'with', 'from', 'have', 'been', - 'will', 'your', 'more', 'when', 'some', 'them', 'than', 'into', 'only', - 'other', 'then', 'also', 'make', 'made', 'like', 'time', 'very', 'just', - 'file', 'code', 'test', 'docs', 'info', 'data', 'type', 'name', 'index', - ]); - return commonWords.has(word); -} -/** - * Build a summary of the context - */ -function buildContextSummary(docs, relevantDocs) { - const docTitles = docs.map(d => d.title).join(', '); - const relevantCount = relevantDocs.length; - let summary = `Architecture Documentation Context:\n`; - summary += `- Total documents: ${docs.length}\n`; - summary += `- Available: ${docTitles}\n`; - summary += `- Relevant sections retrieved: ${relevantCount}\n\n`; - if (relevantCount > 0) { - summary += `Most relevant sections:\n`; - relevantDocs.slice(0, 5).forEach((doc, i) => { - summary += `${i + 1}. ${doc.title} - ${doc.section} (relevance: ${doc.relevance})\n`; - }); - } - return summary; -} -/** - * Format arch-docs context for inclusion in prompts - */ -function formatArchDocsForPrompt(context) { - if (!context.available || context.relevantDocs.length === 0) { - return ''; - } - let prompt = '\n## Repository Architecture Context\n\n'; - prompt += 'The following sections from the architecture documentation are relevant to this PR:\n\n'; - for (const doc of context.relevantDocs) { - prompt += `### ${doc.title} - ${doc.section}\n\n`; - prompt += doc.content + '\n\n'; - prompt += '---\n\n'; - } - return prompt; -} -/** - * Get specific context for risk analysis - */ -function getSecurityContext(docs) { - const securityDoc = docs.find(d => d.filename === 'security'); - if (securityDoc) { - return securityDoc.content; - } - return ''; -} -/** - * Get specific context for architecture understanding - */ -function getArchitectureContext(docs) { - const archDoc = docs.find(d => d.filename === 'architecture'); - if (archDoc) { - return archDoc.content; - } - return ''; -} -/** - * Get specific context for patterns - */ -function getPatternsContext(docs) { - const patternsDoc = docs.find(d => d.filename === 'patterns'); - if (patternsDoc) { - return patternsDoc.content; - } - return ''; -} - -;// CONCATENATED MODULE: ./src/agents/base-pr-agent-workflow.ts -/** - * Base PR Agent Workflow using LangGraph - * Follows architecture-doc-generator patterns with self-refinement - */ - - - - - -/** - * Agent workflow state - */ -const PRAgentState = Annotation.Root({ - // Input context - context: Annotation({ - reducer: (_, update) => update, - }), - // Current iteration - iteration: Annotation({ - reducer: (_, update) => update, - default: () => 0, - }), - // File analyses - fileAnalyses: Annotation({ - reducer: (_, update) => update, - default: () => new Map(), - }), - // Current analysis state - currentSummary: Annotation({ - reducer: (_, update) => update, - default: () => '', - }), - currentRisks: Annotation({ - reducer: (_, update) => update, - default: () => [], - }), - currentComplexity: Annotation({ - reducer: (_, update) => update, - default: () => 1, - }), - // Quality metrics - clarityScore: Annotation({ - reducer: (_, update) => update, - default: () => 0, - }), - missingInformation: Annotation({ - reducer: (_, update) => update, - default: () => [], - }), - // Recommendations - recommendations: Annotation({ - reducer: (_, update) => update, - default: () => [], - }), - // Insights and reasoning - insights: Annotation({ - reducer: (current, update) => [...current, ...update], - default: () => [], - }), - reasoning: Annotation({ - reducer: (current, update) => [...current, ...update], - default: () => [], - }), - // Arch-docs tracking - archDocsInfluencedStages: Annotation({ - reducer: (current, update) => [...current, ...update], - default: () => [], - }), - archDocsKeyInsights: Annotation({ - reducer: (current, update) => [...current, ...update], - default: () => [], - }), - // Token tracking - totalInputTokens: Annotation({ - reducer: (current, update) => current + update, - default: () => 0, - }), - totalOutputTokens: Annotation({ - reducer: (current, update) => current + update, - default: () => 0, - }), -}); -/** - * Base class for PR agents with self-refinement workflow - */ -class BasePRAgentWorkflow { - model; - workflow; - checkpointer = new MemorySaver(); - tools; - constructor(model) { - this.model = model; - // Initialize tools - this.tools = [ - createFileAnalyzerTool(), - createRiskDetectorTool(), - createComplexityScorerTool(), - createSummaryGeneratorTool(), - ]; - this.workflow = this.buildWorkflow(); - } - /** - * Build the PR analysis workflow - */ - buildWorkflow() { - const graph = new StateGraph(PRAgentState); - // Define nodes - graph.addNode('analyzeFiles', this.analyzeFilesNode.bind(this)); - graph.addNode('detectRisks', this.detectRisksNode.bind(this)); - graph.addNode('calculateComplexity', this.calculateComplexityNode.bind(this)); - graph.addNode('generateSummary', this.generateSummaryNode.bind(this)); - graph.addNode('evaluateQuality', this.evaluateQualityNode.bind(this)); - graph.addNode('refineAnalysis', this.refineAnalysisNode.bind(this)); - graph.addNode('finalize', this.finalizeNode.bind(this)); - // Set entry point - const entryPoint = 'analyzeFiles'; - graph.setEntryPoint(entryPoint); - // Build workflow graph - graph.addEdge(entryPoint, 'detectRisks'); - graph.addEdge('detectRisks', 'calculateComplexity'); - graph.addEdge('calculateComplexity', 'generateSummary'); - graph.addEdge('generateSummary', 'evaluateQuality'); - // Conditional: refine or finalize - graph.addConditionalEdges('evaluateQuality', this.shouldRefine.bind(this), { - refine: 'refineAnalysis', - finalize: 'finalize', - }); - // After refinement, evaluate again - graph.addEdge('refineAnalysis', 'evaluateQuality'); - // End after finalization - graph.addEdge('finalize', END); - return graph.compile({ checkpointer: this.checkpointer }); - } - /** - * Execute the agent workflow - */ - async execute(context, options) { - const startTime = Date.now(); - // Fast path: skip self-refinement - if (options?.skipSelfRefinement) { - return this.executeFastPath(context, startTime); - } - const config = { - maxIterations: 3, - clarityThreshold: 80, - skipSelfRefinement: false, - }; - const initialState = { - context, - iteration: 0, - fileAnalyses: new Map(), - currentSummary: '', - currentRisks: [], - currentComplexity: 1, - clarityScore: 0, - missingInformation: [], - recommendations: [], - insights: [], - reasoning: [], - totalInputTokens: 0, - totalOutputTokens: 0, - }; - const workflowConfig = { - configurable: { - thread_id: `pr-agent-${Date.now()}`, - maxIterations: config.maxIterations, - clarityThreshold: config.clarityThreshold, - }, - recursionLimit: 50, - }; - let finalState = initialState; - let totalInputTokens = 0; - let totalOutputTokens = 0; - // Execute workflow - stream returns state updates - try { - for await (const state of await this.workflow.stream(initialState, workflowConfig)) { - // Get the last node's state - const nodeNames = Object.keys(state); - if (nodeNames.length > 0) { - const lastNodeName = nodeNames[nodeNames.length - 1]; - finalState = state[lastNodeName] || finalState; - // Extract token counts if present - const stateAny = finalState; - if (stateAny.totalInputTokens !== undefined) { - totalInputTokens = stateAny.totalInputTokens; - } - if (stateAny.totalOutputTokens !== undefined) { - totalOutputTokens = stateAny.totalOutputTokens; - } - } - } - } - catch (error) { - console.error('Workflow execution error:', error); - throw error; - } - const executionTime = Date.now() - startTime; - // Build arch-docs impact summary with deduplication - const stateAny = finalState; - const archDocsImpact = context.archDocs?.available ? { - used: true, - docsAvailable: context.archDocs.totalDocs, - sectionsUsed: context.archDocs.relevantDocs.length, - influencedStages: [...new Set(stateAny.archDocsInfluencedStages || [])], - keyInsights: [...new Set(stateAny.archDocsKeyInsights || [])], - } : undefined; - return { - summary: finalState.currentSummary, - fileAnalyses: finalState.fileAnalyses, - overallComplexity: finalState.currentComplexity, - overallRisks: finalState.currentRisks, - recommendations: finalState.recommendations, - insights: finalState.insights, - reasoning: finalState.reasoning, - provider: 'ai', - model: this.model.modelName || 'unknown', - totalTokensUsed: totalInputTokens + totalOutputTokens, - executionTime, - mode: context.mode, - archDocsImpact, - }; - } - /** - * Fast path execution - skip refinement loop but still use LLM for detailed analysis - */ - async executeFastPath(context, startTime) { - // Initialize state - const initialState = { - context, - iteration: 0, - fileAnalyses: new Map(), - currentSummary: '', - currentRisks: [], - currentComplexity: 1, - clarityScore: 0, - missingInformation: [], - recommendations: [], - insights: [], - reasoning: [], - totalInputTokens: 0, - totalOutputTokens: 0, - }; - // Execute workflow nodes sequentially (skip refinement loop) - let state = initialState; - try { - // 1. Analyze files - state = await this.analyzeFilesNode(state); - // 2. Detect risks - state = await this.detectRisksNode(state); - // 3. Calculate complexity - state = await this.calculateComplexityNode(state); - // 4. Generate summary - state = await this.generateSummaryNode(state); - // 5. Generate recommendations (skip quality evaluation) - state = await this.refineAnalysisNode(state); - // 6. Finalize - state = await this.finalizeNode(state); - const executionTime = Date.now() - startTime; - // Build arch-docs impact summary with deduplication - const stateAny = state; - const archDocsImpact = context.archDocs?.available ? { - used: true, - docsAvailable: context.archDocs.totalDocs, - sectionsUsed: context.archDocs.relevantDocs.length, - influencedStages: [...new Set(stateAny.archDocsInfluencedStages || [])], - keyInsights: [...new Set(stateAny.archDocsKeyInsights || [])], - } : undefined; - return { - summary: state.currentSummary, - fileAnalyses: state.fileAnalyses, - overallComplexity: state.currentComplexity, - overallRisks: state.currentRisks, - recommendations: state.recommendations, - insights: state.insights, - reasoning: [...state.reasoning, 'Fast path: Self-refinement evaluation skipped for speed'], - provider: 'ai', - model: this.model.modelName || 'unknown', - totalTokensUsed: state.totalInputTokens + state.totalOutputTokens, - executionTime, - mode: context.mode, - archDocsImpact, - }; - } - catch (error) { - console.error('Fast path execution error:', error); - throw error; - } - } - // Workflow nodes - async analyzeFilesNode(state) { - const { context } = state; - const files = parseDiff(context.diff); - console.log(`🔍 Analyzing ${files.length} files...`); - // Show arch-docs status if available - if (context.archDocs?.available) { - console.log(`📚 Using architecture documentation (${context.archDocs.totalDocs} docs, ${context.archDocs.relevantDocs.length} relevant sections)`); - } - const fileAnalyses = new Map(); - // Build arch-docs context if available - let archDocsContext = ''; - if (context.archDocs?.available) { - archDocsContext = formatArchDocsForPrompt(context.archDocs); - } - // Analyze files in batches for detailed insights - const filesToAnalyze = files.slice(0, 15); // Limit to 15 files for detailed analysis - const importantFiles = filesToAnalyze.filter(f => f.additions + f.deletions > 20 || // Significant changes - f.path.includes('config') || - f.path.includes('schema') || - f.path.includes('migration') || - f.path.includes('test')).slice(0, 5); // Top 5 important files - // Get detailed analysis for important files - if (importantFiles.length > 0) { - try { - const fileDetailsPrompt = `Analyze these files from a pull request. For EACH file, provide a detailed analysis considering the repository's architecture standards. -${archDocsContext ? '\n' + archDocsContext : ''} - -Files to analyze: -${importantFiles.map(f => ` -File: ${f.path} -Status: ${f.status || 'modified'} -Changes: +${f.additions} -${f.deletions} -Diff preview: -\`\`\` -${f.diff.substring(0, 500)} -\`\`\` -`).join('\n---\n')} - -${archDocsContext ? `CRITICAL INSTRUCTIONS: -- For EACH file, reference the relevant architecture documentation sections above -- Explain how the changes align with or diverge from established patterns -- Identify specific guidelines that apply to each file -- Mention which parts of the architecture are affected -- Compare changes against documented standards - -` : ''} - -Respond with a JSON object mapping file paths to analysis objects: -{ - "path/to/file": { - "summary": "Description that references relevant arch-docs patterns/guidelines", - "risks": ["risk with arch-docs context", "risk2"], - "complexity": 1-5, - "recommendations": ["recommendation based on arch-docs standards"] - } -} - -${archDocsContext ? 'Each summary MUST reference the specific architecture documentation that applies to this file.' : ''}`; - const response = await this.model.invoke(fileDetailsPrompt); - const content = response.content; - // Track tokens - const usage = response.response_metadata?.usage; - const inputTokens = usage?.input_tokens || 0; - const outputTokens = usage?.output_tokens || 0; - // Parse detailed file analyses - try { - const jsonMatch = content.match(/\{[\s\S]*\}/); - if (jsonMatch) { - const detailedAnalyses = JSON.parse(jsonMatch[0]); - // Apply detailed analysis to file analyses - for (const file of importantFiles) { - const detail = detailedAnalyses[file.path]; - if (detail) { - fileAnalyses.set(file.path, { - path: file.path, - summary: detail.summary || `${file.status || 'M'}: +${file.additions} -${file.deletions}`, - risks: Array.isArray(detail.risks) ? detail.risks : [], - complexity: detail.complexity || Math.min(5, Math.floor((file.additions + file.deletions) / 50) + 1), - changes: { - additions: file.additions, - deletions: file.deletions, - }, - recommendations: Array.isArray(detail.recommendations) ? detail.recommendations : [], - }); - } - } - } - } - catch (parseError) { - console.warn('Failed to parse file analysis JSON, using basic analysis'); - } - // Update state with token tracking - state = { - ...state, - totalInputTokens: (state.totalInputTokens || 0) + inputTokens, - totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens, - }; - } - catch (error) { - console.warn('Error in detailed file analysis, falling back to basic:', error); - } - } - // Add basic analysis for remaining files - for (const file of filesToAnalyze) { - if (!fileAnalyses.has(file.path)) { - const analysis = { - path: file.path, - summary: `${file.status || 'M'}: +${file.additions} -${file.deletions}`, - risks: [], - complexity: Math.min(5, Math.floor((file.additions + file.deletions) / 50) + 1), - changes: { - additions: file.additions, - deletions: file.deletions, - }, - recommendations: [], - }; - fileAnalyses.set(file.path, analysis); - } - } - // Track arch-docs usage - const newInsights = [`Analyzed ${files.length} files (${importantFiles.length} in detail)`]; - const hasArchDocsContext = archDocsContext && archDocsContext.length > 0; - const archDocsStages = hasArchDocsContext ? ['file-analysis'] : []; - const archDocsInsights = []; - if (hasArchDocsContext && context.archDocs?.available) { - archDocsInsights.push(`Applied ${context.archDocs.relevantDocs.length} architecture documentation sections to analyze files in context of repository standards`); - } - return { - ...state, - fileAnalyses, - insights: newInsights, - archDocsInfluencedStages: archDocsStages, - archDocsKeyInsights: archDocsInsights, - }; - } - async detectRisksNode(state) { - const { context, fileAnalyses } = state; - console.log('⚠️ Detecting risks...'); - // Build context for risk analysis - const fileList = Array.from(fileAnalyses.entries()) - .slice(0, 15) - .map(([path, analysis]) => `${path} (+${analysis.changes.additions} -${analysis.changes.deletions})`) - .join('\n'); - // Get a sample of the diff for risk analysis (limit size) - const diffSample = context.diff.substring(0, 8000); // First 8KB for context - // Add security context from arch-docs if available - let securityContext = ''; - let allDocs = []; - let securityDoc = null; - let patternsDoc = null; - if (context.archDocs?.available) { - allDocs = parseAllArchDocs(); - const secDoc = getSecurityContext(allDocs); - if (secDoc) { - securityContext = `\n## Security Guidelines from Repository Documentation\n\n${secDoc.substring(0, 3000)}\n`; - securityDoc = allDocs.find(d => d.filename === 'security'); - } - // Also get patterns that might indicate risks - const patterns = getPatternsContext(allDocs); - if (patterns) { - securityContext += `\n## Repository Patterns and Best Practices\n\n${patterns.substring(0, 2000)}\n`; - patternsDoc = allDocs.find(d => d.filename === 'patterns'); - } - } - const riskPrompt = `You are a security and code quality expert analyzing a pull request for potential risks. -${securityContext} - -Analyze the following changes and identify SPECIFIC risks in these categories: -1. **Security Risks**: Exposed credentials, insecure patterns, authentication/authorization issues -2. **Breaking Changes**: API changes, database schema changes, removed functionality -3. **Performance Concerns**: Inefficient algorithms, memory leaks, N+1 queries -4. **Code Quality**: Complex logic, missing error handling, lack of tests -5. **Operational Risks**: Configuration changes, deployment concerns, dependency updates - -PR Title: ${context.title || 'No title provided'} - -Files changed: -${fileList} - -Diff sample: -\`\`\` -${diffSample} -\`\`\` - -${securityContext ? `CRITICAL INSTRUCTIONS: -- You MUST reference the repository documentation guidelines above when identifying each risk -- For EVERY risk you identify, find the relevant guideline from the documentation -- Explain HOW the code change violates or conflicts with the documented standards -- Quote the specific guideline that makes this a risk -- Be specific about why this matters based on the repository's own standards - -Example format for a risk with documentation: -{ - "description": "File exceeds maximum line count recommended for maintainability", - "archDocsSource": "code-quality.md", - "archDocsExcerpt": "Keep individual files under 500 lines to maintain testability and readability", - "reason": "This file contains 990 lines, nearly 2x the repository standard, which increases maintenance burden and makes comprehensive testing more difficult" -} -` : ''} - -Provide a JSON array of risk objects. Each risk MUST include: -- description: Clear, specific description of the risk -${securityContext ? `- archDocsSource: REQUIRED - Which documentation file from above this relates to (e.g., "security.md", "patterns.md", "code-quality.md") -- archDocsExcerpt: REQUIRED - Direct quote from the repository documentation that this violates -- reason: REQUIRED - Detailed explanation of why this is a risk based on the specific guideline quoted above -` : ''} - -Format: -${securityContext ? `[ - { - "description": "Specific risk description", - "archDocsSource": "documentation-file.md", - "archDocsExcerpt": "Exact quote from the documentation", - "reason": "Detailed explanation connecting the code change to the guideline violation" - } -] - -DO NOT return simple string arrays. Each risk MUST be an object with archDocsSource, archDocsExcerpt, and reason fields.` : '["risk 1", "risk 2", ...]'} - -Only include risks that are actually present. If no significant risks, return an empty array [].`; - try { - const response = await this.model.invoke(riskPrompt); - const content = response.content; - // Track tokens - const usage = response.response_metadata?.usage; - const inputTokens = usage?.input_tokens || 0; - const outputTokens = usage?.output_tokens || 0; - // Parse JSON response - let risks = []; - let hasArchDocsEnhancement = false; - try { - // Extract JSON from markdown code blocks if present - const jsonMatch = content.match(/\[[\s\S]*\]/); - if (jsonMatch) { - const parsedRisks = JSON.parse(jsonMatch[0]); - // Check if risks have arch-docs references - if (parsedRisks.length > 0 && typeof parsedRisks[0] === 'object' && 'archDocsSource' in parsedRisks[0]) { - // Transform to our RiskItem format - risks = parsedRisks.map((r) => ({ - description: r.description, - archDocsReference: r.archDocsSource ? { - source: r.archDocsSource, - excerpt: r.archDocsExcerpt || '', - reason: r.reason || '', - } : undefined, - })); - hasArchDocsEnhancement = true; - } - else if (parsedRisks.length > 0 && typeof parsedRisks[0] === 'string') { - // Legacy format - just strings - risks = parsedRisks; - } - else { - risks = parsedRisks; - } - } - } - catch (parseError) { - console.warn('Failed to parse risk JSON, extracting manually'); - // Fallback: extract bullet points as strings - const lines = content.split('\n'); - risks = lines - .filter(line => line.trim().startsWith('-') || line.trim().startsWith('•')) - .map(line => line.replace(/^[-•]\s*/, '').trim()) - .filter(line => line.length > 0); - } - // Add basic pattern-based checks with arch-docs enhancement - const patternRisks = []; - if (context.diff.includes('password') || context.diff.includes('secret') || context.diff.includes('api_key')) { - const riskDesc = 'Potential credentials or sensitive data in code changes'; - if (securityDoc) { - // Always enhance with arch-docs if available - patternRisks.push({ - description: riskDesc, - archDocsReference: { - source: 'security.md', - excerpt: 'Never commit credentials, API keys, or secrets to the repository. Use environment variables for all sensitive configuration.', - reason: 'Code changes contain keywords like "password", "secret", or "api_key" which may indicate hardcoded credentials. This violates the repository security policy requiring all secrets to be externalized via environment variables.', - }, - }); - } - else { - patternRisks.push(riskDesc); - } - } - if (fileAnalyses.size > 20) { - const qualityDoc = allDocs.find(d => d.filename === 'code-quality'); - if (qualityDoc && securityContext) { - patternRisks.push({ - description: `Large change set (${fileAnalyses.size} files) increases review complexity and error risk`, - archDocsReference: { - source: 'code-quality.md', - excerpt: 'Keep pull requests focused and under 15 files when possible for thorough review', - reason: `This PR modifies ${fileAnalyses.size} files, exceeding the recommended limit. Large PRs are harder to review thoroughly and increase the likelihood of missing critical issues.`, - }, - }); - } - else { - patternRisks.push(`Large change set (${fileAnalyses.size} files) - may be difficult to review thoroughly`); - } - } - if (context.diff.includes('DROP TABLE') || context.diff.includes('ALTER TABLE')) { - if (securityContext) { - patternRisks.push({ - description: 'Database schema changes detected - requires careful migration planning', - archDocsReference: { - source: 'patterns.md', - excerpt: 'All database schema changes must be backwards-compatible and include rollback procedures', - reason: 'The changes include database schema modifications (DROP TABLE or ALTER TABLE) which can cause data loss or application downtime if not properly planned and tested.', - }, - }); - } - else { - patternRisks.push('Database schema changes detected - requires careful migration planning'); - } - } - // Merge risks, avoiding duplicates (for string risks) - let allRisks; - if (hasArchDocsEnhancement) { - // Keep structured risks - allRisks = [...risks, ...patternRisks]; - } - else { - // Deduplicate string risks - allRisks = [...new Set([...risks, ...patternRisks])]; - } - // Track arch-docs usage in risk detection - const archDocsStages = securityContext ? ['risk-detection'] : []; - const archDocsInsights = []; - if (securityContext && context.archDocs?.available) { - const enhancedCount = allRisks.filter(r => typeof r === 'object' && r.archDocsReference).length; - if (enhancedCount > 0) { - archDocsInsights.push(`Linked ${enhancedCount} risks to specific repository security guidelines and best practices`); - } - } - return { - ...state, - currentRisks: allRisks, - insights: [`Identified ${allRisks.length} potential risks`], - totalInputTokens: (state.totalInputTokens || 0) + inputTokens, - totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens, - archDocsInfluencedStages: archDocsStages, - archDocsKeyInsights: archDocsInsights, - }; - } - catch (error) { - console.error('Error in risk detection:', error); - // Fallback to basic pattern matching - const basicRisks = []; - if (context.diff.includes('password') || context.diff.includes('secret')) { - basicRisks.push('Potential credentials in diff'); - } - if (fileAnalyses.size > 15) { - basicRisks.push('Large change set - difficult to review'); - } - return { - ...state, - currentRisks: basicRisks, - insights: [`Identified ${basicRisks.length} potential risks (basic analysis)`], - }; - } - } - async calculateComplexityNode(state) { - const { fileAnalyses, context } = state; - console.log('📊 Calculating complexity...'); - const complexities = Array.from(fileAnalyses.values()).map(f => f.complexity); - const avgComplexity = complexities.length > 0 - ? complexities.reduce((a, b) => a + b, 0) / complexities.length - : 1; - // Track arch-docs influence on complexity - const archDocsStages = context.archDocs?.available ? ['complexity-calculation'] : []; - const archDocsInsights = []; - if (context.archDocs?.available) { - // Check if patterns documentation helped understand complexity - const allDocs = parseAllArchDocs(); - const patterns = getPatternsContext(allDocs); - if (patterns) { - archDocsInsights.push(`Evaluated complexity against repository design patterns and coding standards`); - } - } - return { - ...state, - currentComplexity: Math.round(avgComplexity), - archDocsInfluencedStages: archDocsStages, - archDocsKeyInsights: archDocsInsights, - }; - } - async generateSummaryNode(state) { - const { context, fileAnalyses, currentRisks, currentComplexity } = state; - console.log('📝 Generating detailed summary...'); - const totalFiles = fileAnalyses.size; - const totalAdditions = Array.from(fileAnalyses.values()).reduce((sum, f) => sum + f.changes.additions, 0); - const totalDeletions = Array.from(fileAnalyses.values()).reduce((sum, f) => sum + f.changes.deletions, 0); - // Build file list with changes - const fileList = Array.from(fileAnalyses.entries()) - .slice(0, 20) - .map(([path, analysis]) => `- ${path}: +${analysis.changes.additions} -${analysis.changes.deletions} (complexity: ${analysis.complexity}/5)`) - .join('\n'); - // Add patterns context from arch-docs if available - let patternsContext = ''; - if (context.archDocs?.available) { - const allDocs = parseAllArchDocs(); - const patterns = getPatternsContext(allDocs); - if (patterns) { - patternsContext = `\n## Design Patterns from Repository Documentation\n\n${patterns.substring(0, 2000)}\n`; - } - } - // Create comprehensive prompt for LLM - const summaryPrompt = `You are analyzing a pull request. Provide a DETAILED and COMPREHENSIVE summary that covers: - -1. **Overall Purpose**: What is this PR trying to accomplish? What problem does it solve? -2. **Key Changes**: What are the main changes being made? Group related changes together. -3. **Impact Analysis**: What parts of the system are affected? What are the implications? -4. **Technical Details**: Mention important technical aspects (new dependencies, API changes, data model changes, etc.) -5. **Patterns Observed**: Any design patterns, refactoring, or architectural changes? -${patternsContext} - -PR Title: ${context.title || 'No title provided'} - -Statistics: -- Files changed: ${totalFiles} -- Lines added: ${totalAdditions} -- Lines deleted: ${totalDeletions} -- Overall complexity: ${currentComplexity}/5 -- Risks identified: ${currentRisks.length} - -Files changed: -${fileList} - -${currentRisks.length > 0 ? `\nRisks detected:\n${currentRisks.map(r => `- ${r}`).join('\n')}` : ''} - -${patternsContext ? 'Consider the design patterns and architecture from the repository documentation when analyzing the changes.\n' : ''} - -Provide a detailed, well-structured summary (3-5 paragraphs) that would help a reviewer understand the scope and purpose of this PR.`; - try { - const response = await this.model.invoke(summaryPrompt); - const detailedSummary = response.content; - // Track token usage - const usage = response.response_metadata?.usage; - const inputTokens = usage?.input_tokens || 0; - const outputTokens = usage?.output_tokens || 0; - // Track arch-docs usage in summary - const archDocsStages = patternsContext ? ['summary-generation'] : []; - const archDocsInsights = []; - if (patternsContext && context.archDocs?.available) { - archDocsInsights.push(`Generated summary aligned with repository architecture and established patterns`); - } - return { - ...state, - currentSummary: detailedSummary, - totalInputTokens: inputTokens, - totalOutputTokens: outputTokens, - archDocsInfluencedStages: archDocsStages, - archDocsKeyInsights: archDocsInsights, - }; - } - catch (error) { - console.error('Error generating summary:', error); - // Fallback to basic summary - const fallbackSummary = `PR Analysis Summary: -- Files changed: ${totalFiles} -- Additions: ${totalAdditions} -- Deletions: ${totalDeletions} -- Overall complexity: ${currentComplexity}/5 -- Risks identified: ${currentRisks.length} - -${context.title ? `Title: ${context.title}` : ''}`; - return { - ...state, - currentSummary: fallbackSummary, - }; - } - } - async evaluateQualityNode(state) { - const { iteration } = state; - console.log(`🔍 Evaluating quality (iteration ${iteration + 1})...`); - // Simple quality check - const clarityScore = 85; // Placeholder - return { - ...state, - clarityScore, - iteration: iteration + 1, - }; - } - async refineAnalysisNode(state) { - const { currentSummary, currentRisks, fileAnalyses, context } = state; - console.log('🔄 Refining analysis...'); - // Build arch-docs context for refinement - let archDocsRefinementContext = ''; - if (context.archDocs?.available) { - const allDocs = parseAllArchDocs(); - // Get recommendations from arch-docs - const recommendationsDoc = allDocs.find(d => d.filename === 'recommendations'); - if (recommendationsDoc) { - archDocsRefinementContext += `\n## Repository Improvement Guidelines\n\n${recommendationsDoc.content.substring(0, 2000)}\n`; - } - // Get code quality guidelines - const qualityDoc = allDocs.find(d => d.filename === 'code-quality'); - if (qualityDoc) { - archDocsRefinementContext += `\n## Code Quality Standards\n\n${qualityDoc.content.substring(0, 2000)}\n`; - } - // Get KPI metrics - const kpiDoc = allDocs.find(d => d.filename === 'kpi'); - if (kpiDoc) { - archDocsRefinementContext += `\n## Repository Health KPIs\n\n${kpiDoc.content.substring(0, 1500)}\n`; - } - } - // Generate comprehensive recommendations - const refinementPrompt = `Based on this PR analysis, provide specific, actionable recommendations for the developer and reviewers. -${archDocsRefinementContext} - -PR Summary: -${currentSummary} - -Risks Identified: -${currentRisks.map(r => `- ${r}`).join('\n')} - -Files Changed: ${fileAnalyses.size} - -Consider: -1. Code organization and structure improvements -2. Testing recommendations -3. Documentation needs -4. Performance optimizations -5. Security enhancements -6. Review process suggestions -${archDocsRefinementContext ? '7. Alignment with repository standards and KPIs from arch-docs\n' : ''} - -${archDocsRefinementContext ? 'Use the repository guidelines and standards above to ensure recommendations align with established practices.\n' : ''} - -Provide a JSON array of 3-5 specific, actionable recommendations: -["recommendation 1", "recommendation 2", ...]`; - try { - const response = await this.model.invoke(refinementPrompt); - const content = response.content; - // Track tokens - const usage = response.response_metadata?.usage; - const inputTokens = usage?.input_tokens || 0; - const outputTokens = usage?.output_tokens || 0; - // Parse recommendations - let recommendations = []; - try { - const jsonMatch = content.match(/\[[\s\S]*\]/); - if (jsonMatch) { - recommendations = JSON.parse(jsonMatch[0]); - } - } - catch (parseError) { - // Fallback: extract bullet points - const lines = content.split('\n'); - recommendations = lines - .filter(line => line.trim().startsWith('-') || line.trim().startsWith('•') || /^\d+\./.test(line.trim())) - .map(line => line.replace(/^[-•]\s*/, '').replace(/^\d+\.\s*/, '').trim()) - .filter(line => line.length > 0) - .slice(0, 5); - } - // Add default recommendations if none found - if (recommendations.length === 0) { - recommendations = [ - 'Ensure comprehensive test coverage for new functionality', - 'Update relevant documentation', - 'Consider performance implications of changes', - ]; - } - // Track arch-docs usage in refinement - const archDocsStages = archDocsRefinementContext ? ['refinement'] : []; - const archDocsInsights = []; - if (archDocsRefinementContext && context.archDocs?.available) { - archDocsInsights.push(`Generated ${recommendations.length} recommendations based on repository quality standards and KPIs`); - } - return { - ...state, - recommendations, - totalInputTokens: (state.totalInputTokens || 0) + inputTokens, - totalOutputTokens: (state.totalOutputTokens || 0) + outputTokens, - archDocsInfluencedStages: archDocsStages, - archDocsKeyInsights: archDocsInsights, - }; - } - catch (error) { - console.error('Error refining analysis:', error); - return { - ...state, - recommendations: [ - 'Review changes carefully for potential side effects', - 'Ensure test coverage is adequate', - 'Update documentation as needed', - ], - }; - } - } - async finalizeNode(state) { - console.log('✨ Finalizing analysis...'); - return state; - } - shouldRefine(state) { - // Use defaults if config not accessible - const maxIterations = 3; - const clarityThreshold = 80; - if (state.iteration >= maxIterations) { - console.log(`⏹️ Stopping: Max iterations (${maxIterations}) reached`); - return 'finalize'; - } - if (state.clarityScore >= clarityThreshold) { - console.log(`✅ Stopping: Clarity threshold (${clarityThreshold}) achieved`); - return 'finalize'; - } - console.log(`🔄 Continuing: Iteration ${state.iteration}, clarity ${state.clarityScore}`); - return 'refine'; - } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/output_parsers.js - - - -//#region src/output_parsers.ts -var AnthropicToolsOutputParser = class extends BaseLLMOutputParser { - static lc_name() { - return "AnthropicToolsOutputParser"; - } - lc_namespace = [ - "langchain", - "anthropic", - "output_parsers" - ]; - returnId = false; - /** The type of tool calls to return. */ - keyName; - /** Whether to return only the first tool call. */ - returnSingle = false; - zodSchema; - constructor(params) { - super(params); - this.keyName = params.keyName; - this.returnSingle = params.returnSingle ?? this.returnSingle; - this.zodSchema = params.zodSchema; - } - async _validateResult(result) { - let parsedResult = result; - if (typeof result === "string") try { - parsedResult = JSON.parse(result); - } catch (e) { - throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(e.message)}`, result); - } - else parsedResult = result; - if (this.zodSchema === void 0) return parsedResult; - const zodParsedResult = await interopSafeParseAsync(this.zodSchema, parsedResult); - if (zodParsedResult.success) return zodParsedResult.data; - else throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.issues)}`, JSON.stringify(parsedResult, null, 2)); - } - async parseResult(generations) { - const tools = generations.flatMap((generation) => { - const { message } = generation; - if (!Array.isArray(message.content)) return []; - const tool$1 = extractToolCalls(message.content)[0]; - return tool$1; - }); - if (tools[0] === void 0) throw new Error("No parseable tool calls provided to AnthropicToolsOutputParser."); - const [tool] = tools; - const validatedResult = await this._validateResult(tool.args); - return validatedResult; - } -}; -function extractToolCalls(content) { - const toolCalls = []; - for (const block of content) if (block.type === "tool_use") toolCalls.push({ - name: block.name, - args: block.input, - id: block.id, - type: "tool_call" - }); - return toolCalls; -} - -//#endregion - -//# sourceMappingURL=output_parsers.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/tools.js - - -//#region src/utils/tools.ts -function handleToolChoice(toolChoice) { - if (!toolChoice) return void 0; - else if (toolChoice === "any") return { type: "any" }; - else if (toolChoice === "auto") return { type: "auto" }; - else if (toolChoice === "none") return { type: "none" }; - else if (typeof toolChoice === "string") return { - type: "tool", - name: toolChoice - }; - else return toolChoice; -} -const AnthropicToolExtrasSchema = object({ - cache_control: schemas_custom().optional().nullable(), - defer_loading: schemas_boolean().optional(), - input_examples: array(unknown()).optional(), - allowed_callers: array(unknown()).optional() -}); -/** -* Mapping of Anthropic tool types to their required beta feature flags. -* -* This constant defines which beta header is needed for specific tool types -* when making requests to the Anthropic API. Beta features are experimental -* capabilities that may change or be removed. -*/ -const ANTHROPIC_TOOL_BETAS = { - tool_search_tool_regex_20251119: "advanced-tool-use-2025-11-20", - tool_search_tool_bm25_20251119: "advanced-tool-use-2025-11-20", - memory_20250818: "context-management-2025-06-27", - web_fetch_20250910: "web-fetch-2025-09-10", - code_execution_20250825: "code-execution-2025-08-25", - computer_20251124: "computer-use-2025-11-24", - computer_20250124: "computer-use-2025-01-24", - mcp_toolset: "mcp-client-2025-11-20" -}; - -//#endregion - -//# sourceMappingURL=tools.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/content.js - - -//#region src/utils/content.ts -function _isAnthropicThinkingBlock(block) { - return typeof block === "object" && block !== null && "type" in block && block.type === "thinking"; -} -function _isAnthropicRedactedThinkingBlock(block) { - return typeof block === "object" && block !== null && "type" in block && block.type === "redacted_thinking"; -} -function _isAnthropicSearchResultBlock(block) { - return typeof block === "object" && block !== null && "type" in block && block.type === "search_result"; -} -function _isAnthropicImageBlockParam(block) { - if (typeof block !== "object" || block == null) return false; - if (!("type" in block) || block.type !== "image") return false; - if (!("source" in block) || typeof block.source !== "object" || block.source == null) return false; - if (!("type" in block.source)) return false; - if (block.source.type === "base64") { - if (!("media_type" in block.source)) return false; - if (typeof block.source.media_type !== "string") return false; - if (!("data" in block.source)) return false; - if (typeof block.source.data !== "string") return false; - return true; - } - if (block.source.type === "url") { - if (!("url" in block.source)) return false; - if (typeof block.source.url !== "string") return false; - return true; - } - return false; -} -const standardContentBlockConverter = { - providerName: "anthropic", - fromStandardTextBlock(block) { - return { - type: "text", - text: block.text, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - }, - fromStandardImageBlock(block) { - if (block.source_type === "url") { - const data = parseBase64DataUrl({ - dataUrl: block.url, - asTypedArray: false - }); - if (data) return { - type: "image", - source: { - type: "base64", - data: data.data, - media_type: data.mime_type - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - else return { - type: "image", - source: { - type: "url", - url: block.url - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - } else if (block.source_type === "base64") return { - type: "image", - source: { - type: "base64", - data: block.data, - media_type: block.mime_type ?? "" - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {} - }; - else throw new Error(`Unsupported image source type: ${block.source_type}`); - }, - fromStandardFileBlock(block) { - const mime_type = (block.mime_type ?? "").split(";")[0]; - if (block.source_type === "url") { - if (mime_type === "application/pdf" || mime_type === "") return { - type: "document", - source: { - type: "url", - url: block.url - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - throw new Error(`Unsupported file mime type for file url source: ${block.mime_type}`); - } else if (block.source_type === "text") if (mime_type === "text/plain" || mime_type === "") return { - type: "document", - source: { - type: "text", - data: block.text, - media_type: block.mime_type ?? "" - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - else throw new Error(`Unsupported file mime type for file text source: ${block.mime_type}`); - else if (block.source_type === "base64") if (mime_type === "application/pdf" || mime_type === "") return { - type: "document", - source: { - type: "base64", - data: block.data, - media_type: "application/pdf" - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - else if ([ - "image/jpeg", - "image/png", - "image/gif", - "image/webp" - ].includes(mime_type)) return { - type: "document", - source: { - type: "content", - content: [{ - type: "image", - source: { - type: "base64", - data: block.data, - media_type: mime_type - } - }] - }, - ..."cache_control" in (block.metadata ?? {}) ? { cache_control: block.metadata.cache_control } : {}, - ..."citations" in (block.metadata ?? {}) ? { citations: block.metadata.citations } : {}, - ..."context" in (block.metadata ?? {}) ? { context: block.metadata.context } : {}, - ..."title" in (block.metadata ?? {}) ? { title: block.metadata.title } : {} - }; - else throw new Error(`Unsupported file mime type for file base64 source: ${block.mime_type}`); - else throw new Error(`Unsupported file source type: ${block.source_type}`); - } -}; - -//#endregion - -//# sourceMappingURL=content.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/index.js -//#region src/utils/index.ts -const dist_utils_iife = (fn) => fn(); - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/standard.js - - -//#region src/utils/standard.ts -function _isStandardAnnotation(annotation) { - return typeof annotation === "object" && annotation !== null && "type" in annotation && annotation.type === "citation"; -} -function _formatStandardCitations(annotations) { - function* iterateAnnotations() { - for (const annotation of annotations) if (_isStandardAnnotation(annotation)) { - if (annotation.source === "char") yield { - type: "char_location", - file_id: annotation.url ?? "", - start_char_index: annotation.startIndex ?? 0, - end_char_index: annotation.endIndex ?? 0, - document_title: annotation.title ?? null, - document_index: 0, - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "page") yield { - type: "page_location", - file_id: annotation.url ?? "", - start_page_number: annotation.startIndex ?? 0, - end_page_number: annotation.endIndex ?? 0, - document_title: annotation.title ?? null, - document_index: 0, - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "block") yield { - type: "content_block_location", - file_id: annotation.url ?? "", - start_block_index: annotation.startIndex ?? 0, - end_block_index: annotation.endIndex ?? 0, - document_title: annotation.title ?? null, - document_index: 0, - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "url") yield { - type: "web_search_result_location", - url: annotation.url ?? "", - title: annotation.title ?? null, - encrypted_index: String(annotation.startIndex ?? 0), - cited_text: annotation.citedText ?? "" - }; - else if (annotation.source === "search") yield { - type: "search_result_location", - title: annotation.title ?? null, - start_block_index: annotation.startIndex ?? 0, - end_block_index: annotation.endIndex ?? 0, - search_result_index: 0, - source: annotation.source ?? "", - cited_text: annotation.citedText ?? "" - }; - } - } - return Array.from(iterateAnnotations()); -} -function _formatBase64Data(data) { - if (typeof data === "string") return data; - else return _encodeUint8Array(data); -} -function _encodeUint8Array(data) { - const output = []; - for (let i = 0, { length } = data; i < length; i++) output.push(String.fromCharCode(data[i])); - return btoa(output.join("")); -} -function _normalizeMimeType(mimeType) { - return (mimeType ?? "").split(";")[0].toLowerCase(); -} -function _extractMetadataValue(metadata, key) { - if (metadata !== void 0 && metadata !== null && typeof metadata === "object" && key in metadata) return metadata[key]; - return void 0; -} -function _applyDocumentMetadata(block, metadata) { - const cacheControl = _extractMetadataValue(metadata, "cache_control"); - if (cacheControl !== void 0) block.cache_control = cacheControl; - const citations = _extractMetadataValue(metadata, "citations"); - if (citations !== void 0) block.citations = citations; - const context = _extractMetadataValue(metadata, "context"); - if (context !== void 0) block.context = context; - const title = _extractMetadataValue(metadata, "title"); - if (title !== void 0) block.title = title; - return block; -} -function _applyImageMetadata(block, metadata) { - const cacheControl = _extractMetadataValue(metadata, "cache_control"); - if (cacheControl !== void 0) block.cache_control = cacheControl; - return block; -} -function _hasAllowedImageMimeType(mimeType) { - const ALLOWED_IMAGE_MIME_TYPES = new Set([ - "image/jpeg", - "image/png", - "image/gif", - "image/webp" - ]); - return ALLOWED_IMAGE_MIME_TYPES.has(mimeType); -} -function _formatStandardContent(message) { - const result = []; - const responseMetadata = message.response_metadata; - const isAnthropicMessage = "model_provider" in responseMetadata && responseMetadata?.model_provider === "anthropic"; - for (const block of message.contentBlocks) if (block.type === "text") if (block.annotations) result.push({ - type: "text", - text: block.text, - citations: _formatStandardCitations(block.annotations) - }); - else result.push({ - type: "text", - text: block.text - }); - else if (block.type === "tool_call") result.push({ - type: "tool_use", - id: block.id ?? "", - name: block.name, - input: block.args - }); - else if (block.type === "tool_call_chunk") { - const input = dist_utils_iife(() => { - if (typeof block.args !== "string") return block.args; - try { - return JSON.parse(block.args); - } catch { - return {}; - } - }); - result.push({ - type: "tool_use", - id: block.id ?? "", - name: block.name ?? "", - input - }); - } else if (block.type === "reasoning" && isAnthropicMessage) result.push({ - type: "thinking", - thinking: block.reasoning, - signature: String(block.signature) - }); - else if (block.type === "server_tool_call" && isAnthropicMessage) { - if (block.name === "web_search") result.push({ - type: "server_tool_use", - name: block.name, - id: block.id ?? "", - input: block.args - }); - else if (block.name === "code_execution") result.push({ - type: "server_tool_use", - name: block.name, - id: block.id ?? "", - input: block.args - }); - } else if (block.type === "server_tool_call_result" && isAnthropicMessage) { - if (block.name === "web_search" && Array.isArray(block.output.urls)) { - const content = block.output.urls.map((url) => ({ - type: "web_search_result", - title: "", - encrypted_content: "", - url - })); - result.push({ - type: "web_search_tool_result", - tool_use_id: block.toolCallId ?? "", - content - }); - } else if (block.name === "code_execution") result.push({ - type: "code_execution_tool_result", - tool_use_id: block.toolCallId ?? "", - content: block.output - }); - else if (block.name === "mcp_tool_result") result.push({ - type: "mcp_tool_result", - tool_use_id: block.toolCallId ?? "", - content: block.output - }); - } else if (block.type === "audio") throw new Error("Anthropic does not support audio content blocks."); - else if (block.type === "file") { - const metadata = block.metadata; - if (block.fileId) { - result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "file", - file_id: block.fileId - } - }, metadata)); - continue; - } - if (block.url) { - const mimeType = _normalizeMimeType(block.mimeType); - if (mimeType === "application/pdf" || mimeType === "") { - result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "url", - url: block.url - } - }, metadata)); - continue; - } - } - if (block.data) { - const mimeType = _normalizeMimeType(block.mimeType); - if (mimeType === "" || mimeType === "application/pdf") result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "base64", - data: _formatBase64Data(block.data), - media_type: "application/pdf" - } - }, metadata)); - else if (mimeType === "text/plain") result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "text", - data: _formatBase64Data(block.data), - media_type: "text/plain" - } - }, metadata)); - else if (_hasAllowedImageMimeType(mimeType)) result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "content", - content: [{ - type: "image", - source: { - type: "base64", - data: _formatBase64Data(block.data), - media_type: mimeType - } - }] - } - }, metadata)); - else throw new Error(`Unsupported file mime type for Anthropic base64 source: ${mimeType}`); - continue; - } - throw new Error("File content block must include a fileId, url, or data property."); - } else if (block.type === "image") { - const metadata = block.metadata; - if (block.fileId) { - result.push(_applyImageMetadata({ - type: "image", - source: { - type: "file", - file_id: block.fileId - } - }, metadata)); - continue; - } - if (block.url) { - result.push(_applyImageMetadata({ - type: "image", - source: { - type: "url", - url: block.url - } - }, metadata)); - continue; - } - if (block.data) { - const mimeType = _normalizeMimeType(block.mimeType) || "image/png"; - if (_hasAllowedImageMimeType(mimeType)) result.push(_applyImageMetadata({ - type: "image", - source: { - type: "base64", - data: _formatBase64Data(block.data), - media_type: mimeType - } - }, metadata)); - continue; - } - throw new Error("Image content block must include a fileId, url, or data property."); - } else if (block.type === "video") {} else if (block.type === "text-plain") { - if (block.data) result.push(_applyDocumentMetadata({ - type: "document", - source: { - type: "text", - data: _formatBase64Data(block.data), - media_type: "text/plain" - } - }, block.metadata)); - } else if (block.type === "non_standard" && isAnthropicMessage) result.push(block.value); - return result; -} - -//#endregion - -//# sourceMappingURL=standard.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/message_inputs.js - - - - -//#region src/utils/message_inputs.ts -function _formatImage(imageUrl) { - const parsed = parseBase64DataUrl({ dataUrl: imageUrl }); - if (parsed) return { - type: "base64", - media_type: parsed.mime_type, - data: parsed.data - }; - let parsedUrl; - try { - parsedUrl = new URL(imageUrl); - } catch { - throw new Error([ - `Malformed image URL: ${JSON.stringify(imageUrl)}. Content blocks of type 'image_url' must be a valid http, https, or base64-encoded data URL.`, - "Example: data:image/png;base64,/9j/4AAQSk...", - "Example: https://example.com/image.jpg" - ].join("\n\n")); - } - if (parsedUrl.protocol === "http:" || parsedUrl.protocol === "https:") return { - type: "url", - url: imageUrl - }; - throw new Error([ - `Invalid image URL protocol: ${JSON.stringify(parsedUrl.protocol)}. Anthropic only supports images as http, https, or base64-encoded data URLs on 'image_url' content blocks.`, - "Example: data:image/png;base64,/9j/4AAQSk...", - "Example: https://example.com/image.jpg" - ].join("\n\n")); -} -function _ensureMessageContents(messages) { - const updatedMsgs = []; - for (const message of messages) if (message._getType() === "tool") if (typeof message.content === "string") { - const previousMessage = updatedMsgs[updatedMsgs.length - 1]; - if (previousMessage?._getType() === "human" && Array.isArray(previousMessage.content) && "type" in previousMessage.content[0] && previousMessage.content[0].type === "tool_result") previousMessage.content.push({ - type: "tool_result", - content: message.content, - tool_use_id: message.tool_call_id - }); - else updatedMsgs.push(new HumanMessage({ content: [{ - type: "tool_result", - content: message.content, - tool_use_id: message.tool_call_id - }] })); - } else updatedMsgs.push(new HumanMessage({ content: [{ - type: "tool_result", - ...message.content != null ? { content: _formatContent(message) } : {}, - tool_use_id: message.tool_call_id - }] })); - else updatedMsgs.push(message); - return updatedMsgs; -} -function _convertLangChainToolCallToAnthropic(toolCall) { - if (toolCall.id === void 0) throw new Error(`Anthropic requires all tool calls to have an "id".`); - return { - type: "tool_use", - id: toolCall.id, - name: toolCall.name, - input: toolCall.args - }; -} -function* _formatContentBlocks(content) { - const toolTypes = [ - "bash_code_execution_tool_result", - "input_json_delta", - "server_tool_use", - "text_editor_code_execution_tool_result", - "tool_result", - "tool_use", - "web_search_result", - "web_search_tool_result" - ]; - const textTypes = ["text", "text_delta"]; - for (const contentPart of content) { - if (isDataContentBlock(contentPart)) yield convertToProviderContentBlock(contentPart, standardContentBlockConverter); - const cacheControl = "cache_control" in contentPart ? contentPart.cache_control : void 0; - if (contentPart.type === "image_url") { - let source; - if (typeof contentPart.image_url === "string") source = _formatImage(contentPart.image_url); - else if (typeof contentPart.image_url === "object" && contentPart.image_url !== null && "url" in contentPart.image_url && typeof contentPart.image_url.url === "string") source = _formatImage(contentPart.image_url.url); - if (source) yield { - type: "image", - source, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - } else if (_isAnthropicImageBlockParam(contentPart)) return contentPart; - else if (contentPart.type === "document") yield { - ...contentPart, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - else if (_isAnthropicThinkingBlock(contentPart)) { - const block = { - type: "thinking", - thinking: contentPart.thinking, - signature: contentPart.signature, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - yield block; - } else if (_isAnthropicRedactedThinkingBlock(contentPart)) { - const block = { - type: "redacted_thinking", - data: contentPart.data, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - yield block; - } else if (_isAnthropicSearchResultBlock(contentPart)) { - const block = { - type: "search_result", - title: contentPart.title, - source: contentPart.source, - ..."cache_control" in contentPart && contentPart.cache_control ? { cache_control: contentPart.cache_control } : {}, - ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {}, - content: contentPart.content - }; - yield block; - } else if (textTypes.find((t) => t === contentPart.type) && "text" in contentPart) yield { - type: "text", - text: contentPart.text, - ...cacheControl ? { cache_control: cacheControl } : {}, - ..."citations" in contentPart && contentPart.citations ? { citations: contentPart.citations } : {} - }; - else if (toolTypes.find((t) => t === contentPart.type)) { - const contentPartCopy = { ...contentPart }; - if ("index" in contentPartCopy) delete contentPartCopy.index; - if (contentPartCopy.type === "input_json_delta") contentPartCopy.type = "tool_use"; - if ("input" in contentPartCopy) { - if (typeof contentPartCopy.input === "string") try { - contentPartCopy.input = JSON.parse(contentPartCopy.input); - } catch { - contentPartCopy.input = {}; - } - } - yield { - ...contentPartCopy, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - } else if (contentPart.type === "container_upload") yield { - ...contentPart, - ...cacheControl ? { cache_control: cacheControl } : {} - }; - } -} -function _formatContent(message) { - const { content } = message; - if (typeof content === "string") return content; - else return Array.from(_formatContentBlocks(content)); -} -/** -* Formats messages as a prompt for the model. -* Used in LangSmith, export is important here. -* @param messages The base messages to format as a prompt. -* @returns The formatted prompt. -*/ -function message_inputs_convertMessagesToAnthropicPayload(messages) { - const mergedMessages = _ensureMessageContents(messages); - let system; - if (mergedMessages.length > 0 && mergedMessages[0]._getType() === "system") system = messages[0].content; - const conversationMessages = system !== void 0 ? mergedMessages.slice(1) : mergedMessages; - const formattedMessages = conversationMessages.map((message) => { - let role; - if (message._getType() === "human") role = "user"; - else if (message._getType() === "ai") role = "assistant"; - else if (message._getType() === "tool") role = "user"; - else if (message._getType() === "system") throw new Error("System messages are only permitted as the first passed message."); - else throw new Error(`Message type "${message.type}" is not supported.`); - if (isAIMessage(message) && message.response_metadata?.output_version === "v1") return { - role, - content: _formatStandardContent(message) - }; - if (isAIMessage(message) && !!message.tool_calls?.length) if (typeof message.content === "string") if (message.content === "") return { - role, - content: message.tool_calls.map(_convertLangChainToolCallToAnthropic) - }; - else return { - role, - content: [{ - type: "text", - text: message.content - }, ...message.tool_calls.map(_convertLangChainToolCallToAnthropic)] - }; - else { - const { content } = message; - const hasMismatchedToolCalls = !message.tool_calls.every((toolCall) => content.find((contentPart) => (contentPart.type === "tool_use" || contentPart.type === "input_json_delta" || contentPart.type === "server_tool_use") && contentPart.id === toolCall.id)); - if (hasMismatchedToolCalls) console.warn(`The "tool_calls" field on a message is only respected if content is a string.`); - return { - role, - content: _formatContent(message) - }; - } - else return { - role, - content: _formatContent(message) - }; - }); - return { - messages: mergeMessages(formattedMessages), - system - }; -} -function mergeMessages(messages) { - if (!messages || messages.length <= 1) return messages; - const result = []; - let currentMessage = messages[0]; - const normalizeContent = (content) => { - if (typeof content === "string") return [{ - type: "text", - text: content - }]; - return content; - }; - const isToolResultMessage = (msg) => { - if (msg.role !== "user") return false; - if (typeof msg.content === "string") return false; - return Array.isArray(msg.content) && msg.content.every((item) => item.type === "tool_result"); - }; - for (let i = 1; i < messages.length; i += 1) { - const nextMessage = messages[i]; - if (isToolResultMessage(currentMessage) && isToolResultMessage(nextMessage)) currentMessage = { - ...currentMessage, - content: [...normalizeContent(currentMessage.content), ...normalizeContent(nextMessage.content)] - }; - else { - result.push(currentMessage); - currentMessage = nextMessage; - } - } - result.push(currentMessage); - return result; -} - -//#endregion - -//# sourceMappingURL=message_inputs.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/message_outputs.js - - - -//#region src/utils/message_outputs.ts -function _makeMessageChunkFromAnthropicEvent(data, fields) { - const response_metadata = { model_provider: "anthropic" }; - if (data.type === "message_start") { - const { content, usage,...additionalKwargs } = data.message; - const filteredAdditionalKwargs = {}; - for (const [key, value] of Object.entries(additionalKwargs)) if (value !== void 0 && value !== null) filteredAdditionalKwargs[key] = value; - const { input_tokens, output_tokens,...rest } = usage ?? {}; - const totalInputTokens = input_tokens + rest.cache_creation_input_tokens + rest.cache_read_input_tokens; - const usageMetadata = { - input_tokens: totalInputTokens, - output_tokens, - total_tokens: totalInputTokens + output_tokens, - input_token_details: { - cache_creation: rest.cache_creation_input_tokens, - cache_read: rest.cache_read_input_tokens - } - }; - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [], - additional_kwargs: filteredAdditionalKwargs, - usage_metadata: fields.streamUsage ? usageMetadata : void 0, - response_metadata: { - ...response_metadata, - usage: { ...rest } - }, - id: data.message.id - }) }; - } else if (data.type === "message_delta") { - const usageMetadata = { - input_tokens: 0, - output_tokens: data.usage.output_tokens, - total_tokens: data.usage.output_tokens, - input_token_details: { - cache_creation: data.usage.cache_creation_input_tokens, - cache_read: data.usage.cache_read_input_tokens - } - }; - const responseMetadata = "context_management" in data.delta ? { context_management: data.delta.context_management } : void 0; - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [], - response_metadata: responseMetadata, - additional_kwargs: { ...data.delta }, - usage_metadata: fields.streamUsage ? usageMetadata : void 0 - }) }; - } else if (data.type === "content_block_start" && [ - "tool_use", - "document", - "server_tool_use", - "web_search_tool_result" - ].includes(data.content_block.type)) { - const contentBlock = data.content_block; - let toolCallChunks; - if (contentBlock.type === "tool_use") toolCallChunks = [{ - id: contentBlock.id, - index: data.index, - name: contentBlock.name, - args: "" - }]; - else toolCallChunks = []; - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [{ - index: data.index, - ...data.content_block, - input: contentBlock.type === "server_tool_use" || contentBlock.type === "tool_use" ? "" : void 0 - }], - response_metadata, - additional_kwargs: {}, - tool_call_chunks: toolCallChunks - }) }; - } else if (data.type === "content_block_delta" && [ - "text_delta", - "citations_delta", - "thinking_delta", - "signature_delta" - ].includes(data.delta.type)) if (fields.coerceContentToString && "text" in data.delta) return { chunk: new AIMessageChunk({ content: data.delta.text }) }; - else { - const contentBlock = data.delta; - if ("citation" in contentBlock) { - contentBlock.citations = [contentBlock.citation]; - delete contentBlock.citation; - } - if (contentBlock.type === "thinking_delta" || contentBlock.type === "signature_delta") return { chunk: new AIMessageChunk({ - content: [{ - index: data.index, - ...contentBlock, - type: "thinking" - }], - response_metadata - }) }; - return { chunk: new AIMessageChunk({ - content: [{ - index: data.index, - ...contentBlock, - type: "text" - }], - response_metadata - }) }; - } - else if (data.type === "content_block_delta" && data.delta.type === "input_json_delta") return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [{ - index: data.index, - input: data.delta.partial_json, - type: data.delta.type - }], - response_metadata, - additional_kwargs: {}, - tool_call_chunks: [{ - index: data.index, - args: data.delta.partial_json - }] - }) }; - else if (data.type === "content_block_start" && data.content_block.type === "text") { - const content = data.content_block?.text; - if (content !== void 0) return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? content : [{ - index: data.index, - ...data.content_block - }], - response_metadata, - additional_kwargs: {} - }) }; - } else if (data.type === "content_block_start" && data.content_block.type === "redacted_thinking") return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? "" : [{ - index: data.index, - ...data.content_block - }], - response_metadata - }) }; - else if (data.type === "content_block_start" && data.content_block.type === "thinking") { - const content = data.content_block.thinking; - return { chunk: new AIMessageChunk({ - content: fields.coerceContentToString ? content : [{ - index: data.index, - ...data.content_block - }], - response_metadata - }) }; - } - return null; -} -function anthropicResponseToChatMessages(messages, additionalKwargs) { - const response_metadata = { - ...additionalKwargs, - model_provider: "anthropic" - }; - const usage = additionalKwargs.usage; - const usageMetadata = usage != null ? { - input_tokens: usage.input_tokens ?? 0, - output_tokens: usage.output_tokens ?? 0, - total_tokens: (usage.input_tokens ?? 0) + (usage.output_tokens ?? 0), - input_token_details: { - cache_creation: usage.cache_creation_input_tokens, - cache_read: usage.cache_read_input_tokens - } - } : void 0; - if (messages.length === 1 && messages[0].type === "text") return [{ - text: messages[0].text, - message: new AIMessage({ - content: messages[0].text, - additional_kwargs: additionalKwargs, - usage_metadata: usageMetadata, - response_metadata, - id: additionalKwargs.id - }) - }]; - else { - const toolCalls = extractToolCalls(messages); - const generations = [{ - text: "", - message: new AIMessage({ - content: messages, - additional_kwargs: additionalKwargs, - tool_calls: toolCalls, - usage_metadata: usageMetadata, - response_metadata, - id: additionalKwargs.id - }) - }]; - return generations; - } -} - -//#endregion - -//# sourceMappingURL=message_outputs.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/errors.js -//#region src/utils/errors.ts -function errors_addLangChainErrorFields(error, lc_error_code) { - error.lc_error_code = lc_error_code; - error.message = `${error.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\n`; - return error; -} -function wrapAnthropicClientError(e) { - let error; - if (e.status === 400 && e.message.includes("tool")) error = errors_addLangChainErrorFields(e, "INVALID_TOOL_RESULTS"); - else if (e.status === 401) error = errors_addLangChainErrorFields(e, "MODEL_AUTHENTICATION"); - else if (e.status === 404) error = errors_addLangChainErrorFields(e, "MODEL_NOT_FOUND"); - else if (e.status === 429) error = errors_addLangChainErrorFields(e, "MODEL_RATE_LIMIT"); - else error = e; - return error; -} - -//#endregion - -//# sourceMappingURL=errors.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/profiles.js -//#region src/profiles.ts -const PROFILES = { - "claude-opus-4-0": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-5-sonnet-20241022": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-opus-4-1": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-haiku-4-5": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-5-sonnet-20240620": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-5-haiku-latest": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-opus-20240229": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 4096, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-sonnet-4-5": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-sonnet-4-5-20250929": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-sonnet-4-20250514": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-opus-4-20250514": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-5-haiku-20241022": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-haiku-20240307": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 4096, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-7-sonnet-20250219": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-7-sonnet-latest": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-sonnet-4-0": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-opus-4-1-20250805": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-3-sonnet-20240229": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 4096, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - }, - "claude-haiku-4-5-20251001": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 64e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true - } -}; -var profiles_default = PROFILES; - -//#endregion - -//# sourceMappingURL=profiles.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/tslib.mjs -function __classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; -} -function __classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - - -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/uuid.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -/** - * https://stackoverflow.com/a/2117523 - */ -let uuid_uuid4 = function () { - const { crypto } = globalThis; - if (crypto?.randomUUID) { - uuid_uuid4 = crypto.randomUUID.bind(crypto); - return crypto.randomUUID(); - } - const u8 = new Uint8Array(1); - const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff; - return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16)); -}; -//# sourceMappingURL=uuid.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/errors.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function isAbortError(err) { - return (typeof err === 'object' && - err !== null && - // Spec-compliant fetch implementations - (('name' in err && err.name === 'AbortError') || - // Expo fetch - ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); -} -const castToError = (err) => { - if (err instanceof Error) - return err; - if (typeof err === 'object' && err !== null) { - try { - if (Object.prototype.toString.call(err) === '[object Error]') { - // @ts-ignore - not all envs have native support for cause yet - const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); - if (err.stack) - error.stack = err.stack; - // @ts-ignore - not all envs have native support for cause yet - if (err.cause && !error.cause) - error.cause = err.cause; - if (err.name) - error.name = err.name; - return error; - } - } - catch { } - try { - return new Error(JSON.stringify(err)); - } - catch { } - } - return new Error(err); -}; -//# sourceMappingURL=errors.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/error.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class error_AnthropicError extends Error { -} -class APIError extends error_AnthropicError { - constructor(status, error, message, headers) { - super(`${APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.requestID = headers?.get('request-id'); - this.error = error; - } - static makeMessage(status, error, message) { - const msg = error?.message ? - typeof error.message === 'string' ? - error.message - : JSON.stringify(error.message) - : error ? JSON.stringify(error) - : message; - if (status && msg) { - return `${status} ${msg}`; - } - if (status) { - return `${status} status code (no body)`; - } - if (msg) { - return msg; - } - return '(no status code or body)'; - } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new APIConnectionError({ message, cause: castToError(errorResponse) }); - } - const error = errorResponse; - if (status === 400) { - return new BadRequestError(status, error, message, headers); - } - if (status === 401) { - return new AuthenticationError(status, error, message, headers); - } - if (status === 403) { - return new PermissionDeniedError(status, error, message, headers); - } - if (status === 404) { - return new NotFoundError(status, error, message, headers); - } - if (status === 409) { - return new ConflictError(status, error, message, headers); - } - if (status === 422) { - return new UnprocessableEntityError(status, error, message, headers); - } - if (status === 429) { - return new RateLimitError(status, error, message, headers); - } - if (status >= 500) { - return new InternalServerError(status, error, message, headers); - } - return new APIError(status, error, message, headers); - } -} -class APIUserAbortError extends APIError { - constructor({ message } = {}) { - super(undefined, undefined, message || 'Request was aborted.', undefined); - } -} -class APIConnectionError extends APIError { - constructor({ message, cause }) { - super(undefined, undefined, message || 'Connection error.', undefined); - // in some environments the 'cause' property is already declared - // @ts-ignore - if (cause) - this.cause = cause; - } -} -class APIConnectionTimeoutError extends APIConnectionError { - constructor({ message } = {}) { - super({ message: message ?? 'Request timed out.' }); - } -} -class BadRequestError extends APIError { -} -class AuthenticationError extends APIError { -} -class PermissionDeniedError extends APIError { -} -class NotFoundError extends APIError { -} -class ConflictError extends APIError { -} -class UnprocessableEntityError extends APIError { -} -class RateLimitError extends APIError { -} -class InternalServerError extends APIError { -} -//# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/values.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -// https://url.spec.whatwg.org/#url-scheme-string -const startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; -const isAbsoluteURL = (url) => { - return startsWithSchemeRegexp.test(url); -}; -let values_isArray = (val) => ((values_isArray = Array.isArray), values_isArray(val)); -let isReadonlyArray = values_isArray; -/** Returns an object if the given value isn't an object, otherwise returns as-is */ -function maybeObj(x) { - if (typeof x !== 'object') { - return {}; - } - return x ?? {}; -} -// https://stackoverflow.com/a/34491287 -function isEmptyObj(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -// https://eslint.org/docs/latest/rules/no-prototype-builtins -function hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -function isObj(obj) { - return obj != null && typeof obj === 'object' && !Array.isArray(obj); -} -const ensurePresent = (value) => { - if (value == null) { - throw new AnthropicError(`Expected a value to be given but received ${value} instead.`); - } - return value; -}; -const validatePositiveInteger = (name, n) => { - if (typeof n !== 'number' || !Number.isInteger(n)) { - throw new error_AnthropicError(`${name} must be an integer`); - } - if (n < 0) { - throw new error_AnthropicError(`${name} must be a positive integer`); - } - return n; -}; -const coerceInteger = (value) => { - if (typeof value === 'number') - return Math.round(value); - if (typeof value === 'string') - return parseInt(value, 10); - throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const coerceFloat = (value) => { - if (typeof value === 'number') - return value; - if (typeof value === 'string') - return parseFloat(value); - throw new AnthropicError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const coerceBoolean = (value) => { - if (typeof value === 'boolean') - return value; - if (typeof value === 'string') - return value === 'true'; - return Boolean(value); -}; -const maybeCoerceInteger = (value) => { - if (value == null) { - return undefined; - } - return coerceInteger(value); -}; -const maybeCoerceFloat = (value) => { - if (value == null) { - return undefined; - } - return coerceFloat(value); -}; -const maybeCoerceBoolean = (value) => { - if (value == null) { - return undefined; - } - return coerceBoolean(value); -}; -const safeJSON = (text) => { - try { - return JSON.parse(text); - } - catch (err) { - return undefined; - } -}; -// Gets a value from an object, deletes the key, and returns the value (or undefined if not found) -const pop = (obj, key) => { - const value = obj[key]; - delete obj[key]; - return value; -}; -//# sourceMappingURL=values.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/sleep.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); -//# sourceMappingURL=sleep.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/version.mjs -const VERSION = '0.71.2'; // x-release-please-version -//# sourceMappingURL=version.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/detect-platform.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const isRunningInBrowser = () => { - return ( - // @ts-ignore - typeof window !== 'undefined' && - // @ts-ignore - typeof window.document !== 'undefined' && - // @ts-ignore - typeof navigator !== 'undefined'); -}; -/** - * Note this does not detect 'browser'; for that, use getBrowserInfo(). - */ -function getDetectedPlatform() { - if (typeof Deno !== 'undefined' && Deno.build != null) { - return 'deno'; - } - if (typeof EdgeRuntime !== 'undefined') { - return 'edge'; - } - if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') { - return 'node'; - } - return 'unknown'; -} -const getPlatformProperties = () => { - const detectedPlatform = getDetectedPlatform(); - if (detectedPlatform === 'deno') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': normalizePlatform(Deno.build.os), - 'X-Stainless-Arch': normalizeArch(Deno.build.arch), - 'X-Stainless-Runtime': 'deno', - 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', - }; - } - if (typeof EdgeRuntime !== 'undefined') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': `other:${EdgeRuntime}`, - 'X-Stainless-Runtime': 'edge', - 'X-Stainless-Runtime-Version': globalThis.process.version, - }; - } - // Check if Node.js - if (detectedPlatform === 'node') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': normalizePlatform(globalThis.process.platform ?? 'unknown'), - 'X-Stainless-Arch': normalizeArch(globalThis.process.arch ?? 'unknown'), - 'X-Stainless-Runtime': 'node', - 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown', - }; - } - const browserInfo = getBrowserInfo(); - if (browserInfo) { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, - 'X-Stainless-Runtime-Version': browserInfo.version, - }; - } - // TODO add support for Cloudflare workers, etc. - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': 'unknown', - 'X-Stainless-Runtime-Version': 'unknown', - }; -}; -// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts -function getBrowserInfo() { - if (typeof navigator === 'undefined' || !navigator) { - return null; - } - // NOTE: The order matters here! - const browserPatterns = [ - { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, - ]; - // Find the FIRST matching browser - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; - } - } - return null; -} -const normalizeArch = (arch) => { - // Node docs: - // - https://nodejs.org/api/process.html#processarch - // Deno docs: - // - https://doc.deno.land/deno/stable/~/Deno.build - if (arch === 'x32') - return 'x32'; - if (arch === 'x86_64' || arch === 'x64') - return 'x64'; - if (arch === 'arm') - return 'arm'; - if (arch === 'aarch64' || arch === 'arm64') - return 'arm64'; - if (arch) - return `other:${arch}`; - return 'unknown'; -}; -const normalizePlatform = (platform) => { - // Node platforms: - // - https://nodejs.org/api/process.html#processplatform - // Deno platforms: - // - https://doc.deno.land/deno/stable/~/Deno.build - // - https://github.com/denoland/deno/issues/14799 - platform = platform.toLowerCase(); - // NOTE: this iOS check is untested and may not work - // Node does not work natively on IOS, there is a fork at - // https://github.com/nodejs-mobile/nodejs-mobile - // however it is unknown at the time of writing how to detect if it is running - if (platform.includes('ios')) - return 'iOS'; - if (platform === 'android') - return 'Android'; - if (platform === 'darwin') - return 'MacOS'; - if (platform === 'win32') - return 'Windows'; - if (platform === 'freebsd') - return 'FreeBSD'; - if (platform === 'openbsd') - return 'OpenBSD'; - if (platform === 'linux') - return 'Linux'; - if (platform) - return `Other:${platform}`; - return 'Unknown'; -}; -let _platformHeaders; -const getPlatformHeaders = () => { - return (_platformHeaders ?? (_platformHeaders = getPlatformProperties())); -}; -//# sourceMappingURL=detect-platform.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/shims.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function getDefaultFetch() { - if (typeof fetch !== 'undefined') { - return fetch; - } - throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); -} -function makeReadableStream(...args) { - const ReadableStream = globalThis.ReadableStream; - if (typeof ReadableStream === 'undefined') { - // Note: All of the platforms / runtimes we officially support already define - // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. - throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); - } - return new ReadableStream(...args); -} -function ReadableStreamFrom(iterable) { - let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return makeReadableStream({ - start() { }, - async pull(controller) { - const { done, value } = await iter.next(); - if (done) { - controller.close(); - } - else { - controller.enqueue(value); - } - }, - async cancel() { - await iter.return?.(); - }, - }); -} -/** - * Most browsers don't yet have async iterable support for ReadableStream, - * and Node has a very different way of reading bytes from its "ReadableStream". - * - * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 - */ -function ReadableStreamToAsyncIterable(stream) { - if (stream[Symbol.asyncIterator]) - return stream; - const reader = stream.getReader(); - return { - async next() { - try { - const result = await reader.read(); - if (result?.done) - reader.releaseLock(); // release lock when stream becomes closed - return result; - } - catch (e) { - reader.releaseLock(); // release lock when stream becomes errored - throw e; - } - }, - async return() { - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; - return { done: true, value: undefined }; - }, - [Symbol.asyncIterator]() { - return this; - }, - }; -} -/** - * Cancels a ReadableStream we don't need to consume. - * See https://undici.nodejs.org/#/?id=garbage-collection - */ -async function CancelReadableStream(stream) { - if (stream === null || typeof stream !== 'object') - return; - if (stream[Symbol.asyncIterator]) { - await stream[Symbol.asyncIterator]().return?.(); - return; - } - const reader = stream.getReader(); - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; -} -//# sourceMappingURL=shims.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/request-options.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const FallbackEncoder = ({ headers, body }) => { - return { - bodyHeaders: { - 'content-type': 'application/json', - }, - body: JSON.stringify(body), - }; -}; -//# sourceMappingURL=request-options.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/bytes.mjs -function concatBytes(buffers) { - let length = 0; - for (const buffer of buffers) { - length += buffer.length; - } - const output = new Uint8Array(length); - let index = 0; - for (const buffer of buffers) { - output.set(buffer, index); - index += buffer.length; - } - return output; -} -let encodeUTF8_; -function bytes_encodeUTF8(str) { - let encoder; - return (encodeUTF8_ ?? - ((encoder = new globalThis.TextEncoder()), (encodeUTF8_ = encoder.encode.bind(encoder))))(str); -} -let decodeUTF8_; -function decodeUTF8(bytes) { - let decoder; - return (decodeUTF8_ ?? - ((decoder = new globalThis.TextDecoder()), (decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); -} -//# sourceMappingURL=bytes.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/decoders/line.mjs -var _LineDecoder_buffer, _LineDecoder_carriageReturnIndex; - - -/** - * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally - * reading lines from text. - * - * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 - */ -class LineDecoder { - constructor() { - _LineDecoder_buffer.set(this, void 0); - _LineDecoder_carriageReturnIndex.set(this, void 0); - __classPrivateFieldSet(this, _LineDecoder_buffer, new Uint8Array(), "f"); - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - } - decode(chunk) { - if (chunk == null) { - return []; - } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? bytes_encodeUTF8(chunk) - : chunk; - __classPrivateFieldSet(this, _LineDecoder_buffer, concatBytes([__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), binaryChunk]), "f"); - const lines = []; - let patternIndex; - while ((patternIndex = findNewlineIndex(__classPrivateFieldGet(this, _LineDecoder_buffer, "f"), __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f"))) != null) { - if (patternIndex.carriage && __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") == null) { - // skip until we either get a corresponding `\n`, a new `\r` or nothing - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, patternIndex.index, "f"); - continue; - } - // we got double \r or \rtext\n - if (__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") != null && - (patternIndex.index !== __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { - lines.push(decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") - 1))); - __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(__classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f")), "f"); - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - continue; - } - const endIndex = __classPrivateFieldGet(this, _LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; - const line = decodeUTF8(__classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(0, endIndex)); - lines.push(line); - __classPrivateFieldSet(this, _LineDecoder_buffer, __classPrivateFieldGet(this, _LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); - __classPrivateFieldSet(this, _LineDecoder_carriageReturnIndex, null, "f"); - } - return lines; - } - flush() { - if (!__classPrivateFieldGet(this, _LineDecoder_buffer, "f").length) { - return []; - } - return this.decode('\n'); - } -} -_LineDecoder_buffer = new WeakMap(), _LineDecoder_carriageReturnIndex = new WeakMap(); -// prettier-ignore -LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); -LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; -/** - * This function searches the buffer for the end patterns, (\r or \n) - * and returns an object with the index preceding the matched newline and the - * index after the newline char. `null` is returned if no new line is found. - * - * ```ts - * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } - * ``` - */ -function findNewlineIndex(buffer, startIndex) { - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = startIndex ?? 0; i < buffer.length; i++) { - if (buffer[i] === newline) { - return { preceding: i, index: i + 1, carriage: false }; - } - if (buffer[i] === carriage) { - return { preceding: i, index: i + 1, carriage: true }; - } - } - return null; -} -function findDoubleNewlineIndex(buffer) { - // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) - // and returns the index right after the first occurrence of any pattern, - // or -1 if none of the patterns are found. - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = 0; i < buffer.length - 1; i++) { - if (buffer[i] === newline && buffer[i + 1] === newline) { - // \n\n - return i + 2; - } - if (buffer[i] === carriage && buffer[i + 1] === carriage) { - // \r\r - return i + 2; - } - if (buffer[i] === carriage && - buffer[i + 1] === newline && - i + 3 < buffer.length && - buffer[i + 2] === carriage && - buffer[i + 3] === newline) { - // \r\n\r\n - return i + 4; - } - } - return -1; -} -//# sourceMappingURL=line.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/log.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const levelNumbers = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500, -}; -const parseLogLevel = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return undefined; - } - if (hasOwn(levelNumbers, maybeLevel)) { - return maybeLevel; - } - loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(levelNumbers))}`); - return undefined; -}; -function noop() { } -function makeLogFn(fnLevel, logger, logLevel) { - if (!logger || levelNumbers[fnLevel] > levelNumbers[logLevel]) { - return noop; - } - else { - // Don't wrap logger functions, we want the stacktrace intact! - return logger[fnLevel].bind(logger); - } -} -const noopLogger = { - error: noop, - warn: noop, - info: noop, - debug: noop, -}; -let cachedLoggers = /* @__PURE__ */ new WeakMap(); -function loggerFor(client) { - const logger = client.logger; - const logLevel = client.logLevel ?? 'off'; - if (!logger) { - return noopLogger; - } - const cachedLogger = cachedLoggers.get(logger); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; - } - const levelLogger = { - error: makeLogFn('error', logger, logLevel), - warn: makeLogFn('warn', logger, logLevel), - info: makeLogFn('info', logger, logLevel), - debug: makeLogFn('debug', logger, logLevel), - }; - cachedLoggers.set(logger, [logLevel, levelLogger]); - return levelLogger; -} -const formatRequestDetails = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options['headers']; // redundant + leaks internals - } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - (name.toLowerCase() === 'x-api-key' || - name.toLowerCase() === 'authorization' || - name.toLowerCase() === 'cookie' || - name.toLowerCase() === 'set-cookie') ? - '***' - : value, - ])); - } - if ('retryOfRequestLogID' in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; - } - delete details.retryOfRequestLogID; - } - return details; -}; -//# sourceMappingURL=log.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/streaming.mjs -var _Stream_client; - - - - - - - - - - -class Stream { - constructor(iterator, controller, client) { - this.iterator = iterator; - _Stream_client.set(this, void 0); - this.controller = controller; - __classPrivateFieldSet(this, _Stream_client, client, "f"); - } - static fromSSEResponse(response, controller, client) { - let consumed = false; - const logger = client ? loggerFor(client) : console; - async function* iterator() { - if (consumed) { - throw new error_AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const sse of _iterSSEMessages(response, controller)) { - if (sse.event === 'completion') { - try { - yield JSON.parse(sse.data); - } - catch (e) { - logger.error(`Could not parse message into JSON:`, sse.data); - logger.error(`From chunk:`, sse.raw); - throw e; - } - } - if (sse.event === 'message_start' || - sse.event === 'message_delta' || - sse.event === 'message_stop' || - sse.event === 'content_block_start' || - sse.event === 'content_block_delta' || - sse.event === 'content_block_stop') { - try { - yield JSON.parse(sse.data); - } - catch (e) { - logger.error(`Could not parse message into JSON:`, sse.data); - logger.error(`From chunk:`, sse.raw); - throw e; - } - } - if (sse.event === 'ping') { - continue; - } - if (sse.event === 'error') { - throw new APIError(undefined, safeJSON(sse.data) ?? sse.data, undefined, response.headers); - } - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (isAbortError(e)) - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new Stream(iterator, controller, client); - } - /** - * Generates a Stream from a newline-separated ReadableStream - * where each item is a JSON value. - */ - static fromReadableStream(readableStream, controller, client) { - let consumed = false; - async function* iterLines() { - const lineDecoder = new LineDecoder(); - const iter = ReadableStreamToAsyncIterable(readableStream); - for await (const chunk of iter) { - for (const line of lineDecoder.decode(chunk)) { - yield line; - } - } - for (const line of lineDecoder.flush()) { - yield line; - } - } - async function* iterator() { - if (consumed) { - throw new error_AnthropicError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const line of iterLines()) { - if (done) - continue; - if (line) - yield JSON.parse(line); - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (isAbortError(e)) - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new Stream(iterator, controller, client); - } - [(_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { - return this.iterator(); - } - /** - * Splits the stream into two streams which can be - * independently read from at different speeds. - */ - tee() { - const left = []; - const right = []; - const iterator = this.iterator(); - const teeIterator = (queue) => { - return { - next: () => { - if (queue.length === 0) { - const result = iterator.next(); - left.push(result); - right.push(result); - } - return queue.shift(); - }, - }; - }; - return [ - new Stream(() => teeIterator(left), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), - new Stream(() => teeIterator(right), this.controller, __classPrivateFieldGet(this, _Stream_client, "f")), - ]; - } - /** - * Converts this stream to a newline-separated ReadableStream of - * JSON stringified values in the stream - * which can be turned back into a Stream with `Stream.fromReadableStream()`. - */ - toReadableStream() { - const self = this; - let iter; - return makeReadableStream({ - async start() { - iter = self[Symbol.asyncIterator](); - }, - async pull(ctrl) { - try { - const { value, done } = await iter.next(); - if (done) - return ctrl.close(); - const bytes = bytes_encodeUTF8(JSON.stringify(value) + '\n'); - ctrl.enqueue(bytes); - } - catch (err) { - ctrl.error(err); - } - }, - async cancel() { - await iter.return?.(); - }, - }); - } -} -async function* _iterSSEMessages(response, controller) { - if (!response.body) { - controller.abort(); - if (typeof globalThis.navigator !== 'undefined' && - globalThis.navigator.product === 'ReactNative') { - throw new error_AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); - } - throw new error_AnthropicError(`Attempted to iterate over a response with no body`); - } - const sseDecoder = new SSEDecoder(); - const lineDecoder = new LineDecoder(); - const iter = ReadableStreamToAsyncIterable(response.body); - for await (const sseChunk of iterSSEChunks(iter)) { - for (const line of lineDecoder.decode(sseChunk)) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } - } - for (const line of lineDecoder.flush()) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } -} -/** - * Given an async iterable iterator, iterates over it and yields full - * SSE chunks, i.e. yields when a double new-line is encountered. - */ -async function* iterSSEChunks(iterator) { - let data = new Uint8Array(); - for await (const chunk of iterator) { - if (chunk == null) { - continue; - } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? bytes_encodeUTF8(chunk) - : chunk; - let newData = new Uint8Array(data.length + binaryChunk.length); - newData.set(data); - newData.set(binaryChunk, data.length); - data = newData; - let patternIndex; - while ((patternIndex = findDoubleNewlineIndex(data)) !== -1) { - yield data.slice(0, patternIndex); - data = data.slice(patternIndex); - } - } - if (data.length > 0) { - yield data; - } -} -class SSEDecoder { - constructor() { - this.event = null; - this.data = []; - this.chunks = []; - } - decode(line) { - if (line.endsWith('\r')) { - line = line.substring(0, line.length - 1); - } - if (!line) { - // empty line and we didn't previously encounter any messages - if (!this.event && !this.data.length) - return null; - const sse = { - event: this.event, - data: this.data.join('\n'), - raw: this.chunks, - }; - this.event = null; - this.data = []; - this.chunks = []; - return sse; - } - this.chunks.push(line); - if (line.startsWith(':')) { - return null; - } - let [fieldname, _, value] = partition(line, ':'); - if (value.startsWith(' ')) { - value = value.substring(1); - } - if (fieldname === 'event') { - this.event = value; - } - else if (fieldname === 'data') { - this.data.push(value); - } - return null; - } -} -function partition(str, delimiter) { - const index = str.indexOf(delimiter); - if (index !== -1) { - return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; - } - return [str, '', '']; -} -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/parse.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -async function defaultParseResponse(client, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (props.options.stream) { - loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); - // Note: there is an invariant here that isn't represented in the type system - // that if you set `stream: true` the response type must also be `Stream` - if (props.options.__streamClass) { - return props.options.__streamClass.fromSSEResponse(response, props.controller); - } - return Stream.fromSSEResponse(response, props.controller); - } - // fetch refuses to read the body when the status code is 204. - if (response.status === 204) { - return null; - } - if (props.options.__binaryResponse) { - return response; - } - const contentType = response.headers.get('content-type'); - const mediaType = contentType?.split(';')[0]?.trim(); - const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); - if (isJSON) { - const json = await response.json(); - return addRequestID(json, response); - } - const text = await response.text(); - return text; - })(); - loggerFor(client).debug(`[${requestLogID}] response parsed`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime, - })); - return body; -} -function addRequestID(value, response) { - if (!value || typeof value !== 'object' || Array.isArray(value)) { - return value; - } - return Object.defineProperty(value, '_request_id', { - value: response.headers.get('request-id'), - enumerable: false, - }); -} -//# sourceMappingURL=parse.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/api-promise.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _APIPromise_client; - - -/** - * A subclass of `Promise` providing additional helper methods - * for interacting with the SDK. - */ -class APIPromise extends Promise { - constructor(client, responsePromise, parseResponse = defaultParseResponse) { - super((resolve) => { - // this is maybe a bit weird but this has to be a no-op to not implicitly - // parse the response body; instead .then, .catch, .finally are overridden - // to parse the response - resolve(null); - }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - _APIPromise_client.set(this, void 0); - __classPrivateFieldSet(this, _APIPromise_client, client, "f"); - } - _thenUnwrap(transform) { - return new APIPromise(__classPrivateFieldGet(this, _APIPromise_client, "f"), this.responsePromise, async (client, props) => addRequestID(transform(await this.parseResponse(client, props), props), props.response)); - } - /** - * Gets the raw `Response` instance instead of parsing the response - * data. - * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - asResponse() { - return this.responsePromise.then((p) => p.response); - } - /** - * Gets the parsed response data, the raw `Response` instance and the ID of the request, - * returned via the `request-id` header which is useful for debugging requests and resporting - * issues to Anthropic. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response, request_id: response.headers.get('request-id') }; - } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(__classPrivateFieldGet(this, _APIPromise_client, "f"), data)); - } - return this.parsedPromise; - } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.parse().catch(onrejected); - } - finally(onfinally) { - return this.parse().finally(onfinally); - } -} -_APIPromise_client = new WeakMap(); -//# sourceMappingURL=api-promise.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/pagination.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _AbstractPage_client; - - - - - -class AbstractPage { - constructor(client, response, body, options) { - _AbstractPage_client.set(this, void 0); - __classPrivateFieldSet(this, _AbstractPage_client, client, "f"); - this.options = options; - this.response = response; - this.body = body; - } - hasNextPage() { - const items = this.getPaginatedItems(); - if (!items.length) - return false; - return this.nextPageRequestOptions() != null; - } - async getNextPage() { - const nextOptions = this.nextPageRequestOptions(); - if (!nextOptions) { - throw new error_AnthropicError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); - } - return await __classPrivateFieldGet(this, _AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); - } - async *iterPages() { - let page = this; - yield page; - while (page.hasNextPage()) { - page = await page.getNextPage(); - yield page; - } - } - async *[(_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; - } - } - } -} -/** - * This subclass of Promise will resolve to an instantiated Page once the request completes. - * - * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ -class PagePromise extends APIPromise { - constructor(client, request, Page) { - super(client, request, async (client, props) => new Page(client, props.response, await defaultParseResponse(client, props), props.options)); - } - /** - * Allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ - async *[Symbol.asyncIterator]() { - const page = await this; - for await (const item of page) { - yield item; - } - } -} -class Page extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; - this.first_id = body.first_id || null; - this.last_id = body.last_id || null; - } - getPaginatedItems() { - return this.data ?? []; - } - hasNextPage() { - if (this.has_more === false) { - return false; - } - return super.hasNextPage(); - } - nextPageRequestOptions() { - if (this.options.query?.['before_id']) { - // in reverse - const first_id = this.first_id; - if (!first_id) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - before_id: first_id, - }, - }; - } - const cursor = this.last_id; - if (!cursor) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - after_id: cursor, - }, - }; - } -} -class TokenPage extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; - this.next_page = body.next_page || null; - } - getPaginatedItems() { - return this.data ?? []; - } - hasNextPage() { - if (this.has_more === false) { - return false; - } - return super.hasNextPage(); - } - nextPageRequestOptions() { - const cursor = this.next_page; - if (!cursor) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - page_token: cursor, - }, - }; - } -} -class PageCursor extends AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; - this.next_page = body.next_page || null; - } - getPaginatedItems() { - return this.data ?? []; - } - hasNextPage() { - if (this.has_more === false) { - return false; - } - return super.hasNextPage(); - } - nextPageRequestOptions() { - const cursor = this.next_page; - if (!cursor) { - return null; - } - return { - ...this.options, - query: { - ...maybeObj(this.options.query), - page: cursor, - }, - }; - } -} -//# sourceMappingURL=pagination.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/uploads.mjs - -const checkFileSupport = () => { - if (typeof File === 'undefined') { - const { process } = globalThis; - const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; - throw new Error('`File` is not defined as a global, which is required for file uploads.' + - (isOldNode ? - " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." - : '')); - } -}; -/** - * Construct a `File` instance. This is used to ensure a helpful error is thrown - * for environments that don't define a global `File` yet. - */ -function makeFile(fileBits, fileName, options) { - checkFileSupport(); - return new File(fileBits, fileName ?? 'unknown_file', options); -} -function getName(value) { - return (((typeof value === 'object' && - value !== null && - (('name' in value && value.name && String(value.name)) || - ('url' in value && value.url && String(value.url)) || - ('filename' in value && value.filename && String(value.filename)) || - ('path' in value && value.path && String(value.path)))) || - '') - .split(/[\\/]/) - .pop() || undefined); -} -const uploads_isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; -/** - * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. - * Otherwise returns the request as is. - */ -const maybeMultipartFormRequestOptions = async (opts, fetch) => { - if (!hasUploadableValue(opts.body)) - return opts; - return { ...opts, body: await createForm(opts.body, fetch) }; -}; -const multipartFormRequestOptions = async (opts, fetch) => { - return { ...opts, body: await createForm(opts.body, fetch) }; -}; -const supportsFormDataMap = /* @__PURE__ */ new WeakMap(); -/** - * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending - * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". - * This function detects if the fetch function provided supports the global FormData object to avoid - * confusing error messages later on. - */ -function supportsFormData(fetchObject) { - const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; - const cached = supportsFormDataMap.get(fetch); - if (cached) - return cached; - const promise = (async () => { - try { - const FetchResponse = ('Response' in fetch ? - fetch.Response - : (await fetch('data:,')).constructor); - const data = new FormData(); - if (data.toString() === (await new FetchResponse(data).text())) { - return false; - } - return true; - } - catch { - // avoid false negatives - return true; - } - })(); - supportsFormDataMap.set(fetch, promise); - return promise; -} -const createForm = async (body, fetch) => { - if (!(await supportsFormData(fetch))) { - throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); - } - const form = new FormData(); - await Promise.all(Object.entries(body || {}).map(([key, value]) => addFormValue(form, key, value))); - return form; -}; -// We check for Blob not File because Bun.File doesn't inherit from File, -// but they both inherit from Blob and have a `name` property at runtime. -const isNamedBlob = (value) => value instanceof Blob && 'name' in value; -const isUploadable = (value) => typeof value === 'object' && - value !== null && - (value instanceof Response || uploads_isAsyncIterable(value) || isNamedBlob(value)); -const hasUploadableValue = (value) => { - if (isUploadable(value)) - return true; - if (Array.isArray(value)) - return value.some(hasUploadableValue); - if (value && typeof value === 'object') { - for (const k in value) { - if (hasUploadableValue(value[k])) - return true; - } - } - return false; -}; -const addFormValue = async (form, key, value) => { - if (value === undefined) - return; - if (value == null) { - throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); - } - // TODO: make nested formats configurable - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - form.append(key, String(value)); - } - else if (value instanceof Response) { - let options = {}; - const contentType = value.headers.get('Content-Type'); - if (contentType) { - options = { type: contentType }; - } - form.append(key, makeFile([await value.blob()], getName(value), options)); - } - else if (uploads_isAsyncIterable(value)) { - form.append(key, makeFile([await new Response(ReadableStreamFrom(value)).blob()], getName(value))); - } - else if (isNamedBlob(value)) { - form.append(key, makeFile([value], getName(value), { type: value.type })); - } - else if (Array.isArray(value)) { - await Promise.all(value.map((entry) => addFormValue(form, key + '[]', entry))); - } - else if (typeof value === 'object') { - await Promise.all(Object.entries(value).map(([name, prop]) => addFormValue(form, `${key}[${name}]`, prop))); - } - else { - throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); - } -}; -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/to-file.mjs - - -/** - * This check adds the arrayBuffer() method type because it is available and used at runtime - */ -const isBlobLike = (value) => value != null && - typeof value === 'object' && - typeof value.size === 'number' && - typeof value.type === 'string' && - typeof value.text === 'function' && - typeof value.slice === 'function' && - typeof value.arrayBuffer === 'function'; -/** - * This check adds the arrayBuffer() method type because it is available and used at runtime - */ -const isFileLike = (value) => value != null && - typeof value === 'object' && - typeof value.name === 'string' && - typeof value.lastModified === 'number' && - isBlobLike(value); -const isResponseLike = (value) => value != null && - typeof value === 'object' && - typeof value.url === 'string' && - typeof value.blob === 'function'; -/** - * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats - * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts - * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible - * @param {Object=} options additional properties - * @param {string=} options.type the MIME type of the content - * @param {number=} options.lastModified the last modified timestamp - * @returns a {@link File} with the given properties - */ -async function toFile(value, name, options) { - checkFileSupport(); - // If it's a promise, resolve it. - value = await value; - name || (name = getName(value)); - // If we've been given a `File` we don't need to do anything if the name / options - // have not been customised. - if (isFileLike(value)) { - if (value instanceof File && name == null && options == null) { - return value; - } - return makeFile([await value.arrayBuffer()], name ?? value.name, { - type: value.type, - lastModified: value.lastModified, - ...options, - }); - } - if (isResponseLike(value)) { - const blob = await value.blob(); - name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); - return makeFile(await to_file_getBytes(blob), name, options); - } - const parts = await to_file_getBytes(value); - if (!options?.type) { - const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); - if (typeof type === 'string') { - options = { ...options, type }; - } - } - return makeFile(parts, name, options); -} -async function to_file_getBytes(value) { - let parts = []; - if (typeof value === 'string' || - ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. - value instanceof ArrayBuffer) { - parts.push(value); - } - else if (isBlobLike(value)) { - parts.push(value instanceof Blob ? value : await value.arrayBuffer()); - } - else if (uploads_isAsyncIterable(value) // includes Readable, ReadableStream, etc. - ) { - for await (const chunk of value) { - parts.push(...(await to_file_getBytes(chunk))); // TODO, consider validating? - } - } - else { - const constructor = value?.constructor?.name; - throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${propsForError(value)}`); - } - return parts; -} -function propsForError(value) { - if (typeof value !== 'object' || value === null) - return ''; - const props = Object.getOwnPropertyNames(value); - return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; -} -//# sourceMappingURL=to-file.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/uploads.mjs - -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/core/resource.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class APIResource { - constructor(client) { - this._client = client; - } -} -//# sourceMappingURL=resource.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/headers.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const brand_privateNullableHeaders = Symbol.for('brand.privateNullableHeaders'); -function* iterateHeaders(headers) { - if (!headers) - return; - if (brand_privateNullableHeaders in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) { - yield [name, null]; - } - return; - } - let shouldClear = false; - let iter; - if (headers instanceof Headers) { - iter = headers.entries(); - } - else if (isReadonlyArray(headers)) { - iter = headers; - } - else { - shouldClear = true; - iter = Object.entries(headers ?? {}); - } - for (let row of iter) { - const name = row[0]; - if (typeof name !== 'string') - throw new TypeError('expected header name to be a string'); - const values = isReadonlyArray(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === undefined) - continue; - // Objects keys always overwrite older headers, they never append. - // Yield a null to clear the header before adding the new values. - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; - } - yield [name, value]; - } - } -} -const buildHeaders = (newHeaders) => { - const targetHeaders = new Headers(); - const nullHeaders = new Set(); - for (const headers of newHeaders) { - const seenHeaders = new Set(); - for (const [name, value] of iterateHeaders(headers)) { - const lowerName = name.toLowerCase(); - if (!seenHeaders.has(lowerName)) { - targetHeaders.delete(name); - seenHeaders.add(lowerName); - } - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); - } - else { - targetHeaders.append(name, value); - nullHeaders.delete(lowerName); - } - } - } - return { [brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; -}; -const isEmptyHeaders = (headers) => { - for (const _ of iterateHeaders(headers)) - return false; - return true; -}; -//# sourceMappingURL=headers.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/path.mjs - -/** - * Percent-encode everything that isn't safe to have in a path without encoding safe chars. - * - * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: - * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - */ -function encodeURIPath(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); -} -const EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); -const createPathTagFunction = (pathEncoder = encodeURIPath) => function path(statics, ...params) { - // If there are no params, no processing is needed. - if (statics.length === 1) - return statics[0]; - let postPath = false; - const invalidSegments = []; - const path = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) { - postPath = true; - } - const value = params[index]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); - if (index !== params.length && - (value == null || - (typeof value === 'object' && - // handle values from other realms - value.toString === - Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? EMPTY) ?? EMPTY) - ?.toString))) { - encoded = value + ''; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString - .call(value) - .slice(8, -1)} is not a valid path parameter`, - }); - } - return previousValue + currentValue + (index === params.length ? '' : encoded); - }, ''); - const pathOnly = path.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - // Find all invalid segments - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match.index, - length: match[0].length, - error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, - }); - } - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = ' '.repeat(segment.start - lastEnd); - const arrows = '^'.repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ''); - throw new error_AnthropicError(`Path parameters result in path with invalid segments:\n${invalidSegments - .map((e) => e.error) - .join('\n')}\n${path}\n${underline}`); - } - return path; -}; -/** - * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. - */ -const path = /* @__PURE__ */ createPathTagFunction(encodeURIPath); -//# sourceMappingURL=path.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/files.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class Files extends APIResource { - /** - * List Files - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const fileMetadata of client.beta.files.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/files', (Page), { - query, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, - options?.headers, - ]), - }); - } - /** - * Delete File - * - * @example - * ```ts - * const deletedFile = await client.beta.files.delete( - * 'file_id', - * ); - * ``` - */ - delete(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path `/v1/files/${fileID}`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, - options?.headers, - ]), - }); - } - /** - * Download File - * - * @example - * ```ts - * const response = await client.beta.files.download( - * 'file_id', - * ); - * - * const content = await response.blob(); - * console.log(content); - * ``` - */ - download(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/files/${fileID}/content`, { - ...options, - headers: buildHeaders([ - { - 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString(), - Accept: 'application/binary', - }, - options?.headers, - ]), - __binaryResponse: true, - }); - } - /** - * Get File Metadata - * - * @example - * ```ts - * const fileMetadata = - * await client.beta.files.retrieveMetadata('file_id'); - * ``` - */ - retrieveMetadata(fileID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/files/${fileID}`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, - options?.headers, - ]), - }); - } - /** - * Upload File - * - * @example - * ```ts - * const fileMetadata = await client.beta.files.upload({ - * file: fs.createReadStream('path/to/file'), - * }); - * ``` - */ - upload(params, options) { - const { betas, ...body } = params; - return this._client.post('/v1/files', multipartFormRequestOptions({ - body, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'files-api-2025-04-14'].toString() }, - options?.headers, - ]), - }, this._client)); - } -} -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class Models extends APIResource { - /** - * Get a specific model. - * - * The Models API response can be used to determine information about a specific - * model or resolve a model alias to a model ID. - * - * @example - * ```ts - * const betaModelInfo = await client.beta.models.retrieve( - * 'model_id', - * ); - * ``` - */ - retrieve(modelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/models/${modelID}?beta=true`, { - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - }); - } - /** - * List available models. - * - * The Models API response can be used to determine which models are available for - * use in the API. More recently released models are listed first. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaModelInfo of client.beta.models.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/models?beta=true', (Page), { - query, - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - }); - } -} -//# sourceMappingURL=models.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/constants.mjs -// File containing shared constants -/** - * Model-specific timeout constraints for non-streaming requests - */ -const MODEL_NONSTREAMING_TOKENS = { - 'claude-opus-4-20250514': 8192, - 'claude-opus-4-0': 8192, - 'claude-4-opus-20250514': 8192, - 'anthropic.claude-opus-4-20250514-v1:0': 8192, - 'claude-opus-4@20250514': 8192, - 'claude-opus-4-1-20250805': 8192, - 'anthropic.claude-opus-4-1-20250805-v1:0': 8192, - 'claude-opus-4-1@20250805': 8192, -}; -//# sourceMappingURL=constants.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/beta-parser.mjs - -function maybeParseBetaMessage(message, params, opts) { - if (!params || !('parse' in (params.output_format ?? {}))) { - return { - ...message, - content: message.content.map((block) => { - if (block.type === 'text') { - const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', { - value: null, - enumerable: false, - }); - return Object.defineProperty(parsedBlock, 'parsed', { - get() { - opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.'); - return null; - }, - enumerable: false, - }); - } - return block; - }), - parsed_output: null, - }; - } - return parseBetaMessage(message, params, opts); -} -function parseBetaMessage(message, params, opts) { - let firstParsedOutput = null; - const content = message.content.map((block) => { - if (block.type === 'text') { - const parsedOutput = parseBetaOutputFormat(params, block.text); - if (firstParsedOutput === null) { - firstParsedOutput = parsedOutput; - } - const parsedBlock = Object.defineProperty({ ...block }, 'parsed_output', { - value: parsedOutput, - enumerable: false, - }); - return Object.defineProperty(parsedBlock, 'parsed', { - get() { - opts.logger.warn('The `parsed` property on `text` blocks is deprecated, please use `parsed_output` instead.'); - return parsedOutput; - }, - enumerable: false, - }); - } - return block; - }); - return { - ...message, - content, - parsed_output: firstParsedOutput, - }; -} -function parseBetaOutputFormat(params, content) { - if (params.output_format?.type !== 'json_schema') { - return null; - } - try { - if ('parse' in params.output_format) { - return params.output_format.parse(content); - } - return JSON.parse(content); - } - catch (error) { - throw new error_AnthropicError(`Failed to parse structured output: ${error}`); - } -} -//# sourceMappingURL=beta-parser.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/_vendor/partial-json-parser/parser.mjs -const tokenize = (input) => { - let current = 0; - let tokens = []; - while (current < input.length) { - let char = input[current]; - if (char === '\\') { - current++; - continue; - } - if (char === '{') { - tokens.push({ - type: 'brace', - value: '{', - }); - current++; - continue; - } - if (char === '}') { - tokens.push({ - type: 'brace', - value: '}', - }); - current++; - continue; - } - if (char === '[') { - tokens.push({ - type: 'paren', - value: '[', - }); - current++; - continue; - } - if (char === ']') { - tokens.push({ - type: 'paren', - value: ']', - }); - current++; - continue; - } - if (char === ':') { - tokens.push({ - type: 'separator', - value: ':', - }); - current++; - continue; - } - if (char === ',') { - tokens.push({ - type: 'delimiter', - value: ',', - }); - current++; - continue; - } - if (char === '"') { - let value = ''; - let danglingQuote = false; - char = input[++current]; - while (char !== '"') { - if (current === input.length) { - danglingQuote = true; - break; - } - if (char === '\\') { - current++; - if (current === input.length) { - danglingQuote = true; - break; - } - value += char + input[current]; - char = input[++current]; - } - else { - value += char; - char = input[++current]; - } - } - char = input[++current]; - if (!danglingQuote) { - tokens.push({ - type: 'string', - value, - }); - } - continue; - } - let WHITESPACE = /\s/; - if (char && WHITESPACE.test(char)) { - current++; - continue; - } - let NUMBERS = /[0-9]/; - if ((char && NUMBERS.test(char)) || char === '-' || char === '.') { - let value = ''; - if (char === '-') { - value += char; - char = input[++current]; - } - while ((char && NUMBERS.test(char)) || char === '.') { - value += char; - char = input[++current]; - } - tokens.push({ - type: 'number', - value, - }); - continue; - } - let LETTERS = /[a-z]/i; - if (char && LETTERS.test(char)) { - let value = ''; - while (char && LETTERS.test(char)) { - if (current === input.length) { - break; - } - value += char; - char = input[++current]; - } - if (value == 'true' || value == 'false' || value === 'null') { - tokens.push({ - type: 'name', - value, - }); - } - else { - // unknown token, e.g. `nul` which isn't quite `null` - current++; - continue; - } - continue; - } - current++; - } - return tokens; -}, parser_strip = (tokens) => { - if (tokens.length === 0) { - return tokens; - } - let lastToken = tokens[tokens.length - 1]; - switch (lastToken.type) { - case 'separator': - tokens = tokens.slice(0, tokens.length - 1); - return parser_strip(tokens); - break; - case 'number': - let lastCharacterOfLastToken = lastToken.value[lastToken.value.length - 1]; - if (lastCharacterOfLastToken === '.' || lastCharacterOfLastToken === '-') { - tokens = tokens.slice(0, tokens.length - 1); - return parser_strip(tokens); - } - case 'string': - let tokenBeforeTheLastToken = tokens[tokens.length - 2]; - if (tokenBeforeTheLastToken?.type === 'delimiter') { - tokens = tokens.slice(0, tokens.length - 1); - return parser_strip(tokens); - } - else if (tokenBeforeTheLastToken?.type === 'brace' && tokenBeforeTheLastToken.value === '{') { - tokens = tokens.slice(0, tokens.length - 1); - return parser_strip(tokens); - } - break; - case 'delimiter': - tokens = tokens.slice(0, tokens.length - 1); - return parser_strip(tokens); - break; - } - return tokens; -}, unstrip = (tokens) => { - let tail = []; - tokens.map((token) => { - if (token.type === 'brace') { - if (token.value === '{') { - tail.push('}'); - } - else { - tail.splice(tail.lastIndexOf('}'), 1); - } - } - if (token.type === 'paren') { - if (token.value === '[') { - tail.push(']'); - } - else { - tail.splice(tail.lastIndexOf(']'), 1); - } - } - }); - if (tail.length > 0) { - tail.reverse().map((item) => { - if (item === '}') { - tokens.push({ - type: 'brace', - value: '}', - }); - } - else if (item === ']') { - tokens.push({ - type: 'paren', - value: ']', - }); - } - }); - } - return tokens; -}, generate = (tokens) => { - let output = ''; - tokens.map((token) => { - switch (token.type) { - case 'string': - output += '"' + token.value + '"'; - break; - default: - output += token.value; - break; - } - }); - return output; -}, partialParse = (input) => JSON.parse(generate(unstrip(parser_strip(tokenize(input))))); - -//# sourceMappingURL=parser.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/error.mjs - -//# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/streaming.mjs - -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/BetaMessageStream.mjs -var _BetaMessageStream_instances, _BetaMessageStream_currentMessageSnapshot, _BetaMessageStream_params, _BetaMessageStream_connectedPromise, _BetaMessageStream_resolveConnectedPromise, _BetaMessageStream_rejectConnectedPromise, _BetaMessageStream_endPromise, _BetaMessageStream_resolveEndPromise, _BetaMessageStream_rejectEndPromise, _BetaMessageStream_listeners, _BetaMessageStream_ended, _BetaMessageStream_errored, _BetaMessageStream_aborted, _BetaMessageStream_catchingPromiseCreated, _BetaMessageStream_response, _BetaMessageStream_request_id, _BetaMessageStream_logger, _BetaMessageStream_getFinalMessage, _BetaMessageStream_getFinalText, _BetaMessageStream_handleError, _BetaMessageStream_beginRequest, _BetaMessageStream_addStreamEvent, _BetaMessageStream_endRequest, _BetaMessageStream_accumulateMessage; - - - - - - -const JSON_BUF_PROPERTY = '__json_buf'; -function tracksToolInput(content) { - return content.type === 'tool_use' || content.type === 'server_tool_use' || content.type === 'mcp_tool_use'; -} -class BetaMessageStream { - constructor(params, opts) { - _BetaMessageStream_instances.add(this); - this.messages = []; - this.receivedMessages = []; - _BetaMessageStream_currentMessageSnapshot.set(this, void 0); - _BetaMessageStream_params.set(this, null); - this.controller = new AbortController(); - _BetaMessageStream_connectedPromise.set(this, void 0); - _BetaMessageStream_resolveConnectedPromise.set(this, () => { }); - _BetaMessageStream_rejectConnectedPromise.set(this, () => { }); - _BetaMessageStream_endPromise.set(this, void 0); - _BetaMessageStream_resolveEndPromise.set(this, () => { }); - _BetaMessageStream_rejectEndPromise.set(this, () => { }); - _BetaMessageStream_listeners.set(this, {}); - _BetaMessageStream_ended.set(this, false); - _BetaMessageStream_errored.set(this, false); - _BetaMessageStream_aborted.set(this, false); - _BetaMessageStream_catchingPromiseCreated.set(this, false); - _BetaMessageStream_response.set(this, void 0); - _BetaMessageStream_request_id.set(this, void 0); - _BetaMessageStream_logger.set(this, void 0); - _BetaMessageStream_handleError.set(this, (error) => { - __classPrivateFieldSet(this, _BetaMessageStream_errored, true, "f"); - if (isAbortError(error)) { - error = new APIUserAbortError(); - } - if (error instanceof APIUserAbortError) { - __classPrivateFieldSet(this, _BetaMessageStream_aborted, true, "f"); - return this._emit('abort', error); - } - if (error instanceof error_AnthropicError) { - return this._emit('error', error); - } - if (error instanceof Error) { - const anthropicError = new error_AnthropicError(error.message); - // @ts-ignore - anthropicError.cause = error; - return this._emit('error', anthropicError); - } - return this._emit('error', new error_AnthropicError(String(error))); - }); - __classPrivateFieldSet(this, _BetaMessageStream_connectedPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_resolveConnectedPromise, resolve, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_rejectConnectedPromise, reject, "f"); - }), "f"); - __classPrivateFieldSet(this, _BetaMessageStream_endPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_resolveEndPromise, resolve, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_rejectEndPromise, reject, "f"); - }), "f"); - // Don't let these promises cause unhandled rejection errors. - // we will manually cause an unhandled rejection error later - // if the user hasn't registered any error listener or called - // any promise-returning method. - __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f").catch(() => { }); - __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f").catch(() => { }); - __classPrivateFieldSet(this, _BetaMessageStream_params, params, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_logger, opts?.logger ?? console, "f"); - } - get response() { - return __classPrivateFieldGet(this, _BetaMessageStream_response, "f"); - } - get request_id() { - return __classPrivateFieldGet(this, _BetaMessageStream_request_id, "f"); - } - /** - * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, - * returned vie the `request-id` header which is useful for debugging requests and resporting - * issues to Anthropic. - * - * This is the same as the `APIPromise.withResponse()` method. - * - * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` - * as no `Response` is available. - */ - async withResponse() { - __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - const response = await __classPrivateFieldGet(this, _BetaMessageStream_connectedPromise, "f"); - if (!response) { - throw new Error('Could not resolve a `Response` object'); - } - return { - data: this, - response, - request_id: response.headers.get('request-id'), - }; - } - /** - * Intended for use on the frontend, consuming a stream produced with - * `.toReadableStream()` on the backend. - * - * Note that messages sent to the model do not appear in `.on('message')` - * in this context. - */ - static fromReadableStream(stream) { - const runner = new BetaMessageStream(null); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - static createMessage(messages, params, options, { logger } = {}) { - const runner = new BetaMessageStream(params, { logger }); - for (const message of params.messages) { - runner._addMessageParam(message); - } - __classPrivateFieldSet(runner, _BetaMessageStream_params, { ...params, stream: true }, "f"); - runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); - return runner; - } - _run(executor) { - executor().then(() => { - this._emitFinal(); - this._emit('end'); - }, __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f")); - } - _addMessageParam(message) { - this.messages.push(message); - } - _addMessage(message, emit = true) { - this.receivedMessages.push(message); - if (emit) { - this._emit('message', message); - } - } - async _createMessage(messages, params, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener('abort', abortHandler); - } - try { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - const { response, data: stream } = await messages - .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) - .withResponse(); - this._connected(response); - for await (const event of stream) { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); - } - finally { - if (signal && abortHandler) { - signal.removeEventListener('abort', abortHandler); - } - } - } - _connected(response) { - if (this.ended) - return; - __classPrivateFieldSet(this, _BetaMessageStream_response, response, "f"); - __classPrivateFieldSet(this, _BetaMessageStream_request_id, response?.headers.get('request-id'), "f"); - __classPrivateFieldGet(this, _BetaMessageStream_resolveConnectedPromise, "f").call(this, response); - this._emit('connect'); - } - get ended() { - return __classPrivateFieldGet(this, _BetaMessageStream_ended, "f"); - } - get errored() { - return __classPrivateFieldGet(this, _BetaMessageStream_errored, "f"); - } - get aborted() { - return __classPrivateFieldGet(this, _BetaMessageStream_aborted, "f"); - } - abort() { - this.controller.abort(); - } - /** - * Adds the listener function to the end of the listeners array for the event. - * No checks are made to see if the listener has already been added. Multiple calls passing - * the same combination of event and listener will result in the listener being added, and - * called, multiple times. - * @returns this MessageStream, so that calls can be chained - */ - on(event, listener) { - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); - listeners.push({ listener }); - return this; - } - /** - * Removes the specified listener from the listener array for the event. - * off() will remove, at most, one instance of a listener from the listener array. If any single - * listener has been added multiple times to the listener array for the specified event, then - * off() must be called multiple times to remove each instance. - * @returns this MessageStream, so that calls can be chained - */ - off(event, listener) { - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; - if (!listeners) - return this; - const index = listeners.findIndex((l) => l.listener === listener); - if (index >= 0) - listeners.splice(index, 1); - return this; - } - /** - * Adds a one-time listener function for the event. The next time the event is triggered, - * this listener is removed and then invoked. - * @returns this MessageStream, so that calls can be chained - */ - once(event, listener) { - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = []); - listeners.push({ listener, once: true }); - return this; - } - /** - * This is similar to `.once()`, but returns a Promise that resolves the next time - * the event is triggered, instead of calling a listener callback. - * @returns a Promise that resolves the next time given event is triggered, - * or rejects if an error is emitted. (If you request the 'error' event, - * returns a promise that resolves with the error). - * - * Example: - * - * const message = await stream.emitted('message') // rejects if the stream errors - */ - emitted(event) { - return new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - if (event !== 'error') - this.once('error', reject); - this.once(event, resolve); - }); - } - async done() { - __classPrivateFieldSet(this, _BetaMessageStream_catchingPromiseCreated, true, "f"); - await __classPrivateFieldGet(this, _BetaMessageStream_endPromise, "f"); - } - get currentMessage() { - return __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); - } - /** - * @returns a promise that resolves with the the final assistant Message response, - * or rejects if an error occurred or the stream ended prematurely without producing a Message. - * If structured outputs were used, this will be a ParsedMessage with a `parsed` field. - */ - async finalMessage() { - await this.done(); - return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this); - } - /** - * @returns a promise that resolves with the the final assistant Message's text response, concatenated - * together if there are more than one text blocks. - * Rejects if an error occurred or the stream ended prematurely without producing a Message. - */ - async finalText() { - await this.done(); - return __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalText).call(this); - } - _emit(event, ...args) { - // make sure we don't emit any MessageStreamEvents after end - if (__classPrivateFieldGet(this, _BetaMessageStream_ended, "f")) - return; - if (event === 'end') { - __classPrivateFieldSet(this, _BetaMessageStream_ended, true, "f"); - __classPrivateFieldGet(this, _BetaMessageStream_resolveEndPromise, "f").call(this); - } - const listeners = __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event]; - if (listeners) { - __classPrivateFieldGet(this, _BetaMessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); - } - if (event === 'abort') { - const error = args[0]; - if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error); - } - __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - return; - } - if (event === 'error') { - // NOTE: _emit('error', error) should only be called from #handleError(). - const error = args[0]; - if (!__classPrivateFieldGet(this, _BetaMessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - // Trigger an unhandled rejection if the user hasn't registered any error handlers. - // If you are seeing stack traces here, make sure to handle errors via either: - // - runner.on('error', () => ...) - // - await runner.done() - // - await runner.final...() - // - etc. - Promise.reject(error); - } - __classPrivateFieldGet(this, _BetaMessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _BetaMessageStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - } - } - _emitFinal() { - const finalMessage = this.receivedMessages.at(-1); - if (finalMessage) { - this._emit('finalMessage', __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_getFinalMessage).call(this)); - } - } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener('abort', abortHandler); - } - try { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_beginRequest).call(this); - this._connected(null); - const stream = Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) { - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_addStreamEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_endRequest).call(this); - } - finally { - if (signal && abortHandler) { - signal.removeEventListener('abort', abortHandler); - } - } - } - [(_BetaMessageStream_currentMessageSnapshot = new WeakMap(), _BetaMessageStream_params = new WeakMap(), _BetaMessageStream_connectedPromise = new WeakMap(), _BetaMessageStream_resolveConnectedPromise = new WeakMap(), _BetaMessageStream_rejectConnectedPromise = new WeakMap(), _BetaMessageStream_endPromise = new WeakMap(), _BetaMessageStream_resolveEndPromise = new WeakMap(), _BetaMessageStream_rejectEndPromise = new WeakMap(), _BetaMessageStream_listeners = new WeakMap(), _BetaMessageStream_ended = new WeakMap(), _BetaMessageStream_errored = new WeakMap(), _BetaMessageStream_aborted = new WeakMap(), _BetaMessageStream_catchingPromiseCreated = new WeakMap(), _BetaMessageStream_response = new WeakMap(), _BetaMessageStream_request_id = new WeakMap(), _BetaMessageStream_logger = new WeakMap(), _BetaMessageStream_handleError = new WeakMap(), _BetaMessageStream_instances = new WeakSet(), _BetaMessageStream_getFinalMessage = function _BetaMessageStream_getFinalMessage() { - if (this.receivedMessages.length === 0) { - throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); - } - return this.receivedMessages.at(-1); - }, _BetaMessageStream_getFinalText = function _BetaMessageStream_getFinalText() { - if (this.receivedMessages.length === 0) { - throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); - } - const textBlocks = this.receivedMessages - .at(-1) - .content.filter((block) => block.type === 'text') - .map((block) => block.text); - if (textBlocks.length === 0) { - throw new error_AnthropicError('stream ended without producing a content block with type=text'); - } - return textBlocks.join(' '); - }, _BetaMessageStream_beginRequest = function _BetaMessageStream_beginRequest() { - if (this.ended) - return; - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); - }, _BetaMessageStream_addStreamEvent = function _BetaMessageStream_addStreamEvent(event) { - if (this.ended) - return; - const messageSnapshot = __classPrivateFieldGet(this, _BetaMessageStream_instances, "m", _BetaMessageStream_accumulateMessage).call(this, event); - this._emit('streamEvent', event, messageSnapshot); - switch (event.type) { - case 'content_block_delta': { - const content = messageSnapshot.content.at(-1); - switch (event.delta.type) { - case 'text_delta': { - if (content.type === 'text') { - this._emit('text', event.delta.text, content.text || ''); - } - break; - } - case 'citations_delta': { - if (content.type === 'text') { - this._emit('citation', event.delta.citation, content.citations ?? []); - } - break; - } - case 'input_json_delta': { - if (tracksToolInput(content) && content.input) { - this._emit('inputJson', event.delta.partial_json, content.input); - } - break; - } - case 'thinking_delta': { - if (content.type === 'thinking') { - this._emit('thinking', event.delta.thinking, content.thinking); - } - break; - } - case 'signature_delta': { - if (content.type === 'thinking') { - this._emit('signature', content.signature); - } - break; - } - default: - checkNever(event.delta); - } - break; - } - case 'message_stop': { - this._addMessageParam(messageSnapshot); - this._addMessage(maybeParseBetaMessage(messageSnapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }), true); - break; - } - case 'content_block_stop': { - this._emit('contentBlock', messageSnapshot.content.at(-1)); - break; - } - case 'message_start': { - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, messageSnapshot, "f"); - break; - } - case 'content_block_start': - case 'message_delta': - break; - } - }, _BetaMessageStream_endRequest = function _BetaMessageStream_endRequest() { - if (this.ended) { - throw new error_AnthropicError(`stream has ended, this shouldn't happen`); - } - const snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); - if (!snapshot) { - throw new error_AnthropicError(`request ended without sending any chunks`); - } - __classPrivateFieldSet(this, _BetaMessageStream_currentMessageSnapshot, undefined, "f"); - return maybeParseBetaMessage(snapshot, __classPrivateFieldGet(this, _BetaMessageStream_params, "f"), { logger: __classPrivateFieldGet(this, _BetaMessageStream_logger, "f") }); - }, _BetaMessageStream_accumulateMessage = function _BetaMessageStream_accumulateMessage(event) { - let snapshot = __classPrivateFieldGet(this, _BetaMessageStream_currentMessageSnapshot, "f"); - if (event.type === 'message_start') { - if (snapshot) { - throw new error_AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); - } - return event.message; - } - if (!snapshot) { - throw new error_AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); - } - switch (event.type) { - case 'message_stop': - return snapshot; - case 'message_delta': - snapshot.container = event.delta.container; - snapshot.stop_reason = event.delta.stop_reason; - snapshot.stop_sequence = event.delta.stop_sequence; - snapshot.usage.output_tokens = event.usage.output_tokens; - snapshot.context_management = event.context_management; - if (event.usage.input_tokens != null) { - snapshot.usage.input_tokens = event.usage.input_tokens; - } - if (event.usage.cache_creation_input_tokens != null) { - snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; - } - if (event.usage.cache_read_input_tokens != null) { - snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; - } - if (event.usage.server_tool_use != null) { - snapshot.usage.server_tool_use = event.usage.server_tool_use; - } - return snapshot; - case 'content_block_start': - snapshot.content.push(event.content_block); - return snapshot; - case 'content_block_delta': { - const snapshotContent = snapshot.content.at(event.index); - switch (event.delta.type) { - case 'text_delta': { - if (snapshotContent?.type === 'text') { - snapshot.content[event.index] = { - ...snapshotContent, - text: (snapshotContent.text || '') + event.delta.text, - }; - } - break; - } - case 'citations_delta': { - if (snapshotContent?.type === 'text') { - snapshot.content[event.index] = { - ...snapshotContent, - citations: [...(snapshotContent.citations ?? []), event.delta.citation], - }; - } - break; - } - case 'input_json_delta': { - if (snapshotContent && tracksToolInput(snapshotContent)) { - // we need to keep track of the raw JSON string as well so that we can - // re-parse it for each delta, for now we just store it as an untyped - // non-enumerable property on the snapshot - let jsonBuf = snapshotContent[JSON_BUF_PROPERTY] || ''; - jsonBuf += event.delta.partial_json; - const newContent = { ...snapshotContent }; - Object.defineProperty(newContent, JSON_BUF_PROPERTY, { - value: jsonBuf, - enumerable: false, - writable: true, - }); - if (jsonBuf) { - try { - newContent.input = partialParse(jsonBuf); - } - catch (err) { - const error = new error_AnthropicError(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${err}. JSON: ${jsonBuf}`); - __classPrivateFieldGet(this, _BetaMessageStream_handleError, "f").call(this, error); - } - } - snapshot.content[event.index] = newContent; - } - break; - } - case 'thinking_delta': { - if (snapshotContent?.type === 'thinking') { - snapshot.content[event.index] = { - ...snapshotContent, - thinking: snapshotContent.thinking + event.delta.thinking, - }; - } - break; - } - case 'signature_delta': { - if (snapshotContent?.type === 'thinking') { - snapshot.content[event.index] = { - ...snapshotContent, - signature: event.delta.signature, - }; - } - break; - } - default: - checkNever(event.delta); - } - return snapshot; - } - case 'content_block_stop': - return snapshot; - } - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on('streamEvent', (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); - } - else { - pushQueue.push(event); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; - } - toReadableStream() { - const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream.toReadableStream(); - } -} -// used to ensure exhaustive case matching without throwing a runtime error -function checkNever(x) { } -//# sourceMappingURL=BetaMessageStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/tools/CompactionControl.mjs -const DEFAULT_TOKEN_THRESHOLD = 100000; -const DEFAULT_SUMMARY_PROMPT = `You have been working on the task described above but have not yet completed it. Write a continuation summary that will allow you (or another instance of yourself) to resume work efficiently in a future context window where the conversation history will be replaced with this summary. Your summary should be structured, concise, and actionable. Include: -1. Task Overview -The user's core request and success criteria -Any clarifications or constraints they specified -2. Current State -What has been completed so far -Files created, modified, or analyzed (with paths if relevant) -Key outputs or artifacts produced -3. Important Discoveries -Technical constraints or requirements uncovered -Decisions made and their rationale -Errors encountered and how they were resolved -What approaches were tried that didn't work (and why) -4. Next Steps -Specific actions needed to complete the task -Any blockers or open questions to resolve -Priority order if multiple steps remain -5. Context to Preserve -User preferences or style requirements -Domain-specific details that aren't obvious -Any promises made to the user -Be concise but complete—err on the side of including information that would prevent duplicate work or repeated mistakes. Write in a way that enables immediate resumption of the task. -Wrap your summary in tags.`; -//# sourceMappingURL=CompactionControl.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/tools/BetaToolRunner.mjs -var _BetaToolRunner_instances, _BetaToolRunner_consumed, _BetaToolRunner_mutated, _BetaToolRunner_state, _BetaToolRunner_options, _BetaToolRunner_message, _BetaToolRunner_toolResponse, _BetaToolRunner_completion, _BetaToolRunner_iterationCount, _BetaToolRunner_checkAndCompact, _BetaToolRunner_generateToolResponse; - - - - -/** - * Just Promise.withResolvers(), which is not available in all environments. - */ -function promiseWithResolvers() { - let resolve; - let reject; - const promise = new Promise((res, rej) => { - resolve = res; - reject = rej; - }); - return { promise, resolve: resolve, reject: reject }; -} -/** - * A ToolRunner handles the automatic conversation loop between the assistant and tools. - * - * A ToolRunner is an async iterable that yields either BetaMessage or BetaMessageStream objects - * depending on the streaming configuration. - */ -class BetaToolRunner { - constructor(client, params, options) { - _BetaToolRunner_instances.add(this); - this.client = client; - /** Whether the async iterator has been consumed */ - _BetaToolRunner_consumed.set(this, false); - /** Whether parameters have been mutated since the last API call */ - _BetaToolRunner_mutated.set(this, false); - /** Current state containing the request parameters */ - _BetaToolRunner_state.set(this, void 0); - _BetaToolRunner_options.set(this, void 0); - /** Promise for the last message received from the assistant */ - _BetaToolRunner_message.set(this, void 0); - /** Cached tool response to avoid redundant executions */ - _BetaToolRunner_toolResponse.set(this, void 0); - /** Promise resolvers for waiting on completion */ - _BetaToolRunner_completion.set(this, void 0); - /** Number of iterations (API requests) made so far */ - _BetaToolRunner_iterationCount.set(this, 0); - __classPrivateFieldSet(this, _BetaToolRunner_state, { - params: { - // You can't clone the entire params since there are functions as handlers. - // You also don't really need to clone params.messages, but it probably will prevent a foot gun - // somewhere. - ...params, - messages: structuredClone(params.messages), - }, - }, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_options, { - ...options, - headers: buildHeaders([{ 'x-stainless-helper': 'BetaToolRunner' }, options?.headers]), - }, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); - } - async *[(_BetaToolRunner_consumed = new WeakMap(), _BetaToolRunner_mutated = new WeakMap(), _BetaToolRunner_state = new WeakMap(), _BetaToolRunner_options = new WeakMap(), _BetaToolRunner_message = new WeakMap(), _BetaToolRunner_toolResponse = new WeakMap(), _BetaToolRunner_completion = new WeakMap(), _BetaToolRunner_iterationCount = new WeakMap(), _BetaToolRunner_instances = new WeakSet(), _BetaToolRunner_checkAndCompact = async function _BetaToolRunner_checkAndCompact() { - const compactionControl = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.compactionControl; - if (!compactionControl || !compactionControl.enabled) { - return false; - } - let tokensUsed = 0; - if (__classPrivateFieldGet(this, _BetaToolRunner_message, "f") !== undefined) { - try { - const message = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); - const totalInputTokens = message.usage.input_tokens + - (message.usage.cache_creation_input_tokens ?? 0) + - (message.usage.cache_read_input_tokens ?? 0); - tokensUsed = totalInputTokens + message.usage.output_tokens; - } - catch { - // If we can't get the message, skip compaction - return false; - } - } - const threshold = compactionControl.contextTokenThreshold ?? DEFAULT_TOKEN_THRESHOLD; - if (tokensUsed < threshold) { - return false; - } - const model = compactionControl.model ?? __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.model; - const summaryPrompt = compactionControl.summaryPrompt ?? DEFAULT_SUMMARY_PROMPT; - const messages = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages; - if (messages[messages.length - 1].role === 'assistant') { - // Remove tool_use blocks from the last message to avoid 400 error - // (tool_use requires tool_result, which we don't have yet) - const lastMessage = messages[messages.length - 1]; - if (Array.isArray(lastMessage.content)) { - const nonToolBlocks = lastMessage.content.filter((block) => block.type !== 'tool_use'); - if (nonToolBlocks.length === 0) { - // If all blocks were tool_use, just remove the message entirely - messages.pop(); - } - else { - lastMessage.content = nonToolBlocks; - } - } - } - const response = await this.client.beta.messages.create({ - model, - messages: [ - ...messages, - { - role: 'user', - content: [ - { - type: 'text', - text: summaryPrompt, - }, - ], - }, - ], - max_tokens: __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_tokens, - }, { - headers: { 'x-stainless-helper': 'compaction' }, - }); - if (response.content[0]?.type !== 'text') { - throw new error_AnthropicError('Expected text response for compaction'); - } - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages = [ - { - role: 'user', - content: response.content, - }, - ]; - return true; - }, Symbol.asyncIterator)]() { - var _a; - if (__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { - throw new error_AnthropicError('Cannot iterate over a consumed stream'); - } - __classPrivateFieldSet(this, _BetaToolRunner_consumed, true, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); - try { - while (true) { - let stream; - try { - if (__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations && - __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f") >= __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.max_iterations) { - break; - } - __classPrivateFieldSet(this, _BetaToolRunner_mutated, false, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); - __classPrivateFieldSet(this, _BetaToolRunner_iterationCount, (_a = __classPrivateFieldGet(this, _BetaToolRunner_iterationCount, "f"), _a++, _a), "f"); - __classPrivateFieldSet(this, _BetaToolRunner_message, undefined, "f"); - const { max_iterations, compactionControl, ...params } = __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; - if (params.stream) { - stream = this.client.beta.messages.stream({ ...params }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")); - __classPrivateFieldSet(this, _BetaToolRunner_message, stream.finalMessage(), "f"); - // Make sure that this promise doesn't throw before we get the option to do something about it. - // Error will be caught when we call await this.#message ultimately - __classPrivateFieldGet(this, _BetaToolRunner_message, "f").catch(() => { }); - yield stream; - } - else { - __classPrivateFieldSet(this, _BetaToolRunner_message, this.client.beta.messages.create({ ...params, stream: false }, __classPrivateFieldGet(this, _BetaToolRunner_options, "f")), "f"); - yield __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); - } - const isCompacted = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_checkAndCompact).call(this); - if (!isCompacted) { - if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { - const { role, content } = await __classPrivateFieldGet(this, _BetaToolRunner_message, "f"); - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push({ role, content }); - } - const toolMessage = await __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.at(-1)); - if (toolMessage) { - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params.messages.push(toolMessage); - } - else if (!__classPrivateFieldGet(this, _BetaToolRunner_mutated, "f")) { - break; - } - } - } - finally { - if (stream) { - stream.abort(); - } - } - } - if (!__classPrivateFieldGet(this, _BetaToolRunner_message, "f")) { - throw new error_AnthropicError('ToolRunner concluded without a message from the server'); - } - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").resolve(await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")); - } - catch (error) { - __classPrivateFieldSet(this, _BetaToolRunner_consumed, false, "f"); - // Silence unhandled promise errors - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise.catch(() => { }); - __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").reject(error); - __classPrivateFieldSet(this, _BetaToolRunner_completion, promiseWithResolvers(), "f"); - throw error; - } - } - setMessagesParams(paramsOrMutator) { - if (typeof paramsOrMutator === 'function') { - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params); - } - else { - __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params = paramsOrMutator; - } - __classPrivateFieldSet(this, _BetaToolRunner_mutated, true, "f"); - // Invalidate cached tool response since parameters changed - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, undefined, "f"); - } - /** - * Get the tool response for the last message from the assistant. - * Avoids redundant tool executions by caching results. - * - * @returns A promise that resolves to a BetaMessageParam containing tool results, or null if no tools need to be executed - * - * @example - * const toolResponse = await runner.generateToolResponse(); - * if (toolResponse) { - * console.log('Tool results:', toolResponse.content); - * } - */ - async generateToolResponse() { - const message = (await __classPrivateFieldGet(this, _BetaToolRunner_message, "f")) ?? this.params.messages.at(-1); - if (!message) { - return null; - } - return __classPrivateFieldGet(this, _BetaToolRunner_instances, "m", _BetaToolRunner_generateToolResponse).call(this, message); - } - /** - * Wait for the async iterator to complete. This works even if the async iterator hasn't yet started, and - * will wait for an instance to start and go to completion. - * - * @returns A promise that resolves to the final BetaMessage when the iterator completes - * - * @example - * // Start consuming the iterator - * for await (const message of runner) { - * console.log('Message:', message.content); - * } - * - * // Meanwhile, wait for completion from another part of the code - * const finalMessage = await runner.done(); - * console.log('Final response:', finalMessage.content); - */ - done() { - return __classPrivateFieldGet(this, _BetaToolRunner_completion, "f").promise; - } - /** - * Returns a promise indicating that the stream is done. Unlike .done(), this will eagerly read the stream: - * * If the iterator has not been consumed, consume the entire iterator and return the final message from the - * assistant. - * * If the iterator has been consumed, waits for it to complete and returns the final message. - * - * @returns A promise that resolves to the final BetaMessage from the conversation - * @throws {AnthropicError} If no messages were processed during the conversation - * - * @example - * const finalMessage = await runner.runUntilDone(); - * console.log('Final response:', finalMessage.content); - */ - async runUntilDone() { - // If not yet consumed, start consuming and wait for completion - if (!__classPrivateFieldGet(this, _BetaToolRunner_consumed, "f")) { - for await (const _ of this) { - // Iterator naturally populates this.#message - } - } - // If consumed but not completed, wait for completion - return this.done(); - } - /** - * Get the current parameters being used by the ToolRunner. - * - * @returns A readonly view of the current ToolRunnerParams - * - * @example - * const currentParams = runner.params; - * console.log('Current model:', currentParams.model); - * console.log('Message count:', currentParams.messages.length); - */ - get params() { - return __classPrivateFieldGet(this, _BetaToolRunner_state, "f").params; - } - /** - * Add one or more messages to the conversation history. - * - * @param messages - One or more BetaMessageParam objects to add to the conversation - * - * @example - * runner.pushMessages( - * { role: 'user', content: 'Also, what about the weather in NYC?' } - * ); - * - * @example - * // Adding multiple messages - * runner.pushMessages( - * { role: 'user', content: 'What about NYC?' }, - * { role: 'user', content: 'And Boston?' } - * ); - */ - pushMessages(...messages) { - this.setMessagesParams((params) => ({ - ...params, - messages: [...params.messages, ...messages], - })); - } - /** - * Makes the ToolRunner directly awaitable, equivalent to calling .runUntilDone() - * This allows using `await runner` instead of `await runner.runUntilDone()` - */ - then(onfulfilled, onrejected) { - return this.runUntilDone().then(onfulfilled, onrejected); - } -} -_BetaToolRunner_generateToolResponse = async function _BetaToolRunner_generateToolResponse(lastMessage) { - if (__classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f") !== undefined) { - return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); - } - __classPrivateFieldSet(this, _BetaToolRunner_toolResponse, generateToolResponse(__classPrivateFieldGet(this, _BetaToolRunner_state, "f").params, lastMessage), "f"); - return __classPrivateFieldGet(this, _BetaToolRunner_toolResponse, "f"); -}; -async function generateToolResponse(params, lastMessage = params.messages.at(-1)) { - // Only process if the last message is from the assistant and has tool use blocks - if (!lastMessage || - lastMessage.role !== 'assistant' || - !lastMessage.content || - typeof lastMessage.content === 'string') { - return null; - } - const toolUseBlocks = lastMessage.content.filter((content) => content.type === 'tool_use'); - if (toolUseBlocks.length === 0) { - return null; - } - const toolResults = await Promise.all(toolUseBlocks.map(async (toolUse) => { - const tool = params.tools.find((t) => ('name' in t ? t.name : t.mcp_server_name) === toolUse.name); - if (!tool || !('run' in tool)) { - return { - type: 'tool_result', - tool_use_id: toolUse.id, - content: `Error: Tool '${toolUse.name}' not found`, - is_error: true, - }; - } - try { - let input = toolUse.input; - if ('parse' in tool && tool.parse) { - input = tool.parse(input); - } - const result = await tool.run(input); - return { - type: 'tool_result', - tool_use_id: toolUse.id, - content: result, - }; - } - catch (error) { - return { - type: 'tool_result', - tool_use_id: toolUse.id, - content: `Error: ${error instanceof Error ? error.message : String(error)}`, - is_error: true, - }; - } - })); - return { - role: 'user', - content: toolResults, - }; -} -//# sourceMappingURL=BetaToolRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/decoders/jsonl.mjs - - - -class JSONLDecoder { - constructor(iterator, controller) { - this.iterator = iterator; - this.controller = controller; - } - async *decoder() { - const lineDecoder = new LineDecoder(); - for await (const chunk of this.iterator) { - for (const line of lineDecoder.decode(chunk)) { - yield JSON.parse(line); - } - } - for (const line of lineDecoder.flush()) { - yield JSON.parse(line); - } - } - [Symbol.asyncIterator]() { - return this.decoder(); - } - static fromResponse(response, controller) { - if (!response.body) { - controller.abort(); - if (typeof globalThis.navigator !== 'undefined' && - globalThis.navigator.product === 'ReactNative') { - throw new error_AnthropicError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); - } - throw new error_AnthropicError(`Attempted to iterate over a response with no body`); - } - return new JSONLDecoder(ReadableStreamToAsyncIterable(response.body), controller); - } -} -//# sourceMappingURL=jsonl.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/messages/batches.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -class Batches extends APIResource { - /** - * Send a batch of Message creation requests. - * - * The Message Batches API can be used to process multiple Messages API requests at - * once. Once a Message Batch is created, it begins processing immediately. Batches - * can take up to 24 hours to complete. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.create({ - * requests: [ - * { - * custom_id: 'my-custom-id-1', - * params: { - * max_tokens: 1024, - * messages: [ - * { content: 'Hello, world', role: 'user' }, - * ], - * model: 'claude-sonnet-4-5-20250929', - * }, - * }, - * ], - * }); - * ``` - */ - create(params, options) { - const { betas, ...body } = params; - return this._client.post('/v1/messages/batches?beta=true', { - body, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * This endpoint is idempotent and can be used to poll for Message Batch - * completion. To access the results of a Message Batch, make a request to the - * `results_url` field in the response. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.retrieve( - * 'message_batch_id', - * ); - * ``` - */ - retrieve(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/messages/batches/${messageBatchID}?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * List all Message Batches within a Workspace. Most recently created batches are - * returned first. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const betaMessageBatch of client.beta.messages.batches.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/messages/batches?beta=true', (Page), { - query, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * Delete a Message Batch. - * - * Message Batches can only be deleted once they've finished processing. If you'd - * like to delete an in-progress batch, you must first cancel it. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaDeletedMessageBatch = - * await client.beta.messages.batches.delete( - * 'message_batch_id', - * ); - * ``` - */ - delete(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path `/v1/messages/batches/${messageBatchID}?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * Batches may be canceled any time before processing ends. Once cancellation is - * initiated, the batch enters a `canceling` state, at which time the system may - * complete any in-progress, non-interruptible requests before finalizing - * cancellation. - * - * The number of canceled requests is specified in `request_counts`. To determine - * which requests were canceled, check the individual results within the batch. - * Note that cancellation may not result in any canceled requests if they were - * non-interruptible. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatch = - * await client.beta.messages.batches.cancel( - * 'message_batch_id', - * ); - * ``` - */ - cancel(messageBatchID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString() }, - options?.headers, - ]), - }); - } - /** - * Streams the results of a Message Batch as a `.jsonl` file. - * - * Each line in the file is a JSON object containing the result of a single request - * in the Message Batch. Results are not guaranteed to be in the same order as - * requests. Use the `custom_id` field to match results to requests. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const betaMessageBatchIndividualResponse = - * await client.beta.messages.batches.results( - * 'message_batch_id', - * ); - * ``` - */ - async results(messageBatchID, params = {}, options) { - const batch = await this.retrieve(messageBatchID); - if (!batch.results_url) { - throw new error_AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); - } - const { betas } = params ?? {}; - return this._client - .get(batch.results_url, { - ...options, - headers: buildHeaders([ - { - 'anthropic-beta': [...(betas ?? []), 'message-batches-2024-09-24'].toString(), - Accept: 'application/binary', - }, - options?.headers, - ]), - stream: true, - __binaryResponse: true, - }) - ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); - } -} -//# sourceMappingURL=batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/messages/messages.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - -const DEPRECATED_MODELS = { - 'claude-1.3': 'November 6th, 2024', - 'claude-1.3-100k': 'November 6th, 2024', - 'claude-instant-1.1': 'November 6th, 2024', - 'claude-instant-1.1-100k': 'November 6th, 2024', - 'claude-instant-1.2': 'November 6th, 2024', - 'claude-3-sonnet-20240229': 'July 21st, 2025', - 'claude-3-opus-20240229': 'January 5th, 2026', - 'claude-2.1': 'July 21st, 2025', - 'claude-2.0': 'July 21st, 2025', - 'claude-3-7-sonnet-latest': 'February 19th, 2026', - 'claude-3-7-sonnet-20250219': 'February 19th, 2026', -}; -class Messages extends APIResource { - constructor() { - super(...arguments); - this.batches = new Batches(this._client); - } - create(params, options) { - const { betas, ...body } = params; - if (body.model in DEPRECATED_MODELS) { - console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); - } - let timeout = this._client._options.timeout; - if (!body.stream && timeout == null) { - const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; - timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); - } - return this._client.post('/v1/messages?beta=true', { - body, - timeout: timeout ?? 600000, - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - stream: params.stream ?? false, - }); - } - /** - * Send a structured list of input messages with text and/or image content, along with an expected `output_format` and - * the response will be automatically parsed and available in the `parsed_output` property of the message. - * - * @example - * ```ts - * const message = await client.beta.messages.parse({ - * model: 'claude-3-5-sonnet-20241022', - * max_tokens: 1024, - * messages: [{ role: 'user', content: 'What is 2+2?' }], - * output_format: zodOutputFormat(z.object({ answer: z.number() }), 'math'), - * }); - * - * console.log(message.parsed_output?.answer); // 4 - * ``` - */ - parse(params, options) { - options = { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(params.betas ?? []), 'structured-outputs-2025-11-13'].toString() }, - options?.headers, - ]), - }; - return this.create(params, options).then((message) => parseBetaMessage(message, params, { logger: this._client.logger ?? console })); - } - /** - * Create a Message stream - */ - stream(body, options) { - return BetaMessageStream.createMessage(this, body, options); - } - /** - * Count the number of tokens in a Message. - * - * The Token Count API can be used to count the number of tokens in a Message, - * including tools, images, and documents, without creating it. - * - * Learn more about token counting in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) - * - * @example - * ```ts - * const betaMessageTokensCount = - * await client.beta.messages.countTokens({ - * messages: [{ content: 'string', role: 'user' }], - * model: 'claude-opus-4-5-20251101', - * }); - * ``` - */ - countTokens(params, options) { - const { betas, ...body } = params; - return this._client.post('/v1/messages/count_tokens?beta=true', { - body, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'token-counting-2024-11-01'].toString() }, - options?.headers, - ]), - }); - } - toolRunner(body, options) { - return new BetaToolRunner(this._client, body, options); - } -} - -Messages.Batches = Batches; -Messages.BetaToolRunner = BetaToolRunner; -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/skills/versions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class Versions extends APIResource { - /** - * Create Skill Version - * - * @example - * ```ts - * const version = await client.beta.skills.versions.create( - * 'skill_id', - * ); - * ``` - */ - create(skillID, params = {}, options) { - const { betas, ...body } = params ?? {}; - return this._client.post(path `/v1/skills/${skillID}/versions?beta=true`, multipartFormRequestOptions({ - body, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, - options?.headers, - ]), - }, this._client)); - } - /** - * Get Skill Version - * - * @example - * ```ts - * const version = await client.beta.skills.versions.retrieve( - * 'version', - * { skill_id: 'skill_id' }, - * ); - * ``` - */ - retrieve(version, params, options) { - const { skill_id, betas } = params; - return this._client.get(path `/v1/skills/${skill_id}/versions/${version}?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, - options?.headers, - ]), - }); - } - /** - * List Skill Versions - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const versionListResponse of client.beta.skills.versions.list( - * 'skill_id', - * )) { - * // ... - * } - * ``` - */ - list(skillID, params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList(path `/v1/skills/${skillID}/versions?beta=true`, (PageCursor), { - query, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, - options?.headers, - ]), - }); - } - /** - * Delete Skill Version - * - * @example - * ```ts - * const version = await client.beta.skills.versions.delete( - * 'version', - * { skill_id: 'skill_id' }, - * ); - * ``` - */ - delete(version, params, options) { - const { skill_id, betas } = params; - return this._client.delete(path `/v1/skills/${skill_id}/versions/${version}?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, - options?.headers, - ]), - }); - } -} -//# sourceMappingURL=versions.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/skills/skills.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -class Skills extends APIResource { - constructor() { - super(...arguments); - this.versions = new Versions(this._client); - } - /** - * Create Skill - * - * @example - * ```ts - * const skill = await client.beta.skills.create(); - * ``` - */ - create(params = {}, options) { - const { betas, ...body } = params ?? {}; - return this._client.post('/v1/skills?beta=true', multipartFormRequestOptions({ - body, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, - options?.headers, - ]), - }, this._client)); - } - /** - * Get Skill - * - * @example - * ```ts - * const skill = await client.beta.skills.retrieve('skill_id'); - * ``` - */ - retrieve(skillID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/skills/${skillID}?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, - options?.headers, - ]), - }); - } - /** - * List Skills - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const skillListResponse of client.beta.skills.list()) { - * // ... - * } - * ``` - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/skills?beta=true', (PageCursor), { - query, - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, - options?.headers, - ]), - }); - } - /** - * Delete Skill - * - * @example - * ```ts - * const skill = await client.beta.skills.delete('skill_id'); - * ``` - */ - delete(skillID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.delete(path `/v1/skills/${skillID}?beta=true`, { - ...options, - headers: buildHeaders([ - { 'anthropic-beta': [...(betas ?? []), 'skills-2025-10-02'].toString() }, - options?.headers, - ]), - }); - } -} -Skills.Versions = Versions; -//# sourceMappingURL=skills.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/beta/beta.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - -class Beta extends APIResource { - constructor() { - super(...arguments); - this.models = new Models(this._client); - this.messages = new Messages(this._client); - this.files = new Files(this._client); - this.skills = new Skills(this._client); - } -} -Beta.Models = Models; -Beta.Messages = Messages; -Beta.Files = Files; -Beta.Skills = Skills; -//# sourceMappingURL=beta.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/completions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Completions extends APIResource { - create(params, options) { - const { betas, ...body } = params; - return this._client.post('/v1/complete', { - body, - timeout: this._client._options.timeout ?? 600000, - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - stream: params.stream ?? false, - }); - } -} -//# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/MessageStream.mjs -var _MessageStream_instances, _MessageStream_currentMessageSnapshot, _MessageStream_connectedPromise, _MessageStream_resolveConnectedPromise, _MessageStream_rejectConnectedPromise, _MessageStream_endPromise, _MessageStream_resolveEndPromise, _MessageStream_rejectEndPromise, _MessageStream_listeners, _MessageStream_ended, _MessageStream_errored, _MessageStream_aborted, _MessageStream_catchingPromiseCreated, _MessageStream_response, _MessageStream_request_id, _MessageStream_getFinalMessage, _MessageStream_getFinalText, _MessageStream_handleError, _MessageStream_beginRequest, _MessageStream_addStreamEvent, _MessageStream_endRequest, _MessageStream_accumulateMessage; - - - - - -const MessageStream_JSON_BUF_PROPERTY = '__json_buf'; -function MessageStream_tracksToolInput(content) { - return content.type === 'tool_use' || content.type === 'server_tool_use'; -} -class MessageStream { - constructor() { - _MessageStream_instances.add(this); - this.messages = []; - this.receivedMessages = []; - _MessageStream_currentMessageSnapshot.set(this, void 0); - this.controller = new AbortController(); - _MessageStream_connectedPromise.set(this, void 0); - _MessageStream_resolveConnectedPromise.set(this, () => { }); - _MessageStream_rejectConnectedPromise.set(this, () => { }); - _MessageStream_endPromise.set(this, void 0); - _MessageStream_resolveEndPromise.set(this, () => { }); - _MessageStream_rejectEndPromise.set(this, () => { }); - _MessageStream_listeners.set(this, {}); - _MessageStream_ended.set(this, false); - _MessageStream_errored.set(this, false); - _MessageStream_aborted.set(this, false); - _MessageStream_catchingPromiseCreated.set(this, false); - _MessageStream_response.set(this, void 0); - _MessageStream_request_id.set(this, void 0); - _MessageStream_handleError.set(this, (error) => { - __classPrivateFieldSet(this, _MessageStream_errored, true, "f"); - if (isAbortError(error)) { - error = new APIUserAbortError(); - } - if (error instanceof APIUserAbortError) { - __classPrivateFieldSet(this, _MessageStream_aborted, true, "f"); - return this._emit('abort', error); - } - if (error instanceof error_AnthropicError) { - return this._emit('error', error); - } - if (error instanceof Error) { - const anthropicError = new error_AnthropicError(error.message); - // @ts-ignore - anthropicError.cause = error; - return this._emit('error', anthropicError); - } - return this._emit('error', new error_AnthropicError(String(error))); - }); - __classPrivateFieldSet(this, _MessageStream_connectedPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _MessageStream_resolveConnectedPromise, resolve, "f"); - __classPrivateFieldSet(this, _MessageStream_rejectConnectedPromise, reject, "f"); - }), "f"); - __classPrivateFieldSet(this, _MessageStream_endPromise, new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _MessageStream_resolveEndPromise, resolve, "f"); - __classPrivateFieldSet(this, _MessageStream_rejectEndPromise, reject, "f"); - }), "f"); - // Don't let these promises cause unhandled rejection errors. - // we will manually cause an unhandled rejection error later - // if the user hasn't registered any error listener or called - // any promise-returning method. - __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f").catch(() => { }); - __classPrivateFieldGet(this, _MessageStream_endPromise, "f").catch(() => { }); - } - get response() { - return __classPrivateFieldGet(this, _MessageStream_response, "f"); - } - get request_id() { - return __classPrivateFieldGet(this, _MessageStream_request_id, "f"); - } - /** - * Returns the `MessageStream` data, the raw `Response` instance and the ID of the request, - * returned vie the `request-id` header which is useful for debugging requests and resporting - * issues to Anthropic. - * - * This is the same as the `APIPromise.withResponse()` method. - * - * This method will raise an error if you created the stream using `MessageStream.fromReadableStream` - * as no `Response` is available. - */ - async withResponse() { - __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - const response = await __classPrivateFieldGet(this, _MessageStream_connectedPromise, "f"); - if (!response) { - throw new Error('Could not resolve a `Response` object'); - } - return { - data: this, - response, - request_id: response.headers.get('request-id'), - }; - } - /** - * Intended for use on the frontend, consuming a stream produced with - * `.toReadableStream()` on the backend. - * - * Note that messages sent to the model do not appear in `.on('message')` - * in this context. - */ - static fromReadableStream(stream) { - const runner = new MessageStream(); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - static createMessage(messages, params, options) { - const runner = new MessageStream(); - for (const message of params.messages) { - runner._addMessageParam(message); - } - runner._run(() => runner._createMessage(messages, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); - return runner; - } - _run(executor) { - executor().then(() => { - this._emitFinal(); - this._emit('end'); - }, __classPrivateFieldGet(this, _MessageStream_handleError, "f")); - } - _addMessageParam(message) { - this.messages.push(message); - } - _addMessage(message, emit = true) { - this.receivedMessages.push(message); - if (emit) { - this._emit('message', message); - } - } - async _createMessage(messages, params, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener('abort', abortHandler); - } - try { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - const { response, data: stream } = await messages - .create({ ...params, stream: true }, { ...options, signal: this.controller.signal }) - .withResponse(); - this._connected(response); - for await (const event of stream) { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); - } - finally { - if (signal && abortHandler) { - signal.removeEventListener('abort', abortHandler); - } - } - } - _connected(response) { - if (this.ended) - return; - __classPrivateFieldSet(this, _MessageStream_response, response, "f"); - __classPrivateFieldSet(this, _MessageStream_request_id, response?.headers.get('request-id'), "f"); - __classPrivateFieldGet(this, _MessageStream_resolveConnectedPromise, "f").call(this, response); - this._emit('connect'); - } - get ended() { - return __classPrivateFieldGet(this, _MessageStream_ended, "f"); - } - get errored() { - return __classPrivateFieldGet(this, _MessageStream_errored, "f"); - } - get aborted() { - return __classPrivateFieldGet(this, _MessageStream_aborted, "f"); - } - abort() { - this.controller.abort(); - } - /** - * Adds the listener function to the end of the listeners array for the event. - * No checks are made to see if the listener has already been added. Multiple calls passing - * the same combination of event and listener will result in the listener being added, and - * called, multiple times. - * @returns this MessageStream, so that calls can be chained - */ - on(event, listener) { - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); - listeners.push({ listener }); - return this; - } - /** - * Removes the specified listener from the listener array for the event. - * off() will remove, at most, one instance of a listener from the listener array. If any single - * listener has been added multiple times to the listener array for the specified event, then - * off() must be called multiple times to remove each instance. - * @returns this MessageStream, so that calls can be chained - */ - off(event, listener) { - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; - if (!listeners) - return this; - const index = listeners.findIndex((l) => l.listener === listener); - if (index >= 0) - listeners.splice(index, 1); - return this; - } - /** - * Adds a one-time listener function for the event. The next time the event is triggered, - * this listener is removed and then invoked. - * @returns this MessageStream, so that calls can be chained - */ - once(event, listener) { - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] || (__classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = []); - listeners.push({ listener, once: true }); - return this; - } - /** - * This is similar to `.once()`, but returns a Promise that resolves the next time - * the event is triggered, instead of calling a listener callback. - * @returns a Promise that resolves the next time given event is triggered, - * or rejects if an error is emitted. (If you request the 'error' event, - * returns a promise that resolves with the error). - * - * Example: - * - * const message = await stream.emitted('message') // rejects if the stream errors - */ - emitted(event) { - return new Promise((resolve, reject) => { - __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - if (event !== 'error') - this.once('error', reject); - this.once(event, resolve); - }); - } - async done() { - __classPrivateFieldSet(this, _MessageStream_catchingPromiseCreated, true, "f"); - await __classPrivateFieldGet(this, _MessageStream_endPromise, "f"); - } - get currentMessage() { - return __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - } - /** - * @returns a promise that resolves with the the final assistant Message response, - * or rejects if an error occurred or the stream ended prematurely without producing a Message. - */ - async finalMessage() { - await this.done(); - return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this); - } - /** - * @returns a promise that resolves with the the final assistant Message's text response, concatenated - * together if there are more than one text blocks. - * Rejects if an error occurred or the stream ended prematurely without producing a Message. - */ - async finalText() { - await this.done(); - return __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalText).call(this); - } - _emit(event, ...args) { - // make sure we don't emit any MessageStreamEvents after end - if (__classPrivateFieldGet(this, _MessageStream_ended, "f")) - return; - if (event === 'end') { - __classPrivateFieldSet(this, _MessageStream_ended, true, "f"); - __classPrivateFieldGet(this, _MessageStream_resolveEndPromise, "f").call(this); - } - const listeners = __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event]; - if (listeners) { - __classPrivateFieldGet(this, _MessageStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); - } - if (event === 'abort') { - const error = args[0]; - if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error); - } - __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - return; - } - if (event === 'error') { - // NOTE: _emit('error', error) should only be called from #handleError(). - const error = args[0]; - if (!__classPrivateFieldGet(this, _MessageStream_catchingPromiseCreated, "f") && !listeners?.length) { - // Trigger an unhandled rejection if the user hasn't registered any error handlers. - // If you are seeing stack traces here, make sure to handle errors via either: - // - runner.on('error', () => ...) - // - await runner.done() - // - await runner.final...() - // - etc. - Promise.reject(error); - } - __classPrivateFieldGet(this, _MessageStream_rejectConnectedPromise, "f").call(this, error); - __classPrivateFieldGet(this, _MessageStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - } - } - _emitFinal() { - const finalMessage = this.receivedMessages.at(-1); - if (finalMessage) { - this._emit('finalMessage', __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_getFinalMessage).call(this)); - } - } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - let abortHandler; - if (signal) { - if (signal.aborted) - this.controller.abort(); - abortHandler = this.controller.abort.bind(this.controller); - signal.addEventListener('abort', abortHandler); - } - try { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_beginRequest).call(this); - this._connected(null); - const stream = Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) { - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_addStreamEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new APIUserAbortError(); - } - __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_endRequest).call(this); - } - finally { - if (signal && abortHandler) { - signal.removeEventListener('abort', abortHandler); - } - } - } - [(_MessageStream_currentMessageSnapshot = new WeakMap(), _MessageStream_connectedPromise = new WeakMap(), _MessageStream_resolveConnectedPromise = new WeakMap(), _MessageStream_rejectConnectedPromise = new WeakMap(), _MessageStream_endPromise = new WeakMap(), _MessageStream_resolveEndPromise = new WeakMap(), _MessageStream_rejectEndPromise = new WeakMap(), _MessageStream_listeners = new WeakMap(), _MessageStream_ended = new WeakMap(), _MessageStream_errored = new WeakMap(), _MessageStream_aborted = new WeakMap(), _MessageStream_catchingPromiseCreated = new WeakMap(), _MessageStream_response = new WeakMap(), _MessageStream_request_id = new WeakMap(), _MessageStream_handleError = new WeakMap(), _MessageStream_instances = new WeakSet(), _MessageStream_getFinalMessage = function _MessageStream_getFinalMessage() { - if (this.receivedMessages.length === 0) { - throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); - } - return this.receivedMessages.at(-1); - }, _MessageStream_getFinalText = function _MessageStream_getFinalText() { - if (this.receivedMessages.length === 0) { - throw new error_AnthropicError('stream ended without producing a Message with role=assistant'); - } - const textBlocks = this.receivedMessages - .at(-1) - .content.filter((block) => block.type === 'text') - .map((block) => block.text); - if (textBlocks.length === 0) { - throw new error_AnthropicError('stream ended without producing a content block with type=text'); - } - return textBlocks.join(' '); - }, _MessageStream_beginRequest = function _MessageStream_beginRequest() { - if (this.ended) - return; - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); - }, _MessageStream_addStreamEvent = function _MessageStream_addStreamEvent(event) { - if (this.ended) - return; - const messageSnapshot = __classPrivateFieldGet(this, _MessageStream_instances, "m", _MessageStream_accumulateMessage).call(this, event); - this._emit('streamEvent', event, messageSnapshot); - switch (event.type) { - case 'content_block_delta': { - const content = messageSnapshot.content.at(-1); - switch (event.delta.type) { - case 'text_delta': { - if (content.type === 'text') { - this._emit('text', event.delta.text, content.text || ''); - } - break; - } - case 'citations_delta': { - if (content.type === 'text') { - this._emit('citation', event.delta.citation, content.citations ?? []); - } - break; - } - case 'input_json_delta': { - if (MessageStream_tracksToolInput(content) && content.input) { - this._emit('inputJson', event.delta.partial_json, content.input); - } - break; - } - case 'thinking_delta': { - if (content.type === 'thinking') { - this._emit('thinking', event.delta.thinking, content.thinking); - } - break; - } - case 'signature_delta': { - if (content.type === 'thinking') { - this._emit('signature', content.signature); - } - break; - } - default: - MessageStream_checkNever(event.delta); - } - break; - } - case 'message_stop': { - this._addMessageParam(messageSnapshot); - this._addMessage(messageSnapshot, true); - break; - } - case 'content_block_stop': { - this._emit('contentBlock', messageSnapshot.content.at(-1)); - break; - } - case 'message_start': { - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, messageSnapshot, "f"); - break; - } - case 'content_block_start': - case 'message_delta': - break; - } - }, _MessageStream_endRequest = function _MessageStream_endRequest() { - if (this.ended) { - throw new error_AnthropicError(`stream has ended, this shouldn't happen`); - } - const snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - if (!snapshot) { - throw new error_AnthropicError(`request ended without sending any chunks`); - } - __classPrivateFieldSet(this, _MessageStream_currentMessageSnapshot, undefined, "f"); - return snapshot; - }, _MessageStream_accumulateMessage = function _MessageStream_accumulateMessage(event) { - let snapshot = __classPrivateFieldGet(this, _MessageStream_currentMessageSnapshot, "f"); - if (event.type === 'message_start') { - if (snapshot) { - throw new error_AnthropicError(`Unexpected event order, got ${event.type} before receiving "message_stop"`); - } - return event.message; - } - if (!snapshot) { - throw new error_AnthropicError(`Unexpected event order, got ${event.type} before "message_start"`); - } - switch (event.type) { - case 'message_stop': - return snapshot; - case 'message_delta': - snapshot.stop_reason = event.delta.stop_reason; - snapshot.stop_sequence = event.delta.stop_sequence; - snapshot.usage.output_tokens = event.usage.output_tokens; - // Update other usage fields if they exist in the event - if (event.usage.input_tokens != null) { - snapshot.usage.input_tokens = event.usage.input_tokens; - } - if (event.usage.cache_creation_input_tokens != null) { - snapshot.usage.cache_creation_input_tokens = event.usage.cache_creation_input_tokens; - } - if (event.usage.cache_read_input_tokens != null) { - snapshot.usage.cache_read_input_tokens = event.usage.cache_read_input_tokens; - } - if (event.usage.server_tool_use != null) { - snapshot.usage.server_tool_use = event.usage.server_tool_use; - } - return snapshot; - case 'content_block_start': - snapshot.content.push({ ...event.content_block }); - return snapshot; - case 'content_block_delta': { - const snapshotContent = snapshot.content.at(event.index); - switch (event.delta.type) { - case 'text_delta': { - if (snapshotContent?.type === 'text') { - snapshot.content[event.index] = { - ...snapshotContent, - text: (snapshotContent.text || '') + event.delta.text, - }; - } - break; - } - case 'citations_delta': { - if (snapshotContent?.type === 'text') { - snapshot.content[event.index] = { - ...snapshotContent, - citations: [...(snapshotContent.citations ?? []), event.delta.citation], - }; - } - break; - } - case 'input_json_delta': { - if (snapshotContent && MessageStream_tracksToolInput(snapshotContent)) { - // we need to keep track of the raw JSON string as well so that we can - // re-parse it for each delta, for now we just store it as an untyped - // non-enumerable property on the snapshot - let jsonBuf = snapshotContent[MessageStream_JSON_BUF_PROPERTY] || ''; - jsonBuf += event.delta.partial_json; - const newContent = { ...snapshotContent }; - Object.defineProperty(newContent, MessageStream_JSON_BUF_PROPERTY, { - value: jsonBuf, - enumerable: false, - writable: true, - }); - if (jsonBuf) { - newContent.input = partialParse(jsonBuf); - } - snapshot.content[event.index] = newContent; - } - break; - } - case 'thinking_delta': { - if (snapshotContent?.type === 'thinking') { - snapshot.content[event.index] = { - ...snapshotContent, - thinking: snapshotContent.thinking + event.delta.thinking, - }; - } - break; - } - case 'signature_delta': { - if (snapshotContent?.type === 'thinking') { - snapshot.content[event.index] = { - ...snapshotContent, - signature: event.delta.signature, - }; - } - break; - } - default: - MessageStream_checkNever(event.delta); - } - return snapshot; - } - case 'content_block_stop': - return snapshot; - } - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on('streamEvent', (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); - } - else { - pushQueue.push(event); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; - } - toReadableStream() { - const stream = new Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream.toReadableStream(); - } -} -// used to ensure exhaustive case matching without throwing a runtime error -function MessageStream_checkNever(x) { } -//# sourceMappingURL=MessageStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/messages/batches.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -class batches_Batches extends APIResource { - /** - * Send a batch of Message creation requests. - * - * The Message Batches API can be used to process multiple Messages API requests at - * once. Once a Message Batch is created, it begins processing immediately. Batches - * can take up to 24 hours to complete. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.create({ - * requests: [ - * { - * custom_id: 'my-custom-id-1', - * params: { - * max_tokens: 1024, - * messages: [ - * { content: 'Hello, world', role: 'user' }, - * ], - * model: 'claude-sonnet-4-5-20250929', - * }, - * }, - * ], - * }); - * ``` - */ - create(body, options) { - return this._client.post('/v1/messages/batches', { body, ...options }); - } - /** - * This endpoint is idempotent and can be used to poll for Message Batch - * completion. To access the results of a Message Batch, make a request to the - * `results_url` field in the response. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.retrieve( - * 'message_batch_id', - * ); - * ``` - */ - retrieve(messageBatchID, options) { - return this._client.get(path `/v1/messages/batches/${messageBatchID}`, options); - } - /** - * List all Message Batches within a Workspace. Most recently created batches are - * returned first. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const messageBatch of client.messages.batches.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList('/v1/messages/batches', (Page), { query, ...options }); - } - /** - * Delete a Message Batch. - * - * Message Batches can only be deleted once they've finished processing. If you'd - * like to delete an in-progress batch, you must first cancel it. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const deletedMessageBatch = - * await client.messages.batches.delete('message_batch_id'); - * ``` - */ - delete(messageBatchID, options) { - return this._client.delete(path `/v1/messages/batches/${messageBatchID}`, options); - } - /** - * Batches may be canceled any time before processing ends. Once cancellation is - * initiated, the batch enters a `canceling` state, at which time the system may - * complete any in-progress, non-interruptible requests before finalizing - * cancellation. - * - * The number of canceled requests is specified in `request_counts`. To determine - * which requests were canceled, check the individual results within the batch. - * Note that cancellation may not result in any canceled requests if they were - * non-interruptible. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatch = await client.messages.batches.cancel( - * 'message_batch_id', - * ); - * ``` - */ - cancel(messageBatchID, options) { - return this._client.post(path `/v1/messages/batches/${messageBatchID}/cancel`, options); - } - /** - * Streams the results of a Message Batch as a `.jsonl` file. - * - * Each line in the file is a JSON object containing the result of a single request - * in the Message Batch. Results are not guaranteed to be in the same order as - * requests. Use the `custom_id` field to match results to requests. - * - * Learn more about the Message Batches API in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/batch-processing) - * - * @example - * ```ts - * const messageBatchIndividualResponse = - * await client.messages.batches.results('message_batch_id'); - * ``` - */ - async results(messageBatchID, options) { - const batch = await this.retrieve(messageBatchID); - if (!batch.results_url) { - throw new error_AnthropicError(`No batch \`results_url\`; Has it finished processing? ${batch.processing_status} - ${batch.id}`); - } - return this._client - .get(batch.results_url, { - ...options, - headers: buildHeaders([{ Accept: 'application/binary' }, options?.headers]), - stream: true, - __binaryResponse: true, - }) - ._thenUnwrap((_, props) => JSONLDecoder.fromResponse(props.response, props.controller)); - } -} -//# sourceMappingURL=batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/messages/messages.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class messages_Messages extends APIResource { - constructor() { - super(...arguments); - this.batches = new batches_Batches(this._client); - } - create(body, options) { - if (body.model in messages_DEPRECATED_MODELS) { - console.warn(`The model '${body.model}' is deprecated and will reach end-of-life on ${messages_DEPRECATED_MODELS[body.model]}\nPlease migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`); - } - let timeout = this._client._options.timeout; - if (!body.stream && timeout == null) { - const maxNonstreamingTokens = MODEL_NONSTREAMING_TOKENS[body.model] ?? undefined; - timeout = this._client.calculateNonstreamingTimeout(body.max_tokens, maxNonstreamingTokens); - } - return this._client.post('/v1/messages', { - body, - timeout: timeout ?? 600000, - ...options, - stream: body.stream ?? false, - }); - } - /** - * Create a Message stream - */ - stream(body, options) { - return MessageStream.createMessage(this, body, options); - } - /** - * Count the number of tokens in a Message. - * - * The Token Count API can be used to count the number of tokens in a Message, - * including tools, images, and documents, without creating it. - * - * Learn more about token counting in our - * [user guide](https://docs.claude.com/en/docs/build-with-claude/token-counting) - * - * @example - * ```ts - * const messageTokensCount = - * await client.messages.countTokens({ - * messages: [{ content: 'string', role: 'user' }], - * model: 'claude-opus-4-5-20251101', - * }); - * ``` - */ - countTokens(body, options) { - return this._client.post('/v1/messages/count_tokens', { body, ...options }); - } -} -const messages_DEPRECATED_MODELS = { - 'claude-1.3': 'November 6th, 2024', - 'claude-1.3-100k': 'November 6th, 2024', - 'claude-instant-1.1': 'November 6th, 2024', - 'claude-instant-1.1-100k': 'November 6th, 2024', - 'claude-instant-1.2': 'November 6th, 2024', - 'claude-3-sonnet-20240229': 'July 21st, 2025', - 'claude-3-opus-20240229': 'January 5th, 2026', - 'claude-2.1': 'July 21st, 2025', - 'claude-2.0': 'July 21st, 2025', - 'claude-3-7-sonnet-latest': 'February 19th, 2026', - 'claude-3-7-sonnet-20250219': 'February 19th, 2026', -}; -messages_Messages.Batches = batches_Batches; -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class models_Models extends APIResource { - /** - * Get a specific model. - * - * The Models API response can be used to determine information about a specific - * model or resolve a model alias to a model ID. - */ - retrieve(modelID, params = {}, options) { - const { betas } = params ?? {}; - return this._client.get(path `/v1/models/${modelID}`, { - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - }); - } - /** - * List available models. - * - * The Models API response can be used to determine which models are available for - * use in the API. More recently released models are listed first. - */ - list(params = {}, options) { - const { betas, ...query } = params ?? {}; - return this._client.getAPIList('/v1/models', (Page), { - query, - ...options, - headers: buildHeaders([ - { ...(betas?.toString() != null ? { 'anthropic-beta': betas?.toString() } : undefined) }, - options?.headers, - ]), - }); - } -} -//# sourceMappingURL=models.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/resources/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/env.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -/** - * Read an environment variable. - * - * Trims beginning and trailing whitespace. - * - * Will return undefined if the environment variable doesn't exist or cannot be accessed. - */ -const readEnv = (env) => { - if (typeof globalThis.process !== 'undefined') { - return globalThis.process.env?.[env]?.trim() ?? undefined; - } - if (typeof globalThis.Deno !== 'undefined') { - return globalThis.Deno.env?.get?.(env)?.trim(); - } - return undefined; -}; -//# sourceMappingURL=env.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/client.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _BaseAnthropic_instances, client_a, _BaseAnthropic_encoder, _BaseAnthropic_baseURLOverridden; - - - - - - - - - - - - - - - - - - - - - - - -const HUMAN_PROMPT = '\\n\\nHuman:'; -const AI_PROMPT = '\\n\\nAssistant:'; -/** - * Base class for Anthropic API clients. - */ -class BaseAnthropic { - /** - * API Client for interfacing with the Anthropic API. - * - * @param {string | null | undefined} [opts.apiKey=process.env['ANTHROPIC_API_KEY'] ?? null] - * @param {string | null | undefined} [opts.authToken=process.env['ANTHROPIC_AUTH_TOKEN'] ?? null] - * @param {string} [opts.baseURL=process.env['ANTHROPIC_BASE_URL'] ?? https://api.anthropic.com] - Override the default base URL for the API. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - */ - constructor({ baseURL = readEnv('ANTHROPIC_BASE_URL'), apiKey = readEnv('ANTHROPIC_API_KEY') ?? null, authToken = readEnv('ANTHROPIC_AUTH_TOKEN') ?? null, ...opts } = {}) { - _BaseAnthropic_instances.add(this); - _BaseAnthropic_encoder.set(this, void 0); - const options = { - apiKey, - authToken, - ...opts, - baseURL: baseURL || `https://api.anthropic.com`, - }; - if (!options.dangerouslyAllowBrowser && isRunningInBrowser()) { - throw new error_AnthropicError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Anthropic({ apiKey, dangerouslyAllowBrowser: true });\n"); - } - this.baseURL = options.baseURL; - this.timeout = options.timeout ?? client_a.DEFAULT_TIMEOUT /* 10 minutes */; - this.logger = options.logger ?? console; - const defaultLogLevel = 'warn'; - // Set default logLevel early so that we can log a warning in parseLogLevel. - this.logLevel = defaultLogLevel; - this.logLevel = - parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? - parseLogLevel(readEnv('ANTHROPIC_LOG'), "process.env['ANTHROPIC_LOG']", this) ?? - defaultLogLevel; - this.fetchOptions = options.fetchOptions; - this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? getDefaultFetch(); - __classPrivateFieldSet(this, _BaseAnthropic_encoder, FallbackEncoder, "f"); - this._options = options; - this.apiKey = typeof apiKey === 'string' ? apiKey : null; - this.authToken = authToken; - } - /** - * Create a new client instance re-using the same options given to the current client with optional overriding. - */ - withOptions(options) { - const client = new this.constructor({ - ...this._options, - baseURL: this.baseURL, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetch: this.fetch, - fetchOptions: this.fetchOptions, - apiKey: this.apiKey, - authToken: this.authToken, - ...options, - }); - return client; - } - defaultQuery() { - return this._options.defaultQuery; - } - validateHeaders({ values, nulls }) { - if (values.get('x-api-key') || values.get('authorization')) { - return; - } - if (this.apiKey && values.get('x-api-key')) { - return; - } - if (nulls.has('x-api-key')) { - return; - } - if (this.authToken && values.get('authorization')) { - return; - } - if (nulls.has('authorization')) { - return; - } - throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted'); - } - async authHeaders(opts) { - return buildHeaders([await this.apiKeyAuth(opts), await this.bearerAuth(opts)]); - } - async apiKeyAuth(opts) { - if (this.apiKey == null) { - return undefined; - } - return buildHeaders([{ 'X-Api-Key': this.apiKey }]); - } - async bearerAuth(opts) { - if (this.authToken == null) { - return undefined; - } - return buildHeaders([{ Authorization: `Bearer ${this.authToken}` }]); - } - /** - * Basic re-implementation of `qs.stringify` for primitive types. - */ - stringifyQuery(query) { - return Object.entries(query) - .filter(([_, value]) => typeof value !== 'undefined') - .map(([key, value]) => { - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - return `${encodeURIComponent(key)}=${encodeURIComponent(value)}`; - } - if (value === null) { - return `${encodeURIComponent(key)}=`; - } - throw new error_AnthropicError(`Cannot stringify type ${typeof value}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`); - }) - .join('&'); - } - getUserAgent() { - return `${this.constructor.name}/JS ${VERSION}`; - } - defaultIdempotencyKey() { - return `stainless-node-retry-${uuid_uuid4()}`; - } - makeStatusError(status, error, message, headers) { - return APIError.generate(status, error, message, headers); - } - buildURL(path, query, defaultBaseURL) { - const baseURL = (!__classPrivateFieldGet(this, _BaseAnthropic_instances, "m", _BaseAnthropic_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL; - const url = isAbsoluteURL(path) ? - new URL(path) - : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); - const defaultQuery = this.defaultQuery(); - if (!isEmptyObj(defaultQuery)) { - query = { ...defaultQuery, ...query }; - } - if (typeof query === 'object' && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query); - } - return url.toString(); - } - _calculateNonstreamingTimeout(maxTokens) { - const defaultTimeout = 10 * 60; - const expectedTimeout = (60 * 60 * maxTokens) / 128000; - if (expectedTimeout > defaultTimeout) { - throw new error_AnthropicError('Streaming is required for operations that may take longer than 10 minutes. ' + - 'See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details'); - } - return defaultTimeout * 1000; - } - /** - * Used as a callback for mutating the given `FinalRequestOptions` object. - */ - async prepareOptions(options) { } - /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. - */ - async prepareRequest(request, { url, options }) { } - get(path, opts) { - return this.methodRequest('get', path, opts); - } - post(path, opts) { - return this.methodRequest('post', path, opts); - } - patch(path, opts) { - return this.methodRequest('patch', path, opts); - } - put(path, opts) { - return this.methodRequest('put', path, opts); - } - delete(path, opts) { - return this.methodRequest('delete', path, opts); - } - methodRequest(method, path, opts) { - return this.request(Promise.resolve(opts).then((opts) => { - return { method, path, ...opts }; - })); - } - request(options, remainingRetries = null) { - return new APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); - } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; - } - await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining, - }); - await this.prepareRequest(req, { url, options }); - /** Not an API request ID, just for correlating local log entries. */ - const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); - const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - loggerFor(this).debug(`[${requestLogID}] sending request`, formatRequestDetails({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers, - })); - if (options.signal?.aborted) { - throw new APIUserAbortError(); - } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(castToError); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new APIUserAbortError(); - } - // detect native connection timeout errors - // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" - // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" - // others do not provide enough information to distinguish timeouts from other connection errors - const isTimeout = isAbortError(response) || - /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); - if (retriesRemaining) { - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); - } - loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); - loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - })); - if (isTimeout) { - throw new APIConnectionTimeoutError(); - } - throw new APIConnectionError({ cause: response }); - } - const specialHeaders = [...response.headers.entries()] - .filter(([name]) => name === 'request-id') - .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value)) - .join(''); - const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - // We don't need the body of this response. - await CancelReadableStream(response.body); - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); - } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err) => castToError(err).message); - const errJSON = safeJSON(errText); - const errMessage = errJSON ? undefined : errText; - loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime, - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; - } - loggerFor(this).info(responseInfo); - loggerFor(this).debug(`[${requestLogID}] response start`, formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; - } - getAPIList(path, Page, opts) { - return this.requestAPIList(Page, { method: 'get', path, ...opts }); - } - requestAPIList(Page, options) { - const request = this.makeRequest(options, null, undefined); - return new PagePromise(this, request, Page); - } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, method, ...options } = init || {}; - if (signal) - signal.addEventListener('abort', () => controller.abort()); - const timeout = setTimeout(() => controller.abort(), ms); - const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) || - (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); - const fetchOptions = { - signal: controller.signal, - ...(isReadableBody ? { duplex: 'half' } : {}), - method: 'GET', - ...options, - }; - if (method) { - // Custom methods like 'patch' need to be uppercased - // See https://github.com/nodejs/undici/issues/2294 - fetchOptions.method = method.toUpperCase(); - } - try { - // use undefined this binding; fetch errors if bound to something else in browser/cloudflare - return await this.fetch.call(undefined, url, fetchOptions); - } - finally { - clearTimeout(timeout); - } - } - async shouldRetry(response) { - // Note this is not a standard header. - const shouldRetryHeader = response.headers.get('x-should-retry'); - // If the server explicitly says whether or not to retry, obey. - if (shouldRetryHeader === 'true') - return true; - if (shouldRetryHeader === 'false') - return false; - // Retry on request timeouts. - if (response.status === 408) - return true; - // Retry on lock timeouts. - if (response.status === 409) - return true; - // Retry on rate limits. - if (response.status === 429) - return true; - // Retry internal errors. - if (response.status >= 500) - return true; - return false; - } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. - const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } - } - // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After - const retryAfterHeader = responseHeaders?.get('retry-after'); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1000; - } - else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } - } - // If the API asks us to wait a certain amount of time (and it's a reasonable amount), - // just do what it says, but otherwise calculate a default - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); - } - await sleep(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); - } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8.0; - const numRetries = maxRetries - retriesRemaining; - // Apply exponential backoff, but not more than the max. - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - // Apply some jitter, take up to at most 25 percent of the retry time. - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1000; - } - calculateNonstreamingTimeout(maxTokens, maxNonstreamingTokens) { - const maxTime = 60 * 60 * 1000; // 60 minutes - const defaultTime = 60 * 10 * 1000; // 10 minutes - const expectedTime = (maxTime * maxTokens) / 128000; - if (expectedTime > defaultTime || (maxNonstreamingTokens != null && maxTokens > maxNonstreamingTokens)) { - throw new error_AnthropicError('Streaming is required for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details'); - } - return defaultTime; - } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path, query, defaultBaseURL } = options; - const url = this.buildURL(path, query, defaultBaseURL); - if ('timeout' in options) - validatePositiveInteger('timeout', options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...(options.signal && { signal: options.signal }), - ...(globalThis.ReadableStream && - body instanceof globalThis.ReadableStream && { duplex: 'half' }), - ...(body && { body }), - ...(this.fetchOptions ?? {}), - ...(options.fetchOptions ?? {}), - }; - return { req, url, timeout: options.timeout }; - } - async buildHeaders({ options, method, bodyHeaders, retryCount, }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== 'get') { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; - } - const headers = buildHeaders([ - idempotencyHeaders, - { - Accept: 'application/json', - 'User-Agent': this.getUserAgent(), - 'X-Stainless-Retry-Count': String(retryCount), - ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), - ...getPlatformHeaders(), - ...(this._options.dangerouslyAllowBrowser ? - { 'anthropic-dangerous-direct-browser-access': 'true' } - : undefined), - 'anthropic-version': '2023-06-01', - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers, - ]); - this.validateHeaders(headers); - return headers.values; - } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: undefined, body: undefined }; - } - const headers = buildHeaders([rawHeaders]); - if ( - // Pass raw type verbatim - ArrayBuffer.isView(body) || - body instanceof ArrayBuffer || - body instanceof DataView || - (typeof body === 'string' && - // Preserve legacy string encoding behavior for now - headers.values.has('content-type')) || - // `Blob` is superset of `File` - (globalThis.Blob && body instanceof globalThis.Blob) || - // `FormData` -> `multipart/form-data` - body instanceof FormData || - // `URLSearchParams` -> `application/x-www-form-urlencoded` - body instanceof URLSearchParams || - // Send chunked stream (each chunk has own `length`) - (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) { - return { bodyHeaders: undefined, body: body }; - } - else if (typeof body === 'object' && - (Symbol.asyncIterator in body || - (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { - return { bodyHeaders: undefined, body: ReadableStreamFrom(body) }; - } - else { - return __classPrivateFieldGet(this, _BaseAnthropic_encoder, "f").call(this, { body, headers }); - } - } -} -client_a = BaseAnthropic, _BaseAnthropic_encoder = new WeakMap(), _BaseAnthropic_instances = new WeakSet(), _BaseAnthropic_baseURLOverridden = function _BaseAnthropic_baseURLOverridden() { - return this.baseURL !== 'https://api.anthropic.com'; -}; -BaseAnthropic.Anthropic = client_a; -BaseAnthropic.HUMAN_PROMPT = HUMAN_PROMPT; -BaseAnthropic.AI_PROMPT = AI_PROMPT; -BaseAnthropic.DEFAULT_TIMEOUT = 600000; // 10 minutes -BaseAnthropic.AnthropicError = error_AnthropicError; -BaseAnthropic.APIError = APIError; -BaseAnthropic.APIConnectionError = APIConnectionError; -BaseAnthropic.APIConnectionTimeoutError = APIConnectionTimeoutError; -BaseAnthropic.APIUserAbortError = APIUserAbortError; -BaseAnthropic.NotFoundError = NotFoundError; -BaseAnthropic.ConflictError = ConflictError; -BaseAnthropic.RateLimitError = RateLimitError; -BaseAnthropic.BadRequestError = BadRequestError; -BaseAnthropic.AuthenticationError = AuthenticationError; -BaseAnthropic.InternalServerError = InternalServerError; -BaseAnthropic.PermissionDeniedError = PermissionDeniedError; -BaseAnthropic.UnprocessableEntityError = UnprocessableEntityError; -BaseAnthropic.toFile = toFile; -/** - * API Client for interfacing with the Anthropic API. - */ -class Anthropic extends BaseAnthropic { - constructor() { - super(...arguments); - this.completions = new Completions(this); - this.messages = new messages_Messages(this); - this.models = new models_Models(this); - this.beta = new Beta(this); - } -} -Anthropic.Completions = Completions; -Anthropic.Messages = messages_Messages; -Anthropic.Models = models_Models; -Anthropic.Beta = Beta; -//# sourceMappingURL=client.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils/base64.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -const toBase64 = (data) => { - if (!data) - return ''; - if (typeof globalThis.Buffer !== 'undefined') { - return globalThis.Buffer.from(data).toString('base64'); - } - if (typeof data === 'string') { - data = encodeUTF8(data); - } - if (typeof btoa !== 'undefined') { - return btoa(String.fromCharCode.apply(null, data)); - } - throw new AnthropicError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined'); -}; -const fromBase64 = (str) => { - if (typeof globalThis.Buffer !== 'undefined') { - const buf = globalThis.Buffer.from(str, 'base64'); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); - } - if (typeof atob !== 'undefined') { - const bstr = atob(str); - const buf = new Uint8Array(bstr.length); - for (let i = 0; i < bstr.length; i++) { - buf[i] = bstr.charCodeAt(i); - } - return buf; - } - throw new AnthropicError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined'); -}; -//# sourceMappingURL=base64.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/internal/utils.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -//# sourceMappingURL=utils.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk/lib/transform-json-schema.mjs - -// Supported string formats -const SUPPORTED_STRING_FORMATS = new Set([ - 'date-time', - 'time', - 'date', - 'duration', - 'email', - 'hostname', - 'uri', - 'ipv4', - 'ipv6', - 'uuid', -]); -function transform_json_schema_deepClone(obj) { - return JSON.parse(JSON.stringify(obj)); -} -function transformJSONSchema(jsonSchema) { - const workingCopy = transform_json_schema_deepClone(jsonSchema); - return _transformJSONSchema(workingCopy); -} -function _transformJSONSchema(jsonSchema) { - const strictSchema = {}; - const ref = pop(jsonSchema, '$ref'); - if (ref !== undefined) { - strictSchema['$ref'] = ref; - return strictSchema; - } - const defs = pop(jsonSchema, '$defs'); - if (defs !== undefined) { - const strictDefs = {}; - strictSchema['$defs'] = strictDefs; - for (const [name, defSchema] of Object.entries(defs)) { - strictDefs[name] = _transformJSONSchema(defSchema); - } - } - const type = pop(jsonSchema, 'type'); - const anyOf = pop(jsonSchema, 'anyOf'); - const oneOf = pop(jsonSchema, 'oneOf'); - const allOf = pop(jsonSchema, 'allOf'); - if (Array.isArray(anyOf)) { - strictSchema['anyOf'] = anyOf.map((variant) => _transformJSONSchema(variant)); - } - else if (Array.isArray(oneOf)) { - strictSchema['anyOf'] = oneOf.map((variant) => _transformJSONSchema(variant)); - } - else if (Array.isArray(allOf)) { - strictSchema['allOf'] = allOf.map((entry) => _transformJSONSchema(entry)); - } - else { - if (type === undefined) { - throw new Error('JSON schema must have a type defined if anyOf/oneOf/allOf are not used'); - } - strictSchema['type'] = type; - } - const description = pop(jsonSchema, 'description'); - if (description !== undefined) { - strictSchema['description'] = description; - } - const title = pop(jsonSchema, 'title'); - if (title !== undefined) { - strictSchema['title'] = title; - } - if (type === 'object') { - const properties = pop(jsonSchema, 'properties') || {}; - strictSchema['properties'] = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [ - key, - _transformJSONSchema(propSchema), - ])); - pop(jsonSchema, 'additionalProperties'); - strictSchema['additionalProperties'] = false; - const required = pop(jsonSchema, 'required'); - if (required !== undefined) { - strictSchema['required'] = required; - } - } - else if (type === 'string') { - const format = pop(jsonSchema, 'format'); - if (format !== undefined && SUPPORTED_STRING_FORMATS.has(format)) { - strictSchema['format'] = format; - } - else if (format !== undefined) { - jsonSchema['format'] = format; - } - } - else if (type === 'array') { - const items = pop(jsonSchema, 'items'); - if (items !== undefined) { - strictSchema['items'] = _transformJSONSchema(items); - } - const minItems = pop(jsonSchema, 'minItems'); - if (minItems !== undefined && (minItems === 0 || minItems === 1)) { - strictSchema['minItems'] = minItems; - } - else if (minItems !== undefined) { - jsonSchema['minItems'] = minItems; - } - } - if (Object.keys(jsonSchema).length > 0) { - const existingDescription = strictSchema['description']; - strictSchema['description'] = - (existingDescription ? existingDescription + '\n\n' : '') + - '{' + - Object.entries(jsonSchema) - .map(([key, value]) => `${key}: ${JSON.stringify(value)}`) - .join(', ') + - '}'; - } - return strictSchema; -} -//# sourceMappingURL=transform-json-schema.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/chat_models.js - - - - - - - - - - - - - - - - - - - -//#region src/chat_models.ts -const MODEL_DEFAULT_MAX_OUTPUT_TOKENS = { - "claude-opus-4-1": 8192, - "claude-opus-4": 8192, - "claude-sonnet-4": 8192, - "claude-sonnet-3-7-sonnet": 8192, - "claude-3-5-sonnet": 4096, - "claude-3-5-haiku": 4096, - "claude-3-haiku": 2048 -}; -const FALLBACK_MAX_OUTPUT_TOKENS = 2048; -function defaultMaxOutputTokensForModel(model) { - if (!model) return FALLBACK_MAX_OUTPUT_TOKENS; - const maxTokens = Object.entries(MODEL_DEFAULT_MAX_OUTPUT_TOKENS).find(([key]) => model.startsWith(key))?.[1]; - return maxTokens ?? FALLBACK_MAX_OUTPUT_TOKENS; -} -function _toolsInParams(params) { - return !!(params.tools && params.tools.length > 0); -} -function _documentsInParams(params) { - for (const message of params.messages ?? []) { - if (typeof message.content === "string") continue; - for (const block of message.content ?? []) if (typeof block === "object" && block != null && block.type === "document" && typeof block.citations === "object" && block.citations?.enabled) return true; - } - return false; -} -function _thinkingInParams(params) { - return !!(params.thinking && params.thinking.type === "enabled"); -} -function isAnthropicTool(tool) { - return "input_schema" in tool; -} -function isBuiltinTool(tool) { - const builtInToolPrefixes = [ - "text_editor_", - "computer_", - "bash_", - "web_search_", - "web_fetch_", - "str_replace_editor_", - "str_replace_based_edit_tool_", - "code_execution_", - "memory_", - "tool_search_", - "mcp_toolset" - ]; - return typeof tool === "object" && tool !== null && "type" in tool && ("name" in tool || "mcp_server_name" in tool) && typeof tool.type === "string" && builtInToolPrefixes.some((prefix) => typeof tool.type === "string" && tool.type.startsWith(prefix)); -} -function _combineBetas(a, b, ...rest) { - return Array.from(new Set([ - ...a ?? [], - ...b ?? [], - ...rest.flatMap((x) => Array.from(x)) - ])); -} -function extractToken(chunk) { - if (typeof chunk.content === "string") return chunk.content; - else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "input" in chunk.content[0]) return typeof chunk.content[0].input === "string" ? chunk.content[0].input : JSON.stringify(chunk.content[0].input); - else if (Array.isArray(chunk.content) && chunk.content.length >= 1 && "text" in chunk.content[0] && typeof chunk.content[0].text === "string") return chunk.content[0].text; - return void 0; -} -/** -* Anthropic chat model integration. -* -* Setup: -* Install `@langchain/anthropic` and set an environment variable named `ANTHROPIC_API_KEY`. -* -* ```bash -* npm install @langchain/anthropic -* export ANTHROPIC_API_KEY="your-api-key" -* ``` -* -* ## [Constructor args](https://api.js.langchain.com/classes/langchain_anthropic.ChatAnthropic.html#constructor) -* -* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_anthropic.ChatAnthropicCallOptions.html) -* -* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. -* They can also be passed via `.bind`, or the second arg in `.bindTools`, like shown in the examples below: -* -* ```typescript -* // When calling `.bind`, call options should be passed via the first argument -* const llmWithArgsBound = llm.bindTools([...]).withConfig({ -* stop: ["\n"], -* }); -* -* // When calling `.bindTools`, call options should be passed via the second argument -* const llmWithTools = llm.bindTools( -* [...], -* { -* tool_choice: "auto", -* } -* ); -* ``` -* -* ## Examples -* -*
-* Instantiate -* -* ```typescript -* import { ChatAnthropic } from '@langchain/anthropic'; -* -* const llm = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* temperature: 0, -* maxTokens: undefined, -* maxRetries: 2, -* // apiKey: "...", -* // baseUrl: "...", -* // other params... -* }); -* ``` -*
-* -*
-* -*
-* Invoking -* -* ```typescript -* const input = `Translate "I love programming" into French.`; -* -* // Models also accept a list of chat messages or a formatted prompt -* const result = await llm.invoke(input); -* console.log(result); -* ``` -* -* ```txt -* AIMessage { -* "id": "msg_01QDpd78JUHpRP6bRRNyzbW3", -* "content": "Here's the translation to French:\n\nJ'adore la programmation.", -* "response_metadata": { -* "id": "msg_01QDpd78JUHpRP6bRRNyzbW3", -* "model": "claude-sonnet-4-5-20250929", -* "stop_reason": "end_turn", -* "stop_sequence": null, -* "usage": { -* "input_tokens": 25, -* "output_tokens": 19 -* }, -* "type": "message", -* "role": "assistant" -* }, -* "usage_metadata": { -* "input_tokens": 25, -* "output_tokens": 19, -* "total_tokens": 44 -* } -* } -* ``` -*
-* -*
-* -*
-* Streaming Chunks -* -* ```typescript -* for await (const chunk of await llm.stream(input)) { -* console.log(chunk); -* } -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "msg_01N8MwoYxiKo9w4chE4gXUs4", -* "content": "", -* "additional_kwargs": { -* "id": "msg_01N8MwoYxiKo9w4chE4gXUs4", -* "type": "message", -* "role": "assistant", -* "model": "claude-sonnet-4-5-20250929" -* }, -* "usage_metadata": { -* "input_tokens": 25, -* "output_tokens": 1, -* "total_tokens": 26 -* } -* } -* AIMessageChunk { -* "content": "", -* } -* AIMessageChunk { -* "content": "Here", -* } -* AIMessageChunk { -* "content": "'s", -* } -* AIMessageChunk { -* "content": " the translation to", -* } -* AIMessageChunk { -* "content": " French:\n\nJ", -* } -* AIMessageChunk { -* "content": "'adore la programmation", -* } -* AIMessageChunk { -* "content": ".", -* } -* AIMessageChunk { -* "content": "", -* "additional_kwargs": { -* "stop_reason": "end_turn", -* "stop_sequence": null -* }, -* "usage_metadata": { -* "input_tokens": 0, -* "output_tokens": 19, -* "total_tokens": 19 -* } -* } -* ``` -*
-* -*
-* -*
-* Aggregate Streamed Chunks -* -* ```typescript -* import { AIMessageChunk } from '@langchain/core/messages'; -* import { concat } from '@langchain/core/utils/stream'; -* -* const stream = await llm.stream(input); -* let full: AIMessageChunk | undefined; -* for await (const chunk of stream) { -* full = !full ? chunk : concat(full, chunk); -* } -* console.log(full); -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA", -* "content": "Here's the translation to French:\n\nJ'adore la programmation.", -* "additional_kwargs": { -* "id": "msg_01SBTb5zSGXfjUc7yQ8EKEEA", -* "type": "message", -* "role": "assistant", -* "model": "claude-sonnet-4-5-20250929", -* "stop_reason": "end_turn", -* "stop_sequence": null -* }, -* "usage_metadata": { -* "input_tokens": 25, -* "output_tokens": 20, -* "total_tokens": 45 -* } -* } -* ``` -*
-* -*
-* -*
-* Bind tools -* -* ```typescript -* import { z } from 'zod'; -* -* const GetWeather = { -* name: "GetWeather", -* description: "Get the current weather in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const GetPopulation = { -* name: "GetPopulation", -* description: "Get the current population in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); -* const aiMsg = await llmWithTools.invoke( -* "Which city is hotter today and which is bigger: LA or NY?" -* ); -* console.log(aiMsg.tool_calls); -* ``` -* -* ```txt -* [ -* { -* name: 'GetWeather', -* args: { location: 'Los Angeles, CA' }, -* id: 'toolu_01WjW3Dann6BPJVtLhovdBD5', -* type: 'tool_call' -* }, -* { -* name: 'GetWeather', -* args: { location: 'New York, NY' }, -* id: 'toolu_01G6wfJgqi5zRmJomsmkyZXe', -* type: 'tool_call' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'Los Angeles, CA' }, -* id: 'toolu_0165qYWBA2VFyUst5RA18zew', -* type: 'tool_call' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'New York, NY' }, -* id: 'toolu_01PGNyP33vxr13tGqr7i3rDo', -* type: 'tool_call' -* } -* ] -* ``` -*
-* -*
-* -*
-* Tool Search -* -* Tool search enables Claude to dynamically discover and load tools on-demand -* instead of loading all tool definitions upfront. This is useful when you have -* many tools but want to avoid the overhead of sending all definitions with every request. -* -* ```typescript -* import { ChatAnthropic } from "@langchain/anthropic"; -* -* const model = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* }); -* -* const tools = [ -* // Tool search server tool -* { -* type: "tool_search_tool_regex_20251119", -* name: "tool_search_tool_regex", -* }, -* // Tools with defer_loading are loaded on-demand -* { -* name: "get_weather", -* description: "Get the current weather for a location", -* input_schema: { -* type: "object", -* properties: { -* location: { type: "string", description: "City name" }, -* unit: { -* type: "string", -* enum: ["celsius", "fahrenheit"], -* }, -* }, -* required: ["location"], -* }, -* defer_loading: true, // Tool is loaded on-demand -* }, -* { -* name: "search_files", -* description: "Search through files in the workspace", -* input_schema: { -* type: "object", -* properties: { -* query: { type: "string" }, -* }, -* required: ["query"], -* }, -* defer_loading: true, // Tool is loaded on-demand -* }, -* ]; -* -* const modelWithTools = model.bindTools(tools); -* const response = await modelWithTools.invoke("What's the weather in San Francisco?"); -* ``` -* -* You can also use the `tool()` helper with the `extras` field: -* -* ```typescript -* import { tool } from "@langchain/core/tools"; -* import { z } from "zod"; -* -* const getWeather = tool( -* async (input) => `Weather in ${input.location}`, -* { -* name: "get_weather", -* description: "Get weather for a location", -* schema: z.object({ location: z.string() }), -* extras: { defer_loading: true }, -* } -* ); -* ``` -* -* **Note:** The required `advanced-tool-use-2025-11-20` beta header is automatically -* appended to the request when using tool search tools. -* -* **Best practices:** -* - Tools with `defer_loading: true` are only loaded when Claude discovers them via search -* - Keep your 3-5 most frequently used tools as non-deferred for optimal performance -* - Both regex and bm25 variants search tool names, descriptions, and argument info -* -* See the {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/tool-search-tool | Claude docs} -* for more information. -*
-* -*
-* -*
-* Structured Output -* -* ChatAnthropic supports structured output through two main approaches: -* -* 1. **Function Calling with `withStructuredOutput()`**: Uses Anthropic's tool calling -* under the hood to constrain outputs to a specific schema. -* 2. **JSON Schema Mode**: Uses Anthropic's native JSON schema support for direct -* structured output without tool calling overhead. -* -* **Using withStructuredOutput (Function Calling)** -* -* This method leverages Anthropic's tool calling capabilities to ensure the model -* returns data matching your schema: -* -* ```typescript -* import { z } from 'zod'; -* -* const Joke = z.object({ -* setup: z.string().describe("The setup of the joke"), -* punchline: z.string().describe("The punchline to the joke"), -* rating: z.number().optional().describe("How funny the joke is, from 1 to 10") -* }).describe('Joke to tell user.'); -* -* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); -* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); -* console.log(jokeResult); -* ``` -* -* ```txt -* { -* setup: "Why don't cats play poker in the jungle?", -* punchline: 'Too many cheetahs!', -* rating: 7 -* } -* ``` -* -* **Using JSON Schema Mode** -* -* For more direct control, you can use Anthropic's native JSON schema support by -* passing `method: "jsonSchema"`: -* -* ```typescript -* import { z } from 'zod'; -* -* const RecipeSchema = z.object({ -* recipeName: z.string().describe("Name of the recipe"), -* ingredients: z.array(z.string()).describe("List of ingredients needed"), -* steps: z.array(z.string()).describe("Cooking steps in order"), -* prepTime: z.number().describe("Preparation time in minutes") -* }); -* -* const structuredLlm = llm.withStructuredOutput(RecipeSchema, { -* method: "jsonSchema" -* }); -* -* const recipe = await structuredLlm.invoke( -* "Give me a simple recipe for chocolate chip cookies" -* ); -* console.log(recipe); -* ``` -* -* ```txt -* { -* recipeName: 'Classic Chocolate Chip Cookies', -* ingredients: [ -* '2 1/4 cups all-purpose flour', -* '1 cup butter, softened', -* ... -* ], -* steps: [ -* 'Preheat oven to 375°F', -* 'Mix butter and sugars until creamy', -* ... -* ], -* prepTime: 15 -* } -* ``` -*
-* -*
-* -*
-* Multimodal -* -* ```typescript -* import { HumanMessage } from '@langchain/core/messages'; -* -* const imageUrl = "https://example.com/image.jpg"; -* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); -* const base64Image = Buffer.from(imageData).toString('base64'); -* -* const message = new HumanMessage({ -* content: [ -* { type: "text", text: "describe the weather in this image" }, -* { -* type: "image_url", -* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, -* }, -* ] -* }); -* -* const imageDescriptionAiMsg = await llm.invoke([message]); -* console.log(imageDescriptionAiMsg.content); -* ``` -* -* ```txt -* The weather in this image appears to be beautiful and clear. The sky is a vibrant blue with scattered white clouds, suggesting a sunny and pleasant day. The clouds are wispy and light, indicating calm conditions without any signs of storms or heavy weather. The bright green grass on the rolling hills looks lush and well-watered, which could mean recent rainfall or good growing conditions. Overall, the scene depicts a perfect spring or early summer day with mild temperatures, plenty of sunshine, and gentle breezes - ideal weather for enjoying the outdoors or for plant growth. -* ``` -*
-* -*
-* -*
-* Usage Metadata -* -* ```typescript -* const aiMsgForMetadata = await llm.invoke(input); -* console.log(aiMsgForMetadata.usage_metadata); -* ``` -* -* ```txt -* { input_tokens: 25, output_tokens: 19, total_tokens: 44 } -* ``` -*
-* -*
-* -*
-* Stream Usage Metadata -* -* ```typescript -* const streamForMetadata = await llm.stream( -* input, -* { -* streamUsage: true -* } -* ); -* let fullForMetadata: AIMessageChunk | undefined; -* for await (const chunk of streamForMetadata) { -* fullForMetadata = !fullForMetadata ? chunk : concat(fullForMetadata, chunk); -* } -* console.log(fullForMetadata?.usage_metadata); -* ``` -* -* ```txt -* { input_tokens: 25, output_tokens: 20, total_tokens: 45 } -* ``` -*
-* -*
-* -*
-* Response Metadata -* -* ```typescript -* const aiMsgForResponseMetadata = await llm.invoke(input); -* console.log(aiMsgForResponseMetadata.response_metadata); -* ``` -* -* ```txt -* { -* id: 'msg_01STxeQxJmp4sCSpioD6vK3L', -* model: 'claude-sonnet-4-5-20250929', -* stop_reason: 'end_turn', -* stop_sequence: null, -* usage: { input_tokens: 25, output_tokens: 19 }, -* type: 'message', -* role: 'assistant' -* } -* ``` -*
-* -*
-*/ -var ChatAnthropicMessages = class extends BaseChatModel { - static lc_name() { - return "ChatAnthropic"; - } - get lc_secrets() { - return { - anthropicApiKey: "ANTHROPIC_API_KEY", - apiKey: "ANTHROPIC_API_KEY" - }; - } - get lc_aliases() { - return { modelName: "model" }; - } - lc_serializable = true; - anthropicApiKey; - apiKey; - apiUrl; - temperature; - topK; - topP; - maxTokens; - modelName = "claude-3-5-sonnet-latest"; - model = "claude-3-5-sonnet-latest"; - invocationKwargs; - stopSequences; - streaming = false; - clientOptions; - thinking = { type: "disabled" }; - contextManagement; - batchClient; - streamingClient; - streamUsage = true; - betas; - /** - * Optional method that returns an initialized underlying Anthropic client. - * Useful for accessing Anthropic models hosted on other cloud services - * such as Google Vertex. - */ - createClient; - constructor(fields) { - super(fields ?? {}); - this.anthropicApiKey = fields?.apiKey ?? fields?.anthropicApiKey ?? getEnvironmentVariable("ANTHROPIC_API_KEY"); - if (!this.anthropicApiKey && !fields?.createClient) throw new Error("Anthropic API key not found"); - this.clientOptions = fields?.clientOptions ?? {}; - /** Keep anthropicApiKey for backwards compatibility */ - this.apiKey = this.anthropicApiKey; - this.apiUrl = fields?.anthropicApiUrl; - /** Keep modelName for backwards compatibility */ - this.modelName = fields?.model ?? fields?.modelName ?? this.model; - this.model = this.modelName; - this.invocationKwargs = fields?.invocationKwargs ?? {}; - this.topP = fields?.topP ?? this.topP; - this.temperature = fields?.temperature ?? this.temperature; - this.topK = fields?.topK ?? this.topK; - this.maxTokens = fields?.maxTokens ?? defaultMaxOutputTokensForModel(this.model); - this.stopSequences = fields?.stopSequences ?? this.stopSequences; - this.streaming = fields?.streaming ?? false; - this.streamUsage = fields?.streamUsage ?? this.streamUsage; - this.thinking = fields?.thinking ?? this.thinking; - this.contextManagement = fields?.contextManagement ?? this.contextManagement; - this.betas = fields?.betas ?? this.betas; - this.createClient = fields?.createClient ?? ((options) => new Anthropic(options)); - } - getLsParams(options) { - const params = this.invocationParams(options); - return { - ls_provider: "anthropic", - ls_model_name: this.model, - ls_model_type: "chat", - ls_temperature: params.temperature ?? void 0, - ls_max_tokens: params.max_tokens ?? void 0, - ls_stop: options.stop - }; - } - /** - * Formats LangChain StructuredTools to AnthropicTools. - * - * @param {ChatAnthropicCallOptions["tools"]} tools The tools to format - * @returns {AnthropicTool[] | undefined} The formatted tools, or undefined if none are passed. - */ - formatStructuredToolToAnthropic(tools) { - if (!tools) return void 0; - return tools.map((tool) => { - if (isLangChainTool(tool) && tool.extras?.providerToolDefinition) return tool.extras.providerToolDefinition; - if (isBuiltinTool(tool)) return tool; - if (isAnthropicTool(tool)) return tool; - if (isOpenAITool(tool)) return { - name: tool.function.name, - description: tool.function.description, - input_schema: tool.function.parameters - }; - if (isLangChainTool(tool)) return { - name: tool.name, - description: tool.description, - input_schema: isInteropZodSchema(tool.schema) ? toJsonSchema(tool.schema) : tool.schema, - ...tool.extras ? AnthropicToolExtrasSchema.parse(tool.extras) : {} - }; - throw new Error(`Unknown tool type passed to ChatAnthropic: ${JSON.stringify(tool, null, 2)}`); - }); - } - bindTools(tools, kwargs) { - return this.withConfig({ - tools: this.formatStructuredToolToAnthropic(tools), - ...kwargs - }); - } - /** - * Get the parameters used to invoke the model - */ - invocationParams(options) { - const tool_choice = handleToolChoice(options?.tool_choice); - const toolBetas = options?.tools?.reduce((acc, tool) => { - if (typeof tool === "object" && "type" in tool && tool.type in ANTHROPIC_TOOL_BETAS) { - const beta = ANTHROPIC_TOOL_BETAS[tool.type]; - if (!acc.includes(beta)) return [...acc, beta]; - } - return acc; - }, []); - const output = { - model: this.model, - stop_sequences: options?.stop ?? this.stopSequences, - stream: this.streaming, - max_tokens: this.maxTokens, - tools: this.formatStructuredToolToAnthropic(options?.tools), - tool_choice, - thinking: this.thinking, - context_management: this.contextManagement, - ...this.invocationKwargs, - container: options?.container, - betas: _combineBetas(this.betas, options?.betas, toolBetas ?? []), - output_format: options?.output_format, - mcp_servers: options?.mcp_servers - }; - if (this.thinking.type === "enabled") { - if (this.topP !== void 0 && this.topK !== -1) throw new Error("topK is not supported when thinking is enabled"); - if (this.temperature !== void 0 && this.temperature !== 1) throw new Error("temperature is not supported when thinking is enabled"); - } else { - output.temperature = this.temperature; - output.top_k = this.topK; - output.top_p = this.topP; - } - return output; - } - /** @ignore */ - _identifyingParams() { - return { - model_name: this.model, - ...this.invocationParams() - }; - } - /** - * Get the identifying parameters for the model - */ - identifyingParams() { - return { - model_name: this.model, - ...this.invocationParams() - }; - } - async *_streamResponseChunks(messages, options, runManager) { - const params = this.invocationParams(options); - const formattedMessages = message_inputs_convertMessagesToAnthropicPayload(messages); - const payload = { - ...params, - ...formattedMessages, - stream: true - }; - const coerceContentToString = !_toolsInParams(payload) && !_documentsInParams(payload) && !_thinkingInParams(payload); - const stream = await this.createStreamWithRetry(payload, { headers: options.headers }); - for await (const data of stream) { - if (options.signal?.aborted) { - stream.controller.abort(); - throw new Error("AbortError: User aborted the request."); - } - const shouldStreamUsage = this.streamUsage ?? options.streamUsage; - const result = _makeMessageChunkFromAnthropicEvent(data, { - streamUsage: shouldStreamUsage, - coerceContentToString - }); - if (!result) continue; - const { chunk } = result; - const token = extractToken(chunk); - const generationChunk = new ChatGenerationChunk({ - message: new AIMessageChunk({ - content: chunk.content, - additional_kwargs: chunk.additional_kwargs, - tool_call_chunks: chunk.tool_call_chunks, - usage_metadata: shouldStreamUsage ? chunk.usage_metadata : void 0, - response_metadata: chunk.response_metadata, - id: chunk.id - }), - text: token ?? "" - }); - yield generationChunk; - await runManager?.handleLLMNewToken(token ?? "", void 0, void 0, void 0, void 0, { chunk: generationChunk }); - } - } - /** @ignore */ - async _generateNonStreaming(messages, params, requestOptions) { - const response = await this.completionWithRetry({ - ...params, - stream: false, - ...message_inputs_convertMessagesToAnthropicPayload(messages) - }, requestOptions); - const { content,...additionalKwargs } = response; - const generations = anthropicResponseToChatMessages(content, additionalKwargs); - const { role: _role, type: _type,...rest } = additionalKwargs; - return { - generations, - llmOutput: rest - }; - } - /** @ignore */ - async _generate(messages, options, runManager) { - if (this.stopSequences && options.stop) throw new Error(`"stopSequence" parameter found in input and default params`); - const params = this.invocationParams(options); - if (params.stream) { - let finalChunk; - const stream = this._streamResponseChunks(messages, options, runManager); - for await (const chunk of stream) if (finalChunk === void 0) finalChunk = chunk; - else finalChunk = finalChunk.concat(chunk); - if (finalChunk === void 0) throw new Error("No chunks returned from Anthropic API."); - return { generations: [{ - text: finalChunk.text, - message: finalChunk.message - }] }; - } else return this._generateNonStreaming(messages, params, { - signal: options.signal, - headers: options.headers - }); - } - /** - * Creates a streaming request with retry. - * @param request The parameters for creating a completion. - * @param options - * @returns A streaming request. - */ - async createStreamWithRetry(request, options) { - if (!this.streamingClient) { - const options_ = this.apiUrl ? { baseURL: this.apiUrl } : void 0; - this.streamingClient = this.createClient({ - dangerouslyAllowBrowser: true, - ...this.clientOptions, - ...options_, - apiKey: this.apiKey, - maxRetries: 0 - }); - } - const { betas,...rest } = request; - const makeCompletionRequest = async () => { - try { - if (request?.betas?.length) { - const stream = await this.streamingClient.beta.messages.create({ - ...rest, - betas, - ...this.invocationKwargs, - stream: true - }, options); - return stream; - } - return await this.streamingClient.messages.create({ - ...rest, - ...this.invocationKwargs, - stream: true - }, options); - } catch (e) { - const error = wrapAnthropicClientError(e); - throw error; - } - }; - return this.caller.call(makeCompletionRequest); - } - /** @ignore */ - async completionWithRetry(request, options) { - if (!this.batchClient) { - const options$1 = this.apiUrl ? { baseURL: this.apiUrl } : void 0; - this.batchClient = this.createClient({ - dangerouslyAllowBrowser: true, - ...this.clientOptions, - ...options$1, - apiKey: this.apiKey, - maxRetries: 0 - }); - } - const { betas,...rest } = request; - const makeCompletionRequest = async () => { - try { - if (request?.betas?.length) { - const response = await this.batchClient.beta.messages.create({ - ...rest, - ...this.invocationKwargs, - betas - }, options); - return response; - } - return await this.batchClient.messages.create({ - ...rest, - ...this.invocationKwargs - }, options); - } catch (e) { - const error = wrapAnthropicClientError(e); - throw error; - } - }; - return this.caller.callWithOptions({ signal: options.signal ?? void 0 }, makeCompletionRequest); - } - _llmType() { - return "anthropic"; - } - /** - * Return profiling information for the model. - * - * Provides information about the model's capabilities and constraints, - * including token limits, multimodal support, and advanced features like - * tool calling and structured output. - * - * @returns {ModelProfile} An object describing the model's capabilities and constraints - * - * @example - * ```typescript - * const model = new ChatAnthropic({ model: "claude-opus-4-0" }); - * const profile = model.profile; - * console.log(profile.maxInputTokens); // 200000 - * console.log(profile.imageInputs); // true - * ``` - */ - get profile() { - return profiles_default[this.model] ?? {}; - } - withStructuredOutput(outputSchema, config) { - let llm; - let outputParser; - const { schema, name, includeRaw } = { - ...config, - schema: outputSchema - }; - let method = config?.method ?? "functionCalling"; - if (method === "jsonMode") { - console.warn(`"jsonMode" is not supported for Anthropic models. Falling back to "jsonSchema".`); - method = "jsonSchema"; - } - if (method === "jsonSchema") { - outputParser = isInteropZodSchema(schema) ? StructuredOutputParser.fromZodSchema(schema) : new JsonOutputParser(); - const jsonSchema = transformJSONSchema(toJsonSchema(schema)); - llm = this.withConfig({ - outputVersion: "v0", - output_format: { - type: "json_schema", - schema: jsonSchema - }, - betas: ["structured-outputs-2025-11-13"], - ls_structured_output_format: { - kwargs: { method: "json_schema" }, - schema: jsonSchema - } - }); - } else if (method === "functionCalling") { - let functionName = name ?? "extract"; - let tools; - if (isInteropZodSchema(schema)) { - const jsonSchema = toJsonSchema(schema); - tools = [{ - name: functionName, - description: jsonSchema.description ?? "A function available to call.", - input_schema: jsonSchema - }]; - outputParser = new AnthropicToolsOutputParser({ - returnSingle: true, - keyName: functionName, - zodSchema: schema - }); - } else { - let anthropicTools; - if (typeof schema.name === "string" && typeof schema.description === "string" && typeof schema.input_schema === "object" && schema.input_schema != null) { - anthropicTools = schema; - functionName = schema.name; - } else anthropicTools = { - name: functionName, - description: schema.description ?? "", - input_schema: schema - }; - tools = [anthropicTools]; - outputParser = new AnthropicToolsOutputParser({ - returnSingle: true, - keyName: functionName - }); - } - if (this.thinking?.type === "enabled") { - const thinkingAdmonition = "Anthropic structured output relies on forced tool calling, which is not supported when `thinking` is enabled. This method will raise OutputParserException if tool calls are not generated. Consider disabling `thinking` or adjust your prompt to ensure the tool is called."; - console.warn(thinkingAdmonition); - llm = this.withConfig({ - outputVersion: "v0", - tools, - ls_structured_output_format: { - kwargs: { method: "functionCalling" }, - schema: toJsonSchema(schema) - } - }); - const raiseIfNoToolCalls = (message) => { - if (!message.tool_calls || message.tool_calls.length === 0) throw new Error(thinkingAdmonition); - return message; - }; - llm = llm.pipe(raiseIfNoToolCalls); - } else llm = this.withConfig({ - outputVersion: "v0", - tools, - tool_choice: { - type: "tool", - name: functionName - }, - ls_structured_output_format: { - kwargs: { method: "functionCalling" }, - schema: toJsonSchema(schema) - } - }); - } else throw new TypeError(`Unrecognized structured output method '${method}'. Expected 'functionCalling' or 'jsonSchema'`); - if (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: "ChatAnthropicStructuredOutput" }); - const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); - const parserNone = RunnablePassthrough.assign({ parsed: () => null }); - const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); - return RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" }); - } -}; -var ChatAnthropic = class extends ChatAnthropicMessages {}; - -//#endregion - -//# sourceMappingURL=chat_models.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/utils/prompts.js - - -//#region src/utils/prompts.ts -/** -* Convert a formatted LangChain prompt (e.g. pulled from the hub) into -* a format expected by Anthropic's JS SDK. -* -* Requires the "@langchain/anthropic" package to be installed in addition -* to the Anthropic SDK. -* -* @example -* ```ts -* import { convertPromptToAnthropic } from "langsmith/utils/hub/anthropic"; -* import { pull } from "langchain/hub"; -* -* import Anthropic from '@anthropic-ai/sdk'; -* -* const prompt = await pull("jacob/joke-generator"); -* const formattedPrompt = await prompt.invoke({ -* topic: "cats", -* }); -* -* const { system, messages } = convertPromptToAnthropic(formattedPrompt); -* -* const anthropicClient = new Anthropic({ -* apiKey: 'your_api_key', -* }); -* -* const anthropicResponse = await anthropicClient.messages.create({ -* model: "claude-sonnet-4-5-20250929", -* max_tokens: 1024, -* stream: false, -* system, -* messages, -* }); -* ``` -* @param formattedPrompt -* @returns A partial Anthropic payload. -*/ -function convertPromptToAnthropic(formattedPrompt) { - const messages = formattedPrompt.toChatMessages(); - const anthropicBody = _convertMessagesToAnthropicPayload(messages); - if (anthropicBody.messages === void 0) anthropicBody.messages = []; - return anthropicBody; -} - -//#endregion - -//# sourceMappingURL=prompts.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/types.js - - -//#region src/tools/types.ts -/** -* Memory tool command types as defined by Anthropic's memory tool API. -* @beta -* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/memory-tool -*/ -const Memory20250818ViewCommandSchema = object({ - command: literal("view"), - path: schemas_string() -}); -const Memory20250818CreateCommandSchema = object({ - command: literal("create"), - path: schemas_string(), - file_text: schemas_string() -}); -const Memory20250818StrReplaceCommandSchema = object({ - command: literal("str_replace"), - path: schemas_string(), - old_str: schemas_string(), - new_str: schemas_string() -}); -const Memory20250818InsertCommandSchema = object({ - command: literal("insert"), - path: schemas_string(), - insert_line: schemas_number(), - insert_text: schemas_string() -}); -const Memory20250818DeleteCommandSchema = object({ - command: literal("delete"), - path: schemas_string() -}); -const Memory20250818RenameCommandSchema = object({ - command: literal("rename"), - old_path: schemas_string(), - new_path: schemas_string() -}); -const Memory20250818CommandSchema = discriminatedUnion("command", [ - Memory20250818ViewCommandSchema, - Memory20250818CreateCommandSchema, - Memory20250818StrReplaceCommandSchema, - Memory20250818InsertCommandSchema, - Memory20250818DeleteCommandSchema, - Memory20250818RenameCommandSchema -]); -/** -* Text editor tool command types for Claude 4.x models. -* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/text-editor-tool -*/ -const TextEditor20250728ViewCommandSchema = object({ - command: literal("view"), - path: schemas_string(), - view_range: tuple([schemas_number(), schemas_number()]).optional() -}); -const TextEditor20250728StrReplaceCommandSchema = object({ - command: literal("str_replace"), - path: schemas_string(), - old_str: schemas_string(), - new_str: schemas_string() -}); -const TextEditor20250728CreateCommandSchema = object({ - command: literal("create"), - path: schemas_string(), - file_text: schemas_string() -}); -const TextEditor20250728InsertCommandSchema = object({ - command: literal("insert"), - path: schemas_string(), - insert_line: schemas_number(), - new_str: schemas_string() -}); -const TextEditor20250728CommandSchema = discriminatedUnion("command", [ - TextEditor20250728ViewCommandSchema, - TextEditor20250728StrReplaceCommandSchema, - TextEditor20250728CreateCommandSchema, - TextEditor20250728InsertCommandSchema -]); -const coordinateSchema = tuple([schemas_number(), schemas_number()]); -const ComputerScreenshotActionSchema = object({ action: literal("screenshot") }); -const ComputerLeftClickActionSchema = object({ - action: literal("left_click"), - coordinate: coordinateSchema -}); -const ComputerRightClickActionSchema = object({ - action: literal("right_click"), - coordinate: coordinateSchema -}); -const ComputerMiddleClickActionSchema = object({ - action: literal("middle_click"), - coordinate: coordinateSchema -}); -const ComputerDoubleClickActionSchema = object({ - action: literal("double_click"), - coordinate: coordinateSchema -}); -const ComputerTripleClickActionSchema = object({ - action: literal("triple_click"), - coordinate: coordinateSchema -}); -const ComputerLeftClickDragActionSchema = object({ - action: literal("left_click_drag"), - start_coordinate: coordinateSchema, - end_coordinate: coordinateSchema -}); -const ComputerLeftMouseDownActionSchema = object({ - action: literal("left_mouse_down"), - coordinate: coordinateSchema -}); -const ComputerLeftMouseUpActionSchema = object({ - action: literal("left_mouse_up"), - coordinate: coordinateSchema -}); -const ComputerScrollActionSchema = object({ - action: literal("scroll"), - coordinate: coordinateSchema, - scroll_direction: schemas_enum([ - "up", - "down", - "left", - "right" - ]), - scroll_amount: schemas_number() -}); -const ComputerTypeActionSchema = object({ - action: literal("type"), - text: schemas_string() -}); -const ComputerKeyActionSchema = object({ - action: literal("key"), - key: schemas_string() -}); -const ComputerMouseMoveActionSchema = object({ - action: literal("mouse_move"), - coordinate: coordinateSchema -}); -const ComputerHoldKeyActionSchema = object({ - action: literal("hold_key"), - key: schemas_string() -}); -const ComputerWaitActionSchema = object({ - action: literal("wait"), - duration: schemas_number().optional() -}); -const ComputerZoomActionSchema = object({ - action: literal("zoom"), - region: tuple([ - schemas_number(), - schemas_number(), - schemas_number(), - schemas_number() - ]) -}); -const Computer20250124ActionSchema = discriminatedUnion("action", [ - ComputerScreenshotActionSchema, - ComputerLeftClickActionSchema, - ComputerRightClickActionSchema, - ComputerMiddleClickActionSchema, - ComputerDoubleClickActionSchema, - ComputerTripleClickActionSchema, - ComputerLeftClickDragActionSchema, - ComputerLeftMouseDownActionSchema, - ComputerLeftMouseUpActionSchema, - ComputerScrollActionSchema, - ComputerTypeActionSchema, - ComputerKeyActionSchema, - ComputerMouseMoveActionSchema, - ComputerHoldKeyActionSchema, - ComputerWaitActionSchema -]); -const Computer20251124ActionSchema = discriminatedUnion("action", [ - ComputerScreenshotActionSchema, - ComputerLeftClickActionSchema, - ComputerRightClickActionSchema, - ComputerMiddleClickActionSchema, - ComputerDoubleClickActionSchema, - ComputerTripleClickActionSchema, - ComputerLeftClickDragActionSchema, - ComputerLeftMouseDownActionSchema, - ComputerLeftMouseUpActionSchema, - ComputerScrollActionSchema, - ComputerTypeActionSchema, - ComputerKeyActionSchema, - ComputerMouseMoveActionSchema, - ComputerHoldKeyActionSchema, - ComputerWaitActionSchema, - ComputerZoomActionSchema -]); -/** -* Bash tool command types for Claude 4 models and Claude 3.7. -* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/bash-tool -*/ -const Bash20250124ExecuteCommandSchema = object({ command: schemas_string().describe("The bash command to run") }); -const Bash20250124RestartCommandSchema = object({ restart: literal(true).describe("Set to true to restart the bash session") }); -const Bash20250124CommandSchema = union([Bash20250124ExecuteCommandSchema, Bash20250124RestartCommandSchema]); - -//#endregion - -//# sourceMappingURL=types.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/memory.js - - - -//#region src/tools/memory.ts -/** -* Creates an Anthropic memory tool that can be used with ChatAnthropic. -* -* The memory tool enables Claude to store and retrieve information across conversations -* through a memory file directory. Claude can create, read, update, and delete files that -* persist between sessions, allowing it to build knowledge over time without keeping -* everything in the context window. -* -* @example -* ```typescript -* import { ChatAnthropic, memory_20250818 } from "@langchain/anthropic"; -* -* const llm = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929" -* }); -* -* const memory = memory_20250818({ -* execute: async (args) => { -* // handle memory command execution -* // ... -* }, -* }); -* const llmWithMemory = llm.bindTools([memory]); -* -* const response = await llmWithMemory.invoke("Remember that I like Python"); -* ``` -* -* @param options - Optional configuration for the memory tool (currently unused) -* @param options.execute - Optional execute function that handles memory command execution. -* @returns The memory tool object that can be passed to `bindTools` -* -* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/memory-tool -*/ -function memory_20250818(options) { - const memoryTool = tool(options?.execute, { - name: "memory", - schema: Memory20250818CommandSchema - }); - memoryTool.extras = { - ...memoryTool.extras ?? {}, - providerToolDefinition: { - type: "memory_20250818", - name: "memory" - } - }; - return memoryTool; -} - -//#endregion - -//# sourceMappingURL=memory.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/webSearch.js -//#region src/tools/webSearch.ts -/** -* Creates a web search tool that gives Claude direct access to real-time web content, -* allowing it to answer questions with up-to-date information beyond its knowledge cutoff. -* Claude automatically cites sources from search results as part of its answer. -* -* @see {@link https://docs.anthropic.com/en/docs/build-with-claude/tool-use/web-search-tool | Anthropic Web Search Documentation} -* @param options - Configuration options for the web search tool -* @returns A web search tool definition to be passed to the Anthropic API -* -* @example -* ```typescript -* import { ChatAnthropic, tools } from "@langchain/anthropic"; -* -* const model = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* }); -* -* // Basic usage -* const response = await model.invoke("What is the weather in NYC?", { -* tools: [tools.webSearch_20250305()], -* }); -* -* // With options -* const responseWithOptions = await model.invoke("Latest news about AI?", { -* tools: [tools.webSearch_20250305({ -* maxUses: 5, -* allowedDomains: ["reuters.com", "bbc.com"], -* userLocation: { -* type: "approximate", -* city: "San Francisco", -* region: "California", -* country: "US", -* timezone: "America/Los_Angeles", -* }, -* })], -* }); -* ``` -*/ -function webSearch_20250305(options) { - return { - type: "web_search_20250305", - name: "web_search", - max_uses: options?.maxUses, - allowed_domains: options?.allowedDomains, - blocked_domains: options?.blockedDomains, - cache_control: options?.cacheControl, - defer_loading: options?.deferLoading, - strict: options?.strict, - user_location: options?.userLocation - }; -} - -//#endregion - -//# sourceMappingURL=webSearch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/webFetch.js -//#region src/tools/webFetch.ts -/** -* Creates a web fetch tool that allows Claude to retrieve full content from specified -* web pages and PDF documents. Claude can only fetch URLs that have been explicitly -* provided by the user or that come from previous web search or web fetch results. -* -* @warning Enabling the web fetch tool in environments where Claude processes untrusted -* input alongside sensitive data poses data exfiltration risks. We recommend only using -* this tool in trusted environments or when handling non-sensitive data. -* -* @see {@link https://docs.anthropic.com/en/docs/build-with-claude/tool-use/web-fetch-tool | Anthropic Web Fetch Documentation} -* @param options - Configuration options for the web fetch tool -* @returns A web fetch tool definition to be passed to the Anthropic API -* -* @example -* ```typescript -* import { ChatAnthropic, tools } from "@langchain/anthropic"; -* -* const model = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* }); -* -* // Basic usage - fetch content from a URL -* const response = await model.invoke( -* "Please analyze the content at https://example.com/article", -* { tools: [tools.webFetch_20250910()] } -* ); -* -* // With options -* const responseWithOptions = await model.invoke( -* "Summarize this research paper: https://arxiv.org/abs/2024.12345", -* { -* tools: [tools.webFetch_20250910({ -* maxUses: 5, -* allowedDomains: ["arxiv.org", "example.com"], -* citations: { enabled: true }, -* maxContentTokens: 50000, -* })], -* } -* ); -* -* // Combined with web search for comprehensive information gathering -* const combinedResponse = await model.invoke( -* "Find recent articles about quantum computing and analyze the most relevant one", -* { -* tools: [ -* tools.webSearch_20250305({ maxUses: 3 }), -* tools.webFetch_20250910({ maxUses: 5, citations: { enabled: true } }), -* ], -* } -* ); -* ``` -*/ -function webFetch_20250910(options) { - return { - type: "web_fetch_20250910", - name: "web_fetch", - max_uses: options?.maxUses, - allowed_domains: options?.allowedDomains, - blocked_domains: options?.blockedDomains, - cache_control: options?.cacheControl, - citations: options?.citations, - max_content_tokens: options?.maxContentTokens - }; -} - -//#endregion - -//# sourceMappingURL=webFetch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/toolSearch.js -//#region src/tools/toolSearch.ts -/** -* Creates a regex-based tool search tool that enables Claude to work with hundreds -* or thousands of tools by dynamically discovering and loading them on-demand. -* Claude constructs regex patterns (using Python's `re.search()` syntax) to search -* for tools by name, description, argument names, and argument descriptions. -* -* @note This tool requires the beta header `advanced-tool-use-2025-11-20` in API requests. -* -* @see {@link https://docs.anthropic.com/en/docs/build-with-claude/tool-use/tool-search-tool | Anthropic Tool Search Documentation} -* @param options - Configuration options for the tool search tool -* @returns A tool search tool definition to be passed to the Anthropic API -* -* @example -* ```typescript -* import { ChatAnthropic, tools } from "@langchain/anthropic"; -* -* const model = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* }); -* -* const getWeather = tool( -* async (input: { location: string }) => { -* return `Weather in ${input.location}`; -* }, -* { -* name: "get_weather", -* description: "Get the weather at a specific location", -* schema: z.object({ -* location: z.string(), -* }), -* extras: { defer_loading: true }, -* }, -* ); -* -* // Use with deferred tools - Claude will search and discover tools as needed -* const response = await model.invoke("What is the weather in San Francisco?", { -* tools: [ -* tools.toolSearchRegex_20251119(), -* getWeather, -* ], -* }); -* ``` -*/ -function toolSearchRegex_20251119(options) { - return { - type: "tool_search_tool_regex_20251119", - name: "tool_search_tool_regex", - cache_control: options?.cacheControl - }; -} -/** -* Creates a BM25-based tool search tool that enables Claude to work with hundreds -* or thousands of tools by dynamically discovering and loading them on-demand. -* Claude uses natural language queries to search for tools by name, description, -* argument names, and argument descriptions. -* -* @note This tool requires the beta header `advanced-tool-use-2025-11-20` in API requests. -* -* @see {@link https://docs.anthropic.com/en/docs/build-with-claude/tool-use/tool-search-tool | Anthropic Tool Search Documentation} -* @param options - Configuration options for the tool search tool -* @returns A tool search tool definition to be passed to the Anthropic API -* -* @example -* ```typescript -* import { ChatAnthropic, tools } from "@langchain/anthropic"; -* -* const model = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* clientOptions: { -* defaultHeaders: { "anthropic-beta": "advanced-tool-use-2025-11-20" }, -* }, -* }); -* -* const getWeather = tool( -* async (input: { location: string }) => { -* return `Weather in ${input.location}`; -* }, -* { -* name: "get_weather", -* description: "Get the weather at a specific location", -* schema: z.object({ -* location: z.string(), -* }), -* extras: { defer_loading: true }, -* }, -* ); -* -* // Use with deferred tools - Claude will search using natural language -* const response = await model.invoke("What is the weather in San Francisco?", { -* tools: [ -* tools.toolSearchBM25_20251119(), -* getWeather, -* ], -* }); -* ``` -*/ -function toolSearchBM25_20251119(options) { - return { - type: "tool_search_tool_bm25_20251119", - name: "tool_search_tool_bm25", - cache_control: options?.cacheControl - }; -} - -//#endregion - -//# sourceMappingURL=toolSearch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/textEditor.js - - - -//#region src/tools/textEditor.ts -/** -* Creates an Anthropic text editor tool for Claude 4.x models that can view and modify text files. -* -* The text editor tool enables Claude to view and modify text files, helping debug, fix, -* and improve code or other text documents. Claude can directly interact with files, -* providing hands-on assistance rather than just suggesting changes. -* -* Available commands: -* - `view`: Examine file contents or list directory contents -* - `str_replace`: Replace specific text in a file -* - `create`: Create a new file with specified content -* - `insert`: Insert text at a specific line number -* -* @example -* ```typescript -* import { ChatAnthropic, tools } from "@langchain/anthropic"; -* import * as fs from "fs"; -* -* const llm = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* }); -* -* const textEditor = tools.textEditor_20250728({ -* execute: async (args) => { -* if (args.command === "view") { -* const content = fs.readFileSync(args.path, "utf-8"); -* return content.split("\n").map((line, i) => `${i + 1}: ${line}`).join("\n"); -* } -* if (args.command === "str_replace") { -* let content = fs.readFileSync(args.path, "utf-8"); -* content = content.replace(args.old_str!, args.new_str!); -* fs.writeFileSync(args.path, content); -* return "Successfully replaced text."; -* } -* // Handle other commands... -* return "Command executed"; -* }, -* maxCharacters: 10000, -* }); -* -* const llmWithEditor = llm.bindTools([textEditor]); -* const response = await llmWithEditor.invoke( -* "There's a syntax error in my primes.py file. Can you help me fix it?" -* ); -* ``` -* -* @param options - Configuration options for the text editor tool -* @param options.execute - Function that handles text editor command execution -* @param options.maxCharacters - Maximum characters to return when viewing files -* @returns The text editor tool object that can be passed to `bindTools` -* -* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/text-editor-tool -*/ -function textEditor_20250728(options) { - const name = "str_replace_based_edit_tool"; - const textEditorTool = tool(options?.execute, { - name, - description: "A tool for editing text files", - schema: TextEditor20250728CommandSchema - }); - textEditorTool.extras = { - ...textEditorTool.extras ?? {}, - providerToolDefinition: { - type: "text_editor_20250728", - name, - ...options?.maxCharacters !== void 0 && { max_characters: options.maxCharacters } - } - }; - return textEditorTool; -} - -//#endregion - -//# sourceMappingURL=textEditor.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/computer.js - - - -//#region src/tools/computer.ts -const TOOL_NAME = "computer"; -/** -* Creates an Anthropic computer use tool for Claude Opus 4.5 that provides -* screenshot capabilities and mouse/keyboard control for autonomous desktop interaction. -* -* The computer use tool enables Claude to interact with desktop environments through: -* - **Screenshot capture**: See what's currently displayed on screen -* - **Mouse control**: Click, drag, and move the cursor -* - **Keyboard input**: Type text and use keyboard shortcuts -* - **Zoom**: View specific screen regions at full resolution (when enabled) -* -* @warning Computer use is a beta feature with unique risks. Use a dedicated virtual machine -* or container with minimal privileges. Avoid giving access to sensitive data. -* -* @see {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool | Anthropic Computer Use Documentation} -* -* @example -* ```typescript -* import { ChatAnthropic, tools } from "@langchain/anthropic"; -* -* const llm = new ChatAnthropic({ -* model: "claude-opus-4-5-20251101", -* clientOptions: { -* defaultHeaders: { -* "anthropic-beta": "computer-use-2025-11-24", -* }, -* }, -* }); -* -* const computer = tools.computer_20251124({ -* displayWidthPx: 1024, -* displayHeightPx: 768, -* displayNumber: 1, -* enableZoom: true, -* execute: async (action) => { -* if (action.action === "screenshot") { -* // Capture and return base64-encoded screenshot -* return captureScreenshot(); -* } -* if (action.action === "left_click") { -* // Click at the specified coordinates -* await click(action.coordinate[0], action.coordinate[1]); -* return captureScreenshot(); -* } -* // Handle other actions... -* }, -* }); -* -* const llmWithComputer = llm.bindTools([computer]); -* const response = await llmWithComputer.invoke( -* "Save a picture of a cat to my desktop." -* ); -* ``` -* -* @param options - Configuration options for the computer use tool -* @returns The computer use tool object that can be passed to `bindTools` -*/ -function computer_20251124(options) { - const name = TOOL_NAME; - const computerTool = tool(options.execute, { - name, - schema: Computer20251124ActionSchema - }); - computerTool.extras = { - ...computerTool.extras ?? {}, - providerToolDefinition: { - type: "computer_20251124", - name, - display_width_px: options.displayWidthPx, - display_height_px: options.displayHeightPx, - ...options.displayNumber !== void 0 && { display_number: options.displayNumber }, - ...options.enableZoom !== void 0 && { enable_zoom: options.enableZoom } - } - }; - return computerTool; -} -/** -* Creates an Anthropic computer use tool that provides screenshot capabilities and mouse/keyboard control -* for autonomous desktop interaction. -* -* Supported models: Claude Sonnet 4.5, Haiku 4.5, Opus 4.1, Sonnet 4, Opus 4, and Sonnet 3.7 versions. -* -* The computer use tool enables Claude to interact with desktop environments through: -* - **Screenshot capture**: See what's currently displayed on screen -* - **Mouse control**: Click, drag, and move the cursor -* - **Keyboard input**: Type text and use keyboard shortcuts -* -* @warning Computer use is a beta feature with unique risks. Use a dedicated virtual machine -* or container with minimal privileges. Avoid giving access to sensitive data. -* -* @see {@link https://platform.claude.com/docs/en/agents-and-tools/tool-use/computer-use-tool | Anthropic Computer Use Documentation} -* -* @example -* ```typescript -* import { ChatAnthropic, tools } from "@langchain/anthropic"; -* -* const llm = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* clientOptions: { -* defaultHeaders: { -* "anthropic-beta": "computer-use-2025-01-24", -* }, -* }, -* }); -* -* const computer = tools.computer_20250124({ -* displayWidthPx: 1024, -* displayHeightPx: 768, -* displayNumber: 1, -* execute: async (action) => { -* if (action.action === "screenshot") { -* // Capture and return base64-encoded screenshot -* return captureScreenshot(); -* } -* if (action.action === "left_click") { -* // Click at the specified coordinates -* await click(action.coordinate[0], action.coordinate[1]); -* return captureScreenshot(); -* } -* // Handle other actions... -* }, -* }); -* -* const llmWithComputer = llm.bindTools([computer]); -* const response = await llmWithComputer.invoke( -* "Save a picture of a cat to my desktop." -* ); -* ``` -* -* @param options - Configuration options for the computer use tool -* @returns The computer use tool object that can be passed to `bindTools` -*/ -function computer_20250124(options) { - const name = TOOL_NAME; - const computerTool = tool(options.execute, { - name, - description: "A tool for interacting with the computer", - schema: Computer20250124ActionSchema - }); - computerTool.extras = { - ...computerTool.extras ?? {}, - providerToolDefinition: { - type: "computer_20250124", - name, - display_width_px: options.displayWidthPx, - display_height_px: options.displayHeightPx, - ...options.displayNumber !== void 0 && { display_number: options.displayNumber } - } - }; - return computerTool; -} - -//#endregion - -//# sourceMappingURL=computer.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/codeExecution.js -//#region src/tools/codeExecution.ts -/** -* Creates a code execution tool that allows Claude to run Bash commands and manipulate files -* in a secure, sandboxed environment. Claude can analyze data, create visualizations, -* perform calculations, and process files. -* -* When this tool is provided, Claude automatically gains access to: -* - **Bash commands**: Execute shell commands for system operations -* - **File operations**: Create, view, and edit files directly -* -* @note This tool requires the beta header `code-execution-2025-08-25` in API requests. -* -* @see {@link https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/code-execution-tool | Anthropic Code Execution Documentation} -* @param options - Configuration options for the code execution tool -* @returns A code execution tool definition to be passed to the Anthropic API -* -* @example -* ```typescript -* import { ChatAnthropic, tools } from "@langchain/anthropic"; -* -* const model = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* }); -* -* // Basic usage - calculations and data analysis -* const response = await model.invoke( -* "Calculate the mean and standard deviation of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]", -* { tools: [tools.codeExecution_20250825()] } -* ); -* -* // File operations and visualization -* const response2 = await model.invoke( -* "Create a matplotlib visualization of sales data and save it as chart.png", -* { tools: [tools.codeExecution_20250825()] } -* ); -* ``` -* -* @example Container reuse -* ```typescript -* // First request - creates a container -* const response1 = await model.invoke( -* "Write a random number to /tmp/number.txt", -* { tools: [tools.codeExecution_20250825()] } -* ); -* -* // Extract container ID from response for reuse -* const containerId = response1.response_metadata?.container?.id; -* -* // Second request - reuse container to access the file -* const response2 = await model.invoke( -* "Read /tmp/number.txt and calculate its square", -* { -* tools: [tools.codeExecution_20250825()], -* // Pass container ID to reuse the same environment -* } -* ); -* ``` -*/ -function codeExecution_20250825(options) { - return { - type: "code_execution_20250825", - name: "code_execution", - cache_control: options?.cacheControl - }; -} - -//#endregion - -//# sourceMappingURL=codeExecution.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/bash.js - - - -//#region src/tools/bash.ts -/** -* Creates an Anthropic bash tool for Claude 4 models and Claude 3.7 that enables -* shell command execution in a persistent bash session. -* -* The bash tool provides Claude with: -* - **Persistent bash session**: Maintains state between commands -* - **Shell command execution**: Run any shell command -* - **Environment access**: Access to environment variables and working directory -* - **Command chaining**: Support for pipes, redirects, and scripting -* -* Available commands: -* - Execute a command: `{ command: "ls -la" }` -* - Restart the session: `{ restart: true }` -* -* @warning The bash tool provides direct system access. Implement safety measures -* such as running in isolated environments (Docker/VM), command filtering, -* and resource limits. -* -* @example -* ```typescript -* import { ChatAnthropic, tools } from "@langchain/anthropic"; -* import { execSync } from "child_process"; -* -* const llm = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* }); -* -* const bash = tools.bash_20250124({ -* execute: async (args) => { -* if (args.restart) { -* // Reset session state -* return "Bash session restarted"; -* } -* try { -* const output = execSync(args.command!, { -* encoding: "utf-8", -* timeout: 30000, -* }); -* return output; -* } catch (error) { -* return `Error: ${error.message}`; -* } -* }, -* }); -* -* const llmWithBash = llm.bindTools([bash]); -* const response = await llmWithBash.invoke( -* "List all Python files in the current directory" -* ); -* -* // Outputs: "bash" -* console.log(response.tool_calls[0].name); -* // Outputs: "ls -la *.py 2>/dev/null || echo \"No Python files found in the current directory\" -* console.log(response.tool_calls[0].args.command); -* ``` -* -* @example Multi-step automation -* ```typescript -* // Claude can chain commands in a persistent session: -* // 1. cd /tmp -* // 2. echo "Hello" > test.txt -* // 3. cat test.txt // Works because we're still in /tmp -* ``` -* -* @param options - Configuration options for the bash tool -* @param options.execute - Function that handles bash command execution -* @returns The bash tool object that can be passed to `bindTools` -* -* @see https://docs.anthropic.com/en/docs/agents-and-tools/tool-use/bash-tool -*/ -function bash_20250124(options) { - const name = "bash"; - const bashTool = tool(options?.execute, { - name, - description: "A tool for executing bash commands", - schema: Bash20250124CommandSchema - }); - bashTool.extras = { - ...bashTool.extras ?? {}, - providerToolDefinition: { - type: "bash_20250124", - name - } - }; - return bashTool; -} - -//#endregion - -//# sourceMappingURL=bash.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/mcpToolset.js -//#region src/tools/mcpToolset.ts -/** -* Creates an MCP toolset that connects to a remote MCP server to access its tools. -* This enables Claude to use tools from MCP servers without implementing a separate MCP client. -* -* @note This tool requires the beta header `mcp-client-2025-11-20` in API requests. -* The header is automatically added when using this tool. -* -* @see {@link https://docs.anthropic.com/en/docs/agents-and-tools/mcp-connector | Anthropic MCP Connector Documentation} -* @param options - Configuration options for the MCP toolset -* @returns An MCP toolset definition to be passed to the Anthropic API tools array -* -* @example -* ```typescript -* import { ChatAnthropic, tools } from "@langchain/anthropic"; -* -* const model = new ChatAnthropic({ -* model: "claude-sonnet-4-5-20250929", -* }); -* -* // Basic usage - enable all tools from an MCP server -* const response = await model.invoke("What tools do you have available?", { -* mcp_servers: [{ -* type: "url", -* url: "https://example-server.modelcontextprotocol.io/sse", -* name: "example-mcp", -* authorization_token: "YOUR_TOKEN", -* }], -* tools: [ -* tools.mcpToolset_20251120({ serverName: "example-mcp" }), -* ], -* }); -* -* // Allowlist pattern - enable only specific tools -* const responseAllowlist = await model.invoke("Search for events", { -* mcp_servers: [{ -* type: "url", -* url: "https://calendar.example.com/sse", -* name: "google-calendar-mcp", -* authorization_token: "YOUR_TOKEN", -* }], -* tools: [ -* tools.mcpToolset_20251120({ -* serverName: "google-calendar-mcp", -* defaultConfig: { enabled: false }, -* configs: { -* search_events: { enabled: true }, -* create_event: { enabled: true }, -* }, -* }), -* ], -* }); -* -* // Denylist pattern - disable specific tools -* const responseDenylist = await model.invoke("List my events", { -* mcp_servers: [{ -* type: "url", -* url: "https://calendar.example.com/sse", -* name: "google-calendar-mcp", -* authorization_token: "YOUR_TOKEN", -* }], -* tools: [ -* tools.mcpToolset_20251120({ -* serverName: "google-calendar-mcp", -* configs: { -* delete_all_events: { enabled: false }, -* share_calendar_publicly: { enabled: false }, -* }, -* }), -* ], -* }); -* -* // With deferred loading for use with Tool Search Tool -* const responseDeferred = await model.invoke("Search for tools", { -* mcp_servers: [{ -* type: "url", -* url: "https://example.com/sse", -* name: "example-mcp", -* }], -* tools: [ -* tools.toolSearchRegex_20251119(), -* tools.mcpToolset_20251120({ -* serverName: "example-mcp", -* defaultConfig: { deferLoading: true }, -* }), -* ], -* }); -* ``` -*/ -function mcpToolset_20251120(options) { - const defaultConfig = options.defaultConfig?.enabled !== void 0 || options.defaultConfig?.deferLoading !== void 0 ? { - enabled: options.defaultConfig?.enabled, - defer_loading: options.defaultConfig?.deferLoading - } : void 0; - const configs = options.configs ? Object.fromEntries(Object.entries(options.configs).map(([toolName, config]) => [toolName, { - enabled: config.enabled, - defer_loading: config.deferLoading - }])) : void 0; - return { - type: "mcp_toolset", - mcp_server_name: options.serverName, - default_config: defaultConfig, - configs, - cache_control: options.cacheControl - }; -} - -//#endregion - -//# sourceMappingURL=mcpToolset.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/tools/index.js - - - - - - - - - - -//#region src/tools/index.ts -const tools = { - memory_20250818: memory_20250818, - webSearch_20250305: webSearch_20250305, - webFetch_20250910: webFetch_20250910, - toolSearchRegex_20251119: toolSearchRegex_20251119, - toolSearchBM25_20251119: toolSearchBM25_20251119, - textEditor_20250728: textEditor_20250728, - computer_20251124: computer_20251124, - computer_20250124: computer_20250124, - codeExecution_20250825: codeExecution_20250825, - bash_20250124: bash_20250124, - mcpToolset_20251120: mcpToolset_20251120 -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/anthropic/dist/index.js - - - - - -;// CONCATENATED MODULE: ./src/providers/anthropic.provider.ts - -/** - * Anthropic Claude provider implementation - */ -class AnthropicProvider { - name = 'anthropic'; - apiKey; - constructor(apiKey) { - this.apiKey = apiKey || process.env.ANTHROPIC_API_KEY || ''; - } - isConfigured() { - return !!this.apiKey; - } - getDefaultModel() { - return 'claude-sonnet-4-5-20250929'; - } - getChatModel(config = {}) { - if (!this.isConfigured()) { - throw new Error('Anthropic API key is not configured'); - } - return new ChatAnthropic({ - apiKey: this.apiKey, - modelName: config.model || this.getDefaultModel(), - temperature: config.temperature ?? 0.2, - maxTokens: config.maxTokens ?? 4000, - }); - } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/errors.js -//#region src/utils/errors.ts -function utils_errors_addLangChainErrorFields(error, lc_error_code) { - error.lc_error_code = lc_error_code; - error.message = `${error.message}\n\nTroubleshooting URL: https://docs.langchain.com/oss/javascript/langchain/errors/${lc_error_code}/\n`; - return error; -} - -//#endregion - -//# sourceMappingURL=errors.js.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/tslib.mjs -function tslib_classPrivateFieldSet(receiver, state, value, kind, f) { - if (kind === "m") - throw new TypeError("Private method is not writable"); - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a setter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot write private member to an object whose class did not declare it"); - return kind === "a" ? f.call(receiver, value) : f ? (f.value = value) : state.set(receiver, value), value; -} -function tslib_classPrivateFieldGet(receiver, state, kind, f) { - if (kind === "a" && !f) - throw new TypeError("Private accessor was defined without a getter"); - if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) - throw new TypeError("Cannot read private member from an object whose class did not declare it"); - return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); -} - - -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/uuid.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -/** - * https://stackoverflow.com/a/2117523 - */ -let utils_uuid_uuid4 = function () { - const { crypto } = globalThis; - if (crypto?.randomUUID) { - utils_uuid_uuid4 = crypto.randomUUID.bind(crypto); - return crypto.randomUUID(); - } - const u8 = new Uint8Array(1); - const randomByte = crypto ? () => crypto.getRandomValues(u8)[0] : () => (Math.random() * 0xff) & 0xff; - return '10000000-1000-4000-8000-100000000000'.replace(/[018]/g, (c) => (+c ^ (randomByte() & (15 >> (+c / 4)))).toString(16)); -}; -//# sourceMappingURL=uuid.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/errors.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function errors_isAbortError(err) { - return (typeof err === 'object' && - err !== null && - // Spec-compliant fetch implementations - (('name' in err && err.name === 'AbortError') || - // Expo fetch - ('message' in err && String(err.message).includes('FetchRequestCanceledException')))); -} -const errors_castToError = (err) => { - if (err instanceof Error) - return err; - if (typeof err === 'object' && err !== null) { - try { - if (Object.prototype.toString.call(err) === '[object Error]') { - // @ts-ignore - not all envs have native support for cause yet - const error = new Error(err.message, err.cause ? { cause: err.cause } : {}); - if (err.stack) - error.stack = err.stack; - // @ts-ignore - not all envs have native support for cause yet - if (err.cause && !error.cause) - error.cause = err.cause; - if (err.name) - error.name = err.name; - return error; - } - } - catch { } - try { - return new Error(JSON.stringify(err)); - } - catch { } - } - return new Error(err); -}; -//# sourceMappingURL=errors.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/error.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class error_OpenAIError extends Error { -} -class error_APIError extends error_OpenAIError { - constructor(status, error, message, headers) { - super(`${error_APIError.makeMessage(status, error, message)}`); - this.status = status; - this.headers = headers; - this.requestID = headers?.get('x-request-id'); - this.error = error; - const data = error; - this.code = data?.['code']; - this.param = data?.['param']; - this.type = data?.['type']; - } - static makeMessage(status, error, message) { - const msg = error?.message ? - typeof error.message === 'string' ? - error.message - : JSON.stringify(error.message) - : error ? JSON.stringify(error) - : message; - if (status && msg) { - return `${status} ${msg}`; - } - if (status) { - return `${status} status code (no body)`; - } - if (msg) { - return msg; - } - return '(no status code or body)'; - } - static generate(status, errorResponse, message, headers) { - if (!status || !headers) { - return new error_APIConnectionError({ message, cause: errors_castToError(errorResponse) }); - } - const error = errorResponse?.['error']; - if (status === 400) { - return new error_BadRequestError(status, error, message, headers); - } - if (status === 401) { - return new error_AuthenticationError(status, error, message, headers); - } - if (status === 403) { - return new error_PermissionDeniedError(status, error, message, headers); - } - if (status === 404) { - return new error_NotFoundError(status, error, message, headers); - } - if (status === 409) { - return new error_ConflictError(status, error, message, headers); - } - if (status === 422) { - return new error_UnprocessableEntityError(status, error, message, headers); - } - if (status === 429) { - return new error_RateLimitError(status, error, message, headers); - } - if (status >= 500) { - return new error_InternalServerError(status, error, message, headers); - } - return new error_APIError(status, error, message, headers); - } -} -class error_APIUserAbortError extends error_APIError { - constructor({ message } = {}) { - super(undefined, undefined, message || 'Request was aborted.', undefined); - } -} -class error_APIConnectionError extends error_APIError { - constructor({ message, cause }) { - super(undefined, undefined, message || 'Connection error.', undefined); - // in some environments the 'cause' property is already declared - // @ts-ignore - if (cause) - this.cause = cause; - } -} -class error_APIConnectionTimeoutError extends error_APIConnectionError { - constructor({ message } = {}) { - super({ message: message ?? 'Request timed out.' }); - } -} -class error_BadRequestError extends error_APIError { -} -class error_AuthenticationError extends error_APIError { -} -class error_PermissionDeniedError extends error_APIError { -} -class error_NotFoundError extends error_APIError { -} -class error_ConflictError extends error_APIError { -} -class error_UnprocessableEntityError extends error_APIError { -} -class error_RateLimitError extends error_APIError { -} -class error_InternalServerError extends error_APIError { -} -class LengthFinishReasonError extends error_OpenAIError { - constructor() { - super(`Could not parse response content as the length limit was reached`); - } -} -class ContentFilterFinishReasonError extends error_OpenAIError { - constructor() { - super(`Could not parse response content as the request was rejected by the content filter`); - } -} -class InvalidWebhookSignatureError extends Error { - constructor(message) { - super(message); - } -} -//# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/values.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -// https://url.spec.whatwg.org/#url-scheme-string -const values_startsWithSchemeRegexp = /^[a-z][a-z0-9+.-]*:/i; -const values_isAbsoluteURL = (url) => { - return values_startsWithSchemeRegexp.test(url); -}; -let utils_values_isArray = (val) => ((utils_values_isArray = Array.isArray), utils_values_isArray(val)); -let values_isReadonlyArray = utils_values_isArray; -/** Returns an object if the given value isn't an object, otherwise returns as-is */ -function values_maybeObj(x) { - if (typeof x !== 'object') { - return {}; - } - return x ?? {}; -} -// https://stackoverflow.com/a/34491287 -function values_isEmptyObj(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -// https://eslint.org/docs/latest/rules/no-prototype-builtins -function values_hasOwn(obj, key) { - return Object.prototype.hasOwnProperty.call(obj, key); -} -function values_isObj(obj) { - return obj != null && typeof obj === 'object' && !Array.isArray(obj); -} -const values_ensurePresent = (value) => { - if (value == null) { - throw new OpenAIError(`Expected a value to be given but received ${value} instead.`); - } - return value; -}; -const values_validatePositiveInteger = (name, n) => { - if (typeof n !== 'number' || !Number.isInteger(n)) { - throw new error_OpenAIError(`${name} must be an integer`); - } - if (n < 0) { - throw new error_OpenAIError(`${name} must be a positive integer`); - } - return n; -}; -const values_coerceInteger = (value) => { - if (typeof value === 'number') - return Math.round(value); - if (typeof value === 'string') - return parseInt(value, 10); - throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const values_coerceFloat = (value) => { - if (typeof value === 'number') - return value; - if (typeof value === 'string') - return parseFloat(value); - throw new OpenAIError(`Could not coerce ${value} (type: ${typeof value}) into a number`); -}; -const values_coerceBoolean = (value) => { - if (typeof value === 'boolean') - return value; - if (typeof value === 'string') - return value === 'true'; - return Boolean(value); -}; -const values_maybeCoerceInteger = (value) => { - if (value == null) { - return undefined; - } - return values_coerceInteger(value); -}; -const values_maybeCoerceFloat = (value) => { - if (value == null) { - return undefined; - } - return values_coerceFloat(value); -}; -const values_maybeCoerceBoolean = (value) => { - if (value == null) { - return undefined; - } - return values_coerceBoolean(value); -}; -const values_safeJSON = (text) => { - try { - return JSON.parse(text); - } - catch (err) { - return undefined; - } -}; -//# sourceMappingURL=values.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/sleep.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const sleep_sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); -//# sourceMappingURL=sleep.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/version.mjs -const version_VERSION = '6.15.0'; // x-release-please-version -//# sourceMappingURL=version.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/detect-platform.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const detect_platform_isRunningInBrowser = () => { - return ( - // @ts-ignore - typeof window !== 'undefined' && - // @ts-ignore - typeof window.document !== 'undefined' && - // @ts-ignore - typeof navigator !== 'undefined'); -}; -/** - * Note this does not detect 'browser'; for that, use getBrowserInfo(). - */ -function detect_platform_getDetectedPlatform() { - if (typeof Deno !== 'undefined' && Deno.build != null) { - return 'deno'; - } - if (typeof EdgeRuntime !== 'undefined') { - return 'edge'; - } - if (Object.prototype.toString.call(typeof globalThis.process !== 'undefined' ? globalThis.process : 0) === '[object process]') { - return 'node'; - } - return 'unknown'; -} -const detect_platform_getPlatformProperties = () => { - const detectedPlatform = detect_platform_getDetectedPlatform(); - if (detectedPlatform === 'deno') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': detect_platform_normalizePlatform(Deno.build.os), - 'X-Stainless-Arch': detect_platform_normalizeArch(Deno.build.arch), - 'X-Stainless-Runtime': 'deno', - 'X-Stainless-Runtime-Version': typeof Deno.version === 'string' ? Deno.version : Deno.version?.deno ?? 'unknown', - }; - } - if (typeof EdgeRuntime !== 'undefined') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': `other:${EdgeRuntime}`, - 'X-Stainless-Runtime': 'edge', - 'X-Stainless-Runtime-Version': globalThis.process.version, - }; - } - // Check if Node.js - if (detectedPlatform === 'node') { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': detect_platform_normalizePlatform(globalThis.process.platform ?? 'unknown'), - 'X-Stainless-Arch': detect_platform_normalizeArch(globalThis.process.arch ?? 'unknown'), - 'X-Stainless-Runtime': 'node', - 'X-Stainless-Runtime-Version': globalThis.process.version ?? 'unknown', - }; - } - const browserInfo = detect_platform_getBrowserInfo(); - if (browserInfo) { - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': `browser:${browserInfo.browser}`, - 'X-Stainless-Runtime-Version': browserInfo.version, - }; - } - // TODO add support for Cloudflare workers, etc. - return { - 'X-Stainless-Lang': 'js', - 'X-Stainless-Package-Version': version_VERSION, - 'X-Stainless-OS': 'Unknown', - 'X-Stainless-Arch': 'unknown', - 'X-Stainless-Runtime': 'unknown', - 'X-Stainless-Runtime-Version': 'unknown', - }; -}; -// Note: modified from https://github.com/JS-DevTools/host-environment/blob/b1ab79ecde37db5d6e163c050e54fe7d287d7c92/src/isomorphic.browser.ts -function detect_platform_getBrowserInfo() { - if (typeof navigator === 'undefined' || !navigator) { - return null; - } - // NOTE: The order matters here! - const browserPatterns = [ - { key: 'edge', pattern: /Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'ie', pattern: /Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'chrome', pattern: /Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'firefox', pattern: /Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/ }, - { key: 'safari', pattern: /(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/ }, - ]; - // Find the FIRST matching browser - for (const { key, pattern } of browserPatterns) { - const match = pattern.exec(navigator.userAgent); - if (match) { - const major = match[1] || 0; - const minor = match[2] || 0; - const patch = match[3] || 0; - return { browser: key, version: `${major}.${minor}.${patch}` }; - } - } - return null; -} -const detect_platform_normalizeArch = (arch) => { - // Node docs: - // - https://nodejs.org/api/process.html#processarch - // Deno docs: - // - https://doc.deno.land/deno/stable/~/Deno.build - if (arch === 'x32') - return 'x32'; - if (arch === 'x86_64' || arch === 'x64') - return 'x64'; - if (arch === 'arm') - return 'arm'; - if (arch === 'aarch64' || arch === 'arm64') - return 'arm64'; - if (arch) - return `other:${arch}`; - return 'unknown'; -}; -const detect_platform_normalizePlatform = (platform) => { - // Node platforms: - // - https://nodejs.org/api/process.html#processplatform - // Deno platforms: - // - https://doc.deno.land/deno/stable/~/Deno.build - // - https://github.com/denoland/deno/issues/14799 - platform = platform.toLowerCase(); - // NOTE: this iOS check is untested and may not work - // Node does not work natively on IOS, there is a fork at - // https://github.com/nodejs-mobile/nodejs-mobile - // however it is unknown at the time of writing how to detect if it is running - if (platform.includes('ios')) - return 'iOS'; - if (platform === 'android') - return 'Android'; - if (platform === 'darwin') - return 'MacOS'; - if (platform === 'win32') - return 'Windows'; - if (platform === 'freebsd') - return 'FreeBSD'; - if (platform === 'openbsd') - return 'OpenBSD'; - if (platform === 'linux') - return 'Linux'; - if (platform) - return `Other:${platform}`; - return 'Unknown'; -}; -let detect_platform_platformHeaders; -const detect_platform_getPlatformHeaders = () => { - return (detect_platform_platformHeaders ?? (detect_platform_platformHeaders = detect_platform_getPlatformProperties())); -}; -//# sourceMappingURL=detect-platform.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/shims.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -function shims_getDefaultFetch() { - if (typeof fetch !== 'undefined') { - return fetch; - } - throw new Error('`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`'); -} -function shims_makeReadableStream(...args) { - const ReadableStream = globalThis.ReadableStream; - if (typeof ReadableStream === 'undefined') { - // Note: All of the platforms / runtimes we officially support already define - // `ReadableStream` as a global, so this should only ever be hit on unsupported runtimes. - throw new Error('`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`'); - } - return new ReadableStream(...args); -} -function shims_ReadableStreamFrom(iterable) { - let iter = Symbol.asyncIterator in iterable ? iterable[Symbol.asyncIterator]() : iterable[Symbol.iterator](); - return shims_makeReadableStream({ - start() { }, - async pull(controller) { - const { done, value } = await iter.next(); - if (done) { - controller.close(); - } - else { - controller.enqueue(value); - } - }, - async cancel() { - await iter.return?.(); - }, - }); -} -/** - * Most browsers don't yet have async iterable support for ReadableStream, - * and Node has a very different way of reading bytes from its "ReadableStream". - * - * This polyfill was pulled from https://github.com/MattiasBuelens/web-streams-polyfill/pull/122#issuecomment-1627354490 - */ -function shims_ReadableStreamToAsyncIterable(stream) { - if (stream[Symbol.asyncIterator]) - return stream; - const reader = stream.getReader(); - return { - async next() { - try { - const result = await reader.read(); - if (result?.done) - reader.releaseLock(); // release lock when stream becomes closed - return result; - } - catch (e) { - reader.releaseLock(); // release lock when stream becomes errored - throw e; - } - }, - async return() { - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; - return { done: true, value: undefined }; - }, - [Symbol.asyncIterator]() { - return this; - }, - }; -} -/** - * Cancels a ReadableStream we don't need to consume. - * See https://undici.nodejs.org/#/?id=garbage-collection - */ -async function shims_CancelReadableStream(stream) { - if (stream === null || typeof stream !== 'object') - return; - if (stream[Symbol.asyncIterator]) { - await stream[Symbol.asyncIterator]().return?.(); - return; - } - const reader = stream.getReader(); - const cancelPromise = reader.cancel(); - reader.releaseLock(); - await cancelPromise; -} -//# sourceMappingURL=shims.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/request-options.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -const request_options_FallbackEncoder = ({ headers, body }) => { - return { - bodyHeaders: { - 'content-type': 'application/json', - }, - body: JSON.stringify(body), - }; -}; -//# sourceMappingURL=request-options.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/formats.mjs -const default_format = 'RFC3986'; -const default_formatter = (v) => String(v); -const formatters = { - RFC1738: (v) => String(v).replace(/%20/g, '+'), - RFC3986: default_formatter, -}; -const RFC1738 = 'RFC1738'; -const RFC3986 = 'RFC3986'; -//# sourceMappingURL=formats.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/utils.mjs - - -let has = (obj, key) => ((has = Object.hasOwn ?? Function.prototype.call.bind(Object.prototype.hasOwnProperty)), - has(obj, key)); -const hex_table = /* @__PURE__ */ (() => { - const array = []; - for (let i = 0; i < 256; ++i) { - array.push('%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase()); - } - return array; -})(); -function compact_queue(queue) { - while (queue.length > 1) { - const item = queue.pop(); - if (!item) - continue; - const obj = item.obj[item.prop]; - if (isArray(obj)) { - const compacted = []; - for (let j = 0; j < obj.length; ++j) { - if (typeof obj[j] !== 'undefined') { - compacted.push(obj[j]); - } - } - // @ts-ignore - item.obj[item.prop] = compacted; - } - } -} -function array_to_object(source, options) { - const obj = options && options.plainObjects ? Object.create(null) : {}; - for (let i = 0; i < source.length; ++i) { - if (typeof source[i] !== 'undefined') { - obj[i] = source[i]; - } - } - return obj; -} -function utils_merge(target, source, options = {}) { - if (!source) { - return target; - } - if (typeof source !== 'object') { - if (isArray(target)) { - target.push(source); - } - else if (target && typeof target === 'object') { - if ((options && (options.plainObjects || options.allowPrototypes)) || !has(Object.prototype, source)) { - target[source] = true; - } - } - else { - return [target, source]; - } - return target; - } - if (!target || typeof target !== 'object') { - return [target].concat(source); - } - let mergeTarget = target; - if (isArray(target) && !isArray(source)) { - // @ts-ignore - mergeTarget = array_to_object(target, options); - } - if (isArray(target) && isArray(source)) { - source.forEach(function (item, i) { - if (has(target, i)) { - const targetItem = target[i]; - if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { - target[i] = utils_merge(targetItem, item, options); - } - else { - target.push(item); - } - } - else { - target[i] = item; - } - }); - return target; - } - return Object.keys(source).reduce(function (acc, key) { - const value = source[key]; - if (has(acc, key)) { - acc[key] = utils_merge(acc[key], value, options); - } - else { - acc[key] = value; - } - return acc; - }, mergeTarget); -} -function assign_single_source(target, source) { - return Object.keys(source).reduce(function (acc, key) { - acc[key] = source[key]; - return acc; - }, target); -} -function utils_decode(str, _, charset) { - const strWithoutPlus = str.replace(/\+/g, ' '); - if (charset === 'iso-8859-1') { - // unescape never throws, no try...catch needed: - return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); - } - // utf-8 - try { - return decodeURIComponent(strWithoutPlus); - } - catch (e) { - return strWithoutPlus; - } -} -const limit = 1024; -const utils_encode = (str, _defaultEncoder, charset, _kind, format) => { - // This code was originally written by Brian White for the io.js core querystring library. - // It has been adapted here for stricter adherence to RFC 3986 - if (str.length === 0) { - return str; - } - let string = str; - if (typeof str === 'symbol') { - string = Symbol.prototype.toString.call(str); - } - else if (typeof str !== 'string') { - string = String(str); - } - if (charset === 'iso-8859-1') { - return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { - return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; - }); - } - let out = ''; - for (let j = 0; j < string.length; j += limit) { - const segment = string.length >= limit ? string.slice(j, j + limit) : string; - const arr = []; - for (let i = 0; i < segment.length; ++i) { - let c = segment.charCodeAt(i); - if (c === 0x2d || // - - c === 0x2e || // . - c === 0x5f || // _ - c === 0x7e || // ~ - (c >= 0x30 && c <= 0x39) || // 0-9 - (c >= 0x41 && c <= 0x5a) || // a-z - (c >= 0x61 && c <= 0x7a) || // A-Z - (format === RFC1738 && (c === 0x28 || c === 0x29)) // ( ) - ) { - arr[arr.length] = segment.charAt(i); - continue; - } - if (c < 0x80) { - arr[arr.length] = hex_table[c]; - continue; - } - if (c < 0x800) { - arr[arr.length] = hex_table[0xc0 | (c >> 6)] + hex_table[0x80 | (c & 0x3f)]; - continue; - } - if (c < 0xd800 || c >= 0xe000) { - arr[arr.length] = - hex_table[0xe0 | (c >> 12)] + hex_table[0x80 | ((c >> 6) & 0x3f)] + hex_table[0x80 | (c & 0x3f)]; - continue; - } - i += 1; - c = 0x10000 + (((c & 0x3ff) << 10) | (segment.charCodeAt(i) & 0x3ff)); - arr[arr.length] = - hex_table[0xf0 | (c >> 18)] + - hex_table[0x80 | ((c >> 12) & 0x3f)] + - hex_table[0x80 | ((c >> 6) & 0x3f)] + - hex_table[0x80 | (c & 0x3f)]; - } - out += arr.join(''); - } - return out; -}; -function compact(value) { - const queue = [{ obj: { o: value }, prop: 'o' }]; - const refs = []; - for (let i = 0; i < queue.length; ++i) { - const item = queue[i]; - // @ts-ignore - const obj = item.obj[item.prop]; - const keys = Object.keys(obj); - for (let j = 0; j < keys.length; ++j) { - const key = keys[j]; - const val = obj[key]; - if (typeof val === 'object' && val !== null && refs.indexOf(val) === -1) { - queue.push({ obj: obj, prop: key }); - refs.push(val); - } - } - } - compact_queue(queue); - return value; -} -function is_regexp(obj) { - return Object.prototype.toString.call(obj) === '[object RegExp]'; -} -function is_buffer(obj) { - if (!obj || typeof obj !== 'object') { - return false; - } - return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); -} -function combine(a, b) { - return [].concat(a, b); -} -function maybe_map(val, fn) { - if (utils_values_isArray(val)) { - const mapped = []; - for (let i = 0; i < val.length; i += 1) { - mapped.push(fn(val[i])); - } - return mapped; - } - return fn(val); -} -//# sourceMappingURL=utils.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/stringify.mjs - - - -const array_prefix_generators = { - brackets(prefix) { - return String(prefix) + '[]'; - }, - comma: 'comma', - indices(prefix, key) { - return String(prefix) + '[' + key + ']'; - }, - repeat(prefix) { - return String(prefix); - }, -}; -const push_to_array = function (arr, value_or_array) { - Array.prototype.push.apply(arr, utils_values_isArray(value_or_array) ? value_or_array : [value_or_array]); -}; -let toISOString; -const defaults = { - addQueryPrefix: false, - allowDots: false, - allowEmptyArrays: false, - arrayFormat: 'indices', - charset: 'utf-8', - charsetSentinel: false, - delimiter: '&', - encode: true, - encodeDotInKeys: false, - encoder: utils_encode, - encodeValuesOnly: false, - format: default_format, - formatter: default_formatter, - /** @deprecated */ - indices: false, - serializeDate(date) { - return (toISOString ?? (toISOString = Function.prototype.call.bind(Date.prototype.toISOString)))(date); - }, - skipNulls: false, - strictNullHandling: false, -}; -function is_non_nullish_primitive(v) { - return (typeof v === 'string' || - typeof v === 'number' || - typeof v === 'boolean' || - typeof v === 'symbol' || - typeof v === 'bigint'); -} -const sentinel = {}; -function inner_stringify(object, prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, sideChannel) { - let obj = object; - let tmp_sc = sideChannel; - let step = 0; - let find_flag = false; - while ((tmp_sc = tmp_sc.get(sentinel)) !== void undefined && !find_flag) { - // Where object last appeared in the ref tree - const pos = tmp_sc.get(object); - step += 1; - if (typeof pos !== 'undefined') { - if (pos === step) { - throw new RangeError('Cyclic object value'); - } - else { - find_flag = true; // Break while - } - } - if (typeof tmp_sc.get(sentinel) === 'undefined') { - step = 0; - } - } - if (typeof filter === 'function') { - obj = filter(prefix, obj); - } - else if (obj instanceof Date) { - obj = serializeDate?.(obj); - } - else if (generateArrayPrefix === 'comma' && utils_values_isArray(obj)) { - obj = maybe_map(obj, function (value) { - if (value instanceof Date) { - return serializeDate?.(value); - } - return value; - }); - } - if (obj === null) { - if (strictNullHandling) { - return encoder && !encodeValuesOnly ? - // @ts-expect-error - encoder(prefix, defaults.encoder, charset, 'key', format) - : prefix; - } - obj = ''; - } - if (is_non_nullish_primitive(obj) || is_buffer(obj)) { - if (encoder) { - const key_value = encodeValuesOnly ? prefix - // @ts-expect-error - : encoder(prefix, defaults.encoder, charset, 'key', format); - return [ - formatter?.(key_value) + - '=' + - // @ts-expect-error - formatter?.(encoder(obj, defaults.encoder, charset, 'value', format)), - ]; - } - return [formatter?.(prefix) + '=' + formatter?.(String(obj))]; - } - const values = []; - if (typeof obj === 'undefined') { - return values; - } - let obj_keys; - if (generateArrayPrefix === 'comma' && utils_values_isArray(obj)) { - // we need to join elements in - if (encodeValuesOnly && encoder) { - // @ts-expect-error values only - obj = maybe_map(obj, encoder); - } - obj_keys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; - } - else if (utils_values_isArray(filter)) { - obj_keys = filter; - } - else { - const keys = Object.keys(obj); - obj_keys = sort ? keys.sort(sort) : keys; - } - const encoded_prefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); - const adjusted_prefix = commaRoundTrip && utils_values_isArray(obj) && obj.length === 1 ? encoded_prefix + '[]' : encoded_prefix; - if (allowEmptyArrays && utils_values_isArray(obj) && obj.length === 0) { - return adjusted_prefix + '[]'; - } - for (let j = 0; j < obj_keys.length; ++j) { - const key = obj_keys[j]; - const value = - // @ts-ignore - typeof key === 'object' && typeof key.value !== 'undefined' ? key.value : obj[key]; - if (skipNulls && value === null) { - continue; - } - // @ts-ignore - const encoded_key = allowDots && encodeDotInKeys ? key.replace(/\./g, '%2E') : key; - const key_prefix = utils_values_isArray(obj) ? - typeof generateArrayPrefix === 'function' ? - generateArrayPrefix(adjusted_prefix, encoded_key) - : adjusted_prefix - : adjusted_prefix + (allowDots ? '.' + encoded_key : '[' + encoded_key + ']'); - sideChannel.set(object, step); - const valueSideChannel = new WeakMap(); - valueSideChannel.set(sentinel, sideChannel); - push_to_array(values, inner_stringify(value, key_prefix, generateArrayPrefix, commaRoundTrip, allowEmptyArrays, strictNullHandling, skipNulls, encodeDotInKeys, - // @ts-ignore - generateArrayPrefix === 'comma' && encodeValuesOnly && utils_values_isArray(obj) ? null : encoder, filter, sort, allowDots, serializeDate, format, formatter, encodeValuesOnly, charset, valueSideChannel)); - } - return values; -} -function normalize_stringify_options(opts = defaults) { - if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { - throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); - } - if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { - throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); - } - if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { - throw new TypeError('Encoder has to be a function.'); - } - const charset = opts.charset || defaults.charset; - if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { - throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); - } - let format = default_format; - if (typeof opts.format !== 'undefined') { - if (!has(formatters, opts.format)) { - throw new TypeError('Unknown format option provided.'); - } - format = opts.format; - } - const formatter = formatters[format]; - let filter = defaults.filter; - if (typeof opts.filter === 'function' || utils_values_isArray(opts.filter)) { - filter = opts.filter; - } - let arrayFormat; - if (opts.arrayFormat && opts.arrayFormat in array_prefix_generators) { - arrayFormat = opts.arrayFormat; - } - else if ('indices' in opts) { - arrayFormat = opts.indices ? 'indices' : 'repeat'; - } - else { - arrayFormat = defaults.arrayFormat; - } - if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { - throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); - } - const allowDots = typeof opts.allowDots === 'undefined' ? - !!opts.encodeDotInKeys === true ? - true - : defaults.allowDots - : !!opts.allowDots; - return { - addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, - // @ts-ignore - allowDots: allowDots, - allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, - arrayFormat: arrayFormat, - charset: charset, - charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, - commaRoundTrip: !!opts.commaRoundTrip, - delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, - encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, - encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, - encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, - encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, - filter: filter, - format: format, - formatter: formatter, - serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, - skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, - // @ts-ignore - sort: typeof opts.sort === 'function' ? opts.sort : null, - strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, - }; -} -function stringify_stringify(object, opts = {}) { - let obj = object; - const options = normalize_stringify_options(opts); - let obj_keys; - let filter; - if (typeof options.filter === 'function') { - filter = options.filter; - obj = filter('', obj); - } - else if (utils_values_isArray(options.filter)) { - filter = options.filter; - obj_keys = filter; - } - const keys = []; - if (typeof obj !== 'object' || obj === null) { - return ''; - } - const generateArrayPrefix = array_prefix_generators[options.arrayFormat]; - const commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; - if (!obj_keys) { - obj_keys = Object.keys(obj); - } - if (options.sort) { - obj_keys.sort(options.sort); - } - const sideChannel = new WeakMap(); - for (let i = 0; i < obj_keys.length; ++i) { - const key = obj_keys[i]; - if (options.skipNulls && obj[key] === null) { - continue; - } - push_to_array(keys, inner_stringify(obj[key], key, - // @ts-expect-error - generateArrayPrefix, commaRoundTrip, options.allowEmptyArrays, options.strictNullHandling, options.skipNulls, options.encodeDotInKeys, options.encode ? options.encoder : null, options.filter, options.sort, options.allowDots, options.serializeDate, options.format, options.formatter, options.encodeValuesOnly, options.charset, sideChannel)); - } - const joined = keys.join(options.delimiter); - let prefix = options.addQueryPrefix === true ? '?' : ''; - if (options.charsetSentinel) { - if (options.charset === 'iso-8859-1') { - // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark - prefix += 'utf8=%26%2310003%3B&'; - } - else { - // encodeURIComponent('✓') - prefix += 'utf8=%E2%9C%93&'; - } - } - return joined.length > 0 ? prefix + joined : ''; -} -//# sourceMappingURL=stringify.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/qs/index.mjs - -const formats = { - formatters: formatters, - RFC1738: RFC1738, - RFC3986: RFC3986, - default: default_format, -}; - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/bytes.mjs -function bytes_concatBytes(buffers) { - let length = 0; - for (const buffer of buffers) { - length += buffer.length; - } - const output = new Uint8Array(length); - let index = 0; - for (const buffer of buffers) { - output.set(buffer, index); - index += buffer.length; - } - return output; -} -let bytes_encodeUTF8_; -function utils_bytes_encodeUTF8(str) { - let encoder; - return (bytes_encodeUTF8_ ?? - ((encoder = new globalThis.TextEncoder()), (bytes_encodeUTF8_ = encoder.encode.bind(encoder))))(str); -} -let bytes_decodeUTF8_; -function bytes_decodeUTF8(bytes) { - let decoder; - return (bytes_decodeUTF8_ ?? - ((decoder = new globalThis.TextDecoder()), (bytes_decodeUTF8_ = decoder.decode.bind(decoder))))(bytes); -} -//# sourceMappingURL=bytes.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/decoders/line.mjs -var line_LineDecoder_buffer, line_LineDecoder_carriageReturnIndex; - - -/** - * A re-implementation of httpx's `LineDecoder` in Python that handles incrementally - * reading lines from text. - * - * https://github.com/encode/httpx/blob/920333ea98118e9cf617f246905d7b202510941c/httpx/_decoders.py#L258 - */ -class line_LineDecoder { - constructor() { - line_LineDecoder_buffer.set(this, void 0); - line_LineDecoder_carriageReturnIndex.set(this, void 0); - tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, new Uint8Array(), "f"); - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); - } - decode(chunk) { - if (chunk == null) { - return []; - } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? utils_bytes_encodeUTF8(chunk) - : chunk; - tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, bytes_concatBytes([tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f"), binaryChunk]), "f"); - const lines = []; - let patternIndex; - while ((patternIndex = line_findNewlineIndex(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f"), tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f"))) != null) { - if (patternIndex.carriage && tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") == null) { - // skip until we either get a corresponding `\n`, a new `\r` or nothing - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, patternIndex.index, "f"); - continue; - } - // we got double \r or \rtext\n - if (tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") != null && - (patternIndex.index !== tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") + 1 || patternIndex.carriage)) { - lines.push(bytes_decodeUTF8(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(0, tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") - 1))); - tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f")), "f"); - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); - continue; - } - const endIndex = tslib_classPrivateFieldGet(this, line_LineDecoder_carriageReturnIndex, "f") !== null ? patternIndex.preceding - 1 : patternIndex.preceding; - const line = bytes_decodeUTF8(tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(0, endIndex)); - lines.push(line); - tslib_classPrivateFieldSet(this, line_LineDecoder_buffer, tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").subarray(patternIndex.index), "f"); - tslib_classPrivateFieldSet(this, line_LineDecoder_carriageReturnIndex, null, "f"); - } - return lines; - } - flush() { - if (!tslib_classPrivateFieldGet(this, line_LineDecoder_buffer, "f").length) { - return []; - } - return this.decode('\n'); - } -} -line_LineDecoder_buffer = new WeakMap(), line_LineDecoder_carriageReturnIndex = new WeakMap(); -// prettier-ignore -line_LineDecoder.NEWLINE_CHARS = new Set(['\n', '\r']); -line_LineDecoder.NEWLINE_REGEXP = /\r\n|[\n\r]/g; -/** - * This function searches the buffer for the end patterns, (\r or \n) - * and returns an object with the index preceding the matched newline and the - * index after the newline char. `null` is returned if no new line is found. - * - * ```ts - * findNewLineIndex('abc\ndef') -> { preceding: 2, index: 3 } - * ``` - */ -function line_findNewlineIndex(buffer, startIndex) { - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = startIndex ?? 0; i < buffer.length; i++) { - if (buffer[i] === newline) { - return { preceding: i, index: i + 1, carriage: false }; - } - if (buffer[i] === carriage) { - return { preceding: i, index: i + 1, carriage: true }; - } - } - return null; -} -function line_findDoubleNewlineIndex(buffer) { - // This function searches the buffer for the end patterns (\r\r, \n\n, \r\n\r\n) - // and returns the index right after the first occurrence of any pattern, - // or -1 if none of the patterns are found. - const newline = 0x0a; // \n - const carriage = 0x0d; // \r - for (let i = 0; i < buffer.length - 1; i++) { - if (buffer[i] === newline && buffer[i + 1] === newline) { - // \n\n - return i + 2; - } - if (buffer[i] === carriage && buffer[i + 1] === carriage) { - // \r\r - return i + 2; - } - if (buffer[i] === carriage && - buffer[i + 1] === newline && - i + 3 < buffer.length && - buffer[i + 2] === carriage && - buffer[i + 3] === newline) { - // \r\n\r\n - return i + 4; - } - } - return -1; -} -//# sourceMappingURL=line.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/log.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const log_levelNumbers = { - off: 0, - error: 200, - warn: 300, - info: 400, - debug: 500, -}; -const log_parseLogLevel = (maybeLevel, sourceName, client) => { - if (!maybeLevel) { - return undefined; - } - if (values_hasOwn(log_levelNumbers, maybeLevel)) { - return maybeLevel; - } - log_loggerFor(client).warn(`${sourceName} was set to ${JSON.stringify(maybeLevel)}, expected one of ${JSON.stringify(Object.keys(log_levelNumbers))}`); - return undefined; -}; -function log_noop() { } -function log_makeLogFn(fnLevel, logger, logLevel) { - if (!logger || log_levelNumbers[fnLevel] > log_levelNumbers[logLevel]) { - return log_noop; - } - else { - // Don't wrap logger functions, we want the stacktrace intact! - return logger[fnLevel].bind(logger); - } -} -const log_noopLogger = { - error: log_noop, - warn: log_noop, - info: log_noop, - debug: log_noop, -}; -let log_cachedLoggers = /* @__PURE__ */ new WeakMap(); -function log_loggerFor(client) { - const logger = client.logger; - const logLevel = client.logLevel ?? 'off'; - if (!logger) { - return log_noopLogger; - } - const cachedLogger = log_cachedLoggers.get(logger); - if (cachedLogger && cachedLogger[0] === logLevel) { - return cachedLogger[1]; - } - const levelLogger = { - error: log_makeLogFn('error', logger, logLevel), - warn: log_makeLogFn('warn', logger, logLevel), - info: log_makeLogFn('info', logger, logLevel), - debug: log_makeLogFn('debug', logger, logLevel), - }; - log_cachedLoggers.set(logger, [logLevel, levelLogger]); - return levelLogger; -} -const log_formatRequestDetails = (details) => { - if (details.options) { - details.options = { ...details.options }; - delete details.options['headers']; // redundant + leaks internals - } - if (details.headers) { - details.headers = Object.fromEntries((details.headers instanceof Headers ? [...details.headers] : Object.entries(details.headers)).map(([name, value]) => [ - name, - (name.toLowerCase() === 'authorization' || - name.toLowerCase() === 'cookie' || - name.toLowerCase() === 'set-cookie') ? - '***' - : value, - ])); - } - if ('retryOfRequestLogID' in details) { - if (details.retryOfRequestLogID) { - details.retryOf = details.retryOfRequestLogID; - } - delete details.retryOfRequestLogID; - } - return details; -}; -//# sourceMappingURL=log.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/streaming.mjs -var streaming_Stream_client; - - - - - - - - - -class streaming_Stream { - constructor(iterator, controller, client) { - this.iterator = iterator; - streaming_Stream_client.set(this, void 0); - this.controller = controller; - tslib_classPrivateFieldSet(this, streaming_Stream_client, client, "f"); - } - static fromSSEResponse(response, controller, client) { - let consumed = false; - const logger = client ? log_loggerFor(client) : console; - async function* iterator() { - if (consumed) { - throw new error_OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const sse of streaming_iterSSEMessages(response, controller)) { - if (done) - continue; - if (sse.data.startsWith('[DONE]')) { - done = true; - continue; - } - if (sse.event === null || !sse.event.startsWith('thread.')) { - let data; - try { - data = JSON.parse(sse.data); - } - catch (e) { - logger.error(`Could not parse message into JSON:`, sse.data); - logger.error(`From chunk:`, sse.raw); - throw e; - } - if (data && data.error) { - throw new error_APIError(undefined, data.error, undefined, response.headers); - } - yield data; - } - else { - let data; - try { - data = JSON.parse(sse.data); - } - catch (e) { - console.error(`Could not parse message into JSON:`, sse.data); - console.error(`From chunk:`, sse.raw); - throw e; - } - // TODO: Is this where the error should be thrown? - if (sse.event == 'error') { - throw new error_APIError(undefined, data.error, data.message, undefined); - } - yield { event: sse.event, data: data }; - } - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (errors_isAbortError(e)) - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new streaming_Stream(iterator, controller, client); - } - /** - * Generates a Stream from a newline-separated ReadableStream - * where each item is a JSON value. - */ - static fromReadableStream(readableStream, controller, client) { - let consumed = false; - async function* iterLines() { - const lineDecoder = new line_LineDecoder(); - const iter = shims_ReadableStreamToAsyncIterable(readableStream); - for await (const chunk of iter) { - for (const line of lineDecoder.decode(chunk)) { - yield line; - } - } - for (const line of lineDecoder.flush()) { - yield line; - } - } - async function* iterator() { - if (consumed) { - throw new error_OpenAIError('Cannot iterate over a consumed stream, use `.tee()` to split the stream.'); - } - consumed = true; - let done = false; - try { - for await (const line of iterLines()) { - if (done) - continue; - if (line) - yield JSON.parse(line); - } - done = true; - } - catch (e) { - // If the user calls `stream.controller.abort()`, we should exit without throwing. - if (errors_isAbortError(e)) - return; - throw e; - } - finally { - // If the user `break`s, abort the ongoing request. - if (!done) - controller.abort(); - } - } - return new streaming_Stream(iterator, controller, client); - } - [(streaming_Stream_client = new WeakMap(), Symbol.asyncIterator)]() { - return this.iterator(); - } - /** - * Splits the stream into two streams which can be - * independently read from at different speeds. - */ - tee() { - const left = []; - const right = []; - const iterator = this.iterator(); - const teeIterator = (queue) => { - return { - next: () => { - if (queue.length === 0) { - const result = iterator.next(); - left.push(result); - right.push(result); - } - return queue.shift(); - }, - }; - }; - return [ - new streaming_Stream(() => teeIterator(left), this.controller, tslib_classPrivateFieldGet(this, streaming_Stream_client, "f")), - new streaming_Stream(() => teeIterator(right), this.controller, tslib_classPrivateFieldGet(this, streaming_Stream_client, "f")), - ]; - } - /** - * Converts this stream to a newline-separated ReadableStream of - * JSON stringified values in the stream - * which can be turned back into a Stream with `Stream.fromReadableStream()`. - */ - toReadableStream() { - const self = this; - let iter; - return shims_makeReadableStream({ - async start() { - iter = self[Symbol.asyncIterator](); - }, - async pull(ctrl) { - try { - const { value, done } = await iter.next(); - if (done) - return ctrl.close(); - const bytes = utils_bytes_encodeUTF8(JSON.stringify(value) + '\n'); - ctrl.enqueue(bytes); - } - catch (err) { - ctrl.error(err); - } - }, - async cancel() { - await iter.return?.(); - }, - }); - } -} -async function* streaming_iterSSEMessages(response, controller) { - if (!response.body) { - controller.abort(); - if (typeof globalThis.navigator !== 'undefined' && - globalThis.navigator.product === 'ReactNative') { - throw new error_OpenAIError(`The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api`); - } - throw new error_OpenAIError(`Attempted to iterate over a response with no body`); - } - const sseDecoder = new streaming_SSEDecoder(); - const lineDecoder = new line_LineDecoder(); - const iter = shims_ReadableStreamToAsyncIterable(response.body); - for await (const sseChunk of streaming_iterSSEChunks(iter)) { - for (const line of lineDecoder.decode(sseChunk)) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } - } - for (const line of lineDecoder.flush()) { - const sse = sseDecoder.decode(line); - if (sse) - yield sse; - } -} -/** - * Given an async iterable iterator, iterates over it and yields full - * SSE chunks, i.e. yields when a double new-line is encountered. - */ -async function* streaming_iterSSEChunks(iterator) { - let data = new Uint8Array(); - for await (const chunk of iterator) { - if (chunk == null) { - continue; - } - const binaryChunk = chunk instanceof ArrayBuffer ? new Uint8Array(chunk) - : typeof chunk === 'string' ? utils_bytes_encodeUTF8(chunk) - : chunk; - let newData = new Uint8Array(data.length + binaryChunk.length); - newData.set(data); - newData.set(binaryChunk, data.length); - data = newData; - let patternIndex; - while ((patternIndex = line_findDoubleNewlineIndex(data)) !== -1) { - yield data.slice(0, patternIndex); - data = data.slice(patternIndex); - } - } - if (data.length > 0) { - yield data; - } -} -class streaming_SSEDecoder { - constructor() { - this.event = null; - this.data = []; - this.chunks = []; - } - decode(line) { - if (line.endsWith('\r')) { - line = line.substring(0, line.length - 1); - } - if (!line) { - // empty line and we didn't previously encounter any messages - if (!this.event && !this.data.length) - return null; - const sse = { - event: this.event, - data: this.data.join('\n'), - raw: this.chunks, - }; - this.event = null; - this.data = []; - this.chunks = []; - return sse; - } - this.chunks.push(line); - if (line.startsWith(':')) { - return null; - } - let [fieldname, _, value] = streaming_partition(line, ':'); - if (value.startsWith(' ')) { - value = value.substring(1); - } - if (fieldname === 'event') { - this.event = value; - } - else if (fieldname === 'data') { - this.data.push(value); - } - return null; - } -} -function streaming_partition(str, delimiter) { - const index = str.indexOf(delimiter); - if (index !== -1) { - return [str.substring(0, index), delimiter, str.substring(index + delimiter.length)]; - } - return [str, '', '']; -} -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/parse.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -async function parse_defaultParseResponse(client, props) { - const { response, requestLogID, retryOfRequestLogID, startTime } = props; - const body = await (async () => { - if (props.options.stream) { - log_loggerFor(client).debug('response', response.status, response.url, response.headers, response.body); - // Note: there is an invariant here that isn't represented in the type system - // that if you set `stream: true` the response type must also be `Stream` - if (props.options.__streamClass) { - return props.options.__streamClass.fromSSEResponse(response, props.controller, client); - } - return streaming_Stream.fromSSEResponse(response, props.controller, client); - } - // fetch refuses to read the body when the status code is 204. - if (response.status === 204) { - return null; - } - if (props.options.__binaryResponse) { - return response; - } - const contentType = response.headers.get('content-type'); - const mediaType = contentType?.split(';')[0]?.trim(); - const isJSON = mediaType?.includes('application/json') || mediaType?.endsWith('+json'); - if (isJSON) { - const json = await response.json(); - return parse_addRequestID(json, response); - } - const text = await response.text(); - return text; - })(); - log_loggerFor(client).debug(`[${requestLogID}] response parsed`, log_formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - body, - durationMs: Date.now() - startTime, - })); - return body; -} -function parse_addRequestID(value, response) { - if (!value || typeof value !== 'object' || Array.isArray(value)) { - return value; - } - return Object.defineProperty(value, '_request_id', { - value: response.headers.get('x-request-id'), - enumerable: false, - }); -} -//# sourceMappingURL=parse.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/api-promise.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var api_promise_APIPromise_client; - - -/** - * A subclass of `Promise` providing additional helper methods - * for interacting with the SDK. - */ -class api_promise_APIPromise extends Promise { - constructor(client, responsePromise, parseResponse = parse_defaultParseResponse) { - super((resolve) => { - // this is maybe a bit weird but this has to be a no-op to not implicitly - // parse the response body; instead .then, .catch, .finally are overridden - // to parse the response - resolve(null); - }); - this.responsePromise = responsePromise; - this.parseResponse = parseResponse; - api_promise_APIPromise_client.set(this, void 0); - tslib_classPrivateFieldSet(this, api_promise_APIPromise_client, client, "f"); - } - _thenUnwrap(transform) { - return new api_promise_APIPromise(tslib_classPrivateFieldGet(this, api_promise_APIPromise_client, "f"), this.responsePromise, async (client, props) => parse_addRequestID(transform(await this.parseResponse(client, props), props), props.response)); - } - /** - * Gets the raw `Response` instance instead of parsing the response - * data. - * - * If you want to parse the response body but still get the `Response` - * instance, you can use {@link withResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - asResponse() { - return this.responsePromise.then((p) => p.response); - } - /** - * Gets the parsed response data, the raw `Response` instance and the ID of the request, - * returned via the X-Request-ID header which is useful for debugging requests and reporting - * issues to OpenAI. - * - * If you just want to get the raw `Response` instance without parsing it, - * you can use {@link asResponse()}. - * - * 👋 Getting the wrong TypeScript type for `Response`? - * Try setting `"moduleResolution": "NodeNext"` or add `"lib": ["DOM"]` - * to your `tsconfig.json`. - */ - async withResponse() { - const [data, response] = await Promise.all([this.parse(), this.asResponse()]); - return { data, response, request_id: response.headers.get('x-request-id') }; - } - parse() { - if (!this.parsedPromise) { - this.parsedPromise = this.responsePromise.then((data) => this.parseResponse(tslib_classPrivateFieldGet(this, api_promise_APIPromise_client, "f"), data)); - } - return this.parsedPromise; - } - then(onfulfilled, onrejected) { - return this.parse().then(onfulfilled, onrejected); - } - catch(onrejected) { - return this.parse().catch(onrejected); - } - finally(onfinally) { - return this.parse().finally(onfinally); - } -} -api_promise_APIPromise_client = new WeakMap(); -//# sourceMappingURL=api-promise.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/pagination.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var pagination_AbstractPage_client; - - - - - -class pagination_AbstractPage { - constructor(client, response, body, options) { - pagination_AbstractPage_client.set(this, void 0); - tslib_classPrivateFieldSet(this, pagination_AbstractPage_client, client, "f"); - this.options = options; - this.response = response; - this.body = body; - } - hasNextPage() { - const items = this.getPaginatedItems(); - if (!items.length) - return false; - return this.nextPageRequestOptions() != null; - } - async getNextPage() { - const nextOptions = this.nextPageRequestOptions(); - if (!nextOptions) { - throw new error_OpenAIError('No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.'); - } - return await tslib_classPrivateFieldGet(this, pagination_AbstractPage_client, "f").requestAPIList(this.constructor, nextOptions); - } - async *iterPages() { - let page = this; - yield page; - while (page.hasNextPage()) { - page = await page.getNextPage(); - yield page; - } - } - async *[(pagination_AbstractPage_client = new WeakMap(), Symbol.asyncIterator)]() { - for await (const page of this.iterPages()) { - for (const item of page.getPaginatedItems()) { - yield item; - } - } - } -} -/** - * This subclass of Promise will resolve to an instantiated Page once the request completes. - * - * It also implements AsyncIterable to allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ -class pagination_PagePromise extends api_promise_APIPromise { - constructor(client, request, Page) { - super(client, request, async (client, props) => new Page(client, props.response, await parse_defaultParseResponse(client, props), props.options)); - } - /** - * Allow auto-paginating iteration on an unawaited list call, eg: - * - * for await (const item of client.items.list()) { - * console.log(item) - * } - */ - async *[Symbol.asyncIterator]() { - const page = await this; - for await (const item of page) { - yield item; - } - } -} -/** - * Note: no pagination actually occurs yet, this is for forwards-compatibility. - */ -class pagination_Page extends pagination_AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.object = body.object; - } - getPaginatedItems() { - return this.data ?? []; - } - nextPageRequestOptions() { - return null; - } -} -class CursorPage extends pagination_AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; - } - getPaginatedItems() { - return this.data ?? []; - } - hasNextPage() { - if (this.has_more === false) { - return false; - } - return super.hasNextPage(); - } - nextPageRequestOptions() { - const data = this.getPaginatedItems(); - const id = data[data.length - 1]?.id; - if (!id) { - return null; - } - return { - ...this.options, - query: { - ...values_maybeObj(this.options.query), - after: id, - }, - }; - } -} -class ConversationCursorPage extends pagination_AbstractPage { - constructor(client, response, body, options) { - super(client, response, body, options); - this.data = body.data || []; - this.has_more = body.has_more || false; - this.last_id = body.last_id || ''; - } - getPaginatedItems() { - return this.data ?? []; - } - hasNextPage() { - if (this.has_more === false) { - return false; - } - return super.hasNextPage(); - } - nextPageRequestOptions() { - const cursor = this.last_id; - if (!cursor) { - return null; - } - return { - ...this.options, - query: { - ...values_maybeObj(this.options.query), - after: cursor, - }, - }; - } -} -//# sourceMappingURL=pagination.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/uploads.mjs - -const uploads_checkFileSupport = () => { - if (typeof File === 'undefined') { - const { process } = globalThis; - const isOldNode = typeof process?.versions?.node === 'string' && parseInt(process.versions.node.split('.')) < 20; - throw new Error('`File` is not defined as a global, which is required for file uploads.' + - (isOldNode ? - " Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`." - : '')); - } -}; -/** - * Construct a `File` instance. This is used to ensure a helpful error is thrown - * for environments that don't define a global `File` yet. - */ -function uploads_makeFile(fileBits, fileName, options) { - uploads_checkFileSupport(); - return new File(fileBits, fileName ?? 'unknown_file', options); -} -function uploads_getName(value) { - return (((typeof value === 'object' && - value !== null && - (('name' in value && value.name && String(value.name)) || - ('url' in value && value.url && String(value.url)) || - ('filename' in value && value.filename && String(value.filename)) || - ('path' in value && value.path && String(value.path)))) || - '') - .split(/[\\/]/) - .pop() || undefined); -} -const internal_uploads_isAsyncIterable = (value) => value != null && typeof value === 'object' && typeof value[Symbol.asyncIterator] === 'function'; -/** - * Returns a multipart/form-data request if any part of the given request body contains a File / Blob value. - * Otherwise returns the request as is. - */ -const uploads_maybeMultipartFormRequestOptions = async (opts, fetch) => { - if (!uploads_hasUploadableValue(opts.body)) - return opts; - return { ...opts, body: await uploads_createForm(opts.body, fetch) }; -}; -const uploads_multipartFormRequestOptions = async (opts, fetch) => { - return { ...opts, body: await uploads_createForm(opts.body, fetch) }; -}; -const uploads_supportsFormDataMap = /* @__PURE__ */ new WeakMap(); -/** - * node-fetch doesn't support the global FormData object in recent node versions. Instead of sending - * properly-encoded form data, it just stringifies the object, resulting in a request body of "[object FormData]". - * This function detects if the fetch function provided supports the global FormData object to avoid - * confusing error messages later on. - */ -function uploads_supportsFormData(fetchObject) { - const fetch = typeof fetchObject === 'function' ? fetchObject : fetchObject.fetch; - const cached = uploads_supportsFormDataMap.get(fetch); - if (cached) - return cached; - const promise = (async () => { - try { - const FetchResponse = ('Response' in fetch ? - fetch.Response - : (await fetch('data:,')).constructor); - const data = new FormData(); - if (data.toString() === (await new FetchResponse(data).text())) { - return false; - } - return true; - } - catch { - // avoid false negatives - return true; - } - })(); - uploads_supportsFormDataMap.set(fetch, promise); - return promise; -} -const uploads_createForm = async (body, fetch) => { - if (!(await uploads_supportsFormData(fetch))) { - throw new TypeError('The provided fetch function does not support file uploads with the current global FormData class.'); - } - const form = new FormData(); - await Promise.all(Object.entries(body || {}).map(([key, value]) => uploads_addFormValue(form, key, value))); - return form; -}; -// We check for Blob not File because Bun.File doesn't inherit from File, -// but they both inherit from Blob and have a `name` property at runtime. -const uploads_isNamedBlob = (value) => value instanceof Blob && 'name' in value; -const uploads_isUploadable = (value) => typeof value === 'object' && - value !== null && - (value instanceof Response || internal_uploads_isAsyncIterable(value) || uploads_isNamedBlob(value)); -const uploads_hasUploadableValue = (value) => { - if (uploads_isUploadable(value)) - return true; - if (Array.isArray(value)) - return value.some(uploads_hasUploadableValue); - if (value && typeof value === 'object') { - for (const k in value) { - if (uploads_hasUploadableValue(value[k])) - return true; - } - } - return false; -}; -const uploads_addFormValue = async (form, key, value) => { - if (value === undefined) - return; - if (value == null) { - throw new TypeError(`Received null for "${key}"; to pass null in FormData, you must use the string 'null'`); - } - // TODO: make nested formats configurable - if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') { - form.append(key, String(value)); - } - else if (value instanceof Response) { - form.append(key, uploads_makeFile([await value.blob()], uploads_getName(value))); - } - else if (internal_uploads_isAsyncIterable(value)) { - form.append(key, uploads_makeFile([await new Response(shims_ReadableStreamFrom(value)).blob()], uploads_getName(value))); - } - else if (uploads_isNamedBlob(value)) { - form.append(key, value, uploads_getName(value)); - } - else if (Array.isArray(value)) { - await Promise.all(value.map((entry) => uploads_addFormValue(form, key + '[]', entry))); - } - else if (typeof value === 'object') { - await Promise.all(Object.entries(value).map(([name, prop]) => uploads_addFormValue(form, `${key}[${name}]`, prop))); - } - else { - throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${value} instead`); - } -}; -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/to-file.mjs - - -/** - * This check adds the arrayBuffer() method type because it is available and used at runtime - */ -const to_file_isBlobLike = (value) => value != null && - typeof value === 'object' && - typeof value.size === 'number' && - typeof value.type === 'string' && - typeof value.text === 'function' && - typeof value.slice === 'function' && - typeof value.arrayBuffer === 'function'; -/** - * This check adds the arrayBuffer() method type because it is available and used at runtime - */ -const to_file_isFileLike = (value) => value != null && - typeof value === 'object' && - typeof value.name === 'string' && - typeof value.lastModified === 'number' && - to_file_isBlobLike(value); -const to_file_isResponseLike = (value) => value != null && - typeof value === 'object' && - typeof value.url === 'string' && - typeof value.blob === 'function'; -/** - * Helper for creating a {@link File} to pass to an SDK upload method from a variety of different data formats - * @param value the raw content of the file. Can be an {@link Uploadable}, BlobLikePart, or AsyncIterable of BlobLikeParts - * @param {string=} name the name of the file. If omitted, toFile will try to determine a file name from bits if possible - * @param {Object=} options additional properties - * @param {string=} options.type the MIME type of the content - * @param {number=} options.lastModified the last modified timestamp - * @returns a {@link File} with the given properties - */ -async function to_file_toFile(value, name, options) { - uploads_checkFileSupport(); - // If it's a promise, resolve it. - value = await value; - // If we've been given a `File` we don't need to do anything - if (to_file_isFileLike(value)) { - if (value instanceof File) { - return value; - } - return uploads_makeFile([await value.arrayBuffer()], value.name); - } - if (to_file_isResponseLike(value)) { - const blob = await value.blob(); - name || (name = new URL(value.url).pathname.split(/[\\/]/).pop()); - return uploads_makeFile(await internal_to_file_getBytes(blob), name, options); - } - const parts = await internal_to_file_getBytes(value); - name || (name = uploads_getName(value)); - if (!options?.type) { - const type = parts.find((part) => typeof part === 'object' && 'type' in part && part.type); - if (typeof type === 'string') { - options = { ...options, type }; - } - } - return uploads_makeFile(parts, name, options); -} -async function internal_to_file_getBytes(value) { - let parts = []; - if (typeof value === 'string' || - ArrayBuffer.isView(value) || // includes Uint8Array, Buffer, etc. - value instanceof ArrayBuffer) { - parts.push(value); - } - else if (to_file_isBlobLike(value)) { - parts.push(value instanceof Blob ? value : await value.arrayBuffer()); - } - else if (internal_uploads_isAsyncIterable(value) // includes Readable, ReadableStream, etc. - ) { - for await (const chunk of value) { - parts.push(...(await internal_to_file_getBytes(chunk))); // TODO, consider validating? - } - } - else { - const constructor = value?.constructor?.name; - throw new Error(`Unexpected data type: ${typeof value}${constructor ? `; constructor: ${constructor}` : ''}${to_file_propsForError(value)}`); - } - return parts; -} -function to_file_propsForError(value) { - if (typeof value !== 'object' || value === null) - return ''; - const props = Object.getOwnPropertyNames(value); - return `; props: [${props.map((p) => `"${p}"`).join(', ')}]`; -} -//# sourceMappingURL=to-file.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/uploads.mjs - -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/core/resource.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -class resource_APIResource { - constructor(client) { - this._client = client; - } -} -//# sourceMappingURL=resource.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/path.mjs - -/** - * Percent-encode everything that isn't safe to have in a path without encoding safe chars. - * - * Taken from https://datatracker.ietf.org/doc/html/rfc3986#section-3.3: - * > unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~" - * > sub-delims = "!" / "$" / "&" / "'" / "(" / ")" / "*" / "+" / "," / ";" / "=" - * > pchar = unreserved / pct-encoded / sub-delims / ":" / "@" - */ -function path_encodeURIPath(str) { - return str.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g, encodeURIComponent); -} -const path_EMPTY = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.create(null)); -const path_createPathTagFunction = (pathEncoder = path_encodeURIPath) => function path(statics, ...params) { - // If there are no params, no processing is needed. - if (statics.length === 1) - return statics[0]; - let postPath = false; - const invalidSegments = []; - const path = statics.reduce((previousValue, currentValue, index) => { - if (/[?#]/.test(currentValue)) { - postPath = true; - } - const value = params[index]; - let encoded = (postPath ? encodeURIComponent : pathEncoder)('' + value); - if (index !== params.length && - (value == null || - (typeof value === 'object' && - // handle values from other realms - value.toString === - Object.getPrototypeOf(Object.getPrototypeOf(value.hasOwnProperty ?? path_EMPTY) ?? path_EMPTY) - ?.toString))) { - encoded = value + ''; - invalidSegments.push({ - start: previousValue.length + currentValue.length, - length: encoded.length, - error: `Value of type ${Object.prototype.toString - .call(value) - .slice(8, -1)} is not a valid path parameter`, - }); - } - return previousValue + currentValue + (index === params.length ? '' : encoded); - }, ''); - const pathOnly = path.split(/[?#]/, 1)[0]; - const invalidSegmentPattern = /(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi; - let match; - // Find all invalid segments - while ((match = invalidSegmentPattern.exec(pathOnly)) !== null) { - invalidSegments.push({ - start: match.index, - length: match[0].length, - error: `Value "${match[0]}" can\'t be safely passed as a path parameter`, - }); - } - invalidSegments.sort((a, b) => a.start - b.start); - if (invalidSegments.length > 0) { - let lastEnd = 0; - const underline = invalidSegments.reduce((acc, segment) => { - const spaces = ' '.repeat(segment.start - lastEnd); - const arrows = '^'.repeat(segment.length); - lastEnd = segment.start + segment.length; - return acc + spaces + arrows; - }, ''); - throw new error_OpenAIError(`Path parameters result in path with invalid segments:\n${invalidSegments - .map((e) => e.error) - .join('\n')}\n${path}\n${underline}`); - } - return path; -}; -/** - * URI-encodes path params and ensures no unsafe /./ or /../ path segments are introduced. - */ -const path_path = /* @__PURE__ */ path_createPathTagFunction(path_encodeURIPath); -//# sourceMappingURL=path.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/messages.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class completions_messages_Messages extends resource_APIResource { - /** - * Get the messages in a stored chat completion. Only Chat Completions that have - * been created with the `store` parameter set to `true` will be returned. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const chatCompletionStoreMessage of client.chat.completions.messages.list( - * 'completion_id', - * )) { - * // ... - * } - * ``` - */ - list(completionID, query = {}, options) { - return this._client.getAPIList(path_path `/chat/completions/${completionID}/messages`, (CursorPage), { query, ...options }); - } -} -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/error.mjs - -//# sourceMappingURL=error.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/parser.mjs - -function isChatCompletionFunctionTool(tool) { - return tool !== undefined && 'function' in tool && tool.function !== undefined; -} -function makeParseableResponseFormat(response_format, parser) { - const obj = { ...response_format }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-response-format', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - }); - return obj; -} -function parser_makeParseableTextFormat(response_format, parser) { - const obj = { ...response_format }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-response-format', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - }); - return obj; -} -function isAutoParsableResponseFormat(response_format) { - return response_format?.['$brand'] === 'auto-parseable-response-format'; -} -function parser_makeParseableTool(tool, { parser, callback, }) { - const obj = { ...tool }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-tool', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - $callback: { - value: callback, - enumerable: false, - }, - }); - return obj; -} -function isAutoParsableTool(tool) { - return tool?.['$brand'] === 'auto-parseable-tool'; -} -function maybeParseChatCompletion(completion, params) { - if (!params || !hasAutoParseableInput(params)) { - return { - ...completion, - choices: completion.choices.map((choice) => { - assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); - return { - ...choice, - message: { - ...choice.message, - parsed: null, - ...(choice.message.tool_calls ? - { - tool_calls: choice.message.tool_calls, - } - : undefined), - }, - }; - }), - }; - } - return parseChatCompletion(completion, params); -} -function parseChatCompletion(completion, params) { - const choices = completion.choices.map((choice) => { - if (choice.finish_reason === 'length') { - throw new LengthFinishReasonError(); - } - if (choice.finish_reason === 'content_filter') { - throw new ContentFilterFinishReasonError(); - } - assertToolCallsAreChatCompletionFunctionToolCalls(choice.message.tool_calls); - return { - ...choice, - message: { - ...choice.message, - ...(choice.message.tool_calls ? - { - tool_calls: choice.message.tool_calls?.map((toolCall) => parser_parseToolCall(params, toolCall)) ?? undefined, - } - : undefined), - parsed: choice.message.content && !choice.message.refusal ? - parseResponseFormat(params, choice.message.content) - : null, - }, - }; - }); - return { ...completion, choices }; -} -function parseResponseFormat(params, content) { - if (params.response_format?.type !== 'json_schema') { - return null; - } - if (params.response_format?.type === 'json_schema') { - if ('$parseRaw' in params.response_format) { - const response_format = params.response_format; - return response_format.$parseRaw(content); - } - return JSON.parse(content); - } - return null; -} -function parser_parseToolCall(params, toolCall) { - const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); // TS doesn't narrow based on isChatCompletionTool - return { - ...toolCall, - function: { - ...toolCall.function, - parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.function.arguments) - : inputTool?.function.strict ? JSON.parse(toolCall.function.arguments) - : null, - }, - }; -} -function shouldParseToolCall(params, toolCall) { - if (!params || !('tools' in params) || !params.tools) { - return false; - } - const inputTool = params.tools?.find((inputTool) => isChatCompletionFunctionTool(inputTool) && inputTool.function?.name === toolCall.function.name); - return (isChatCompletionFunctionTool(inputTool) && - (isAutoParsableTool(inputTool) || inputTool?.function.strict || false)); -} -function hasAutoParseableInput(params) { - if (isAutoParsableResponseFormat(params.response_format)) { - return true; - } - return (params.tools?.some((t) => isAutoParsableTool(t) || (t.type === 'function' && t.function.strict === true)) ?? false); -} -function assertToolCallsAreChatCompletionFunctionToolCalls(toolCalls) { - for (const toolCall of toolCalls || []) { - if (toolCall.type !== 'function') { - throw new error_OpenAIError(`Currently only \`function\` tool calls are supported; Received \`${toolCall.type}\``); - } - } -} -function validateInputTools(tools) { - for (const tool of tools ?? []) { - if (tool.type !== 'function') { - throw new error_OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); - } - if (tool.function.strict !== true) { - throw new error_OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); - } - } -} -//# sourceMappingURL=parser.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/chatCompletionUtils.mjs -const isAssistantMessage = (message) => { - return message?.role === 'assistant'; -}; -const chatCompletionUtils_isToolMessage = (message) => { - return message?.role === 'tool'; -}; -function isPresent(obj) { - return obj != null; -} -//# sourceMappingURL=chatCompletionUtils.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/EventStream.mjs -var _EventStream_instances, _EventStream_connectedPromise, _EventStream_resolveConnectedPromise, _EventStream_rejectConnectedPromise, _EventStream_endPromise, _EventStream_resolveEndPromise, _EventStream_rejectEndPromise, _EventStream_listeners, _EventStream_ended, _EventStream_errored, _EventStream_aborted, _EventStream_catchingPromiseCreated, _EventStream_handleError; - - -class EventStream { - constructor() { - _EventStream_instances.add(this); - this.controller = new AbortController(); - _EventStream_connectedPromise.set(this, void 0); - _EventStream_resolveConnectedPromise.set(this, () => { }); - _EventStream_rejectConnectedPromise.set(this, () => { }); - _EventStream_endPromise.set(this, void 0); - _EventStream_resolveEndPromise.set(this, () => { }); - _EventStream_rejectEndPromise.set(this, () => { }); - _EventStream_listeners.set(this, {}); - _EventStream_ended.set(this, false); - _EventStream_errored.set(this, false); - _EventStream_aborted.set(this, false); - _EventStream_catchingPromiseCreated.set(this, false); - tslib_classPrivateFieldSet(this, _EventStream_connectedPromise, new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _EventStream_resolveConnectedPromise, resolve, "f"); - tslib_classPrivateFieldSet(this, _EventStream_rejectConnectedPromise, reject, "f"); - }), "f"); - tslib_classPrivateFieldSet(this, _EventStream_endPromise, new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _EventStream_resolveEndPromise, resolve, "f"); - tslib_classPrivateFieldSet(this, _EventStream_rejectEndPromise, reject, "f"); - }), "f"); - // Don't let these promises cause unhandled rejection errors. - // we will manually cause an unhandled rejection error later - // if the user hasn't registered any error listener or called - // any promise-returning method. - tslib_classPrivateFieldGet(this, _EventStream_connectedPromise, "f").catch(() => { }); - tslib_classPrivateFieldGet(this, _EventStream_endPromise, "f").catch(() => { }); - } - _run(executor) { - // Unfortunately if we call `executor()` immediately we get runtime errors about - // references to `this` before the `super()` constructor call returns. - setTimeout(() => { - executor().then(() => { - this._emitFinal(); - this._emit('end'); - }, tslib_classPrivateFieldGet(this, _EventStream_instances, "m", _EventStream_handleError).bind(this)); - }, 0); - } - _connected() { - if (this.ended) - return; - tslib_classPrivateFieldGet(this, _EventStream_resolveConnectedPromise, "f").call(this); - this._emit('connect'); - } - get ended() { - return tslib_classPrivateFieldGet(this, _EventStream_ended, "f"); - } - get errored() { - return tslib_classPrivateFieldGet(this, _EventStream_errored, "f"); - } - get aborted() { - return tslib_classPrivateFieldGet(this, _EventStream_aborted, "f"); - } - abort() { - this.controller.abort(); - } - /** - * Adds the listener function to the end of the listeners array for the event. - * No checks are made to see if the listener has already been added. Multiple calls passing - * the same combination of event and listener will result in the listener being added, and - * called, multiple times. - * @returns this ChatCompletionStream, so that calls can be chained - */ - on(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); - listeners.push({ listener }); - return this; - } - /** - * Removes the specified listener from the listener array for the event. - * off() will remove, at most, one instance of a listener from the listener array. If any single - * listener has been added multiple times to the listener array for the specified event, then - * off() must be called multiple times to remove each instance. - * @returns this ChatCompletionStream, so that calls can be chained - */ - off(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; - if (!listeners) - return this; - const index = listeners.findIndex((l) => l.listener === listener); - if (index >= 0) - listeners.splice(index, 1); - return this; - } - /** - * Adds a one-time listener function for the event. The next time the event is triggered, - * this listener is removed and then invoked. - * @returns this ChatCompletionStream, so that calls can be chained - */ - once(event, listener) { - const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] || (tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = []); - listeners.push({ listener, once: true }); - return this; - } - /** - * This is similar to `.once()`, but returns a Promise that resolves the next time - * the event is triggered, instead of calling a listener callback. - * @returns a Promise that resolves the next time given event is triggered, - * or rejects if an error is emitted. (If you request the 'error' event, - * returns a promise that resolves with the error). - * - * Example: - * - * const message = await stream.emitted('message') // rejects if the stream errors - */ - emitted(event) { - return new Promise((resolve, reject) => { - tslib_classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); - if (event !== 'error') - this.once('error', reject); - this.once(event, resolve); - }); - } - async done() { - tslib_classPrivateFieldSet(this, _EventStream_catchingPromiseCreated, true, "f"); - await tslib_classPrivateFieldGet(this, _EventStream_endPromise, "f"); - } - _emit(event, ...args) { - // make sure we don't emit any events after end - if (tslib_classPrivateFieldGet(this, _EventStream_ended, "f")) { - return; - } - if (event === 'end') { - tslib_classPrivateFieldSet(this, _EventStream_ended, true, "f"); - tslib_classPrivateFieldGet(this, _EventStream_resolveEndPromise, "f").call(this); - } - const listeners = tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event]; - if (listeners) { - tslib_classPrivateFieldGet(this, _EventStream_listeners, "f")[event] = listeners.filter((l) => !l.once); - listeners.forEach(({ listener }) => listener(...args)); - } - if (event === 'abort') { - const error = args[0]; - if (!tslib_classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { - Promise.reject(error); - } - tslib_classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); - tslib_classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - return; - } - if (event === 'error') { - // NOTE: _emit('error', error) should only be called from #handleError(). - const error = args[0]; - if (!tslib_classPrivateFieldGet(this, _EventStream_catchingPromiseCreated, "f") && !listeners?.length) { - // Trigger an unhandled rejection if the user hasn't registered any error handlers. - // If you are seeing stack traces here, make sure to handle errors via either: - // - runner.on('error', () => ...) - // - await runner.done() - // - await runner.finalChatCompletion() - // - etc. - Promise.reject(error); - } - tslib_classPrivateFieldGet(this, _EventStream_rejectConnectedPromise, "f").call(this, error); - tslib_classPrivateFieldGet(this, _EventStream_rejectEndPromise, "f").call(this, error); - this._emit('end'); - } - } - _emitFinal() { } -} -_EventStream_connectedPromise = new WeakMap(), _EventStream_resolveConnectedPromise = new WeakMap(), _EventStream_rejectConnectedPromise = new WeakMap(), _EventStream_endPromise = new WeakMap(), _EventStream_resolveEndPromise = new WeakMap(), _EventStream_rejectEndPromise = new WeakMap(), _EventStream_listeners = new WeakMap(), _EventStream_ended = new WeakMap(), _EventStream_errored = new WeakMap(), _EventStream_aborted = new WeakMap(), _EventStream_catchingPromiseCreated = new WeakMap(), _EventStream_instances = new WeakSet(), _EventStream_handleError = function _EventStream_handleError(error) { - tslib_classPrivateFieldSet(this, _EventStream_errored, true, "f"); - if (error instanceof Error && error.name === 'AbortError') { - error = new error_APIUserAbortError(); - } - if (error instanceof error_APIUserAbortError) { - tslib_classPrivateFieldSet(this, _EventStream_aborted, true, "f"); - return this._emit('abort', error); - } - if (error instanceof error_OpenAIError) { - return this._emit('error', error); - } - if (error instanceof Error) { - const openAIError = new error_OpenAIError(error.message); - // @ts-ignore - openAIError.cause = error; - return this._emit('error', openAIError); - } - return this._emit('error', new error_OpenAIError(String(error))); -}; -//# sourceMappingURL=EventStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/RunnableFunction.mjs -function isRunnableFunctionWithParse(fn) { - return typeof fn.parse === 'function'; -} -/** - * This is helper class for passing a `function` and `parse` where the `function` - * argument type matches the `parse` return type. - */ -class ParsingToolFunction { - constructor(input) { - this.type = 'function'; - this.function = input; - } -} -//# sourceMappingURL=RunnableFunction.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/AbstractChatCompletionRunner.mjs -var _AbstractChatCompletionRunner_instances, _AbstractChatCompletionRunner_getFinalContent, _AbstractChatCompletionRunner_getFinalMessage, _AbstractChatCompletionRunner_getFinalFunctionToolCall, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult, _AbstractChatCompletionRunner_calculateTotalUsage, _AbstractChatCompletionRunner_validateParams, _AbstractChatCompletionRunner_stringifyFunctionCallResult; - - - - - - -const DEFAULT_MAX_CHAT_COMPLETIONS = 10; -class AbstractChatCompletionRunner extends EventStream { - constructor() { - super(...arguments); - _AbstractChatCompletionRunner_instances.add(this); - this._chatCompletions = []; - this.messages = []; - } - _addChatCompletion(chatCompletion) { - this._chatCompletions.push(chatCompletion); - this._emit('chatCompletion', chatCompletion); - const message = chatCompletion.choices[0]?.message; - if (message) - this._addMessage(message); - return chatCompletion; - } - _addMessage(message, emit = true) { - if (!('content' in message)) - message.content = null; - this.messages.push(message); - if (emit) { - this._emit('message', message); - if (chatCompletionUtils_isToolMessage(message) && message.content) { - // Note, this assumes that {role: 'tool', content: …} is always the result of a call of tool of type=function. - this._emit('functionToolCallResult', message.content); - } - else if (isAssistantMessage(message) && message.tool_calls) { - for (const tool_call of message.tool_calls) { - if (tool_call.type === 'function') { - this._emit('functionToolCall', tool_call.function); - } - } - } - } - } - /** - * @returns a promise that resolves with the final ChatCompletion, or rejects - * if an error occurred or the stream ended prematurely without producing a ChatCompletion. - */ - async finalChatCompletion() { - await this.done(); - const completion = this._chatCompletions[this._chatCompletions.length - 1]; - if (!completion) - throw new error_OpenAIError('stream ended without producing a ChatCompletion'); - return completion; - } - /** - * @returns a promise that resolves with the content of the final ChatCompletionMessage, or rejects - * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. - */ - async finalContent() { - await this.done(); - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); - } - /** - * @returns a promise that resolves with the the final assistant ChatCompletionMessage response, - * or rejects if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. - */ - async finalMessage() { - await this.done(); - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); - } - /** - * @returns a promise that resolves with the content of the final FunctionCall, or rejects - * if an error occurred or the stream ended prematurely without producing a ChatCompletionMessage. - */ - async finalFunctionToolCall() { - await this.done(); - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); - } - async finalFunctionToolCallResult() { - await this.done(); - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); - } - async totalUsage() { - await this.done(); - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this); - } - allChatCompletions() { - return [...this._chatCompletions]; - } - _emitFinal() { - const completion = this._chatCompletions[this._chatCompletions.length - 1]; - if (completion) - this._emit('finalChatCompletion', completion); - const finalMessage = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this); - if (finalMessage) - this._emit('finalMessage', finalMessage); - const finalContent = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalContent).call(this); - if (finalContent) - this._emit('finalContent', finalContent); - const finalFunctionCall = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCall).call(this); - if (finalFunctionCall) - this._emit('finalFunctionToolCall', finalFunctionCall); - const finalFunctionCallResult = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalFunctionToolCallResult).call(this); - if (finalFunctionCallResult != null) - this._emit('finalFunctionToolCallResult', finalFunctionCallResult); - if (this._chatCompletions.some((c) => c.usage)) { - this._emit('totalUsage', tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_calculateTotalUsage).call(this)); - } - } - async _createChatCompletion(client, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_validateParams).call(this, params); - const chatCompletion = await client.chat.completions.create({ ...params, stream: false }, { ...options, signal: this.controller.signal }); - this._connected(); - return this._addChatCompletion(parseChatCompletion(chatCompletion, params)); - } - async _runChatCompletion(client, params, options) { - for (const message of params.messages) { - this._addMessage(message, false); - } - return await this._createChatCompletion(client, params, options); - } - async _runTools(client, params, options) { - const role = 'tool'; - const { tool_choice = 'auto', stream, ...restParams } = params; - const singleFunctionToCall = typeof tool_choice !== 'string' && tool_choice.type === 'function' && tool_choice?.function?.name; - const { maxChatCompletions = DEFAULT_MAX_CHAT_COMPLETIONS } = options || {}; - // TODO(someday): clean this logic up - const inputTools = params.tools.map((tool) => { - if (isAutoParsableTool(tool)) { - if (!tool.$callback) { - throw new error_OpenAIError('Tool given to `.runTools()` that does not have an associated function'); - } - return { - type: 'function', - function: { - function: tool.$callback, - name: tool.function.name, - description: tool.function.description || '', - parameters: tool.function.parameters, - parse: tool.$parseRaw, - strict: true, - }, - }; - } - return tool; - }); - const functionsByName = {}; - for (const f of inputTools) { - if (f.type === 'function') { - functionsByName[f.function.name || f.function.function.name] = f.function; - } - } - const tools = 'tools' in params ? - inputTools.map((t) => t.type === 'function' ? - { - type: 'function', - function: { - name: t.function.name || t.function.function.name, - parameters: t.function.parameters, - description: t.function.description, - strict: t.function.strict, - }, - } - : t) - : undefined; - for (const message of params.messages) { - this._addMessage(message, false); - } - for (let i = 0; i < maxChatCompletions; ++i) { - const chatCompletion = await this._createChatCompletion(client, { - ...restParams, - tool_choice, - tools, - messages: [...this.messages], - }, options); - const message = chatCompletion.choices[0]?.message; - if (!message) { - throw new error_OpenAIError(`missing message in ChatCompletion response`); - } - if (!message.tool_calls?.length) { - return; - } - for (const tool_call of message.tool_calls) { - if (tool_call.type !== 'function') - continue; - const tool_call_id = tool_call.id; - const { name, arguments: args } = tool_call.function; - const fn = functionsByName[name]; - if (!fn) { - const content = `Invalid tool_call: ${JSON.stringify(name)}. Available options are: ${Object.keys(functionsByName) - .map((name) => JSON.stringify(name)) - .join(', ')}. Please try again`; - this._addMessage({ role, tool_call_id, content }); - continue; - } - else if (singleFunctionToCall && singleFunctionToCall !== name) { - const content = `Invalid tool_call: ${JSON.stringify(name)}. ${JSON.stringify(singleFunctionToCall)} requested. Please try again`; - this._addMessage({ role, tool_call_id, content }); - continue; - } - let parsed; - try { - parsed = isRunnableFunctionWithParse(fn) ? await fn.parse(args) : args; - } - catch (error) { - const content = error instanceof Error ? error.message : String(error); - this._addMessage({ role, tool_call_id, content }); - continue; - } - // @ts-expect-error it can't rule out `never` type. - const rawContent = await fn.function(parsed, this); - const content = tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_stringifyFunctionCallResult).call(this, rawContent); - this._addMessage({ role, tool_call_id, content }); - if (singleFunctionToCall) { - return; - } - } - } - return; - } -} -_AbstractChatCompletionRunner_instances = new WeakSet(), _AbstractChatCompletionRunner_getFinalContent = function _AbstractChatCompletionRunner_getFinalContent() { - return tslib_classPrivateFieldGet(this, _AbstractChatCompletionRunner_instances, "m", _AbstractChatCompletionRunner_getFinalMessage).call(this).content ?? null; -}, _AbstractChatCompletionRunner_getFinalMessage = function _AbstractChatCompletionRunner_getFinalMessage() { - let i = this.messages.length; - while (i-- > 0) { - const message = this.messages[i]; - if (isAssistantMessage(message)) { - // TODO: support audio here - const ret = { - ...message, - content: message.content ?? null, - refusal: message.refusal ?? null, - }; - return ret; - } - } - throw new error_OpenAIError('stream ended without producing a ChatCompletionMessage with role=assistant'); -}, _AbstractChatCompletionRunner_getFinalFunctionToolCall = function _AbstractChatCompletionRunner_getFinalFunctionToolCall() { - for (let i = this.messages.length - 1; i >= 0; i--) { - const message = this.messages[i]; - if (isAssistantMessage(message) && message?.tool_calls?.length) { - return message.tool_calls.filter((x) => x.type === 'function').at(-1)?.function; - } - } - return; -}, _AbstractChatCompletionRunner_getFinalFunctionToolCallResult = function _AbstractChatCompletionRunner_getFinalFunctionToolCallResult() { - for (let i = this.messages.length - 1; i >= 0; i--) { - const message = this.messages[i]; - if (chatCompletionUtils_isToolMessage(message) && - message.content != null && - typeof message.content === 'string' && - this.messages.some((x) => x.role === 'assistant' && - x.tool_calls?.some((y) => y.type === 'function' && y.id === message.tool_call_id))) { - return message.content; - } - } - return; -}, _AbstractChatCompletionRunner_calculateTotalUsage = function _AbstractChatCompletionRunner_calculateTotalUsage() { - const total = { - completion_tokens: 0, - prompt_tokens: 0, - total_tokens: 0, - }; - for (const { usage } of this._chatCompletions) { - if (usage) { - total.completion_tokens += usage.completion_tokens; - total.prompt_tokens += usage.prompt_tokens; - total.total_tokens += usage.total_tokens; - } - } - return total; -}, _AbstractChatCompletionRunner_validateParams = function _AbstractChatCompletionRunner_validateParams(params) { - if (params.n != null && params.n > 1) { - throw new error_OpenAIError('ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.'); - } -}, _AbstractChatCompletionRunner_stringifyFunctionCallResult = function _AbstractChatCompletionRunner_stringifyFunctionCallResult(rawContent) { - return (typeof rawContent === 'string' ? rawContent - : rawContent === undefined ? 'undefined' - : JSON.stringify(rawContent)); -}; -//# sourceMappingURL=AbstractChatCompletionRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionRunner.mjs - - -class ChatCompletionRunner extends AbstractChatCompletionRunner { - static runTools(client, params, options) { - const runner = new ChatCompletionRunner(); - const opts = { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, - }; - runner._run(() => runner._runTools(client, params, opts)); - return runner; - } - _addMessage(message, emit = true) { - super._addMessage(message, emit); - if (isAssistantMessage(message) && message.content) { - this._emit('content', message.content); - } - } -} -//# sourceMappingURL=ChatCompletionRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/partial-json-parser/parser.mjs -const STR = 0b000000001; -const NUM = 0b000000010; -const ARR = 0b000000100; -const OBJ = 0b000001000; -const NULL = 0b000010000; -const BOOL = 0b000100000; -const NAN = 0b001000000; -const INFINITY = 0b010000000; -const MINUS_INFINITY = 0b100000000; -const INF = INFINITY | MINUS_INFINITY; -const SPECIAL = NULL | BOOL | INF | NAN; -const ATOM = STR | NUM | SPECIAL; -const COLLECTION = ARR | OBJ; -const ALL = ATOM | COLLECTION; -const Allow = { - STR, - NUM, - ARR, - OBJ, - NULL, - BOOL, - NAN, - INFINITY, - MINUS_INFINITY, - INF, - SPECIAL, - ATOM, - COLLECTION, - ALL, -}; -// The JSON string segment was unable to be parsed completely -class PartialJSON extends Error { -} -class MalformedJSON extends Error { -} -/** - * Parse incomplete JSON - * @param {string} jsonString Partial JSON to be parsed - * @param {number} allowPartial Specify what types are allowed to be partial, see {@link Allow} for details - * @returns The parsed JSON - * @throws {PartialJSON} If the JSON is incomplete (related to the `allow` parameter) - * @throws {MalformedJSON} If the JSON is malformed - */ -function parseJSON(jsonString, allowPartial = Allow.ALL) { - if (typeof jsonString !== 'string') { - throw new TypeError(`expecting str, got ${typeof jsonString}`); - } - if (!jsonString.trim()) { - throw new Error(`${jsonString} is empty`); - } - return _parseJSON(jsonString.trim(), allowPartial); -} -const _parseJSON = (jsonString, allow) => { - const length = jsonString.length; - let index = 0; - const markPartialJSON = (msg) => { - throw new PartialJSON(`${msg} at position ${index}`); - }; - const throwMalformedError = (msg) => { - throw new MalformedJSON(`${msg} at position ${index}`); - }; - const parseAny = () => { - skipBlank(); - if (index >= length) - markPartialJSON('Unexpected end of input'); - if (jsonString[index] === '"') - return parseStr(); - if (jsonString[index] === '{') - return parseObj(); - if (jsonString[index] === '[') - return parseArr(); - if (jsonString.substring(index, index + 4) === 'null' || - (Allow.NULL & allow && length - index < 4 && 'null'.startsWith(jsonString.substring(index)))) { - index += 4; - return null; - } - if (jsonString.substring(index, index + 4) === 'true' || - (Allow.BOOL & allow && length - index < 4 && 'true'.startsWith(jsonString.substring(index)))) { - index += 4; - return true; - } - if (jsonString.substring(index, index + 5) === 'false' || - (Allow.BOOL & allow && length - index < 5 && 'false'.startsWith(jsonString.substring(index)))) { - index += 5; - return false; - } - if (jsonString.substring(index, index + 8) === 'Infinity' || - (Allow.INFINITY & allow && length - index < 8 && 'Infinity'.startsWith(jsonString.substring(index)))) { - index += 8; - return Infinity; - } - if (jsonString.substring(index, index + 9) === '-Infinity' || - (Allow.MINUS_INFINITY & allow && - 1 < length - index && - length - index < 9 && - '-Infinity'.startsWith(jsonString.substring(index)))) { - index += 9; - return -Infinity; - } - if (jsonString.substring(index, index + 3) === 'NaN' || - (Allow.NAN & allow && length - index < 3 && 'NaN'.startsWith(jsonString.substring(index)))) { - index += 3; - return NaN; - } - return parseNum(); - }; - const parseStr = () => { - const start = index; - let escape = false; - index++; // skip initial quote - while (index < length && (jsonString[index] !== '"' || (escape && jsonString[index - 1] === '\\'))) { - escape = jsonString[index] === '\\' ? !escape : false; - index++; - } - if (jsonString.charAt(index) == '"') { - try { - return JSON.parse(jsonString.substring(start, ++index - Number(escape))); - } - catch (e) { - throwMalformedError(String(e)); - } - } - else if (Allow.STR & allow) { - try { - return JSON.parse(jsonString.substring(start, index - Number(escape)) + '"'); - } - catch (e) { - // SyntaxError: Invalid escape sequence - return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('\\')) + '"'); - } - } - markPartialJSON('Unterminated string literal'); - }; - const parseObj = () => { - index++; // skip initial brace - skipBlank(); - const obj = {}; - try { - while (jsonString[index] !== '}') { - skipBlank(); - if (index >= length && Allow.OBJ & allow) - return obj; - const key = parseStr(); - skipBlank(); - index++; // skip colon - try { - const value = parseAny(); - Object.defineProperty(obj, key, { value, writable: true, enumerable: true, configurable: true }); - } - catch (e) { - if (Allow.OBJ & allow) - return obj; - else - throw e; - } - skipBlank(); - if (jsonString[index] === ',') - index++; // skip comma - } - } - catch (e) { - if (Allow.OBJ & allow) - return obj; - else - markPartialJSON("Expected '}' at end of object"); - } - index++; // skip final brace - return obj; - }; - const parseArr = () => { - index++; // skip initial bracket - const arr = []; - try { - while (jsonString[index] !== ']') { - arr.push(parseAny()); - skipBlank(); - if (jsonString[index] === ',') { - index++; // skip comma - } - } - } - catch (e) { - if (Allow.ARR & allow) { - return arr; - } - markPartialJSON("Expected ']' at end of array"); - } - index++; // skip final bracket - return arr; - }; - const parseNum = () => { - if (index === 0) { - if (jsonString === '-' && Allow.NUM & allow) - markPartialJSON("Not sure what '-' is"); - try { - return JSON.parse(jsonString); - } - catch (e) { - if (Allow.NUM & allow) { - try { - if ('.' === jsonString[jsonString.length - 1]) - return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('.'))); - return JSON.parse(jsonString.substring(0, jsonString.lastIndexOf('e'))); - } - catch (e) { } - } - throwMalformedError(String(e)); - } - } - const start = index; - if (jsonString[index] === '-') - index++; - while (jsonString[index] && !',]}'.includes(jsonString[index])) - index++; - if (index == length && !(Allow.NUM & allow)) - markPartialJSON('Unterminated number literal'); - try { - return JSON.parse(jsonString.substring(start, index)); - } - catch (e) { - if (jsonString.substring(start, index) === '-' && Allow.NUM & allow) - markPartialJSON("Not sure what '-' is"); - try { - return JSON.parse(jsonString.substring(start, jsonString.lastIndexOf('e'))); - } - catch (e) { - throwMalformedError(String(e)); - } - } - }; - const skipBlank = () => { - while (index < length && ' \n\r\t'.includes(jsonString[index])) { - index++; - } - }; - return parseAny(); -}; -// using this function with malformed JSON is undefined behavior -const parser_partialParse = (input) => parseJSON(input, Allow.ALL ^ Allow.NUM); - -//# sourceMappingURL=parser.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/streaming.mjs - -//# sourceMappingURL=streaming.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStream.mjs -var _ChatCompletionStream_instances, _ChatCompletionStream_params, _ChatCompletionStream_choiceEventStates, _ChatCompletionStream_currentChatCompletionSnapshot, _ChatCompletionStream_beginRequest, _ChatCompletionStream_getChoiceEventState, _ChatCompletionStream_addChunk, _ChatCompletionStream_emitToolCallDoneEvent, _ChatCompletionStream_emitContentDoneEvents, _ChatCompletionStream_endRequest, _ChatCompletionStream_getAutoParseableResponseFormat, _ChatCompletionStream_accumulateChatCompletion; - - - - - - -class ChatCompletionStream extends AbstractChatCompletionRunner { - constructor(params) { - super(); - _ChatCompletionStream_instances.add(this); - _ChatCompletionStream_params.set(this, void 0); - _ChatCompletionStream_choiceEventStates.set(this, void 0); - _ChatCompletionStream_currentChatCompletionSnapshot.set(this, void 0); - tslib_classPrivateFieldSet(this, _ChatCompletionStream_params, params, "f"); - tslib_classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); - } - get currentChatCompletionSnapshot() { - return tslib_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); - } - /** - * Intended for use on the frontend, consuming a stream produced with - * `.toReadableStream()` on the backend. - * - * Note that messages sent to the model do not appear in `.on('message')` - * in this context. - */ - static fromReadableStream(stream) { - const runner = new ChatCompletionStream(null); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - static createChatCompletion(client, params, options) { - const runner = new ChatCompletionStream(params); - runner._run(() => runner._runChatCompletion(client, { ...params, stream: true }, { ...options, headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' } })); - return runner; - } - async _createChatCompletion(client, params, options) { - super._createChatCompletion; - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); - const stream = await client.chat.completions.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); - this._connected(); - for await (const chunk of stream) { - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addChatCompletion(tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); - } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_beginRequest).call(this); - this._connected(); - const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); - let chatId; - for await (const chunk of stream) { - if (chatId && chatId !== chunk.id) { - // A new request has been made. - this._addChatCompletion(tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); - } - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_addChunk).call(this, chunk); - chatId = chunk.id; - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addChatCompletion(tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_endRequest).call(this)); - } - [(_ChatCompletionStream_params = new WeakMap(), _ChatCompletionStream_choiceEventStates = new WeakMap(), _ChatCompletionStream_currentChatCompletionSnapshot = new WeakMap(), _ChatCompletionStream_instances = new WeakSet(), _ChatCompletionStream_beginRequest = function _ChatCompletionStream_beginRequest() { - if (this.ended) - return; - tslib_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); - }, _ChatCompletionStream_getChoiceEventState = function _ChatCompletionStream_getChoiceEventState(choice) { - let state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index]; - if (state) { - return state; - } - state = { - content_done: false, - refusal_done: false, - logprobs_content_done: false, - logprobs_refusal_done: false, - done_tool_calls: new Set(), - current_tool_call_index: null, - }; - tslib_classPrivateFieldGet(this, _ChatCompletionStream_choiceEventStates, "f")[choice.index] = state; - return state; - }, _ChatCompletionStream_addChunk = function _ChatCompletionStream_addChunk(chunk) { - if (this.ended) - return; - const completion = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_accumulateChatCompletion).call(this, chunk); - this._emit('chunk', chunk, completion); - for (const choice of chunk.choices) { - const choiceSnapshot = completion.choices[choice.index]; - if (choice.delta.content != null && - choiceSnapshot.message?.role === 'assistant' && - choiceSnapshot.message?.content) { - this._emit('content', choice.delta.content, choiceSnapshot.message.content); - this._emit('content.delta', { - delta: choice.delta.content, - snapshot: choiceSnapshot.message.content, - parsed: choiceSnapshot.message.parsed, - }); - } - if (choice.delta.refusal != null && - choiceSnapshot.message?.role === 'assistant' && - choiceSnapshot.message?.refusal) { - this._emit('refusal.delta', { - delta: choice.delta.refusal, - snapshot: choiceSnapshot.message.refusal, - }); - } - if (choice.logprobs?.content != null && choiceSnapshot.message?.role === 'assistant') { - this._emit('logprobs.content.delta', { - content: choice.logprobs?.content, - snapshot: choiceSnapshot.logprobs?.content ?? [], - }); - } - if (choice.logprobs?.refusal != null && choiceSnapshot.message?.role === 'assistant') { - this._emit('logprobs.refusal.delta', { - refusal: choice.logprobs?.refusal, - snapshot: choiceSnapshot.logprobs?.refusal ?? [], - }); - } - const state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); - if (choiceSnapshot.finish_reason) { - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); - if (state.current_tool_call_index != null) { - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); - } - } - for (const toolCall of choice.delta.tool_calls ?? []) { - if (state.current_tool_call_index !== toolCall.index) { - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitContentDoneEvents).call(this, choiceSnapshot); - // new tool call started, the previous one is done - if (state.current_tool_call_index != null) { - tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_emitToolCallDoneEvent).call(this, choiceSnapshot, state.current_tool_call_index); - } - } - state.current_tool_call_index = toolCall.index; - } - for (const toolCallDelta of choice.delta.tool_calls ?? []) { - const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallDelta.index]; - if (!toolCallSnapshot?.type) { - continue; - } - if (toolCallSnapshot?.type === 'function') { - this._emit('tool_calls.function.arguments.delta', { - name: toolCallSnapshot.function?.name, - index: toolCallDelta.index, - arguments: toolCallSnapshot.function.arguments, - parsed_arguments: toolCallSnapshot.function.parsed_arguments, - arguments_delta: toolCallDelta.function?.arguments ?? '', - }); - } - else { - ChatCompletionStream_assertNever(toolCallSnapshot?.type); - } - } - } - }, _ChatCompletionStream_emitToolCallDoneEvent = function _ChatCompletionStream_emitToolCallDoneEvent(choiceSnapshot, toolCallIndex) { - const state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); - if (state.done_tool_calls.has(toolCallIndex)) { - // we've already fired the done event - return; - } - const toolCallSnapshot = choiceSnapshot.message.tool_calls?.[toolCallIndex]; - if (!toolCallSnapshot) { - throw new Error('no tool call snapshot'); - } - if (!toolCallSnapshot.type) { - throw new Error('tool call snapshot missing `type`'); - } - if (toolCallSnapshot.type === 'function') { - const inputTool = tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.tools?.find((tool) => isChatCompletionFunctionTool(tool) && tool.function.name === toolCallSnapshot.function.name); // TS doesn't narrow based on isChatCompletionTool - this._emit('tool_calls.function.arguments.done', { - name: toolCallSnapshot.function.name, - index: toolCallIndex, - arguments: toolCallSnapshot.function.arguments, - parsed_arguments: isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCallSnapshot.function.arguments) - : inputTool?.function.strict ? JSON.parse(toolCallSnapshot.function.arguments) - : null, - }); - } - else { - ChatCompletionStream_assertNever(toolCallSnapshot.type); - } - }, _ChatCompletionStream_emitContentDoneEvents = function _ChatCompletionStream_emitContentDoneEvents(choiceSnapshot) { - const state = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getChoiceEventState).call(this, choiceSnapshot); - if (choiceSnapshot.message.content && !state.content_done) { - state.content_done = true; - const responseFormat = tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this); - this._emit('content.done', { - content: choiceSnapshot.message.content, - parsed: responseFormat ? responseFormat.$parseRaw(choiceSnapshot.message.content) : null, - }); - } - if (choiceSnapshot.message.refusal && !state.refusal_done) { - state.refusal_done = true; - this._emit('refusal.done', { refusal: choiceSnapshot.message.refusal }); - } - if (choiceSnapshot.logprobs?.content && !state.logprobs_content_done) { - state.logprobs_content_done = true; - this._emit('logprobs.content.done', { content: choiceSnapshot.logprobs.content }); - } - if (choiceSnapshot.logprobs?.refusal && !state.logprobs_refusal_done) { - state.logprobs_refusal_done = true; - this._emit('logprobs.refusal.done', { refusal: choiceSnapshot.logprobs.refusal }); - } - }, _ChatCompletionStream_endRequest = function _ChatCompletionStream_endRequest() { - if (this.ended) { - throw new error_OpenAIError(`stream has ended, this shouldn't happen`); - } - const snapshot = tslib_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); - if (!snapshot) { - throw new error_OpenAIError(`request ended without sending any chunks`); - } - tslib_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, undefined, "f"); - tslib_classPrivateFieldSet(this, _ChatCompletionStream_choiceEventStates, [], "f"); - return finalizeChatCompletion(snapshot, tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")); - }, _ChatCompletionStream_getAutoParseableResponseFormat = function _ChatCompletionStream_getAutoParseableResponseFormat() { - const responseFormat = tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f")?.response_format; - if (isAutoParsableResponseFormat(responseFormat)) { - return responseFormat; - } - return null; - }, _ChatCompletionStream_accumulateChatCompletion = function _ChatCompletionStream_accumulateChatCompletion(chunk) { - var _a, _b, _c, _d; - let snapshot = tslib_classPrivateFieldGet(this, _ChatCompletionStream_currentChatCompletionSnapshot, "f"); - const { choices, ...rest } = chunk; - if (!snapshot) { - snapshot = tslib_classPrivateFieldSet(this, _ChatCompletionStream_currentChatCompletionSnapshot, { - ...rest, - choices: [], - }, "f"); - } - else { - Object.assign(snapshot, rest); - } - for (const { delta, finish_reason, index, logprobs = null, ...other } of chunk.choices) { - let choice = snapshot.choices[index]; - if (!choice) { - choice = snapshot.choices[index] = { finish_reason, index, message: {}, logprobs, ...other }; - } - if (logprobs) { - if (!choice.logprobs) { - choice.logprobs = Object.assign({}, logprobs); - } - else { - const { content, refusal, ...rest } = logprobs; - assertIsEmpty(rest); - Object.assign(choice.logprobs, rest); - if (content) { - (_a = choice.logprobs).content ?? (_a.content = []); - choice.logprobs.content.push(...content); - } - if (refusal) { - (_b = choice.logprobs).refusal ?? (_b.refusal = []); - choice.logprobs.refusal.push(...refusal); - } - } - } - if (finish_reason) { - choice.finish_reason = finish_reason; - if (tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f") && hasAutoParseableInput(tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f"))) { - if (finish_reason === 'length') { - throw new LengthFinishReasonError(); - } - if (finish_reason === 'content_filter') { - throw new ContentFilterFinishReasonError(); - } - } - } - Object.assign(choice, other); - if (!delta) - continue; // Shouldn't happen; just in case. - const { content, refusal, function_call, role, tool_calls, ...rest } = delta; - assertIsEmpty(rest); - Object.assign(choice.message, rest); - if (refusal) { - choice.message.refusal = (choice.message.refusal || '') + refusal; - } - if (role) - choice.message.role = role; - if (function_call) { - if (!choice.message.function_call) { - choice.message.function_call = function_call; - } - else { - if (function_call.name) - choice.message.function_call.name = function_call.name; - if (function_call.arguments) { - (_c = choice.message.function_call).arguments ?? (_c.arguments = ''); - choice.message.function_call.arguments += function_call.arguments; - } - } - } - if (content) { - choice.message.content = (choice.message.content || '') + content; - if (!choice.message.refusal && tslib_classPrivateFieldGet(this, _ChatCompletionStream_instances, "m", _ChatCompletionStream_getAutoParseableResponseFormat).call(this)) { - choice.message.parsed = parser_partialParse(choice.message.content); - } - } - if (tool_calls) { - if (!choice.message.tool_calls) - choice.message.tool_calls = []; - for (const { index, id, type, function: fn, ...rest } of tool_calls) { - const tool_call = ((_d = choice.message.tool_calls)[index] ?? (_d[index] = {})); - Object.assign(tool_call, rest); - if (id) - tool_call.id = id; - if (type) - tool_call.type = type; - if (fn) - tool_call.function ?? (tool_call.function = { name: fn.name ?? '', arguments: '' }); - if (fn?.name) - tool_call.function.name = fn.name; - if (fn?.arguments) { - tool_call.function.arguments += fn.arguments; - if (shouldParseToolCall(tslib_classPrivateFieldGet(this, _ChatCompletionStream_params, "f"), tool_call)) { - tool_call.function.parsed_arguments = parser_partialParse(tool_call.function.arguments); - } - } - } - } - } - return snapshot; - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on('chunk', (chunk) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(chunk); - } - else { - pushQueue.push(chunk); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; - } - toReadableStream() { - const stream = new streaming_Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream.toReadableStream(); - } -} -function finalizeChatCompletion(snapshot, params) { - const { id, choices, created, model, system_fingerprint, ...rest } = snapshot; - const completion = { - ...rest, - id, - choices: choices.map(({ message, finish_reason, index, logprobs, ...choiceRest }) => { - if (!finish_reason) { - throw new error_OpenAIError(`missing finish_reason for choice ${index}`); - } - const { content = null, function_call, tool_calls, ...messageRest } = message; - const role = message.role; // this is what we expect; in theory it could be different which would make our types a slight lie but would be fine. - if (!role) { - throw new error_OpenAIError(`missing role for choice ${index}`); - } - if (function_call) { - const { arguments: args, name } = function_call; - if (args == null) { - throw new error_OpenAIError(`missing function_call.arguments for choice ${index}`); - } - if (!name) { - throw new error_OpenAIError(`missing function_call.name for choice ${index}`); - } - return { - ...choiceRest, - message: { - content, - function_call: { arguments: args, name }, - role, - refusal: message.refusal ?? null, - }, - finish_reason, - index, - logprobs, - }; - } - if (tool_calls) { - return { - ...choiceRest, - index, - finish_reason, - logprobs, - message: { - ...messageRest, - role, - content, - refusal: message.refusal ?? null, - tool_calls: tool_calls.map((tool_call, i) => { - const { function: fn, type, id, ...toolRest } = tool_call; - const { arguments: args, name, ...fnRest } = fn || {}; - if (id == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].id\n${str(snapshot)}`); - } - if (type == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].type\n${str(snapshot)}`); - } - if (name == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].function.name\n${str(snapshot)}`); - } - if (args == null) { - throw new error_OpenAIError(`missing choices[${index}].tool_calls[${i}].function.arguments\n${str(snapshot)}`); - } - return { ...toolRest, id, type, function: { ...fnRest, name, arguments: args } }; - }), - }, - }; - } - return { - ...choiceRest, - message: { ...messageRest, content, role, refusal: message.refusal ?? null }, - finish_reason, - index, - logprobs, - }; - }), - created, - model, - object: 'chat.completion', - ...(system_fingerprint ? { system_fingerprint } : {}), - }; - return maybeParseChatCompletion(completion, params); -} -function str(x) { - return JSON.stringify(x); -} -/** - * Ensures the given argument is an empty object, useful for - * asserting that all known properties on an object have been - * destructured. - */ -function assertIsEmpty(obj) { - return; -} -function ChatCompletionStream_assertNever(_x) { } -//# sourceMappingURL=ChatCompletionStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ChatCompletionStreamingRunner.mjs - -class ChatCompletionStreamingRunner extends ChatCompletionStream { - static fromReadableStream(stream) { - const runner = new ChatCompletionStreamingRunner(null); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - static runTools(client, params, options) { - const runner = new ChatCompletionStreamingRunner( - // @ts-expect-error TODO these types are incompatible - params); - const opts = { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'runTools' }, - }; - runner._run(() => runner._runTools(client, params, opts)); - return runner; - } -} -//# sourceMappingURL=ChatCompletionStreamingRunner.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/completions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - -class completions_Completions extends resource_APIResource { - constructor() { - super(...arguments); - this.messages = new completions_messages_Messages(this._client); - } - create(body, options) { - return this._client.post('/chat/completions', { body, ...options, stream: body.stream ?? false }); - } - /** - * Get a stored chat completion. Only Chat Completions that have been created with - * the `store` parameter set to `true` will be returned. - * - * @example - * ```ts - * const chatCompletion = - * await client.chat.completions.retrieve('completion_id'); - * ``` - */ - retrieve(completionID, options) { - return this._client.get(path_path `/chat/completions/${completionID}`, options); - } - /** - * Modify a stored chat completion. Only Chat Completions that have been created - * with the `store` parameter set to `true` can be modified. Currently, the only - * supported modification is to update the `metadata` field. - * - * @example - * ```ts - * const chatCompletion = await client.chat.completions.update( - * 'completion_id', - * { metadata: { foo: 'string' } }, - * ); - * ``` - */ - update(completionID, body, options) { - return this._client.post(path_path `/chat/completions/${completionID}`, { body, ...options }); - } - /** - * List stored Chat Completions. Only Chat Completions that have been stored with - * the `store` parameter set to `true` will be returned. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const chatCompletion of client.chat.completions.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList('/chat/completions', (CursorPage), { query, ...options }); - } - /** - * Delete a stored chat completion. Only Chat Completions that have been created - * with the `store` parameter set to `true` can be deleted. - * - * @example - * ```ts - * const chatCompletionDeleted = - * await client.chat.completions.delete('completion_id'); - * ``` - */ - delete(completionID, options) { - return this._client.delete(path_path `/chat/completions/${completionID}`, options); - } - parse(body, options) { - validateInputTools(body.tools); - return this._client.chat.completions - .create(body, { - ...options, - headers: { - ...options?.headers, - 'X-Stainless-Helper-Method': 'chat.completions.parse', - }, - }) - ._thenUnwrap((completion) => parseChatCompletion(completion, body)); - } - runTools(body, options) { - if (body.stream) { - return ChatCompletionStreamingRunner.runTools(this._client, body, options); - } - return ChatCompletionRunner.runTools(this._client, body, options); - } - /** - * Creates a chat completion stream - */ - stream(body, options) { - return ChatCompletionStream.createChatCompletion(this._client, body, options); - } -} - - - - -completions_Completions.Messages = completions_messages_Messages; -//# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/chat.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Chat extends resource_APIResource { - constructor() { - super(...arguments); - this.completions = new completions_Completions(this._client); - } -} -Chat.Completions = completions_Completions; -//# sourceMappingURL=chat.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/completions/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/chat/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/headers.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -const headers_brand_privateNullableHeaders = /* @__PURE__ */ Symbol('brand.privateNullableHeaders'); -function* headers_iterateHeaders(headers) { - if (!headers) - return; - if (headers_brand_privateNullableHeaders in headers) { - const { values, nulls } = headers; - yield* values.entries(); - for (const name of nulls) { - yield [name, null]; - } - return; - } - let shouldClear = false; - let iter; - if (headers instanceof Headers) { - iter = headers.entries(); - } - else if (values_isReadonlyArray(headers)) { - iter = headers; - } - else { - shouldClear = true; - iter = Object.entries(headers ?? {}); - } - for (let row of iter) { - const name = row[0]; - if (typeof name !== 'string') - throw new TypeError('expected header name to be a string'); - const values = values_isReadonlyArray(row[1]) ? row[1] : [row[1]]; - let didClear = false; - for (const value of values) { - if (value === undefined) - continue; - // Objects keys always overwrite older headers, they never append. - // Yield a null to clear the header before adding the new values. - if (shouldClear && !didClear) { - didClear = true; - yield [name, null]; - } - yield [name, value]; - } - } -} -const headers_buildHeaders = (newHeaders) => { - const targetHeaders = new Headers(); - const nullHeaders = new Set(); - for (const headers of newHeaders) { - const seenHeaders = new Set(); - for (const [name, value] of headers_iterateHeaders(headers)) { - const lowerName = name.toLowerCase(); - if (!seenHeaders.has(lowerName)) { - targetHeaders.delete(name); - seenHeaders.add(lowerName); - } - if (value === null) { - targetHeaders.delete(name); - nullHeaders.add(lowerName); - } - else { - targetHeaders.append(name, value); - nullHeaders.delete(lowerName); - } - } - } - return { [headers_brand_privateNullableHeaders]: true, values: targetHeaders, nulls: nullHeaders }; -}; -const headers_isEmptyHeaders = (headers) => { - for (const _ of headers_iterateHeaders(headers)) - return false; - return true; -}; -//# sourceMappingURL=headers.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/speech.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Speech extends resource_APIResource { - /** - * Generates audio from the input text. - * - * @example - * ```ts - * const speech = await client.audio.speech.create({ - * input: 'input', - * model: 'string', - * voice: 'ash', - * }); - * - * const content = await speech.blob(); - * console.log(content); - * ``` - */ - create(body, options) { - return this._client.post('/audio/speech', { - body, - ...options, - headers: headers_buildHeaders([{ Accept: 'application/octet-stream' }, options?.headers]), - __binaryResponse: true, - }); - } -} -//# sourceMappingURL=speech.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/transcriptions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Transcriptions extends resource_APIResource { - create(body, options) { - return this._client.post('/audio/transcriptions', uploads_multipartFormRequestOptions({ - body, - ...options, - stream: body.stream ?? false, - __metadata: { model: body.model }, - }, this._client)); - } -} -//# sourceMappingURL=transcriptions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/translations.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Translations extends resource_APIResource { - create(body, options) { - return this._client.post('/audio/translations', uploads_multipartFormRequestOptions({ body, ...options, __metadata: { model: body.model } }, this._client)); - } -} -//# sourceMappingURL=translations.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/audio/audio.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -class Audio extends resource_APIResource { - constructor() { - super(...arguments); - this.transcriptions = new Transcriptions(this._client); - this.translations = new Translations(this._client); - this.speech = new Speech(this._client); - } -} -Audio.Transcriptions = Transcriptions; -Audio.Translations = Translations; -Audio.Speech = Speech; -//# sourceMappingURL=audio.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/batches.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class resources_batches_Batches extends resource_APIResource { - /** - * Creates and executes a batch from an uploaded file of requests - */ - create(body, options) { - return this._client.post('/batches', { body, ...options }); - } - /** - * Retrieves a batch. - */ - retrieve(batchID, options) { - return this._client.get(path_path `/batches/${batchID}`, options); - } - /** - * List your organization's batches. - */ - list(query = {}, options) { - return this._client.getAPIList('/batches', (CursorPage), { query, ...options }); - } - /** - * Cancels an in-progress batch. The batch will be in status `cancelling` for up to - * 10 minutes, before changing to `cancelled`, where it will have partial results - * (if any) available in the output file. - */ - cancel(batchID, options) { - return this._client.post(path_path `/batches/${batchID}/cancel`, options); - } -} -//# sourceMappingURL=batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/assistants.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class Assistants extends resource_APIResource { - /** - * Create an assistant with a model and instructions. - * - * @example - * ```ts - * const assistant = await client.beta.assistants.create({ - * model: 'gpt-4o', - * }); - * ``` - */ - create(body, options) { - return this._client.post('/assistants', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieves an assistant. - * - * @example - * ```ts - * const assistant = await client.beta.assistants.retrieve( - * 'assistant_id', - * ); - * ``` - */ - retrieve(assistantID, options) { - return this._client.get(path_path `/assistants/${assistantID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Modifies an assistant. - * - * @example - * ```ts - * const assistant = await client.beta.assistants.update( - * 'assistant_id', - * ); - * ``` - */ - update(assistantID, body, options) { - return this._client.post(path_path `/assistants/${assistantID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of assistants. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const assistant of client.beta.assistants.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList('/assistants', (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Delete an assistant. - * - * @example - * ```ts - * const assistantDeleted = - * await client.beta.assistants.delete('assistant_id'); - * ``` - */ - delete(assistantID, options) { - return this._client.delete(path_path `/assistants/${assistantID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -//# sourceMappingURL=assistants.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/sessions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Sessions extends resource_APIResource { - /** - * Create an ephemeral API token for use in client-side applications with the - * Realtime API. Can be configured with the same session parameters as the - * `session.update` client event. - * - * It responds with a session object, plus a `client_secret` key which contains a - * usable ephemeral API token that can be used to authenticate browser clients for - * the Realtime API. - * - * @example - * ```ts - * const session = - * await client.beta.realtime.sessions.create(); - * ``` - */ - create(body, options) { - return this._client.post('/realtime/sessions', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -//# sourceMappingURL=sessions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/transcription-sessions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class TranscriptionSessions extends resource_APIResource { - /** - * Create an ephemeral API token for use in client-side applications with the - * Realtime API specifically for realtime transcriptions. Can be configured with - * the same session parameters as the `transcription_session.update` client event. - * - * It responds with a session object, plus a `client_secret` key which contains a - * usable ephemeral API token that can be used to authenticate browser clients for - * the Realtime API. - * - * @example - * ```ts - * const transcriptionSession = - * await client.beta.realtime.transcriptionSessions.create(); - * ``` - */ - create(body, options) { - return this._client.post('/realtime/transcription_sessions', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -//# sourceMappingURL=transcription-sessions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/realtime/realtime.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -/** - * @deprecated Realtime has now launched and is generally available. The old beta API is now deprecated. - */ -class Realtime extends resource_APIResource { - constructor() { - super(...arguments); - this.sessions = new Sessions(this._client); - this.transcriptionSessions = new TranscriptionSessions(this._client); - } -} -Realtime.Sessions = Sessions; -Realtime.TranscriptionSessions = TranscriptionSessions; -//# sourceMappingURL=realtime.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chatkit/sessions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class sessions_Sessions extends resource_APIResource { - /** - * Create a ChatKit session - * - * @example - * ```ts - * const chatSession = - * await client.beta.chatkit.sessions.create({ - * user: 'x', - * workflow: { id: 'id' }, - * }); - * ``` - */ - create(body, options) { - return this._client.post('/chatkit/sessions', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), - }); - } - /** - * Cancel a ChatKit session - * - * @example - * ```ts - * const chatSession = - * await client.beta.chatkit.sessions.cancel('cksess_123'); - * ``` - */ - cancel(sessionID, options) { - return this._client.post(path_path `/chatkit/sessions/${sessionID}/cancel`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), - }); - } -} -//# sourceMappingURL=sessions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chatkit/threads.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class Threads extends resource_APIResource { - /** - * Retrieve a ChatKit thread - * - * @example - * ```ts - * const chatkitThread = - * await client.beta.chatkit.threads.retrieve('cthr_123'); - * ``` - */ - retrieve(threadID, options) { - return this._client.get(path_path `/chatkit/threads/${threadID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), - }); - } - /** - * List ChatKit threads - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const chatkitThread of client.beta.chatkit.threads.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList('/chatkit/threads', (ConversationCursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), - }); - } - /** - * Delete a ChatKit thread - * - * @example - * ```ts - * const thread = await client.beta.chatkit.threads.delete( - * 'cthr_123', - * ); - * ``` - */ - delete(threadID, options) { - return this._client.delete(path_path `/chatkit/threads/${threadID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]), - }); - } - /** - * List ChatKit thread items - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const thread of client.beta.chatkit.threads.listItems( - * 'cthr_123', - * )) { - * // ... - * } - * ``` - */ - listItems(threadID, query = {}, options) { - return this._client.getAPIList(path_path `/chatkit/threads/${threadID}/items`, (ConversationCursorPage), { query, ...options, headers: headers_buildHeaders([{ 'OpenAI-Beta': 'chatkit_beta=v1' }, options?.headers]) }); - } -} -//# sourceMappingURL=threads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/chatkit/chatkit.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class ChatKit extends resource_APIResource { - constructor() { - super(...arguments); - this.sessions = new sessions_Sessions(this._client); - this.threads = new Threads(this._client); - } -} -ChatKit.Sessions = sessions_Sessions; -ChatKit.Threads = Threads; -//# sourceMappingURL=chatkit.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/messages.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -/** - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ -class threads_messages_Messages extends resource_APIResource { - /** - * Create a message. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - create(threadID, body, options) { - return this._client.post(path_path `/threads/${threadID}/messages`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieve a message. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - retrieve(messageID, params, options) { - const { thread_id } = params; - return this._client.get(path_path `/threads/${thread_id}/messages/${messageID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Modifies a message. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - update(messageID, params, options) { - const { thread_id, ...body } = params; - return this._client.post(path_path `/threads/${thread_id}/messages/${messageID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of messages for a given thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - list(threadID, query = {}, options) { - return this._client.getAPIList(path_path `/threads/${threadID}/messages`, (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Deletes a message. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - delete(messageID, params, options) { - const { thread_id } = params; - return this._client.delete(path_path `/threads/${thread_id}/messages/${messageID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -//# sourceMappingURL=messages.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/steps.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -/** - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ -class Steps extends resource_APIResource { - /** - * Retrieves a run step. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - retrieve(stepID, params, options) { - const { thread_id, run_id, ...query } = params; - return this._client.get(path_path `/threads/${thread_id}/runs/${run_id}/steps/${stepID}`, { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of run steps belonging to a run. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - list(runID, params, options) { - const { thread_id, ...query } = params; - return this._client.getAPIList(path_path `/threads/${thread_id}/runs/${runID}/steps`, (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -//# sourceMappingURL=steps.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/base64.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -const base64_toBase64 = (data) => { - if (!data) - return ''; - if (typeof globalThis.Buffer !== 'undefined') { - return globalThis.Buffer.from(data).toString('base64'); - } - if (typeof data === 'string') { - data = encodeUTF8(data); - } - if (typeof btoa !== 'undefined') { - return btoa(String.fromCharCode.apply(null, data)); - } - throw new OpenAIError('Cannot generate base64 string; Expected `Buffer` or `btoa` to be defined'); -}; -const base64_fromBase64 = (str) => { - if (typeof globalThis.Buffer !== 'undefined') { - const buf = globalThis.Buffer.from(str, 'base64'); - return new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); - } - if (typeof atob !== 'undefined') { - const bstr = atob(str); - const buf = new Uint8Array(bstr.length); - for (let i = 0; i < bstr.length; i++) { - buf[i] = bstr.charCodeAt(i); - } - return buf; - } - throw new OpenAIError('Cannot decode base64 string; Expected `Buffer` or `atob` to be defined'); -}; -/** - * Converts a Base64 encoded string to a Float32Array. - * @param base64Str - The Base64 encoded string. - * @returns An Array of numbers interpreted as Float32 values. - */ -const toFloat32Array = (base64Str) => { - if (typeof Buffer !== 'undefined') { - // for Node.js environment - const buf = Buffer.from(base64Str, 'base64'); - return Array.from(new Float32Array(buf.buffer, buf.byteOffset, buf.length / Float32Array.BYTES_PER_ELEMENT)); - } - else { - // for legacy web platform APIs - const binaryStr = atob(base64Str); - const len = binaryStr.length; - const bytes = new Uint8Array(len); - for (let i = 0; i < len; i++) { - bytes[i] = binaryStr.charCodeAt(i); - } - return Array.from(new Float32Array(bytes.buffer)); - } -}; -//# sourceMappingURL=base64.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils/env.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -/** - * Read an environment variable. - * - * Trims beginning and trailing whitespace. - * - * Will return undefined if the environment variable doesn't exist or cannot be accessed. - */ -const env_readEnv = (env) => { - if (typeof globalThis.process !== 'undefined') { - return globalThis.process.env?.[env]?.trim() ?? undefined; - } - if (typeof globalThis.Deno !== 'undefined') { - return globalThis.Deno.env?.get?.(env)?.trim(); - } - return undefined; -}; -//# sourceMappingURL=env.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/internal/utils.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -//# sourceMappingURL=utils.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/AssistantStream.mjs -var _AssistantStream_instances, AssistantStream_a, _AssistantStream_events, _AssistantStream_runStepSnapshots, _AssistantStream_messageSnapshots, _AssistantStream_messageSnapshot, _AssistantStream_finalRun, _AssistantStream_currentContentIndex, _AssistantStream_currentContent, _AssistantStream_currentToolCallIndex, _AssistantStream_currentToolCall, _AssistantStream_currentEvent, _AssistantStream_currentRunSnapshot, _AssistantStream_currentRunStepSnapshot, _AssistantStream_addEvent, _AssistantStream_endRequest, _AssistantStream_handleMessage, _AssistantStream_handleRunStep, _AssistantStream_handleEvent, _AssistantStream_accumulateRunStep, _AssistantStream_accumulateMessage, _AssistantStream_accumulateContent, _AssistantStream_handleRun; - - - - - -class AssistantStream extends EventStream { - constructor() { - super(...arguments); - _AssistantStream_instances.add(this); - //Track all events in a single list for reference - _AssistantStream_events.set(this, []); - //Used to accumulate deltas - //We are accumulating many types so the value here is not strict - _AssistantStream_runStepSnapshots.set(this, {}); - _AssistantStream_messageSnapshots.set(this, {}); - _AssistantStream_messageSnapshot.set(this, void 0); - _AssistantStream_finalRun.set(this, void 0); - _AssistantStream_currentContentIndex.set(this, void 0); - _AssistantStream_currentContent.set(this, void 0); - _AssistantStream_currentToolCallIndex.set(this, void 0); - _AssistantStream_currentToolCall.set(this, void 0); - //For current snapshot methods - _AssistantStream_currentEvent.set(this, void 0); - _AssistantStream_currentRunSnapshot.set(this, void 0); - _AssistantStream_currentRunStepSnapshot.set(this, void 0); - } - [(_AssistantStream_events = new WeakMap(), _AssistantStream_runStepSnapshots = new WeakMap(), _AssistantStream_messageSnapshots = new WeakMap(), _AssistantStream_messageSnapshot = new WeakMap(), _AssistantStream_finalRun = new WeakMap(), _AssistantStream_currentContentIndex = new WeakMap(), _AssistantStream_currentContent = new WeakMap(), _AssistantStream_currentToolCallIndex = new WeakMap(), _AssistantStream_currentToolCall = new WeakMap(), _AssistantStream_currentEvent = new WeakMap(), _AssistantStream_currentRunSnapshot = new WeakMap(), _AssistantStream_currentRunStepSnapshot = new WeakMap(), _AssistantStream_instances = new WeakSet(), Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - //Catch all for passing along all events - this.on('event', (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); - } - else { - pushQueue.push(event); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((chunk) => (chunk ? { value: chunk, done: false } : { value: undefined, done: true })); - } - const chunk = pushQueue.shift(); - return { value: chunk, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; - } - static fromReadableStream(stream) { - const runner = new AssistantStream_a(); - runner._run(() => runner._fromReadableStream(stream)); - return runner; - } - async _fromReadableStream(readableStream, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - this._connected(); - const stream = streaming_Stream.fromReadableStream(readableStream, this.controller); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); - } - toReadableStream() { - const stream = new streaming_Stream(this[Symbol.asyncIterator].bind(this), this.controller); - return stream.toReadableStream(); - } - static createToolAssistantStream(runId, runs, params, options) { - const runner = new AssistantStream_a(); - runner._run(() => runner._runToolAssistantStream(runId, runs, params, { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; - } - async _createToolAssistantStream(run, runId, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - const body = { ...params, stream: true }; - const stream = await run.submitToolOutputs(runId, body, { - ...options, - signal: this.controller.signal, - }); - this._connected(); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); - } - static createThreadAssistantStream(params, thread, options) { - const runner = new AssistantStream_a(); - runner._run(() => runner._threadAssistantStream(params, thread, { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; - } - static createAssistantStream(threadId, runs, params, options) { - const runner = new AssistantStream_a(); - runner._run(() => runner._runAssistantStream(threadId, runs, params, { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; - } - currentEvent() { - return tslib_classPrivateFieldGet(this, _AssistantStream_currentEvent, "f"); - } - currentRun() { - return tslib_classPrivateFieldGet(this, _AssistantStream_currentRunSnapshot, "f"); - } - currentMessageSnapshot() { - return tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f"); - } - currentRunStepSnapshot() { - return tslib_classPrivateFieldGet(this, _AssistantStream_currentRunStepSnapshot, "f"); - } - async finalRunSteps() { - await this.done(); - return Object.values(tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")); - } - async finalMessages() { - await this.done(); - return Object.values(tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")); - } - async finalRun() { - await this.done(); - if (!tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) - throw Error('Final run was not received.'); - return tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); - } - async _createThreadAssistantStream(thread, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - const body = { ...params, stream: true }; - const stream = await thread.createAndRun(body, { ...options, signal: this.controller.signal }); - this._connected(); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); - } - async _createAssistantStream(run, threadId, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - const body = { ...params, stream: true }; - const stream = await run.create(threadId, body, { ...options, signal: this.controller.signal }); - this._connected(); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_addEvent).call(this, event); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return this._addRun(tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_endRequest).call(this)); - } - static accumulateDelta(acc, delta) { - for (const [key, deltaValue] of Object.entries(delta)) { - if (!acc.hasOwnProperty(key)) { - acc[key] = deltaValue; - continue; - } - let accValue = acc[key]; - if (accValue === null || accValue === undefined) { - acc[key] = deltaValue; - continue; - } - // We don't accumulate these special properties - if (key === 'index' || key === 'type') { - acc[key] = deltaValue; - continue; - } - // Type-specific accumulation logic - if (typeof accValue === 'string' && typeof deltaValue === 'string') { - accValue += deltaValue; - } - else if (typeof accValue === 'number' && typeof deltaValue === 'number') { - accValue += deltaValue; - } - else if (values_isObj(accValue) && values_isObj(deltaValue)) { - accValue = this.accumulateDelta(accValue, deltaValue); - } - else if (Array.isArray(accValue) && Array.isArray(deltaValue)) { - if (accValue.every((x) => typeof x === 'string' || typeof x === 'number')) { - accValue.push(...deltaValue); // Use spread syntax for efficient addition - continue; - } - for (const deltaEntry of deltaValue) { - if (!values_isObj(deltaEntry)) { - throw new Error(`Expected array delta entry to be an object but got: ${deltaEntry}`); - } - const index = deltaEntry['index']; - if (index == null) { - console.error(deltaEntry); - throw new Error('Expected array delta entry to have an `index` property'); - } - if (typeof index !== 'number') { - throw new Error(`Expected array delta entry \`index\` property to be a number but got ${index}`); - } - const accEntry = accValue[index]; - if (accEntry == null) { - accValue.push(deltaEntry); - } - else { - accValue[index] = this.accumulateDelta(accEntry, deltaEntry); - } - } - continue; - } - else { - throw Error(`Unhandled record type: ${key}, deltaValue: ${deltaValue}, accValue: ${accValue}`); - } - acc[key] = accValue; - } - return acc; - } - _addRun(run) { - return run; - } - async _threadAssistantStream(params, thread, options) { - return await this._createThreadAssistantStream(thread, params, options); - } - async _runAssistantStream(threadId, runs, params, options) { - return await this._createAssistantStream(runs, threadId, params, options); - } - async _runToolAssistantStream(runId, runs, params, options) { - return await this._createToolAssistantStream(runs, runId, params, options); - } -} -AssistantStream_a = AssistantStream, _AssistantStream_addEvent = function _AssistantStream_addEvent(event) { - if (this.ended) - return; - tslib_classPrivateFieldSet(this, _AssistantStream_currentEvent, event, "f"); - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleEvent).call(this, event); - switch (event.event) { - case 'thread.created': - //No action on this event. - break; - case 'thread.run.created': - case 'thread.run.queued': - case 'thread.run.in_progress': - case 'thread.run.requires_action': - case 'thread.run.completed': - case 'thread.run.incomplete': - case 'thread.run.failed': - case 'thread.run.cancelling': - case 'thread.run.cancelled': - case 'thread.run.expired': - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRun).call(this, event); - break; - case 'thread.run.step.created': - case 'thread.run.step.in_progress': - case 'thread.run.step.delta': - case 'thread.run.step.completed': - case 'thread.run.step.failed': - case 'thread.run.step.cancelled': - case 'thread.run.step.expired': - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleRunStep).call(this, event); - break; - case 'thread.message.created': - case 'thread.message.in_progress': - case 'thread.message.delta': - case 'thread.message.completed': - case 'thread.message.incomplete': - tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_handleMessage).call(this, event); - break; - case 'error': - //This is included for completeness, but errors are processed in the SSE event processing so this should not occur - throw new Error('Encountered an error event in event processing - errors should be processed earlier'); - default: - AssistantStream_assertNever(event); - } -}, _AssistantStream_endRequest = function _AssistantStream_endRequest() { - if (this.ended) { - throw new error_OpenAIError(`stream has ended, this shouldn't happen`); - } - if (!tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f")) - throw Error('Final run has not been received'); - return tslib_classPrivateFieldGet(this, _AssistantStream_finalRun, "f"); -}, _AssistantStream_handleMessage = function _AssistantStream_handleMessage(event) { - const [accumulatedMessage, newContent] = tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateMessage).call(this, event, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - tslib_classPrivateFieldSet(this, _AssistantStream_messageSnapshot, accumulatedMessage, "f"); - tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshots, "f")[accumulatedMessage.id] = accumulatedMessage; - for (const content of newContent) { - const snapshotContent = accumulatedMessage.content[content.index]; - if (snapshotContent?.type == 'text') { - this._emit('textCreated', snapshotContent.text); - } - } - switch (event.event) { - case 'thread.message.created': - this._emit('messageCreated', event.data); - break; - case 'thread.message.in_progress': - break; - case 'thread.message.delta': - this._emit('messageDelta', event.data.delta, accumulatedMessage); - if (event.data.delta.content) { - for (const content of event.data.delta.content) { - //If it is text delta, emit a text delta event - if (content.type == 'text' && content.text) { - let textDelta = content.text; - let snapshot = accumulatedMessage.content[content.index]; - if (snapshot && snapshot.type == 'text') { - this._emit('textDelta', textDelta, snapshot.text); - } - else { - throw Error('The snapshot associated with this text delta is not text or missing'); - } - } - if (content.index != tslib_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")) { - //See if we have in progress content - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f")) { - switch (tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").type) { - case 'text': - this._emit('textDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").text, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; - case 'image_file': - this._emit('imageFileDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentContent, "f").image_file, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; - } - } - tslib_classPrivateFieldSet(this, _AssistantStream_currentContentIndex, content.index, "f"); - } - tslib_classPrivateFieldSet(this, _AssistantStream_currentContent, accumulatedMessage.content[content.index], "f"); - } - } - break; - case 'thread.message.completed': - case 'thread.message.incomplete': - //We emit the latest content we were working on on completion (including incomplete) - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f") !== undefined) { - const currentContent = event.data.content[tslib_classPrivateFieldGet(this, _AssistantStream_currentContentIndex, "f")]; - if (currentContent) { - switch (currentContent.type) { - case 'image_file': - this._emit('imageFileDone', currentContent.image_file, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; - case 'text': - this._emit('textDone', currentContent.text, tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")); - break; - } - } - } - if (tslib_classPrivateFieldGet(this, _AssistantStream_messageSnapshot, "f")) { - this._emit('messageDone', event.data); - } - tslib_classPrivateFieldSet(this, _AssistantStream_messageSnapshot, undefined, "f"); - } -}, _AssistantStream_handleRunStep = function _AssistantStream_handleRunStep(event) { - const accumulatedRunStep = tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateRunStep).call(this, event); - tslib_classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, accumulatedRunStep, "f"); - switch (event.event) { - case 'thread.run.step.created': - this._emit('runStepCreated', event.data); - break; - case 'thread.run.step.delta': - const delta = event.data.delta; - if (delta.step_details && - delta.step_details.type == 'tool_calls' && - delta.step_details.tool_calls && - accumulatedRunStep.step_details.type == 'tool_calls') { - for (const toolCall of delta.step_details.tool_calls) { - if (toolCall.index == tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCallIndex, "f")) { - this._emit('toolCallDelta', toolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index]); - } - else { - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - } - tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCallIndex, toolCall.index, "f"); - tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCall, accumulatedRunStep.step_details.tool_calls[toolCall.index], "f"); - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) - this._emit('toolCallCreated', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - } - } - } - this._emit('runStepDelta', event.data.delta, accumulatedRunStep); - break; - case 'thread.run.step.completed': - case 'thread.run.step.failed': - case 'thread.run.step.cancelled': - case 'thread.run.step.expired': - tslib_classPrivateFieldSet(this, _AssistantStream_currentRunStepSnapshot, undefined, "f"); - const details = event.data.step_details; - if (details.type == 'tool_calls') { - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); - } - } - this._emit('runStepDone', event.data, accumulatedRunStep); - break; - case 'thread.run.step.in_progress': - break; - } -}, _AssistantStream_handleEvent = function _AssistantStream_handleEvent(event) { - tslib_classPrivateFieldGet(this, _AssistantStream_events, "f").push(event); - this._emit('event', event); -}, _AssistantStream_accumulateRunStep = function _AssistantStream_accumulateRunStep(event) { - switch (event.event) { - case 'thread.run.step.created': - tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; - return event.data; - case 'thread.run.step.delta': - let snapshot = tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; - if (!snapshot) { - throw Error('Received a RunStepDelta before creation of a snapshot'); - } - let data = event.data; - if (data.delta) { - const accumulated = AssistantStream_a.accumulateDelta(snapshot, data.delta); - tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = accumulated; - } - return tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; - case 'thread.run.step.completed': - case 'thread.run.step.failed': - case 'thread.run.step.cancelled': - case 'thread.run.step.expired': - case 'thread.run.step.in_progress': - tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id] = event.data; - break; - } - if (tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]) - return tslib_classPrivateFieldGet(this, _AssistantStream_runStepSnapshots, "f")[event.data.id]; - throw new Error('No snapshot available'); -}, _AssistantStream_accumulateMessage = function _AssistantStream_accumulateMessage(event, snapshot) { - let newContent = []; - switch (event.event) { - case 'thread.message.created': - //On creation the snapshot is just the initial message - return [event.data, newContent]; - case 'thread.message.delta': - if (!snapshot) { - throw Error('Received a delta with no existing snapshot (there should be one from message creation)'); - } - let data = event.data; - //If this delta does not have content, nothing to process - if (data.delta.content) { - for (const contentElement of data.delta.content) { - if (contentElement.index in snapshot.content) { - let currentContent = snapshot.content[contentElement.index]; - snapshot.content[contentElement.index] = tslib_classPrivateFieldGet(this, _AssistantStream_instances, "m", _AssistantStream_accumulateContent).call(this, contentElement, currentContent); - } - else { - snapshot.content[contentElement.index] = contentElement; - // This is a new element - newContent.push(contentElement); - } - } - } - return [snapshot, newContent]; - case 'thread.message.in_progress': - case 'thread.message.completed': - case 'thread.message.incomplete': - //No changes on other thread events - if (snapshot) { - return [snapshot, newContent]; - } - else { - throw Error('Received thread message event with no existing snapshot'); - } - } - throw Error('Tried to accumulate a non-message event'); -}, _AssistantStream_accumulateContent = function _AssistantStream_accumulateContent(contentElement, currentContent) { - return AssistantStream_a.accumulateDelta(currentContent, contentElement); -}, _AssistantStream_handleRun = function _AssistantStream_handleRun(event) { - tslib_classPrivateFieldSet(this, _AssistantStream_currentRunSnapshot, event.data, "f"); - switch (event.event) { - case 'thread.run.created': - break; - case 'thread.run.queued': - break; - case 'thread.run.in_progress': - break; - case 'thread.run.requires_action': - case 'thread.run.cancelled': - case 'thread.run.failed': - case 'thread.run.completed': - case 'thread.run.expired': - case 'thread.run.incomplete': - tslib_classPrivateFieldSet(this, _AssistantStream_finalRun, event.data, "f"); - if (tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")) { - this._emit('toolCallDone', tslib_classPrivateFieldGet(this, _AssistantStream_currentToolCall, "f")); - tslib_classPrivateFieldSet(this, _AssistantStream_currentToolCall, undefined, "f"); - } - break; - case 'thread.run.cancelling': - break; - } -}; -function AssistantStream_assertNever(_x) { } -//# sourceMappingURL=AssistantStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/runs/runs.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - -/** - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ -class Runs extends resource_APIResource { - constructor() { - super(...arguments); - this.steps = new Steps(this._client); - } - create(threadID, params, options) { - const { include, ...body } = params; - return this._client.post(path_path `/threads/${threadID}/runs`, { - query: { include }, - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - stream: params.stream ?? false, - }); - } - /** - * Retrieves a run. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - retrieve(runID, params, options) { - const { thread_id } = params; - return this._client.get(path_path `/threads/${thread_id}/runs/${runID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Modifies a run. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - update(runID, params, options) { - const { thread_id, ...body } = params; - return this._client.post(path_path `/threads/${thread_id}/runs/${runID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of runs belonging to a thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - list(threadID, query = {}, options) { - return this._client.getAPIList(path_path `/threads/${threadID}/runs`, (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Cancels a run that is `in_progress`. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - cancel(runID, params, options) { - const { thread_id } = params; - return this._client.post(path_path `/threads/${thread_id}/runs/${runID}/cancel`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * A helper to create a run an poll for a terminal state. More information on Run - * lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async createAndPoll(threadId, body, options) { - const run = await this.create(threadId, body, options); - return await this.poll(run.id, { thread_id: threadId }, options); - } - /** - * Create a Run stream - * - * @deprecated use `stream` instead - */ - createAndStream(threadId, body, options) { - return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); - } - /** - * A helper to poll a run status until it reaches a terminal state. More - * information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async poll(runId, params, options) { - const headers = headers_buildHeaders([ - options?.headers, - { - 'X-Stainless-Poll-Helper': 'true', - 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, - }, - ]); - while (true) { - const { data: run, response } = await this.retrieve(runId, params, { - ...options, - headers: { ...options?.headers, ...headers }, - }).withResponse(); - switch (run.status) { - //If we are in any sort of intermediate state we poll - case 'queued': - case 'in_progress': - case 'cancelling': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep_sleep(sleepInterval); - break; - //We return the run in any terminal state. - case 'requires_action': - case 'incomplete': - case 'cancelled': - case 'completed': - case 'failed': - case 'expired': - return run; - } - } - } - /** - * Create a Run stream - */ - stream(threadId, body, options) { - return AssistantStream.createAssistantStream(threadId, this._client.beta.threads.runs, body, options); - } - submitToolOutputs(runID, params, options) { - const { thread_id, ...body } = params; - return this._client.post(path_path `/threads/${thread_id}/runs/${runID}/submit_tool_outputs`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - stream: params.stream ?? false, - }); - } - /** - * A helper to submit a tool output to a run and poll for a terminal run state. - * More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async submitToolOutputsAndPoll(runId, params, options) { - const run = await this.submitToolOutputs(runId, params, options); - return await this.poll(run.id, params, options); - } - /** - * Submit the tool outputs from a previous run and stream the run to a terminal - * state. More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - submitToolOutputsStream(runId, params, options) { - return AssistantStream.createToolAssistantStream(runId, this._client.beta.threads.runs, params, options); - } -} -Runs.Steps = Steps; -//# sourceMappingURL=runs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/threads/threads.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - -/** - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ -class threads_Threads extends resource_APIResource { - constructor() { - super(...arguments); - this.runs = new Runs(this._client); - this.messages = new threads_messages_Messages(this._client); - } - /** - * Create a thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - create(body = {}, options) { - return this._client.post('/threads', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieves a thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - retrieve(threadID, options) { - return this._client.get(path_path `/threads/${threadID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Modifies a thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - update(threadID, body, options) { - return this._client.post(path_path `/threads/${threadID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Delete a thread. - * - * @deprecated The Assistants API is deprecated in favor of the Responses API - */ - delete(threadID, options) { - return this._client.delete(path_path `/threads/${threadID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - createAndRun(body, options) { - return this._client.post('/threads/runs', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - stream: body.stream ?? false, - }); - } - /** - * A helper to create a thread, start a run and then poll for a terminal state. - * More information on Run lifecycles can be found here: - * https://platform.openai.com/docs/assistants/how-it-works/runs-and-run-steps - */ - async createAndRunPoll(body, options) { - const run = await this.createAndRun(body, options); - return await this.runs.poll(run.id, { thread_id: run.thread_id }, options); - } - /** - * Create a thread and stream the run back - */ - createAndRunStream(body, options) { - return AssistantStream.createThreadAssistantStream(body, this._client.beta.threads, options); - } -} -threads_Threads.Runs = Runs; -threads_Threads.Messages = threads_messages_Messages; -//# sourceMappingURL=threads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/beta/beta.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - -class beta_Beta extends resource_APIResource { - constructor() { - super(...arguments); - this.realtime = new Realtime(this._client); - this.chatkit = new ChatKit(this._client); - this.assistants = new Assistants(this._client); - this.threads = new threads_Threads(this._client); - } -} -beta_Beta.Realtime = Realtime; -beta_Beta.ChatKit = ChatKit; -beta_Beta.Assistants = Assistants; -beta_Beta.Threads = threads_Threads; -//# sourceMappingURL=beta.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/completions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class resources_completions_Completions extends resource_APIResource { - create(body, options) { - return this._client.post('/completions', { body, ...options, stream: body.stream ?? false }); - } -} -//# sourceMappingURL=completions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/files/content.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Content extends resource_APIResource { - /** - * Retrieve Container File Content - */ - retrieve(fileID, params, options) { - const { container_id } = params; - return this._client.get(path_path `/containers/${container_id}/files/${fileID}/content`, { - ...options, - headers: headers_buildHeaders([{ Accept: 'application/binary' }, options?.headers]), - __binaryResponse: true, - }); - } -} -//# sourceMappingURL=content.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/files/files.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -class files_Files extends resource_APIResource { - constructor() { - super(...arguments); - this.content = new Content(this._client); - } - /** - * Create a Container File - * - * You can send either a multipart/form-data request with the raw file content, or - * a JSON request with a file ID. - */ - create(containerID, body, options) { - return this._client.post(path_path `/containers/${containerID}/files`, uploads_multipartFormRequestOptions({ body, ...options }, this._client)); - } - /** - * Retrieve Container File - */ - retrieve(fileID, params, options) { - const { container_id } = params; - return this._client.get(path_path `/containers/${container_id}/files/${fileID}`, options); - } - /** - * List Container files - */ - list(containerID, query = {}, options) { - return this._client.getAPIList(path_path `/containers/${containerID}/files`, (CursorPage), { - query, - ...options, - }); - } - /** - * Delete Container File - */ - delete(fileID, params, options) { - const { container_id } = params; - return this._client.delete(path_path `/containers/${container_id}/files/${fileID}`, { - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } -} -files_Files.Content = Content; -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/containers/containers.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -class Containers extends resource_APIResource { - constructor() { - super(...arguments); - this.files = new files_Files(this._client); - } - /** - * Create Container - */ - create(body, options) { - return this._client.post('/containers', { body, ...options }); - } - /** - * Retrieve Container - */ - retrieve(containerID, options) { - return this._client.get(path_path `/containers/${containerID}`, options); - } - /** - * List Containers - */ - list(query = {}, options) { - return this._client.getAPIList('/containers', (CursorPage), { query, ...options }); - } - /** - * Delete Container - */ - delete(containerID, options) { - return this._client.delete(path_path `/containers/${containerID}`, { - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } -} -Containers.Files = files_Files; -//# sourceMappingURL=containers.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/conversations/items.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Items extends resource_APIResource { - /** - * Create items in a conversation with the given ID. - */ - create(conversationID, params, options) { - const { include, ...body } = params; - return this._client.post(path_path `/conversations/${conversationID}/items`, { - query: { include }, - body, - ...options, - }); - } - /** - * Get a single item from a conversation with the given IDs. - */ - retrieve(itemID, params, options) { - const { conversation_id, ...query } = params; - return this._client.get(path_path `/conversations/${conversation_id}/items/${itemID}`, { query, ...options }); - } - /** - * List all items for a conversation with the given ID. - */ - list(conversationID, query = {}, options) { - return this._client.getAPIList(path_path `/conversations/${conversationID}/items`, (ConversationCursorPage), { query, ...options }); - } - /** - * Delete an item from a conversation with the given IDs. - */ - delete(itemID, params, options) { - const { conversation_id } = params; - return this._client.delete(path_path `/conversations/${conversation_id}/items/${itemID}`, options); - } -} -//# sourceMappingURL=items.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/conversations/conversations.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class Conversations extends resource_APIResource { - constructor() { - super(...arguments); - this.items = new Items(this._client); - } - /** - * Create a conversation. - */ - create(body = {}, options) { - return this._client.post('/conversations', { body, ...options }); - } - /** - * Get a conversation - */ - retrieve(conversationID, options) { - return this._client.get(path_path `/conversations/${conversationID}`, options); - } - /** - * Update a conversation - */ - update(conversationID, body, options) { - return this._client.post(path_path `/conversations/${conversationID}`, { body, ...options }); - } - /** - * Delete a conversation. Items in the conversation will not be deleted. - */ - delete(conversationID, options) { - return this._client.delete(path_path `/conversations/${conversationID}`, options); - } -} -Conversations.Items = Items; -//# sourceMappingURL=conversations.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/embeddings.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class embeddings_Embeddings extends resource_APIResource { - /** - * Creates an embedding vector representing the input text. - * - * @example - * ```ts - * const createEmbeddingResponse = - * await client.embeddings.create({ - * input: 'The quick brown fox jumped over the lazy dog', - * model: 'text-embedding-3-small', - * }); - * ``` - */ - create(body, options) { - const hasUserProvidedEncodingFormat = !!body.encoding_format; - // No encoding_format specified, defaulting to base64 for performance reasons - // See https://github.com/openai/openai-node/pull/1312 - let encoding_format = hasUserProvidedEncodingFormat ? body.encoding_format : 'base64'; - if (hasUserProvidedEncodingFormat) { - log_loggerFor(this._client).debug('embeddings/user defined encoding_format:', body.encoding_format); - } - const response = this._client.post('/embeddings', { - body: { - ...body, - encoding_format: encoding_format, - }, - ...options, - }); - // if the user specified an encoding_format, return the response as-is - if (hasUserProvidedEncodingFormat) { - return response; - } - // in this stage, we are sure the user did not specify an encoding_format - // and we defaulted to base64 for performance reasons - // we are sure then that the response is base64 encoded, let's decode it - // the returned result will be a float32 array since this is OpenAI API's default encoding - log_loggerFor(this._client).debug('embeddings/decoding base64 embeddings from base64'); - return response._thenUnwrap((response) => { - if (response && response.data) { - response.data.forEach((embeddingBase64Obj) => { - const embeddingBase64Str = embeddingBase64Obj.embedding; - embeddingBase64Obj.embedding = toFloat32Array(embeddingBase64Str); - }); - } - return response; - }); - } -} -//# sourceMappingURL=embeddings.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/output-items.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class OutputItems extends resource_APIResource { - /** - * Get an evaluation run output item by ID. - */ - retrieve(outputItemID, params, options) { - const { eval_id, run_id } = params; - return this._client.get(path_path `/evals/${eval_id}/runs/${run_id}/output_items/${outputItemID}`, options); - } - /** - * Get a list of output items for an evaluation run. - */ - list(runID, params, options) { - const { eval_id, ...query } = params; - return this._client.getAPIList(path_path `/evals/${eval_id}/runs/${runID}/output_items`, (CursorPage), { query, ...options }); - } -} -//# sourceMappingURL=output-items.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/runs/runs.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class runs_Runs extends resource_APIResource { - constructor() { - super(...arguments); - this.outputItems = new OutputItems(this._client); - } - /** - * Kicks off a new run for a given evaluation, specifying the data source, and what - * model configuration to use to test. The datasource will be validated against the - * schema specified in the config of the evaluation. - */ - create(evalID, body, options) { - return this._client.post(path_path `/evals/${evalID}/runs`, { body, ...options }); - } - /** - * Get an evaluation run by ID. - */ - retrieve(runID, params, options) { - const { eval_id } = params; - return this._client.get(path_path `/evals/${eval_id}/runs/${runID}`, options); - } - /** - * Get a list of runs for an evaluation. - */ - list(evalID, query = {}, options) { - return this._client.getAPIList(path_path `/evals/${evalID}/runs`, (CursorPage), { - query, - ...options, - }); - } - /** - * Delete an eval run. - */ - delete(runID, params, options) { - const { eval_id } = params; - return this._client.delete(path_path `/evals/${eval_id}/runs/${runID}`, options); - } - /** - * Cancel an ongoing evaluation run. - */ - cancel(runID, params, options) { - const { eval_id } = params; - return this._client.post(path_path `/evals/${eval_id}/runs/${runID}`, options); - } -} -runs_Runs.OutputItems = OutputItems; -//# sourceMappingURL=runs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/evals/evals.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class Evals extends resource_APIResource { - constructor() { - super(...arguments); - this.runs = new runs_Runs(this._client); - } - /** - * Create the structure of an evaluation that can be used to test a model's - * performance. An evaluation is a set of testing criteria and the config for a - * data source, which dictates the schema of the data used in the evaluation. After - * creating an evaluation, you can run it on different models and model parameters. - * We support several types of graders and datasources. For more information, see - * the [Evals guide](https://platform.openai.com/docs/guides/evals). - */ - create(body, options) { - return this._client.post('/evals', { body, ...options }); - } - /** - * Get an evaluation by ID. - */ - retrieve(evalID, options) { - return this._client.get(path_path `/evals/${evalID}`, options); - } - /** - * Update certain properties of an evaluation. - */ - update(evalID, body, options) { - return this._client.post(path_path `/evals/${evalID}`, { body, ...options }); - } - /** - * List evaluations for a project. - */ - list(query = {}, options) { - return this._client.getAPIList('/evals', (CursorPage), { query, ...options }); - } - /** - * Delete an evaluation. - */ - delete(evalID, options) { - return this._client.delete(path_path `/evals/${evalID}`, options); - } -} -Evals.Runs = runs_Runs; -//# sourceMappingURL=evals.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/files.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -class resources_files_Files extends resource_APIResource { - /** - * Upload a file that can be used across various endpoints. Individual files can be - * up to 512 MB, and the size of all files uploaded by one organization can be up - * to 1 TB. - * - * - The Assistants API supports files up to 2 million tokens and of specific file - * types. See the - * [Assistants Tools guide](https://platform.openai.com/docs/assistants/tools) - * for details. - * - The Fine-tuning API only supports `.jsonl` files. The input also has certain - * required formats for fine-tuning - * [chat](https://platform.openai.com/docs/api-reference/fine-tuning/chat-input) - * or - * [completions](https://platform.openai.com/docs/api-reference/fine-tuning/completions-input) - * models. - * - The Batch API only supports `.jsonl` files up to 200 MB in size. The input - * also has a specific required - * [format](https://platform.openai.com/docs/api-reference/batch/request-input). - * - * Please [contact us](https://help.openai.com/) if you need to increase these - * storage limits. - */ - create(body, options) { - return this._client.post('/files', uploads_multipartFormRequestOptions({ body, ...options }, this._client)); - } - /** - * Returns information about a specific file. - */ - retrieve(fileID, options) { - return this._client.get(path_path `/files/${fileID}`, options); - } - /** - * Returns a list of files. - */ - list(query = {}, options) { - return this._client.getAPIList('/files', (CursorPage), { query, ...options }); - } - /** - * Delete a file and remove it from all vector stores. - */ - delete(fileID, options) { - return this._client.delete(path_path `/files/${fileID}`, options); - } - /** - * Returns the contents of the specified file. - */ - content(fileID, options) { - return this._client.get(path_path `/files/${fileID}/content`, { - ...options, - headers: headers_buildHeaders([{ Accept: 'application/binary' }, options?.headers]), - __binaryResponse: true, - }); - } - /** - * Waits for the given file to be processed, default timeout is 30 mins. - */ - async waitForProcessing(id, { pollInterval = 5000, maxWait = 30 * 60 * 1000 } = {}) { - const TERMINAL_STATES = new Set(['processed', 'error', 'deleted']); - const start = Date.now(); - let file = await this.retrieve(id); - while (!file.status || !TERMINAL_STATES.has(file.status)) { - await sleep_sleep(pollInterval); - file = await this.retrieve(id); - if (Date.now() - start > maxWait) { - throw new error_APIConnectionTimeoutError({ - message: `Giving up on waiting for file ${id} to finish processing after ${maxWait} milliseconds.`, - }); - } - } - return file; - } -} -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/methods.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Methods extends resource_APIResource { -} -//# sourceMappingURL=methods.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/graders.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Graders extends resource_APIResource { - /** - * Run a grader. - * - * @example - * ```ts - * const response = await client.fineTuning.alpha.graders.run({ - * grader: { - * input: 'input', - * name: 'name', - * operation: 'eq', - * reference: 'reference', - * type: 'string_check', - * }, - * model_sample: 'model_sample', - * }); - * ``` - */ - run(body, options) { - return this._client.post('/fine_tuning/alpha/graders/run', { body, ...options }); - } - /** - * Validate a grader. - * - * @example - * ```ts - * const response = - * await client.fineTuning.alpha.graders.validate({ - * grader: { - * input: 'input', - * name: 'name', - * operation: 'eq', - * reference: 'reference', - * type: 'string_check', - * }, - * }); - * ``` - */ - validate(body, options) { - return this._client.post('/fine_tuning/alpha/graders/validate', { body, ...options }); - } -} -//# sourceMappingURL=graders.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/alpha/alpha.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Alpha extends resource_APIResource { - constructor() { - super(...arguments); - this.graders = new Graders(this._client); - } -} -Alpha.Graders = Graders; -//# sourceMappingURL=alpha.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/permissions.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Permissions extends resource_APIResource { - /** - * **NOTE:** Calling this endpoint requires an [admin API key](../admin-api-keys). - * - * This enables organization owners to share fine-tuned models with other projects - * in their organization. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const permissionCreateResponse of client.fineTuning.checkpoints.permissions.create( - * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', - * { project_ids: ['string'] }, - * )) { - * // ... - * } - * ``` - */ - create(fineTunedModelCheckpoint, body, options) { - return this._client.getAPIList(path_path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, (pagination_Page), { body, method: 'post', ...options }); - } - /** - * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). - * - * Organization owners can use this endpoint to view all permissions for a - * fine-tuned model checkpoint. - * - * @example - * ```ts - * const permission = - * await client.fineTuning.checkpoints.permissions.retrieve( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - retrieve(fineTunedModelCheckpoint, query = {}, options) { - return this._client.get(path_path `/fine_tuning/checkpoints/${fineTunedModelCheckpoint}/permissions`, { - query, - ...options, - }); - } - /** - * **NOTE:** This endpoint requires an [admin API key](../admin-api-keys). - * - * Organization owners can use this endpoint to delete a permission for a - * fine-tuned model checkpoint. - * - * @example - * ```ts - * const permission = - * await client.fineTuning.checkpoints.permissions.delete( - * 'cp_zc4Q7MP6XxulcVzj4MZdwsAB', - * { - * fine_tuned_model_checkpoint: - * 'ft:gpt-4o-mini-2024-07-18:org:weather:B7R9VjQd', - * }, - * ); - * ``` - */ - delete(permissionID, params, options) { - const { fine_tuned_model_checkpoint } = params; - return this._client.delete(path_path `/fine_tuning/checkpoints/${fine_tuned_model_checkpoint}/permissions/${permissionID}`, options); - } -} -//# sourceMappingURL=permissions.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/checkpoints/checkpoints.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Checkpoints extends resource_APIResource { - constructor() { - super(...arguments); - this.permissions = new Permissions(this._client); - } -} -Checkpoints.Permissions = Permissions; -//# sourceMappingURL=checkpoints.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/checkpoints.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class checkpoints_Checkpoints extends resource_APIResource { - /** - * List checkpoints for a fine-tuning job. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const fineTuningJobCheckpoint of client.fineTuning.jobs.checkpoints.list( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * )) { - * // ... - * } - * ``` - */ - list(fineTuningJobID, query = {}, options) { - return this._client.getAPIList(path_path `/fine_tuning/jobs/${fineTuningJobID}/checkpoints`, (CursorPage), { query, ...options }); - } -} -//# sourceMappingURL=checkpoints.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/jobs/jobs.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class Jobs extends resource_APIResource { - constructor() { - super(...arguments); - this.checkpoints = new checkpoints_Checkpoints(this._client); - } - /** - * Creates a fine-tuning job which begins the process of creating a new model from - * a given dataset. - * - * Response includes details of the enqueued job including job status and the name - * of the fine-tuned models once complete. - * - * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.create({ - * model: 'gpt-4o-mini', - * training_file: 'file-abc123', - * }); - * ``` - */ - create(body, options) { - return this._client.post('/fine_tuning/jobs', { body, ...options }); - } - /** - * Get info about a fine-tuning job. - * - * [Learn more about fine-tuning](https://platform.openai.com/docs/guides/model-optimization) - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.retrieve( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - retrieve(fineTuningJobID, options) { - return this._client.get(path_path `/fine_tuning/jobs/${fineTuningJobID}`, options); - } - /** - * List your organization's fine-tuning jobs - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const fineTuningJob of client.fineTuning.jobs.list()) { - * // ... - * } - * ``` - */ - list(query = {}, options) { - return this._client.getAPIList('/fine_tuning/jobs', (CursorPage), { query, ...options }); - } - /** - * Immediately cancel a fine-tune job. - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.cancel( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - cancel(fineTuningJobID, options) { - return this._client.post(path_path `/fine_tuning/jobs/${fineTuningJobID}/cancel`, options); - } - /** - * Get status updates for a fine-tuning job. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const fineTuningJobEvent of client.fineTuning.jobs.listEvents( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * )) { - * // ... - * } - * ``` - */ - listEvents(fineTuningJobID, query = {}, options) { - return this._client.getAPIList(path_path `/fine_tuning/jobs/${fineTuningJobID}/events`, (CursorPage), { query, ...options }); - } - /** - * Pause a fine-tune job. - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.pause( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - pause(fineTuningJobID, options) { - return this._client.post(path_path `/fine_tuning/jobs/${fineTuningJobID}/pause`, options); - } - /** - * Resume a fine-tune job. - * - * @example - * ```ts - * const fineTuningJob = await client.fineTuning.jobs.resume( - * 'ft-AF1WoRqd3aJAHsqc9NY7iL8F', - * ); - * ``` - */ - resume(fineTuningJobID, options) { - return this._client.post(path_path `/fine_tuning/jobs/${fineTuningJobID}/resume`, options); - } -} -Jobs.Checkpoints = checkpoints_Checkpoints; -//# sourceMappingURL=jobs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/fine-tuning/fine-tuning.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - -class FineTuning extends resource_APIResource { - constructor() { - super(...arguments); - this.methods = new Methods(this._client); - this.jobs = new Jobs(this._client); - this.checkpoints = new Checkpoints(this._client); - this.alpha = new Alpha(this._client); - } -} -FineTuning.Methods = Methods; -FineTuning.Jobs = Jobs; -FineTuning.Checkpoints = Checkpoints; -FineTuning.Alpha = Alpha; -//# sourceMappingURL=fine-tuning.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/grader-models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class GraderModels extends resource_APIResource { -} -//# sourceMappingURL=grader-models.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/graders/graders.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class graders_Graders extends resource_APIResource { - constructor() { - super(...arguments); - this.graderModels = new GraderModels(this._client); - } -} -graders_Graders.GraderModels = GraderModels; -//# sourceMappingURL=graders.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/images.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - -class Images extends resource_APIResource { - /** - * Creates a variation of a given image. This endpoint only supports `dall-e-2`. - * - * @example - * ```ts - * const imagesResponse = await client.images.createVariation({ - * image: fs.createReadStream('otter.png'), - * }); - * ``` - */ - createVariation(body, options) { - return this._client.post('/images/variations', uploads_multipartFormRequestOptions({ body, ...options }, this._client)); - } - edit(body, options) { - return this._client.post('/images/edits', uploads_multipartFormRequestOptions({ body, ...options, stream: body.stream ?? false }, this._client)); - } - generate(body, options) { - return this._client.post('/images/generations', { body, ...options, stream: body.stream ?? false }); - } -} -//# sourceMappingURL=images.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/models.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class resources_models_Models extends resource_APIResource { - /** - * Retrieves a model instance, providing basic information about the model such as - * the owner and permissioning. - */ - retrieve(model, options) { - return this._client.get(path_path `/models/${model}`, options); - } - /** - * Lists the currently available models, and provides basic information about each - * one such as the owner and availability. - */ - list(options) { - return this._client.getAPIList('/models', (pagination_Page), options); - } - /** - * Delete a fine-tuned model. You must have the Owner role in your organization to - * delete a model. - */ - delete(model, options) { - return this._client.delete(path_path `/models/${model}`, options); - } -} -//# sourceMappingURL=models.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/moderations.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class Moderations extends resource_APIResource { - /** - * Classifies if text and/or image inputs are potentially harmful. Learn more in - * the [moderation guide](https://platform.openai.com/docs/guides/moderation). - */ - create(body, options) { - return this._client.post('/moderations', { body, ...options }); - } -} -//# sourceMappingURL=moderations.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/realtime/calls.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Calls extends resource_APIResource { - /** - * Accept an incoming SIP call and configure the realtime session that will handle - * it. - * - * @example - * ```ts - * await client.realtime.calls.accept('call_id', { - * type: 'realtime', - * }); - * ``` - */ - accept(callID, body, options) { - return this._client.post(path_path `/realtime/calls/${callID}/accept`, { - body, - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } - /** - * End an active Realtime API call, whether it was initiated over SIP or WebRTC. - * - * @example - * ```ts - * await client.realtime.calls.hangup('call_id'); - * ``` - */ - hangup(callID, options) { - return this._client.post(path_path `/realtime/calls/${callID}/hangup`, { - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } - /** - * Transfer an active SIP call to a new destination using the SIP REFER verb. - * - * @example - * ```ts - * await client.realtime.calls.refer('call_id', { - * target_uri: 'tel:+14155550123', - * }); - * ``` - */ - refer(callID, body, options) { - return this._client.post(path_path `/realtime/calls/${callID}/refer`, { - body, - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } - /** - * Decline an incoming SIP call by returning a SIP status code to the caller. - * - * @example - * ```ts - * await client.realtime.calls.reject('call_id'); - * ``` - */ - reject(callID, body = {}, options) { - return this._client.post(path_path `/realtime/calls/${callID}/reject`, { - body, - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } -} -//# sourceMappingURL=calls.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/realtime/client-secrets.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class ClientSecrets extends resource_APIResource { - /** - * Create a Realtime client secret with an associated session configuration. - * - * @example - * ```ts - * const clientSecret = - * await client.realtime.clientSecrets.create(); - * ``` - */ - create(body, options) { - return this._client.post('/realtime/client_secrets', { body, ...options }); - } -} -//# sourceMappingURL=client-secrets.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/realtime/realtime.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class realtime_Realtime extends resource_APIResource { - constructor() { - super(...arguments); - this.clientSecrets = new ClientSecrets(this._client); - this.calls = new Calls(this._client); - } -} -realtime_Realtime.ClientSecrets = ClientSecrets; -realtime_Realtime.Calls = Calls; -//# sourceMappingURL=realtime.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/ResponsesParser.mjs - - -function maybeParseResponse(response, params) { - if (!params || !ResponsesParser_hasAutoParseableInput(params)) { - return { - ...response, - output_parsed: null, - output: response.output.map((item) => { - if (item.type === 'function_call') { - return { - ...item, - parsed_arguments: null, - }; - } - if (item.type === 'message') { - return { - ...item, - content: item.content.map((content) => ({ - ...content, - parsed: null, - })), - }; - } - else { - return item; - } - }), - }; - } - return parseResponse(response, params); -} -function parseResponse(response, params) { - const output = response.output.map((item) => { - if (item.type === 'function_call') { - return { - ...item, - parsed_arguments: ResponsesParser_parseToolCall(params, item), - }; - } - if (item.type === 'message') { - const content = item.content.map((content) => { - if (content.type === 'output_text') { - return { - ...content, - parsed: parseTextFormat(params, content.text), - }; - } - return content; - }); - return { - ...item, - content, - }; - } - return item; - }); - const parsed = Object.assign({}, response, { output }); - if (!Object.getOwnPropertyDescriptor(response, 'output_text')) { - addOutputText(parsed); - } - Object.defineProperty(parsed, 'output_parsed', { - enumerable: true, - get() { - for (const output of parsed.output) { - if (output.type !== 'message') { - continue; - } - for (const content of output.content) { - if (content.type === 'output_text' && content.parsed !== null) { - return content.parsed; - } - } - } - return null; - }, - }); - return parsed; -} -function parseTextFormat(params, content) { - if (params.text?.format?.type !== 'json_schema') { - return null; - } - if ('$parseRaw' in params.text?.format) { - const text_format = params.text?.format; - return text_format.$parseRaw(content); - } - return JSON.parse(content); -} -function ResponsesParser_hasAutoParseableInput(params) { - if (isAutoParsableResponseFormat(params.text?.format)) { - return true; - } - return false; -} -function ResponsesParser_makeParseableResponseTool(tool, { parser, callback, }) { - const obj = { ...tool }; - Object.defineProperties(obj, { - $brand: { - value: 'auto-parseable-tool', - enumerable: false, - }, - $parseRaw: { - value: parser, - enumerable: false, - }, - $callback: { - value: callback, - enumerable: false, - }, - }); - return obj; -} -function ResponsesParser_isAutoParsableTool(tool) { - return tool?.['$brand'] === 'auto-parseable-tool'; -} -function getInputToolByName(input_tools, name) { - return input_tools.find((tool) => tool.type === 'function' && tool.name === name); -} -function ResponsesParser_parseToolCall(params, toolCall) { - const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); - return { - ...toolCall, - ...toolCall, - parsed_arguments: ResponsesParser_isAutoParsableTool(inputTool) ? inputTool.$parseRaw(toolCall.arguments) - : inputTool?.strict ? JSON.parse(toolCall.arguments) - : null, - }; -} -function ResponsesParser_shouldParseToolCall(params, toolCall) { - if (!params) { - return false; - } - const inputTool = getInputToolByName(params.tools ?? [], toolCall.name); - return ResponsesParser_isAutoParsableTool(inputTool) || inputTool?.strict || false; -} -function ResponsesParser_validateInputTools(tools) { - for (const tool of tools ?? []) { - if (tool.type !== 'function') { - throw new OpenAIError(`Currently only \`function\` tool types support auto-parsing; Received \`${tool.type}\``); - } - if (tool.function.strict !== true) { - throw new OpenAIError(`The \`${tool.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`); - } - } -} -function addOutputText(rsp) { - const texts = []; - for (const output of rsp.output) { - if (output.type !== 'message') { - continue; - } - for (const content of output.content) { - if (content.type === 'output_text') { - texts.push(content.text); - } - } - } - rsp.output_text = texts.join(''); -} -//# sourceMappingURL=ResponsesParser.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/responses/ResponseStream.mjs -var _ResponseStream_instances, _ResponseStream_params, _ResponseStream_currentResponseSnapshot, _ResponseStream_finalResponse, _ResponseStream_beginRequest, _ResponseStream_addEvent, _ResponseStream_endRequest, _ResponseStream_accumulateResponse; - - - - -class ResponseStream extends EventStream { - constructor(params) { - super(); - _ResponseStream_instances.add(this); - _ResponseStream_params.set(this, void 0); - _ResponseStream_currentResponseSnapshot.set(this, void 0); - _ResponseStream_finalResponse.set(this, void 0); - tslib_classPrivateFieldSet(this, _ResponseStream_params, params, "f"); - } - static createResponse(client, params, options) { - const runner = new ResponseStream(params); - runner._run(() => runner._createOrRetrieveResponse(client, params, { - ...options, - headers: { ...options?.headers, 'X-Stainless-Helper-Method': 'stream' }, - })); - return runner; - } - async _createOrRetrieveResponse(client, params, options) { - const signal = options?.signal; - if (signal) { - if (signal.aborted) - this.controller.abort(); - signal.addEventListener('abort', () => this.controller.abort()); - } - tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_beginRequest).call(this); - let stream; - let starting_after = null; - if ('response_id' in params) { - stream = await client.responses.retrieve(params.response_id, { stream: true }, { ...options, signal: this.controller.signal, stream: true }); - starting_after = params.starting_after ?? null; - } - else { - stream = await client.responses.create({ ...params, stream: true }, { ...options, signal: this.controller.signal }); - } - this._connected(); - for await (const event of stream) { - tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_addEvent).call(this, event, starting_after); - } - if (stream.controller.signal?.aborted) { - throw new error_APIUserAbortError(); - } - return tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_endRequest).call(this); - } - [(_ResponseStream_params = new WeakMap(), _ResponseStream_currentResponseSnapshot = new WeakMap(), _ResponseStream_finalResponse = new WeakMap(), _ResponseStream_instances = new WeakSet(), _ResponseStream_beginRequest = function _ResponseStream_beginRequest() { - if (this.ended) - return; - tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); - }, _ResponseStream_addEvent = function _ResponseStream_addEvent(event, starting_after) { - if (this.ended) - return; - const maybeEmit = (name, event) => { - if (starting_after == null || event.sequence_number > starting_after) { - this._emit(name, event); - } - }; - const response = tslib_classPrivateFieldGet(this, _ResponseStream_instances, "m", _ResponseStream_accumulateResponse).call(this, event); - maybeEmit('event', event); - switch (event.type) { - case 'response.output_text.delta': { - const output = response.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'message') { - const content = output.content[event.content_index]; - if (!content) { - throw new error_OpenAIError(`missing content at index ${event.content_index}`); - } - if (content.type !== 'output_text') { - throw new error_OpenAIError(`expected content to be 'output_text', got ${content.type}`); - } - maybeEmit('response.output_text.delta', { - ...event, - snapshot: content.text, - }); - } - break; - } - case 'response.function_call_arguments.delta': { - const output = response.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'function_call') { - maybeEmit('response.function_call_arguments.delta', { - ...event, - snapshot: output.arguments, - }); - } - break; - } - default: - maybeEmit(event.type, event); - break; - } - }, _ResponseStream_endRequest = function _ResponseStream_endRequest() { - if (this.ended) { - throw new error_OpenAIError(`stream has ended, this shouldn't happen`); - } - const snapshot = tslib_classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); - if (!snapshot) { - throw new error_OpenAIError(`request ended without sending any events`); - } - tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, undefined, "f"); - const parsedResponse = finalizeResponse(snapshot, tslib_classPrivateFieldGet(this, _ResponseStream_params, "f")); - tslib_classPrivateFieldSet(this, _ResponseStream_finalResponse, parsedResponse, "f"); - return parsedResponse; - }, _ResponseStream_accumulateResponse = function _ResponseStream_accumulateResponse(event) { - let snapshot = tslib_classPrivateFieldGet(this, _ResponseStream_currentResponseSnapshot, "f"); - if (!snapshot) { - if (event.type !== 'response.created') { - throw new error_OpenAIError(`When snapshot hasn't been set yet, expected 'response.created' event, got ${event.type}`); - } - snapshot = tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); - return snapshot; - } - switch (event.type) { - case 'response.output_item.added': { - snapshot.output.push(event.item); - break; - } - case 'response.content_part.added': { - const output = snapshot.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - const type = output.type; - const part = event.part; - if (type === 'message' && part.type !== 'reasoning_text') { - output.content.push(part); - } - else if (type === 'reasoning' && part.type === 'reasoning_text') { - if (!output.content) { - output.content = []; - } - output.content.push(part); - } - break; - } - case 'response.output_text.delta': { - const output = snapshot.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'message') { - const content = output.content[event.content_index]; - if (!content) { - throw new error_OpenAIError(`missing content at index ${event.content_index}`); - } - if (content.type !== 'output_text') { - throw new error_OpenAIError(`expected content to be 'output_text', got ${content.type}`); - } - content.text += event.delta; - } - break; - } - case 'response.function_call_arguments.delta': { - const output = snapshot.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'function_call') { - output.arguments += event.delta; - } - break; - } - case 'response.reasoning_text.delta': { - const output = snapshot.output[event.output_index]; - if (!output) { - throw new error_OpenAIError(`missing output at index ${event.output_index}`); - } - if (output.type === 'reasoning') { - const content = output.content?.[event.content_index]; - if (!content) { - throw new error_OpenAIError(`missing content at index ${event.content_index}`); - } - if (content.type !== 'reasoning_text') { - throw new error_OpenAIError(`expected content to be 'reasoning_text', got ${content.type}`); - } - content.text += event.delta; - } - break; - } - case 'response.completed': { - tslib_classPrivateFieldSet(this, _ResponseStream_currentResponseSnapshot, event.response, "f"); - break; - } - } - return snapshot; - }, Symbol.asyncIterator)]() { - const pushQueue = []; - const readQueue = []; - let done = false; - this.on('event', (event) => { - const reader = readQueue.shift(); - if (reader) { - reader.resolve(event); - } - else { - pushQueue.push(event); - } - }); - this.on('end', () => { - done = true; - for (const reader of readQueue) { - reader.resolve(undefined); - } - readQueue.length = 0; - }); - this.on('abort', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - this.on('error', (err) => { - done = true; - for (const reader of readQueue) { - reader.reject(err); - } - readQueue.length = 0; - }); - return { - next: async () => { - if (!pushQueue.length) { - if (done) { - return { value: undefined, done: true }; - } - return new Promise((resolve, reject) => readQueue.push({ resolve, reject })).then((event) => (event ? { value: event, done: false } : { value: undefined, done: true })); - } - const event = pushQueue.shift(); - return { value: event, done: false }; - }, - return: async () => { - this.abort(); - return { value: undefined, done: true }; - }, - }; - } - /** - * @returns a promise that resolves with the final Response, or rejects - * if an error occurred or the stream ended prematurely without producing a REsponse. - */ - async finalResponse() { - await this.done(); - const response = tslib_classPrivateFieldGet(this, _ResponseStream_finalResponse, "f"); - if (!response) - throw new error_OpenAIError('stream ended without producing a ChatCompletion'); - return response; - } -} -function finalizeResponse(snapshot, params) { - return maybeParseResponse(snapshot, params); -} -//# sourceMappingURL=ResponseStream.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/input-items.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class InputItems extends resource_APIResource { - /** - * Returns a list of input items for a given response. - * - * @example - * ```ts - * // Automatically fetches more pages as needed. - * for await (const responseItem of client.responses.inputItems.list( - * 'response_id', - * )) { - * // ... - * } - * ``` - */ - list(responseID, query = {}, options) { - return this._client.getAPIList(path_path `/responses/${responseID}/input_items`, (CursorPage), { query, ...options }); - } -} -//# sourceMappingURL=input-items.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/input-tokens.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - -class InputTokens extends resource_APIResource { - /** - * Get input token counts - * - * @example - * ```ts - * const response = await client.responses.inputTokens.count(); - * ``` - */ - count(body = {}, options) { - return this._client.post('/responses/input_tokens', { body, ...options }); - } -} -//# sourceMappingURL=input-tokens.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/responses/responses.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - -class Responses extends resource_APIResource { - constructor() { - super(...arguments); - this.inputItems = new InputItems(this._client); - this.inputTokens = new InputTokens(this._client); - } - create(body, options) { - return this._client.post('/responses', { body, ...options, stream: body.stream ?? false })._thenUnwrap((rsp) => { - if ('object' in rsp && rsp.object === 'response') { - addOutputText(rsp); - } - return rsp; - }); - } - retrieve(responseID, query = {}, options) { - return this._client.get(path_path `/responses/${responseID}`, { - query, - ...options, - stream: query?.stream ?? false, - })._thenUnwrap((rsp) => { - if ('object' in rsp && rsp.object === 'response') { - addOutputText(rsp); - } - return rsp; - }); - } - /** - * Deletes a model response with the given ID. - * - * @example - * ```ts - * await client.responses.delete( - * 'resp_677efb5139a88190b512bc3fef8e535d', - * ); - * ``` - */ - delete(responseID, options) { - return this._client.delete(path_path `/responses/${responseID}`, { - ...options, - headers: headers_buildHeaders([{ Accept: '*/*' }, options?.headers]), - }); - } - parse(body, options) { - return this._client.responses - .create(body, options) - ._thenUnwrap((response) => parseResponse(response, body)); - } - /** - * Creates a model response stream - */ - stream(body, options) { - return ResponseStream.createResponse(this._client, body, options); - } - /** - * Cancels a model response with the given ID. Only responses created with the - * `background` parameter set to `true` can be cancelled. - * [Learn more](https://platform.openai.com/docs/guides/background). - * - * @example - * ```ts - * const response = await client.responses.cancel( - * 'resp_677efb5139a88190b512bc3fef8e535d', - * ); - * ``` - */ - cancel(responseID, options) { - return this._client.post(path_path `/responses/${responseID}/cancel`, options); - } - /** - * Compact conversation - * - * @example - * ```ts - * const compactedResponse = await client.responses.compact({ - * model: 'gpt-5.2', - * }); - * ``` - */ - compact(body, options) { - return this._client.post('/responses/compact', { body, ...options }); - } -} -Responses.InputItems = InputItems; -Responses.InputTokens = InputTokens; -//# sourceMappingURL=responses.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/parts.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - -class Parts extends resource_APIResource { - /** - * Adds a - * [Part](https://platform.openai.com/docs/api-reference/uploads/part-object) to an - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object. - * A Part represents a chunk of bytes from the file you are trying to upload. - * - * Each Part can be at most 64 MB, and you can add Parts until you hit the Upload - * maximum of 8 GB. - * - * It is possible to add multiple Parts in parallel. You can decide the intended - * order of the Parts when you - * [complete the Upload](https://platform.openai.com/docs/api-reference/uploads/complete). - */ - create(uploadID, body, options) { - return this._client.post(path_path `/uploads/${uploadID}/parts`, uploads_multipartFormRequestOptions({ body, ...options }, this._client)); - } -} -//# sourceMappingURL=parts.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/uploads/uploads.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - -class Uploads extends resource_APIResource { - constructor() { - super(...arguments); - this.parts = new Parts(this._client); - } - /** - * Creates an intermediate - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object) object - * that you can add - * [Parts](https://platform.openai.com/docs/api-reference/uploads/part-object) to. - * Currently, an Upload can accept at most 8 GB in total and expires after an hour - * after you create it. - * - * Once you complete the Upload, we will create a - * [File](https://platform.openai.com/docs/api-reference/files/object) object that - * contains all the parts you uploaded. This File is usable in the rest of our - * platform as a regular File object. - * - * For certain `purpose` values, the correct `mime_type` must be specified. Please - * refer to documentation for the - * [supported MIME types for your use case](https://platform.openai.com/docs/assistants/tools/file-search#supported-files). - * - * For guidance on the proper filename extensions for each purpose, please follow - * the documentation on - * [creating a File](https://platform.openai.com/docs/api-reference/files/create). - */ - create(body, options) { - return this._client.post('/uploads', { body, ...options }); - } - /** - * Cancels the Upload. No Parts may be added after an Upload is cancelled. - */ - cancel(uploadID, options) { - return this._client.post(path_path `/uploads/${uploadID}/cancel`, options); - } - /** - * Completes the - * [Upload](https://platform.openai.com/docs/api-reference/uploads/object). - * - * Within the returned Upload object, there is a nested - * [File](https://platform.openai.com/docs/api-reference/files/object) object that - * is ready to use in the rest of the platform. - * - * You can specify the order of the Parts by passing in an ordered list of the Part - * IDs. - * - * The number of bytes uploaded upon completion must match the number of bytes - * initially specified when creating the Upload object. No Parts may be added after - * an Upload is completed. - */ - complete(uploadID, body, options) { - return this._client.post(path_path `/uploads/${uploadID}/complete`, { body, ...options }); - } -} -Uploads.Parts = Parts; -//# sourceMappingURL=uploads.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/Util.mjs -/** - * Like `Promise.allSettled()` but throws an error if any promises are rejected. - */ -const allSettledWithThrow = async (promises) => { - const results = await Promise.allSettled(promises); - const rejected = results.filter((result) => result.status === 'rejected'); - if (rejected.length) { - for (const result of rejected) { - console.error(result.reason); - } - throw new Error(`${rejected.length} promise(s) failed - see the above errors`); - } - // Note: TS was complaining about using `.filter().map()` here for some reason - const values = []; - for (const result of results) { - if (result.status === 'fulfilled') { - values.push(result.value); - } - } - return values; -}; -//# sourceMappingURL=Util.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/file-batches.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - -class FileBatches extends resource_APIResource { - /** - * Create a vector store file batch. - */ - create(vectorStoreID, body, options) { - return this._client.post(path_path `/vector_stores/${vectorStoreID}/file_batches`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieves a vector store file batch. - */ - retrieve(batchID, params, options) { - const { vector_store_id } = params; - return this._client.get(path_path `/vector_stores/${vector_store_id}/file_batches/${batchID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Cancel a vector store file batch. This attempts to cancel the processing of - * files in this batch as soon as possible. - */ - cancel(batchID, params, options) { - const { vector_store_id } = params; - return this._client.post(path_path `/vector_stores/${vector_store_id}/file_batches/${batchID}/cancel`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Create a vector store batch and poll until all files have been processed. - */ - async createAndPoll(vectorStoreId, body, options) { - const batch = await this.create(vectorStoreId, body); - return await this.poll(vectorStoreId, batch.id, options); - } - /** - * Returns a list of vector store files in a batch. - */ - listFiles(batchID, params, options) { - const { vector_store_id, ...query } = params; - return this._client.getAPIList(path_path `/vector_stores/${vector_store_id}/file_batches/${batchID}/files`, (CursorPage), { query, ...options, headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }); - } - /** - * Wait for the given file batch to be processed. - * - * Note: this will return even if one of the files failed to process, you need to - * check batch.file_counts.failed_count to handle this case. - */ - async poll(vectorStoreID, batchID, options) { - const headers = headers_buildHeaders([ - options?.headers, - { - 'X-Stainless-Poll-Helper': 'true', - 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, - }, - ]); - while (true) { - const { data: batch, response } = await this.retrieve(batchID, { vector_store_id: vectorStoreID }, { - ...options, - headers, - }).withResponse(); - switch (batch.status) { - case 'in_progress': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep_sleep(sleepInterval); - break; - case 'failed': - case 'cancelled': - case 'completed': - return batch; - } - } - } - /** - * Uploads the given files concurrently and then creates a vector store file batch. - * - * The concurrency limit is configurable using the `maxConcurrency` parameter. - */ - async uploadAndPoll(vectorStoreId, { files, fileIds = [] }, options) { - if (files == null || files.length == 0) { - throw new Error(`No \`files\` provided to process. If you've already uploaded files you should use \`.createAndPoll()\` instead`); - } - const configuredConcurrency = options?.maxConcurrency ?? 5; - // We cap the number of workers at the number of files (so we don't start any unnecessary workers) - const concurrencyLimit = Math.min(configuredConcurrency, files.length); - const client = this._client; - const fileIterator = files.values(); - const allFileIds = [...fileIds]; - // This code is based on this design. The libraries don't accommodate our environment limits. - // https://stackoverflow.com/questions/40639432/what-is-the-best-way-to-limit-concurrency-when-using-es6s-promise-all - async function processFiles(iterator) { - for (let item of iterator) { - const fileObj = await client.files.create({ file: item, purpose: 'assistants' }, options); - allFileIds.push(fileObj.id); - } - } - // Start workers to process results - const workers = Array(concurrencyLimit).fill(fileIterator).map(processFiles); - // Wait for all processing to complete. - await allSettledWithThrow(workers); - return await this.createAndPoll(vectorStoreId, { - file_ids: allFileIds, - }); - } -} -//# sourceMappingURL=file-batches.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/files.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class vector_stores_files_Files extends resource_APIResource { - /** - * Create a vector store file by attaching a - * [File](https://platform.openai.com/docs/api-reference/files) to a - * [vector store](https://platform.openai.com/docs/api-reference/vector-stores/object). - */ - create(vectorStoreID, body, options) { - return this._client.post(path_path `/vector_stores/${vectorStoreID}/files`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieves a vector store file. - */ - retrieve(fileID, params, options) { - const { vector_store_id } = params; - return this._client.get(path_path `/vector_stores/${vector_store_id}/files/${fileID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Update attributes on a vector store file. - */ - update(fileID, params, options) { - const { vector_store_id, ...body } = params; - return this._client.post(path_path `/vector_stores/${vector_store_id}/files/${fileID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of vector store files. - */ - list(vectorStoreID, query = {}, options) { - return this._client.getAPIList(path_path `/vector_stores/${vectorStoreID}/files`, (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Delete a vector store file. This will remove the file from the vector store but - * the file itself will not be deleted. To delete the file, use the - * [delete file](https://platform.openai.com/docs/api-reference/files/delete) - * endpoint. - */ - delete(fileID, params, options) { - const { vector_store_id } = params; - return this._client.delete(path_path `/vector_stores/${vector_store_id}/files/${fileID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Attach a file to the given vector store and wait for it to be processed. - */ - async createAndPoll(vectorStoreId, body, options) { - const file = await this.create(vectorStoreId, body, options); - return await this.poll(vectorStoreId, file.id, options); - } - /** - * Wait for the vector store file to finish processing. - * - * Note: this will return even if the file failed to process, you need to check - * file.last_error and file.status to handle these cases - */ - async poll(vectorStoreID, fileID, options) { - const headers = headers_buildHeaders([ - options?.headers, - { - 'X-Stainless-Poll-Helper': 'true', - 'X-Stainless-Custom-Poll-Interval': options?.pollIntervalMs?.toString() ?? undefined, - }, - ]); - while (true) { - const fileResponse = await this.retrieve(fileID, { - vector_store_id: vectorStoreID, - }, { ...options, headers }).withResponse(); - const file = fileResponse.data; - switch (file.status) { - case 'in_progress': - let sleepInterval = 5000; - if (options?.pollIntervalMs) { - sleepInterval = options.pollIntervalMs; - } - else { - const headerInterval = fileResponse.response.headers.get('openai-poll-after-ms'); - if (headerInterval) { - const headerIntervalMs = parseInt(headerInterval); - if (!isNaN(headerIntervalMs)) { - sleepInterval = headerIntervalMs; - } - } - } - await sleep_sleep(sleepInterval); - break; - case 'failed': - case 'completed': - return file; - } - } - } - /** - * Upload a file to the `files` API and then attach it to the given vector store. - * - * Note the file will be asynchronously processed (you can use the alternative - * polling helper method to wait for processing to complete). - */ - async upload(vectorStoreId, file, options) { - const fileInfo = await this._client.files.create({ file: file, purpose: 'assistants' }, options); - return this.create(vectorStoreId, { file_id: fileInfo.id }, options); - } - /** - * Add a file to a vector store and poll until processing is complete. - */ - async uploadAndPoll(vectorStoreId, file, options) { - const fileInfo = await this.upload(vectorStoreId, file, options); - return await this.poll(vectorStoreId, fileInfo.id, options); - } - /** - * Retrieve the parsed contents of a vector store file. - */ - content(fileID, params, options) { - const { vector_store_id } = params; - return this._client.getAPIList(path_path `/vector_stores/${vector_store_id}/files/${fileID}/content`, (pagination_Page), { ...options, headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]) }); - } -} -//# sourceMappingURL=files.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/vector-stores/vector-stores.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - -class VectorStores extends resource_APIResource { - constructor() { - super(...arguments); - this.files = new vector_stores_files_Files(this._client); - this.fileBatches = new FileBatches(this._client); - } - /** - * Create a vector store. - */ - create(body, options) { - return this._client.post('/vector_stores', { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Retrieves a vector store. - */ - retrieve(vectorStoreID, options) { - return this._client.get(path_path `/vector_stores/${vectorStoreID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Modifies a vector store. - */ - update(vectorStoreID, body, options) { - return this._client.post(path_path `/vector_stores/${vectorStoreID}`, { - body, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Returns a list of vector stores. - */ - list(query = {}, options) { - return this._client.getAPIList('/vector_stores', (CursorPage), { - query, - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Delete a vector store. - */ - delete(vectorStoreID, options) { - return this._client.delete(path_path `/vector_stores/${vectorStoreID}`, { - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } - /** - * Search a vector store for relevant chunks based on a query and file attributes - * filter. - */ - search(vectorStoreID, body, options) { - return this._client.getAPIList(path_path `/vector_stores/${vectorStoreID}/search`, (pagination_Page), { - body, - method: 'post', - ...options, - headers: headers_buildHeaders([{ 'OpenAI-Beta': 'assistants=v2' }, options?.headers]), - }); - } -} -VectorStores.Files = vector_stores_files_Files; -VectorStores.FileBatches = FileBatches; -//# sourceMappingURL=vector-stores.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/videos.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - -class Videos extends resource_APIResource { - /** - * Create a video - */ - create(body, options) { - return this._client.post('/videos', uploads_maybeMultipartFormRequestOptions({ body, ...options }, this._client)); - } - /** - * Retrieve a video - */ - retrieve(videoID, options) { - return this._client.get(path_path `/videos/${videoID}`, options); - } - /** - * List videos - */ - list(query = {}, options) { - return this._client.getAPIList('/videos', (ConversationCursorPage), { query, ...options }); - } - /** - * Delete a video - */ - delete(videoID, options) { - return this._client.delete(path_path `/videos/${videoID}`, options); - } - /** - * Download video content - */ - downloadContent(videoID, query = {}, options) { - return this._client.get(path_path `/videos/${videoID}/content`, { - query, - ...options, - headers: headers_buildHeaders([{ Accept: 'application/binary' }, options?.headers]), - __binaryResponse: true, - }); - } - /** - * Create a video remix - */ - remix(videoID, body, options) { - return this._client.post(path_path `/videos/${videoID}/remix`, uploads_maybeMultipartFormRequestOptions({ body, ...options }, this._client)); - } -} -//# sourceMappingURL=videos.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/webhooks.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _Webhooks_instances, _Webhooks_validateSecret, _Webhooks_getRequiredHeader; - - - - -class Webhooks extends resource_APIResource { - constructor() { - super(...arguments); - _Webhooks_instances.add(this); - } - /** - * Validates that the given payload was sent by OpenAI and parses the payload. - */ - async unwrap(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { - await this.verifySignature(payload, headers, secret, tolerance); - return JSON.parse(payload); - } - /** - * Validates whether or not the webhook payload was sent by OpenAI. - * - * An error will be raised if the webhook payload was not sent by OpenAI. - * - * @param payload - The webhook payload - * @param headers - The webhook headers - * @param secret - The webhook secret (optional, will use client secret if not provided) - * @param tolerance - Maximum age of the webhook in seconds (default: 300 = 5 minutes) - */ - async verifySignature(payload, headers, secret = this._client.webhookSecret, tolerance = 300) { - if (typeof crypto === 'undefined' || - typeof crypto.subtle.importKey !== 'function' || - typeof crypto.subtle.verify !== 'function') { - throw new Error('Webhook signature verification is only supported when the `crypto` global is defined'); - } - tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_validateSecret).call(this, secret); - const headersObj = headers_buildHeaders([headers]).values; - const signatureHeader = tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-signature'); - const timestamp = tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-timestamp'); - const webhookId = tslib_classPrivateFieldGet(this, _Webhooks_instances, "m", _Webhooks_getRequiredHeader).call(this, headersObj, 'webhook-id'); - // Validate timestamp to prevent replay attacks - const timestampSeconds = parseInt(timestamp, 10); - if (isNaN(timestampSeconds)) { - throw new InvalidWebhookSignatureError('Invalid webhook timestamp format'); - } - const nowSeconds = Math.floor(Date.now() / 1000); - if (nowSeconds - timestampSeconds > tolerance) { - throw new InvalidWebhookSignatureError('Webhook timestamp is too old'); - } - if (timestampSeconds > nowSeconds + tolerance) { - throw new InvalidWebhookSignatureError('Webhook timestamp is too new'); - } - // Extract signatures from v1, format - // The signature header can have multiple values, separated by spaces. - // Each value is in the format v1,. We should accept if any match. - const signatures = signatureHeader - .split(' ') - .map((part) => (part.startsWith('v1,') ? part.substring(3) : part)); - // Decode the secret if it starts with whsec_ - const decodedSecret = secret.startsWith('whsec_') ? - Buffer.from(secret.replace('whsec_', ''), 'base64') - : Buffer.from(secret, 'utf-8'); - // Create the signed payload: {webhook_id}.{timestamp}.{payload} - const signedPayload = webhookId ? `${webhookId}.${timestamp}.${payload}` : `${timestamp}.${payload}`; - // Import the secret as a cryptographic key for HMAC - const key = await crypto.subtle.importKey('raw', decodedSecret, { name: 'HMAC', hash: 'SHA-256' }, false, ['verify']); - // Check if any signature matches using timing-safe WebCrypto verify - for (const signature of signatures) { - try { - const signatureBytes = Buffer.from(signature, 'base64'); - const isValid = await crypto.subtle.verify('HMAC', key, signatureBytes, new TextEncoder().encode(signedPayload)); - if (isValid) { - return; // Valid signature found - } - } - catch { - // Invalid base64 or signature format, continue to next signature - continue; - } - } - throw new InvalidWebhookSignatureError('The given webhook signature does not match the expected signature'); - } -} -_Webhooks_instances = new WeakSet(), _Webhooks_validateSecret = function _Webhooks_validateSecret(secret) { - if (typeof secret !== 'string' || secret.length === 0) { - throw new Error(`The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function`); - } -}, _Webhooks_getRequiredHeader = function _Webhooks_getRequiredHeader(headers, name) { - if (!headers) { - throw new Error(`Headers are required`); - } - const value = headers.get(name); - if (value === null || value === undefined) { - throw new Error(`Missing required header: ${name}`); - } - return value; -}; -//# sourceMappingURL=webhooks.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/resources/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - - - - - - - - - - - - - - - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/client.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. -var _OpenAI_instances, openai_client_a, _OpenAI_encoder, _OpenAI_baseURLOverridden; - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/** - * API Client for interfacing with the OpenAI API. - */ -class OpenAI { - /** - * API Client for interfacing with the OpenAI API. - * - * @param {string | undefined} [opts.apiKey=process.env['OPENAI_API_KEY'] ?? undefined] - * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] - * @param {string | null | undefined} [opts.project=process.env['OPENAI_PROJECT_ID'] ?? null] - * @param {string | null | undefined} [opts.webhookSecret=process.env['OPENAI_WEBHOOK_SECRET'] ?? null] - * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL'] ?? https://api.openai.com/v1] - Override the default base URL for the API. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {MergedRequestInit} [opts.fetchOptions] - Additional `RequestInit` options to be passed to `fetch` calls. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {HeadersLike} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {Record} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - */ - constructor({ baseURL = env_readEnv('OPENAI_BASE_URL'), apiKey = env_readEnv('OPENAI_API_KEY'), organization = env_readEnv('OPENAI_ORG_ID') ?? null, project = env_readEnv('OPENAI_PROJECT_ID') ?? null, webhookSecret = env_readEnv('OPENAI_WEBHOOK_SECRET') ?? null, ...opts } = {}) { - _OpenAI_instances.add(this); - _OpenAI_encoder.set(this, void 0); - this.completions = new resources_completions_Completions(this); - this.chat = new Chat(this); - this.embeddings = new embeddings_Embeddings(this); - this.files = new resources_files_Files(this); - this.images = new Images(this); - this.audio = new Audio(this); - this.moderations = new Moderations(this); - this.models = new resources_models_Models(this); - this.fineTuning = new FineTuning(this); - this.graders = new graders_Graders(this); - this.vectorStores = new VectorStores(this); - this.webhooks = new Webhooks(this); - this.beta = new beta_Beta(this); - this.batches = new resources_batches_Batches(this); - this.uploads = new Uploads(this); - this.responses = new Responses(this); - this.realtime = new realtime_Realtime(this); - this.conversations = new Conversations(this); - this.evals = new Evals(this); - this.containers = new Containers(this); - this.videos = new Videos(this); - if (apiKey === undefined) { - throw new error_OpenAIError('Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.'); - } - const options = { - apiKey, - organization, - project, - webhookSecret, - ...opts, - baseURL: baseURL || `https://api.openai.com/v1`, - }; - if (!options.dangerouslyAllowBrowser && detect_platform_isRunningInBrowser()) { - throw new error_OpenAIError("It looks like you're running in a browser-like environment.\n\nThis is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew OpenAI({ apiKey, dangerouslyAllowBrowser: true });\n\nhttps://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety\n"); - } - this.baseURL = options.baseURL; - this.timeout = options.timeout ?? openai_client_a.DEFAULT_TIMEOUT /* 10 minutes */; - this.logger = options.logger ?? console; - const defaultLogLevel = 'warn'; - // Set default logLevel early so that we can log a warning in parseLogLevel. - this.logLevel = defaultLogLevel; - this.logLevel = - log_parseLogLevel(options.logLevel, 'ClientOptions.logLevel', this) ?? - log_parseLogLevel(env_readEnv('OPENAI_LOG'), "process.env['OPENAI_LOG']", this) ?? - defaultLogLevel; - this.fetchOptions = options.fetchOptions; - this.maxRetries = options.maxRetries ?? 2; - this.fetch = options.fetch ?? shims_getDefaultFetch(); - tslib_classPrivateFieldSet(this, _OpenAI_encoder, request_options_FallbackEncoder, "f"); - this._options = options; - this.apiKey = typeof apiKey === 'string' ? apiKey : 'Missing Key'; - this.organization = organization; - this.project = project; - this.webhookSecret = webhookSecret; - } - /** - * Create a new client instance re-using the same options given to the current client with optional overriding. - */ - withOptions(options) { - const client = new this.constructor({ - ...this._options, - baseURL: this.baseURL, - maxRetries: this.maxRetries, - timeout: this.timeout, - logger: this.logger, - logLevel: this.logLevel, - fetch: this.fetch, - fetchOptions: this.fetchOptions, - apiKey: this.apiKey, - organization: this.organization, - project: this.project, - webhookSecret: this.webhookSecret, - ...options, - }); - return client; - } - defaultQuery() { - return this._options.defaultQuery; - } - validateHeaders({ values, nulls }) { - return; - } - async authHeaders(opts) { - return headers_buildHeaders([{ Authorization: `Bearer ${this.apiKey}` }]); - } - stringifyQuery(query) { - return stringify_stringify(query, { arrayFormat: 'brackets' }); - } - getUserAgent() { - return `${this.constructor.name}/JS ${version_VERSION}`; - } - defaultIdempotencyKey() { - return `stainless-node-retry-${utils_uuid_uuid4()}`; - } - makeStatusError(status, error, message, headers) { - return error_APIError.generate(status, error, message, headers); - } - async _callApiKey() { - const apiKey = this._options.apiKey; - if (typeof apiKey !== 'function') - return false; - let token; - try { - token = await apiKey(); - } - catch (err) { - if (err instanceof error_OpenAIError) - throw err; - throw new error_OpenAIError(`Failed to get token from 'apiKey' function: ${err.message}`, - // @ts-ignore - { cause: err }); - } - if (typeof token !== 'string' || !token) { - throw new error_OpenAIError(`Expected 'apiKey' function argument to return a string but it returned ${token}`); - } - this.apiKey = token; - return true; - } - buildURL(path, query, defaultBaseURL) { - const baseURL = (!tslib_classPrivateFieldGet(this, _OpenAI_instances, "m", _OpenAI_baseURLOverridden).call(this) && defaultBaseURL) || this.baseURL; - const url = values_isAbsoluteURL(path) ? - new URL(path) - : new URL(baseURL + (baseURL.endsWith('/') && path.startsWith('/') ? path.slice(1) : path)); - const defaultQuery = this.defaultQuery(); - if (!values_isEmptyObj(defaultQuery)) { - query = { ...defaultQuery, ...query }; - } - if (typeof query === 'object' && query && !Array.isArray(query)) { - url.search = this.stringifyQuery(query); - } - return url.toString(); - } - /** - * Used as a callback for mutating the given `FinalRequestOptions` object. - */ - async prepareOptions(options) { - await this._callApiKey(); - } - /** - * Used as a callback for mutating the given `RequestInit` object. - * - * This is useful for cases where you want to add certain headers based off of - * the request properties, e.g. `method` or `url`. - */ - async prepareRequest(request, { url, options }) { } - get(path, opts) { - return this.methodRequest('get', path, opts); - } - post(path, opts) { - return this.methodRequest('post', path, opts); - } - patch(path, opts) { - return this.methodRequest('patch', path, opts); - } - put(path, opts) { - return this.methodRequest('put', path, opts); - } - delete(path, opts) { - return this.methodRequest('delete', path, opts); - } - methodRequest(method, path, opts) { - return this.request(Promise.resolve(opts).then((opts) => { - return { method, path, ...opts }; - })); - } - request(options, remainingRetries = null) { - return new api_promise_APIPromise(this, this.makeRequest(options, remainingRetries, undefined)); - } - async makeRequest(optionsInput, retriesRemaining, retryOfRequestLogID) { - const options = await optionsInput; - const maxRetries = options.maxRetries ?? this.maxRetries; - if (retriesRemaining == null) { - retriesRemaining = maxRetries; - } - await this.prepareOptions(options); - const { req, url, timeout } = await this.buildRequest(options, { - retryCount: maxRetries - retriesRemaining, - }); - await this.prepareRequest(req, { url, options }); - /** Not an API request ID, just for correlating local log entries. */ - const requestLogID = 'log_' + ((Math.random() * (1 << 24)) | 0).toString(16).padStart(6, '0'); - const retryLogStr = retryOfRequestLogID === undefined ? '' : `, retryOf: ${retryOfRequestLogID}`; - const startTime = Date.now(); - log_loggerFor(this).debug(`[${requestLogID}] sending request`, log_formatRequestDetails({ - retryOfRequestLogID, - method: options.method, - url, - options, - headers: req.headers, - })); - if (options.signal?.aborted) { - throw new error_APIUserAbortError(); - } - const controller = new AbortController(); - const response = await this.fetchWithTimeout(url, req, timeout, controller).catch(errors_castToError); - const headersTime = Date.now(); - if (response instanceof globalThis.Error) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - if (options.signal?.aborted) { - throw new error_APIUserAbortError(); - } - // detect native connection timeout errors - // deno throws "TypeError: error sending request for url (https://example/): client error (Connect): tcp connect error: Operation timed out (os error 60): Operation timed out (os error 60)" - // undici throws "TypeError: fetch failed" with cause "ConnectTimeoutError: Connect Timeout Error (attempted address: example:443, timeout: 1ms)" - // others do not provide enough information to distinguish timeouts from other connection errors - const isTimeout = errors_isAbortError(response) || - /timed? ?out/i.test(String(response) + ('cause' in response ? String(response.cause) : '')); - if (retriesRemaining) { - log_loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - ${retryMessage}`); - log_loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (${retryMessage})`, log_formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID); - } - log_loggerFor(this).info(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} - error; no more retries left`); - log_loggerFor(this).debug(`[${requestLogID}] connection ${isTimeout ? 'timed out' : 'failed'} (error; no more retries left)`, log_formatRequestDetails({ - retryOfRequestLogID, - url, - durationMs: headersTime - startTime, - message: response.message, - })); - if (isTimeout) { - throw new error_APIConnectionTimeoutError(); - } - throw new error_APIConnectionError({ cause: response }); - } - const specialHeaders = [...response.headers.entries()] - .filter(([name]) => name === 'x-request-id') - .map(([name, value]) => ', ' + name + ': ' + JSON.stringify(value)) - .join(''); - const responseInfo = `[${requestLogID}${retryLogStr}${specialHeaders}] ${req.method} ${url} ${response.ok ? 'succeeded' : 'failed'} with status ${response.status} in ${headersTime - startTime}ms`; - if (!response.ok) { - const shouldRetry = await this.shouldRetry(response); - if (retriesRemaining && shouldRetry) { - const retryMessage = `retrying, ${retriesRemaining} attempts remaining`; - // We don't need the body of this response. - await shims_CancelReadableStream(response.body); - log_loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - log_loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, log_formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - })); - return this.retryRequest(options, retriesRemaining, retryOfRequestLogID ?? requestLogID, response.headers); - } - const retryMessage = shouldRetry ? `error; no more retries left` : `error; not retryable`; - log_loggerFor(this).info(`${responseInfo} - ${retryMessage}`); - const errText = await response.text().catch((err) => errors_castToError(err).message); - const errJSON = values_safeJSON(errText); - const errMessage = errJSON ? undefined : errText; - log_loggerFor(this).debug(`[${requestLogID}] response error (${retryMessage})`, log_formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - message: errMessage, - durationMs: Date.now() - startTime, - })); - const err = this.makeStatusError(response.status, errJSON, errMessage, response.headers); - throw err; - } - log_loggerFor(this).info(responseInfo); - log_loggerFor(this).debug(`[${requestLogID}] response start`, log_formatRequestDetails({ - retryOfRequestLogID, - url: response.url, - status: response.status, - headers: response.headers, - durationMs: headersTime - startTime, - })); - return { response, options, controller, requestLogID, retryOfRequestLogID, startTime }; - } - getAPIList(path, Page, opts) { - return this.requestAPIList(Page, { method: 'get', path, ...opts }); - } - requestAPIList(Page, options) { - const request = this.makeRequest(options, null, undefined); - return new pagination_PagePromise(this, request, Page); - } - async fetchWithTimeout(url, init, ms, controller) { - const { signal, method, ...options } = init || {}; - if (signal) - signal.addEventListener('abort', () => controller.abort()); - const timeout = setTimeout(() => controller.abort(), ms); - const isReadableBody = (globalThis.ReadableStream && options.body instanceof globalThis.ReadableStream) || - (typeof options.body === 'object' && options.body !== null && Symbol.asyncIterator in options.body); - const fetchOptions = { - signal: controller.signal, - ...(isReadableBody ? { duplex: 'half' } : {}), - method: 'GET', - ...options, - }; - if (method) { - // Custom methods like 'patch' need to be uppercased - // See https://github.com/nodejs/undici/issues/2294 - fetchOptions.method = method.toUpperCase(); - } - try { - // use undefined this binding; fetch errors if bound to something else in browser/cloudflare - return await this.fetch.call(undefined, url, fetchOptions); - } - finally { - clearTimeout(timeout); - } - } - async shouldRetry(response) { - // Note this is not a standard header. - const shouldRetryHeader = response.headers.get('x-should-retry'); - // If the server explicitly says whether or not to retry, obey. - if (shouldRetryHeader === 'true') - return true; - if (shouldRetryHeader === 'false') - return false; - // Retry on request timeouts. - if (response.status === 408) - return true; - // Retry on lock timeouts. - if (response.status === 409) - return true; - // Retry on rate limits. - if (response.status === 429) - return true; - // Retry internal errors. - if (response.status >= 500) - return true; - return false; - } - async retryRequest(options, retriesRemaining, requestLogID, responseHeaders) { - let timeoutMillis; - // Note the `retry-after-ms` header may not be standard, but is a good idea and we'd like proactive support for it. - const retryAfterMillisHeader = responseHeaders?.get('retry-after-ms'); - if (retryAfterMillisHeader) { - const timeoutMs = parseFloat(retryAfterMillisHeader); - if (!Number.isNaN(timeoutMs)) { - timeoutMillis = timeoutMs; - } - } - // About the Retry-After header: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After - const retryAfterHeader = responseHeaders?.get('retry-after'); - if (retryAfterHeader && !timeoutMillis) { - const timeoutSeconds = parseFloat(retryAfterHeader); - if (!Number.isNaN(timeoutSeconds)) { - timeoutMillis = timeoutSeconds * 1000; - } - else { - timeoutMillis = Date.parse(retryAfterHeader) - Date.now(); - } - } - // If the API asks us to wait a certain amount of time (and it's a reasonable amount), - // just do what it says, but otherwise calculate a default - if (!(timeoutMillis && 0 <= timeoutMillis && timeoutMillis < 60 * 1000)) { - const maxRetries = options.maxRetries ?? this.maxRetries; - timeoutMillis = this.calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries); - } - await sleep_sleep(timeoutMillis); - return this.makeRequest(options, retriesRemaining - 1, requestLogID); - } - calculateDefaultRetryTimeoutMillis(retriesRemaining, maxRetries) { - const initialRetryDelay = 0.5; - const maxRetryDelay = 8.0; - const numRetries = maxRetries - retriesRemaining; - // Apply exponential backoff, but not more than the max. - const sleepSeconds = Math.min(initialRetryDelay * Math.pow(2, numRetries), maxRetryDelay); - // Apply some jitter, take up to at most 25 percent of the retry time. - const jitter = 1 - Math.random() * 0.25; - return sleepSeconds * jitter * 1000; - } - async buildRequest(inputOptions, { retryCount = 0 } = {}) { - const options = { ...inputOptions }; - const { method, path, query, defaultBaseURL } = options; - const url = this.buildURL(path, query, defaultBaseURL); - if ('timeout' in options) - values_validatePositiveInteger('timeout', options.timeout); - options.timeout = options.timeout ?? this.timeout; - const { bodyHeaders, body } = this.buildBody({ options }); - const reqHeaders = await this.buildHeaders({ options: inputOptions, method, bodyHeaders, retryCount }); - const req = { - method, - headers: reqHeaders, - ...(options.signal && { signal: options.signal }), - ...(globalThis.ReadableStream && - body instanceof globalThis.ReadableStream && { duplex: 'half' }), - ...(body && { body }), - ...(this.fetchOptions ?? {}), - ...(options.fetchOptions ?? {}), - }; - return { req, url, timeout: options.timeout }; - } - async buildHeaders({ options, method, bodyHeaders, retryCount, }) { - let idempotencyHeaders = {}; - if (this.idempotencyHeader && method !== 'get') { - if (!options.idempotencyKey) - options.idempotencyKey = this.defaultIdempotencyKey(); - idempotencyHeaders[this.idempotencyHeader] = options.idempotencyKey; - } - const headers = headers_buildHeaders([ - idempotencyHeaders, - { - Accept: 'application/json', - 'User-Agent': this.getUserAgent(), - 'X-Stainless-Retry-Count': String(retryCount), - ...(options.timeout ? { 'X-Stainless-Timeout': String(Math.trunc(options.timeout / 1000)) } : {}), - ...detect_platform_getPlatformHeaders(), - 'OpenAI-Organization': this.organization, - 'OpenAI-Project': this.project, - }, - await this.authHeaders(options), - this._options.defaultHeaders, - bodyHeaders, - options.headers, - ]); - this.validateHeaders(headers); - return headers.values; - } - buildBody({ options: { body, headers: rawHeaders } }) { - if (!body) { - return { bodyHeaders: undefined, body: undefined }; - } - const headers = headers_buildHeaders([rawHeaders]); - if ( - // Pass raw type verbatim - ArrayBuffer.isView(body) || - body instanceof ArrayBuffer || - body instanceof DataView || - (typeof body === 'string' && - // Preserve legacy string encoding behavior for now - headers.values.has('content-type')) || - // `Blob` is superset of `File` - (globalThis.Blob && body instanceof globalThis.Blob) || - // `FormData` -> `multipart/form-data` - body instanceof FormData || - // `URLSearchParams` -> `application/x-www-form-urlencoded` - body instanceof URLSearchParams || - // Send chunked stream (each chunk has own `length`) - (globalThis.ReadableStream && body instanceof globalThis.ReadableStream)) { - return { bodyHeaders: undefined, body: body }; - } - else if (typeof body === 'object' && - (Symbol.asyncIterator in body || - (Symbol.iterator in body && 'next' in body && typeof body.next === 'function'))) { - return { bodyHeaders: undefined, body: shims_ReadableStreamFrom(body) }; - } - else { - return tslib_classPrivateFieldGet(this, _OpenAI_encoder, "f").call(this, { body, headers }); - } - } -} -openai_client_a = OpenAI, _OpenAI_encoder = new WeakMap(), _OpenAI_instances = new WeakSet(), _OpenAI_baseURLOverridden = function _OpenAI_baseURLOverridden() { - return this.baseURL !== 'https://api.openai.com/v1'; -}; -OpenAI.OpenAI = openai_client_a; -OpenAI.DEFAULT_TIMEOUT = 600000; // 10 minutes -OpenAI.OpenAIError = error_OpenAIError; -OpenAI.APIError = error_APIError; -OpenAI.APIConnectionError = error_APIConnectionError; -OpenAI.APIConnectionTimeoutError = error_APIConnectionTimeoutError; -OpenAI.APIUserAbortError = error_APIUserAbortError; -OpenAI.NotFoundError = error_NotFoundError; -OpenAI.ConflictError = error_ConflictError; -OpenAI.RateLimitError = error_RateLimitError; -OpenAI.BadRequestError = error_BadRequestError; -OpenAI.AuthenticationError = error_AuthenticationError; -OpenAI.InternalServerError = error_InternalServerError; -OpenAI.PermissionDeniedError = error_PermissionDeniedError; -OpenAI.UnprocessableEntityError = error_UnprocessableEntityError; -OpenAI.InvalidWebhookSignatureError = InvalidWebhookSignatureError; -OpenAI.toFile = to_file_toFile; -OpenAI.Completions = resources_completions_Completions; -OpenAI.Chat = Chat; -OpenAI.Embeddings = embeddings_Embeddings; -OpenAI.Files = resources_files_Files; -OpenAI.Images = Images; -OpenAI.Audio = Audio; -OpenAI.Moderations = Moderations; -OpenAI.Models = resources_models_Models; -OpenAI.FineTuning = FineTuning; -OpenAI.Graders = graders_Graders; -OpenAI.VectorStores = VectorStores; -OpenAI.Webhooks = Webhooks; -OpenAI.Beta = beta_Beta; -OpenAI.Batches = resources_batches_Batches; -OpenAI.Uploads = Uploads; -OpenAI.Responses = Responses; -OpenAI.Realtime = realtime_Realtime; -OpenAI.Conversations = Conversations; -OpenAI.Evals = Evals; -OpenAI.Containers = Containers; -OpenAI.Videos = Videos; -//# sourceMappingURL=client.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/azure.mjs - - - - -/** API Client for interfacing with the Azure OpenAI API. */ -class AzureOpenAI extends OpenAI { - /** - * API Client for interfacing with the Azure OpenAI API. - * - * @param {string | undefined} [opts.apiVersion=process.env['OPENAI_API_VERSION'] ?? undefined] - * @param {string | undefined} [opts.endpoint=process.env['AZURE_OPENAI_ENDPOINT'] ?? undefined] - Your Azure endpoint, including the resource, e.g. `https://example-resource.azure.openai.com/` - * @param {string | undefined} [opts.apiKey=process.env['AZURE_OPENAI_API_KEY'] ?? undefined] - * @param {string | undefined} opts.deployment - A model deployment, if given, sets the base client URL to include `/deployments/{deployment}`. - * @param {string | null | undefined} [opts.organization=process.env['OPENAI_ORG_ID'] ?? null] - * @param {string} [opts.baseURL=process.env['OPENAI_BASE_URL']] - Sets the base URL for the API, e.g. `https://example-resource.azure.openai.com/openai/`. - * @param {number} [opts.timeout=10 minutes] - The maximum amount of time (in milliseconds) the client will wait for a response before timing out. - * @param {number} [opts.httpAgent] - An HTTP agent used to manage HTTP(s) connections. - * @param {Fetch} [opts.fetch] - Specify a custom `fetch` function implementation. - * @param {number} [opts.maxRetries=2] - The maximum number of times the client will retry a request. - * @param {Headers} opts.defaultHeaders - Default headers to include with every request to the API. - * @param {DefaultQuery} opts.defaultQuery - Default query parameters to include with every request to the API. - * @param {boolean} [opts.dangerouslyAllowBrowser=false] - By default, client-side use of this library is not allowed, as it risks exposing your secret API credentials to attackers. - */ - constructor({ baseURL = env_readEnv('OPENAI_BASE_URL'), apiKey = env_readEnv('AZURE_OPENAI_API_KEY'), apiVersion = env_readEnv('OPENAI_API_VERSION'), endpoint, deployment, azureADTokenProvider, dangerouslyAllowBrowser, ...opts } = {}) { - if (!apiVersion) { - throw new error_OpenAIError("The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' })."); - } - if (typeof azureADTokenProvider === 'function') { - dangerouslyAllowBrowser = true; - } - if (!azureADTokenProvider && !apiKey) { - throw new error_OpenAIError('Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.'); - } - if (azureADTokenProvider && apiKey) { - throw new error_OpenAIError('The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.'); - } - opts.defaultQuery = { ...opts.defaultQuery, 'api-version': apiVersion }; - if (!baseURL) { - if (!endpoint) { - endpoint = process.env['AZURE_OPENAI_ENDPOINT']; - } - if (!endpoint) { - throw new error_OpenAIError('Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable'); - } - baseURL = `${endpoint}/openai`; - } - else { - if (endpoint) { - throw new error_OpenAIError('baseURL and endpoint are mutually exclusive'); - } - } - super({ - apiKey: azureADTokenProvider ?? apiKey, - baseURL, - ...opts, - ...(dangerouslyAllowBrowser !== undefined ? { dangerouslyAllowBrowser } : {}), - }); - this.apiVersion = ''; - this.apiVersion = apiVersion; - this.deploymentName = deployment; - } - async buildRequest(options, props = {}) { - if (_deployments_endpoints.has(options.path) && options.method === 'post' && options.body !== undefined) { - if (!values_isObj(options.body)) { - throw new Error('Expected request body to be an object'); - } - const model = this.deploymentName || options.body['model'] || options.__metadata?.['model']; - if (model !== undefined && !this.baseURL.includes('/deployments')) { - options.path = `/deployments/${model}${options.path}`; - } - } - return super.buildRequest(options, props); - } - async authHeaders(opts) { - if (typeof this._options.apiKey === 'string') { - return headers_buildHeaders([{ 'api-key': this.apiKey }]); - } - return super.authHeaders(opts); - } -} -const _deployments_endpoints = new Set([ - '/completions', - '/chat/completions', - '/embeddings', - '/audio/transcriptions', - '/audio/translations', - '/audio/speech', - '/images/generations', - '/batches', - '/images/edits', -]); -//# sourceMappingURL=azure.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/index.mjs -// File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details. - - - - - - - -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/client.js - - - -//#region src/utils/client.ts -function wrapOpenAIClientError(e) { - if (!e || typeof e !== "object") return e; - let error; - if (e.constructor.name === error_APIConnectionTimeoutError.name && "message" in e && typeof e.message === "string") { - error = new Error(e.message); - error.name = "TimeoutError"; - } else if (e.constructor.name === error_APIUserAbortError.name && "message" in e && typeof e.message === "string") { - error = new Error(e.message); - error.name = "AbortError"; - } else if ("status" in e && e.status === 400 && "message" in e && typeof e.message === "string" && e.message.includes("tool_calls")) error = utils_errors_addLangChainErrorFields(e, "INVALID_TOOL_RESULTS"); - else if ("status" in e && e.status === 401) error = utils_errors_addLangChainErrorFields(e, "MODEL_AUTHENTICATION"); - else if ("status" in e && e.status === 429) error = utils_errors_addLangChainErrorFields(e, "MODEL_RATE_LIMIT"); - else if ("status" in e && e.status === 404) error = utils_errors_addLangChainErrorFields(e, "MODEL_NOT_FOUND"); - else error = e; - return error; -} - -//#endregion - -//# sourceMappingURL=client.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/misc.js - - -//#region src/utils/misc.ts -const iife$1 = (fn) => fn(); -function isReasoningModel(model) { - if (!model) return false; - if (/^o\d/.test(model ?? "")) return true; - if (model.startsWith("gpt-5") && !model.startsWith("gpt-5-chat")) return true; - return false; -} -function extractGenericMessageCustomRole(message) { - if (message.role !== "system" && message.role !== "developer" && message.role !== "assistant" && message.role !== "user" && message.role !== "function" && message.role !== "tool") console.warn(`Unknown message role: ${message.role}`); - return message.role; -} -function getRequiredFilenameFromMetadata(block) { - const filename = block.metadata?.filename ?? block.metadata?.name ?? block.metadata?.title; - if (!filename) throw new Error("a filename or name or title is needed via meta-data for OpenAI when working with multimodal blocks"); - return filename; -} -function messageToOpenAIRole(message) { - const type = message._getType(); - switch (type) { - case "system": return "system"; - case "ai": return "assistant"; - case "human": return "user"; - case "function": return "function"; - case "tool": return "tool"; - case "generic": - if (!ChatMessage.isInstance(message)) throw new Error("Invalid generic chat message"); - return extractGenericMessageCustomRole(message); - default: throw new Error(`Unknown message type: ${type}`); - } -} -function _modelPrefersResponsesAPI(model) { - return model.includes("gpt-5.2-pro"); -} - -//#endregion - -//# sourceMappingURL=misc.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/azure.js - - - -//#region src/utils/azure.ts -/** -* This function generates an endpoint URL for (Azure) OpenAI -* based on the configuration parameters provided. -* -* @param {OpenAIEndpointConfig} config - The configuration object for the (Azure) endpoint. -* -* @property {string} config.azureOpenAIApiDeploymentName - The deployment name of Azure OpenAI. -* @property {string} config.azureOpenAIApiInstanceName - The instance name of Azure OpenAI, e.g. `example-resource`. -* @property {string} config.azureOpenAIApiKey - The API Key for Azure OpenAI. -* @property {string} config.azureOpenAIBasePath - The base path for Azure OpenAI, e.g. `https://example-resource.azure.openai.com/openai/deployments/`. -* @property {string} config.baseURL - Some other custom base path URL. -* @property {string} config.azureOpenAIEndpoint - The endpoint for the Azure OpenAI instance, e.g. `https://example-resource.azure.openai.com/`. -* -* The function operates as follows: -* - If both `azureOpenAIBasePath` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`). -* - If both `azureOpenAIEndpoint` and `azureOpenAIApiDeploymentName` (plus `azureOpenAIApiKey`) are provided, it returns an URL combining these two parameters (`${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`). -* - If `azureOpenAIApiKey` is provided, it checks for `azureOpenAIApiInstanceName` and `azureOpenAIApiDeploymentName` and throws an error if any of these is missing. If both are provided, it generates an URL incorporating these parameters. -* - If none of the above conditions are met, return any custom `baseURL`. -* - The function returns the generated URL as a string, or undefined if no custom paths are specified. -* -* @throws Will throw an error if the necessary parameters for generating the URL are missing. -* -* @returns {string | undefined} The generated (Azure) OpenAI endpoint URL. -*/ -function getEndpoint(config) { - const { azureOpenAIApiDeploymentName, azureOpenAIApiInstanceName, azureOpenAIApiKey, azureOpenAIBasePath, baseURL, azureADTokenProvider, azureOpenAIEndpoint } = config; - if ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIBasePath && azureOpenAIApiDeploymentName) return `${azureOpenAIBasePath}/${azureOpenAIApiDeploymentName}`; - if ((azureOpenAIApiKey || azureADTokenProvider) && azureOpenAIEndpoint && azureOpenAIApiDeploymentName) return `${azureOpenAIEndpoint}/openai/deployments/${azureOpenAIApiDeploymentName}`; - if (azureOpenAIApiKey || azureADTokenProvider) { - if (!azureOpenAIApiInstanceName) throw new Error("azureOpenAIApiInstanceName is required when using azureOpenAIApiKey"); - if (!azureOpenAIApiDeploymentName) throw new Error("azureOpenAIApiDeploymentName is a required parameter when using azureOpenAIApiKey"); - return `https://${azureOpenAIApiInstanceName}.openai.azure.com/openai/deployments/${azureOpenAIApiDeploymentName}`; - } - return baseURL; -} -function isHeaders(headers) { - return typeof Headers !== "undefined" && headers !== null && typeof headers === "object" && Object.prototype.toString.call(headers) === "[object Headers]"; -} -/** -* Normalizes various header formats into a consistent Record format. -* -* This function accepts headers in multiple formats and converts them to a -* Record for consistent handling. -* -* @param headers - The headers to normalize. Can be: -* - A Headers instance -* - An array of [key, value] pairs -* - A plain object with string keys -* - A NullableHeaders-like object with a 'values' property containing Headers -* - null or undefined -* @returns A normalized Record containing the header key-value pairs -* -* @example -* ```ts -* // With Headers instance -* const headers1 = new Headers([['content-type', 'application/json']]); -* const normalized1 = normalizeHeaders(headers1); -* -* // With plain object -* const headers2 = { 'content-type': 'application/json' }; -* const normalized2 = normalizeHeaders(headers2); -* -* // With array of pairs -* const headers3 = [['content-type', 'application/json']]; -* const normalized3 = normalizeHeaders(headers3); -* ``` -*/ -function normalizeHeaders(headers) { - const output = iife$1(() => { - if (isHeaders(headers)) return headers; - else if (Array.isArray(headers)) return new Headers(headers); - else if (typeof headers === "object" && headers !== null && "values" in headers && isHeaders(headers.values)) return headers.values; - else if (typeof headers === "object" && headers !== null) { - const entries = Object.entries(headers).filter(([, v]) => typeof v === "string").map(([k, v]) => [k, v]); - return new Headers(entries); - } - return new Headers(); - }); - return Object.fromEntries(output.entries()); -} -function getFormattedEnv() { - let env = getEnv(); - if (env === "node" || env === "deno") env = `(${env}/${process.version}; ${process.platform}; ${process.arch})`; - return env; -} -function getHeadersWithUserAgent(headers, isAzure = false, version = "1.0.0") { - const normalizedHeaders = normalizeHeaders(headers); - const env = getFormattedEnv(); - const library = `langchainjs${isAzure ? "-azure" : ""}-openai`; - return { - ...normalizedHeaders, - "User-Agent": normalizedHeaders["User-Agent"] ? `${library}/${version} (${env})${normalizedHeaders["User-Agent"]}` : `${library}/${version} (${env})` - }; -} - -//#endregion - -//# sourceMappingURL=azure.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/tools.js - - - - -//#region src/utils/tools.ts -/** -* Formats a tool in either OpenAI format, or LangChain structured tool format -* into an OpenAI tool format. If the tool is already in OpenAI format, return without -* any changes. If it is in LangChain structured tool format, convert it to OpenAI tool format -* using OpenAI's `zodFunction` util, falling back to `convertToOpenAIFunction` if the parameters -* returned from the `zodFunction` util are not defined. -* -* @param {BindToolsInput} tool The tool to convert to an OpenAI tool. -* @param {Object} [fields] Additional fields to add to the OpenAI tool. -* @returns {ToolDefinition} The inputted tool in OpenAI tool format. -*/ -function _convertToOpenAITool(tool, fields) { - let toolDef; - if (isLangChainTool(tool)) toolDef = convertToOpenAITool(tool); - else toolDef = tool; - if (fields?.strict !== void 0) toolDef.function.strict = fields.strict; - return toolDef; -} -function isAnyOfProp(prop) { - return prop.anyOf !== void 0 && Array.isArray(prop.anyOf); -} -function formatFunctionDefinitions(functions) { - const lines = ["namespace functions {", ""]; - for (const f of functions) { - if (f.description) lines.push(`// ${f.description}`); - if (Object.keys(f.parameters.properties ?? {}).length > 0) { - lines.push(`type ${f.name} = (_: {`); - lines.push(formatObjectProperties(f.parameters, 0)); - lines.push("}) => any;"); - } else lines.push(`type ${f.name} = () => any;`); - lines.push(""); - } - lines.push("} // namespace functions"); - return lines.join("\n"); -} -function formatObjectProperties(obj, indent) { - const lines = []; - for (const [name, param] of Object.entries(obj.properties ?? {})) { - if (param.description && indent < 2) lines.push(`// ${param.description}`); - if (obj.required?.includes(name)) lines.push(`${name}: ${formatType(param, indent)},`); - else lines.push(`${name}?: ${formatType(param, indent)},`); - } - return lines.map((line) => " ".repeat(indent) + line).join("\n"); -} -function formatType(param, indent) { - if (isAnyOfProp(param)) return param.anyOf.map((v) => formatType(v, indent)).join(" | "); - switch (param.type) { - case "string": - if (param.enum) return param.enum.map((v) => `"${v}"`).join(" | "); - return "string"; - case "number": - if (param.enum) return param.enum.map((v) => `${v}`).join(" | "); - return "number"; - case "integer": - if (param.enum) return param.enum.map((v) => `${v}`).join(" | "); - return "number"; - case "boolean": return "boolean"; - case "null": return "null"; - case "object": return [ - "{", - formatObjectProperties(param, indent + 2), - "}" - ].join("\n"); - case "array": - if (param.items) return `${formatType(param.items, indent)}[]`; - return "any[]"; - default: return ""; - } -} -function formatToOpenAIToolChoice(toolChoice) { - if (!toolChoice) return void 0; - else if (toolChoice === "any" || toolChoice === "required") return "required"; - else if (toolChoice === "auto") return "auto"; - else if (toolChoice === "none") return "none"; - else if (typeof toolChoice === "string") return { - type: "function", - function: { name: toolChoice } - }; - else return toolChoice; -} -function isBuiltInTool(tool) { - return "type" in tool && tool.type !== "function"; -} -/** -* Checks if a tool has a provider-specific tool definition in extras.providerToolDefinition. -* This is used for tools like localShell, shell, computerUse, and applyPatch -* that need to be sent as built-in tool types to the OpenAI API. -*/ -function hasProviderToolDefinition(tool) { - return typeof tool === "object" && tool !== null && "extras" in tool && typeof tool.extras === "object" && tool.extras !== null && "providerToolDefinition" in tool.extras && typeof tool.extras.providerToolDefinition === "object" && tool.extras.providerToolDefinition !== null; -} -function isBuiltInToolChoice(tool_choice) { - return tool_choice != null && typeof tool_choice === "object" && "type" in tool_choice && tool_choice.type !== "function"; -} -function isCustomTool(tool) { - return typeof tool === "object" && tool !== null && "metadata" in tool && typeof tool.metadata === "object" && tool.metadata !== null && "customTool" in tool.metadata && typeof tool.metadata.customTool === "object" && tool.metadata.customTool !== null; -} -function isOpenAICustomTool(tool) { - return "type" in tool && tool.type === "custom" && "custom" in tool && typeof tool.custom === "object" && tool.custom !== null; -} -function parseCustomToolCall(rawToolCall) { - if (rawToolCall.type !== "custom_tool_call") return void 0; - return { - ...rawToolCall, - type: "tool_call", - call_id: rawToolCall.id, - id: rawToolCall.call_id, - name: rawToolCall.name, - isCustomTool: true, - args: { input: rawToolCall.input } - }; -} -/** -* Parses a computer_call output item from the OpenAI Responses API -* into a ToolCall format that can be processed by the ToolNode. -* -* @param rawToolCall - The raw computer_call output item from the API -* @returns A ComputerToolCall object if valid, undefined otherwise -*/ -function parseComputerCall(rawToolCall) { - if (rawToolCall.type !== "computer_call") return void 0; - return { - ...rawToolCall, - type: "tool_call", - call_id: rawToolCall.id, - id: rawToolCall.call_id, - name: "computer_use", - isComputerTool: true, - args: { action: rawToolCall.action } - }; -} -/** -* Checks if a tool call is a computer tool call. -* @param toolCall - The tool call to check. -* @returns True if the tool call is a computer tool call, false otherwise. -*/ -function isComputerToolCall(toolCall) { - return typeof toolCall === "object" && toolCall !== null && "type" in toolCall && toolCall.type === "tool_call" && "isComputerTool" in toolCall && toolCall.isComputerTool === true; -} -function isCustomToolCall(toolCall) { - return typeof toolCall === "object" && toolCall !== null && "type" in toolCall && toolCall.type === "tool_call" && "isCustomTool" in toolCall && toolCall.isCustomTool === true; -} -function convertCompletionsCustomTool(tool) { - const getFormat = () => { - if (!tool.custom.format) return void 0; - if (tool.custom.format.type === "grammar") return { - type: "grammar", - definition: tool.custom.format.grammar.definition, - syntax: tool.custom.format.grammar.syntax - }; - if (tool.custom.format.type === "text") return { type: "text" }; - return void 0; - }; - return { - type: "custom", - name: tool.custom.name, - description: tool.custom.description, - format: getFormat() - }; -} -function convertResponsesCustomTool(tool) { - const getFormat = () => { - if (!tool.format) return void 0; - if (tool.format.type === "grammar") return { - type: "grammar", - grammar: { - definition: tool.format.definition, - syntax: tool.format.syntax - } - }; - if (tool.format.type === "text") return { type: "text" }; - return void 0; - }; - return { - type: "custom", - custom: { - name: tool.name, - description: tool.description, - format: getFormat() - } - }; -} - -//#endregion - -//# sourceMappingURL=tools.js.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/Options.mjs -const Options_ignoreOverride = Symbol('Let zodToJsonSchema decide on which parser to use'); -const zod_to_json_schema_Options_defaultOptions = { - name: undefined, - $refStrategy: 'root', - effectStrategy: 'input', - pipeStrategy: 'all', - dateStrategy: 'format:date-time', - mapStrategy: 'entries', - nullableStrategy: 'from-target', - removeAdditionalStrategy: 'passthrough', - definitionPath: 'definitions', - target: 'jsonSchema7', - strictUnions: false, - errorMessages: false, - markdownDescription: false, - patternStrategy: 'escape', - applyRegexFlags: false, - emailStrategy: 'format:email', - base64Strategy: 'contentEncoding:base64', - nameStrategy: 'ref', -}; -const Options_getDefaultOptions = (options) => { - // We need to add `definitions` here as we may mutate it - return (typeof options === 'string' ? - { - ...zod_to_json_schema_Options_defaultOptions, - basePath: ['#'], - definitions: {}, - name: options, - } - : { - ...zod_to_json_schema_Options_defaultOptions, - basePath: ['#'], - definitions: {}, - ...options, - }); -}; -//# sourceMappingURL=Options.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/util.mjs -const zodDef = (zodSchema) => { - return '_def' in zodSchema ? zodSchema._def : zodSchema; -}; -function util_isEmptyObj(obj) { - if (!obj) - return true; - for (const _k in obj) - return false; - return true; -} -//# sourceMappingURL=util.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/Refs.mjs - - -const Refs_getRefs = (options) => { - const _options = Options_getDefaultOptions(options); - const currentPath = _options.name !== undefined ? - [..._options.basePath, _options.definitionPath, _options.name] - : _options.basePath; - return { - ..._options, - currentPath: currentPath, - propertyPath: undefined, - seenRefs: new Set(), - seen: new Map(Object.entries(_options.definitions).map(([name, def]) => [ - zodDef(def), - { - def: zodDef(def), - path: [..._options.basePath, _options.definitionPath, name], - // Resolution of references will be forced even though seen, so it's ok that the schema is undefined here for now. - jsonSchema: undefined, - }, - ])), - }; -}; -//# sourceMappingURL=Refs.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/any.mjs -function any_parseAnyDef() { - return {}; -} -//# sourceMappingURL=any.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/errorMessages.mjs -function errorMessages_addErrorMessage(res, key, errorMessage, refs) { - if (!refs?.errorMessages) - return; - if (errorMessage) { - res.errorMessage = { - ...res.errorMessage, - [key]: errorMessage, - }; - } -} -function errorMessages_setResponseValueAndErrors(res, key, value, errorMessage, refs) { - res[key] = value; - errorMessages_addErrorMessage(res, key, errorMessage, refs); -} -//# sourceMappingURL=errorMessages.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/array.mjs - - - -function array_parseArrayDef(def, refs) { - const res = { - type: 'array', - }; - if (def.type?._def?.typeName !== ZodFirstPartyTypeKind.ZodAny) { - res.items = parseDef_parseDef(def.type._def, { - ...refs, - currentPath: [...refs.currentPath, 'items'], - }); - } - if (def.minLength) { - errorMessages_setResponseValueAndErrors(res, 'minItems', def.minLength.value, def.minLength.message, refs); - } - if (def.maxLength) { - errorMessages_setResponseValueAndErrors(res, 'maxItems', def.maxLength.value, def.maxLength.message, refs); - } - if (def.exactLength) { - errorMessages_setResponseValueAndErrors(res, 'minItems', def.exactLength.value, def.exactLength.message, refs); - errorMessages_setResponseValueAndErrors(res, 'maxItems', def.exactLength.value, def.exactLength.message, refs); - } - return res; -} -//# sourceMappingURL=array.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/bigint.mjs - -function bigint_parseBigintDef(def, refs) { - const res = { - type: 'integer', - format: 'int64', - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case 'min': - if (refs.target === 'jsonSchema7') { - if (check.inclusive) { - errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); - } - else { - errorMessages_setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); - } - break; - case 'max': - if (refs.target === 'jsonSchema7') { - if (check.inclusive) { - errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); - } - else { - errorMessages_setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); - } - break; - case 'multipleOf': - errorMessages_setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs); - break; - } - } - return res; -} -//# sourceMappingURL=bigint.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/boolean.mjs -function boolean_parseBooleanDef() { - return { - type: 'boolean', - }; -} -//# sourceMappingURL=boolean.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/branded.mjs - -function branded_parseBrandedDef(_def, refs) { - return parseDef_parseDef(_def.type._def, refs); -} -//# sourceMappingURL=branded.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/catch.mjs - -const catch_parseCatchDef = (def, refs) => { - return parseDef_parseDef(def.innerType._def, refs); -}; -//# sourceMappingURL=catch.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/date.mjs - -function date_parseDateDef(def, refs, overrideDateStrategy) { - const strategy = overrideDateStrategy ?? refs.dateStrategy; - if (Array.isArray(strategy)) { - return { - anyOf: strategy.map((item, i) => date_parseDateDef(def, refs, item)), - }; - } - switch (strategy) { - case 'string': - case 'format:date-time': - return { - type: 'string', - format: 'date-time', - }; - case 'format:date': - return { - type: 'string', - format: 'date', - }; - case 'integer': - return date_integerDateParser(def, refs); - } -} -const date_integerDateParser = (def, refs) => { - const res = { - type: 'integer', - format: 'unix-time', - }; - if (refs.target === 'openApi3') { - return res; - } - for (const check of def.checks) { - switch (check.kind) { - case 'min': - errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, // This is in milliseconds - check.message, refs); - break; - case 'max': - errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, // This is in milliseconds - check.message, refs); - break; - } - } - return res; -}; -//# sourceMappingURL=date.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/default.mjs - -function default_parseDefaultDef(_def, refs) { - return { - ...parseDef_parseDef(_def.innerType._def, refs), - default: _def.defaultValue(), - }; -} -//# sourceMappingURL=default.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/effects.mjs - -function effects_parseEffectsDef(_def, refs, forceResolution) { - return refs.effectStrategy === 'input' ? parseDef_parseDef(_def.schema._def, refs, forceResolution) : {}; -} -//# sourceMappingURL=effects.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/enum.mjs -function enum_parseEnumDef(def) { - return { - type: 'string', - enum: [...def.values], - }; -} -//# sourceMappingURL=enum.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/intersection.mjs - -const intersection_isJsonSchema7AllOfType = (type) => { - if ('type' in type && type.type === 'string') - return false; - return 'allOf' in type; -}; -function intersection_parseIntersectionDef(def, refs) { - const allOf = [ - parseDef_parseDef(def.left._def, { - ...refs, - currentPath: [...refs.currentPath, 'allOf', '0'], - }), - parseDef_parseDef(def.right._def, { - ...refs, - currentPath: [...refs.currentPath, 'allOf', '1'], - }), - ].filter((x) => !!x); - let unevaluatedProperties = refs.target === 'jsonSchema2019-09' ? { unevaluatedProperties: false } : undefined; - const mergedAllOf = []; - // If either of the schemas is an allOf, merge them into a single allOf - allOf.forEach((schema) => { - if (intersection_isJsonSchema7AllOfType(schema)) { - mergedAllOf.push(...schema.allOf); - if (schema.unevaluatedProperties === undefined) { - // If one of the schemas has no unevaluatedProperties set, - // the merged schema should also have no unevaluatedProperties set - unevaluatedProperties = undefined; - } - } - else { - let nestedSchema = schema; - if ('additionalProperties' in schema && schema.additionalProperties === false) { - const { additionalProperties, ...rest } = schema; - nestedSchema = rest; - } - else { - // As soon as one of the schemas has additionalProperties set not to false, we allow unevaluatedProperties - unevaluatedProperties = undefined; - } - mergedAllOf.push(nestedSchema); - } - }); - return mergedAllOf.length ? - { - allOf: mergedAllOf, - ...unevaluatedProperties, - } - : undefined; -} -//# sourceMappingURL=intersection.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/literal.mjs -function literal_parseLiteralDef(def, refs) { - const parsedType = typeof def.value; - if (parsedType !== 'bigint' && - parsedType !== 'number' && - parsedType !== 'boolean' && - parsedType !== 'string') { - return { - type: Array.isArray(def.value) ? 'array' : 'object', - }; - } - if (refs.target === 'openApi3') { - return { - type: parsedType === 'bigint' ? 'integer' : parsedType, - enum: [def.value], - }; - } - return { - type: parsedType === 'bigint' ? 'integer' : parsedType, - const: def.value, - }; -} -//# sourceMappingURL=literal.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/string.mjs - -let parsers_string_emojiRegex; -/** - * Generated from the regular expressions found here as of 2024-05-22: - * https://github.com/colinhacks/zod/blob/master/src/types.ts. - * - * Expressions with /i flag have been changed accordingly. - */ -const string_zodPatterns = { - /** - * `c` was changed to `[cC]` to replicate /i flag - */ - cuid: /^[cC][^\s-]{8,}$/, - cuid2: /^[0-9a-z]+$/, - ulid: /^[0-9A-HJKMNP-TV-Z]{26}$/, - /** - * `a-z` was added to replicate /i flag - */ - email: /^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/, - /** - * Constructed a valid Unicode RegExp - * - * Lazily instantiate since this type of regex isn't supported - * in all envs (e.g. React Native). - * - * See: - * https://github.com/colinhacks/zod/issues/2433 - * Fix in Zod: - * https://github.com/colinhacks/zod/commit/9340fd51e48576a75adc919bff65dbc4a5d4c99b - */ - emoji: () => { - if (parsers_string_emojiRegex === undefined) { - parsers_string_emojiRegex = RegExp('^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$', 'u'); - } - return parsers_string_emojiRegex; - }, - /** - * Unused - */ - uuid: /^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/, - /** - * Unused - */ - ipv4: /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/, - /** - * Unused - */ - ipv6: /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/, - base64: /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/, - nanoid: /^[a-zA-Z0-9_-]{21}$/, -}; -function string_parseStringDef(def, refs) { - const res = { - type: 'string', - }; - function processPattern(value) { - return refs.patternStrategy === 'escape' ? string_escapeNonAlphaNumeric(value) : value; - } - if (def.checks) { - for (const check of def.checks) { - switch (check.kind) { - case 'min': - errorMessages_setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - break; - case 'max': - errorMessages_setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case 'email': - switch (refs.emailStrategy) { - case 'format:email': - string_addFormat(res, 'email', check.message, refs); - break; - case 'format:idn-email': - string_addFormat(res, 'idn-email', check.message, refs); - break; - case 'pattern:zod': - string_addPattern(res, string_zodPatterns.email, check.message, refs); - break; - } - break; - case 'url': - string_addFormat(res, 'uri', check.message, refs); - break; - case 'uuid': - string_addFormat(res, 'uuid', check.message, refs); - break; - case 'regex': - string_addPattern(res, check.regex, check.message, refs); - break; - case 'cuid': - string_addPattern(res, string_zodPatterns.cuid, check.message, refs); - break; - case 'cuid2': - string_addPattern(res, string_zodPatterns.cuid2, check.message, refs); - break; - case 'startsWith': - string_addPattern(res, RegExp(`^${processPattern(check.value)}`), check.message, refs); - break; - case 'endsWith': - string_addPattern(res, RegExp(`${processPattern(check.value)}$`), check.message, refs); - break; - case 'datetime': - string_addFormat(res, 'date-time', check.message, refs); - break; - case 'date': - string_addFormat(res, 'date', check.message, refs); - break; - case 'time': - string_addFormat(res, 'time', check.message, refs); - break; - case 'duration': - string_addFormat(res, 'duration', check.message, refs); - break; - case 'length': - errorMessages_setResponseValueAndErrors(res, 'minLength', typeof res.minLength === 'number' ? Math.max(res.minLength, check.value) : check.value, check.message, refs); - errorMessages_setResponseValueAndErrors(res, 'maxLength', typeof res.maxLength === 'number' ? Math.min(res.maxLength, check.value) : check.value, check.message, refs); - break; - case 'includes': { - string_addPattern(res, RegExp(processPattern(check.value)), check.message, refs); - break; - } - case 'ip': { - if (check.version !== 'v6') { - string_addFormat(res, 'ipv4', check.message, refs); - } - if (check.version !== 'v4') { - string_addFormat(res, 'ipv6', check.message, refs); - } - break; - } - case 'emoji': - string_addPattern(res, string_zodPatterns.emoji, check.message, refs); - break; - case 'ulid': { - string_addPattern(res, string_zodPatterns.ulid, check.message, refs); - break; - } - case 'base64': { - switch (refs.base64Strategy) { - case 'format:binary': { - string_addFormat(res, 'binary', check.message, refs); - break; - } - case 'contentEncoding:base64': { - errorMessages_setResponseValueAndErrors(res, 'contentEncoding', 'base64', check.message, refs); - break; - } - case 'pattern:zod': { - string_addPattern(res, string_zodPatterns.base64, check.message, refs); - break; - } - } - break; - } - case 'nanoid': { - string_addPattern(res, string_zodPatterns.nanoid, check.message, refs); - } - case 'toLowerCase': - case 'toUpperCase': - case 'trim': - break; - default: - ((_) => { })(check); - } - } - } - return res; -} -const string_escapeNonAlphaNumeric = (value) => Array.from(value) - .map((c) => (/[a-zA-Z0-9]/.test(c) ? c : `\\${c}`)) - .join(''); -const string_addFormat = (schema, value, message, refs) => { - if (schema.format || schema.anyOf?.some((x) => x.format)) { - if (!schema.anyOf) { - schema.anyOf = []; - } - if (schema.format) { - schema.anyOf.push({ - format: schema.format, - ...(schema.errorMessage && - refs.errorMessages && { - errorMessage: { format: schema.errorMessage.format }, - }), - }); - delete schema.format; - if (schema.errorMessage) { - delete schema.errorMessage.format; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.anyOf.push({ - format: value, - ...(message && refs.errorMessages && { errorMessage: { format: message } }), - }); - } - else { - errorMessages_setResponseValueAndErrors(schema, 'format', value, message, refs); - } -}; -const string_addPattern = (schema, regex, message, refs) => { - if (schema.pattern || schema.allOf?.some((x) => x.pattern)) { - if (!schema.allOf) { - schema.allOf = []; - } - if (schema.pattern) { - schema.allOf.push({ - pattern: schema.pattern, - ...(schema.errorMessage && - refs.errorMessages && { - errorMessage: { pattern: schema.errorMessage.pattern }, - }), - }); - delete schema.pattern; - if (schema.errorMessage) { - delete schema.errorMessage.pattern; - if (Object.keys(schema.errorMessage).length === 0) { - delete schema.errorMessage; - } - } - } - schema.allOf.push({ - pattern: processRegExp(regex, refs), - ...(message && refs.errorMessages && { errorMessage: { pattern: message } }), - }); - } - else { - errorMessages_setResponseValueAndErrors(schema, 'pattern', processRegExp(regex, refs), message, refs); - } -}; -// Mutate z.string.regex() in a best attempt to accommodate for regex flags when applyRegexFlags is true -const processRegExp = (regexOrFunction, refs) => { - const regex = typeof regexOrFunction === 'function' ? regexOrFunction() : regexOrFunction; - if (!refs.applyRegexFlags || !regex.flags) - return regex.source; - // Currently handled flags - const flags = { - i: regex.flags.includes('i'), // Case-insensitive - m: regex.flags.includes('m'), // `^` and `$` matches adjacent to newline characters - s: regex.flags.includes('s'), // `.` matches newlines - }; - // The general principle here is to step through each character, one at a time, applying mutations as flags require. We keep track when the current character is escaped, and when it's inside a group /like [this]/ or (also) a range like /[a-z]/. The following is fairly brittle imperative code; edit at your peril! - const source = flags.i ? regex.source.toLowerCase() : regex.source; - let pattern = ''; - let isEscaped = false; - let inCharGroup = false; - let inCharRange = false; - for (let i = 0; i < source.length; i++) { - if (isEscaped) { - pattern += source[i]; - isEscaped = false; - continue; - } - if (flags.i) { - if (inCharGroup) { - if (source[i].match(/[a-z]/)) { - if (inCharRange) { - pattern += source[i]; - pattern += `${source[i - 2]}-${source[i]}`.toUpperCase(); - inCharRange = false; - } - else if (source[i + 1] === '-' && source[i + 2]?.match(/[a-z]/)) { - pattern += source[i]; - inCharRange = true; - } - else { - pattern += `${source[i]}${source[i].toUpperCase()}`; - } - continue; - } - } - else if (source[i].match(/[a-z]/)) { - pattern += `[${source[i]}${source[i].toUpperCase()}]`; - continue; - } - } - if (flags.m) { - if (source[i] === '^') { - pattern += `(^|(?<=[\r\n]))`; - continue; - } - else if (source[i] === '$') { - pattern += `($|(?=[\r\n]))`; - continue; - } - } - if (flags.s && source[i] === '.') { - pattern += inCharGroup ? `${source[i]}\r\n` : `[${source[i]}\r\n]`; - continue; - } - pattern += source[i]; - if (source[i] === '\\') { - isEscaped = true; - } - else if (inCharGroup && source[i] === ']') { - inCharGroup = false; - } - else if (!inCharGroup && source[i] === '[') { - inCharGroup = true; - } - } - try { - const regexTest = new RegExp(pattern); - } - catch { - console.warn(`Could not convert regex pattern at ${refs.currentPath.join('/')} to a flag-independent form! Falling back to the flag-ignorant source`); - return regex.source; - } - return pattern; -}; -//# sourceMappingURL=string.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/record.mjs - - - -function record_parseRecordDef(def, refs) { - if (refs.target === 'openApi3' && def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - type: 'object', - required: def.keyType._def.values, - properties: def.keyType._def.values.reduce((acc, key) => ({ - ...acc, - [key]: parseDef_parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, 'properties', key], - }) ?? {}, - }), {}), - additionalProperties: false, - }; - } - const schema = { - type: 'object', - additionalProperties: parseDef_parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, 'additionalProperties'], - }) ?? {}, - }; - if (refs.target === 'openApi3') { - return schema; - } - if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodString && def.keyType._def.checks?.length) { - const keyType = Object.entries(string_parseStringDef(def.keyType._def, refs)).reduce((acc, [key, value]) => (key === 'type' ? acc : { ...acc, [key]: value }), {}); - return { - ...schema, - propertyNames: keyType, - }; - } - else if (def.keyType?._def.typeName === ZodFirstPartyTypeKind.ZodEnum) { - return { - ...schema, - propertyNames: { - enum: def.keyType._def.values, - }, - }; - } - return schema; -} -//# sourceMappingURL=record.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/map.mjs - - -function map_parseMapDef(def, refs) { - if (refs.mapStrategy === 'record') { - return record_parseRecordDef(def, refs); - } - const keys = parseDef_parseDef(def.keyType._def, { - ...refs, - currentPath: [...refs.currentPath, 'items', 'items', '0'], - }) || {}; - const values = parseDef_parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, 'items', 'items', '1'], - }) || {}; - return { - type: 'array', - maxItems: 125, - items: { - type: 'array', - items: [keys, values], - minItems: 2, - maxItems: 2, - }, - }; -} -//# sourceMappingURL=map.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/nativeEnum.mjs -function nativeEnum_parseNativeEnumDef(def) { - const object = def.values; - const actualKeys = Object.keys(def.values).filter((key) => { - return typeof object[object[key]] !== 'number'; - }); - const actualValues = actualKeys.map((key) => object[key]); - const parsedTypes = Array.from(new Set(actualValues.map((values) => typeof values))); - return { - type: parsedTypes.length === 1 ? - parsedTypes[0] === 'string' ? - 'string' - : 'number' - : ['string', 'number'], - enum: actualValues, - }; -} -//# sourceMappingURL=nativeEnum.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/never.mjs -function never_parseNeverDef() { - return { - not: {}, - }; -} -//# sourceMappingURL=never.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/null.mjs -function null_parseNullDef(refs) { - return refs.target === 'openApi3' ? - { - enum: ['null'], - nullable: true, - } - : { - type: 'null', - }; -} -//# sourceMappingURL=null.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/union.mjs - -const union_primitiveMappings = { - ZodString: 'string', - ZodNumber: 'number', - ZodBigInt: 'integer', - ZodBoolean: 'boolean', - ZodNull: 'null', -}; -function union_parseUnionDef(def, refs) { - if (refs.target === 'openApi3') - return union_asAnyOf(def, refs); - const options = def.options instanceof Map ? Array.from(def.options.values()) : def.options; - // This blocks tries to look ahead a bit to produce nicer looking schemas with type array instead of anyOf. - if (options.every((x) => x._def.typeName in union_primitiveMappings && (!x._def.checks || !x._def.checks.length))) { - // all types in union are primitive and lack checks, so might as well squash into {type: [...]} - const types = options.reduce((types, x) => { - const type = union_primitiveMappings[x._def.typeName]; //Can be safely casted due to row 43 - return type && !types.includes(type) ? [...types, type] : types; - }, []); - return { - type: types.length > 1 ? types : types[0], - }; - } - else if (options.every((x) => x._def.typeName === 'ZodLiteral' && !x.description)) { - // all options literals - const types = options.reduce((acc, x) => { - const type = typeof x._def.value; - switch (type) { - case 'string': - case 'number': - case 'boolean': - return [...acc, type]; - case 'bigint': - return [...acc, 'integer']; - case 'object': - if (x._def.value === null) - return [...acc, 'null']; - case 'symbol': - case 'undefined': - case 'function': - default: - return acc; - } - }, []); - if (types.length === options.length) { - // all the literals are primitive, as far as null can be considered primitive - const uniqueTypes = types.filter((x, i, a) => a.indexOf(x) === i); - return { - type: uniqueTypes.length > 1 ? uniqueTypes : uniqueTypes[0], - enum: options.reduce((acc, x) => { - return acc.includes(x._def.value) ? acc : [...acc, x._def.value]; - }, []), - }; - } - } - else if (options.every((x) => x._def.typeName === 'ZodEnum')) { - return { - type: 'string', - enum: options.reduce((acc, x) => [...acc, ...x._def.values.filter((x) => !acc.includes(x))], []), - }; - } - return union_asAnyOf(def, refs); -} -const union_asAnyOf = (def, refs) => { - const anyOf = (def.options instanceof Map ? Array.from(def.options.values()) : def.options) - .map((x, i) => parseDef_parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, 'anyOf', `${i}`], - })) - .filter((x) => !!x && (!refs.strictUnions || (typeof x === 'object' && Object.keys(x).length > 0))); - return anyOf.length ? { anyOf } : undefined; -}; -//# sourceMappingURL=union.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/nullable.mjs - - -function nullable_parseNullableDef(def, refs) { - if (['ZodString', 'ZodNumber', 'ZodBigInt', 'ZodBoolean', 'ZodNull'].includes(def.innerType._def.typeName) && - (!def.innerType._def.checks || !def.innerType._def.checks.length)) { - if (refs.target === 'openApi3' || refs.nullableStrategy === 'property') { - return { - type: union_primitiveMappings[def.innerType._def.typeName], - nullable: true, - }; - } - return { - type: [union_primitiveMappings[def.innerType._def.typeName], 'null'], - }; - } - if (refs.target === 'openApi3') { - const base = parseDef_parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath], - }); - if (base && '$ref' in base) - return { allOf: [base], nullable: true }; - return base && { ...base, nullable: true }; - } - const base = parseDef_parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, 'anyOf', '0'], - }); - return base && { anyOf: [base, { type: 'null' }] }; -} -//# sourceMappingURL=nullable.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/number.mjs - -function number_parseNumberDef(def, refs) { - const res = { - type: 'number', - }; - if (!def.checks) - return res; - for (const check of def.checks) { - switch (check.kind) { - case 'int': - res.type = 'integer'; - errorMessages_addErrorMessage(res, 'type', check.message, refs); - break; - case 'min': - if (refs.target === 'jsonSchema7') { - if (check.inclusive) { - errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); - } - else { - errorMessages_setResponseValueAndErrors(res, 'exclusiveMinimum', check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMinimum = true; - } - errorMessages_setResponseValueAndErrors(res, 'minimum', check.value, check.message, refs); - } - break; - case 'max': - if (refs.target === 'jsonSchema7') { - if (check.inclusive) { - errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); - } - else { - errorMessages_setResponseValueAndErrors(res, 'exclusiveMaximum', check.value, check.message, refs); - } - } - else { - if (!check.inclusive) { - res.exclusiveMaximum = true; - } - errorMessages_setResponseValueAndErrors(res, 'maximum', check.value, check.message, refs); - } - break; - case 'multipleOf': - errorMessages_setResponseValueAndErrors(res, 'multipleOf', check.value, check.message, refs); - break; - } - } - return res; -} -//# sourceMappingURL=number.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/object.mjs - -function object_decideAdditionalProperties(def, refs) { - if (refs.removeAdditionalStrategy === 'strict') { - return def.catchall._def.typeName === 'ZodNever' ? - def.unknownKeys !== 'strict' - : parseDef_parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, 'additionalProperties'], - }) ?? true; - } - else { - return def.catchall._def.typeName === 'ZodNever' ? - def.unknownKeys === 'passthrough' - : parseDef_parseDef(def.catchall._def, { - ...refs, - currentPath: [...refs.currentPath, 'additionalProperties'], - }) ?? true; - } -} -function object_parseObjectDef(def, refs) { - const result = { - type: 'object', - ...Object.entries(def.shape()).reduce((acc, [propName, propDef]) => { - if (propDef === undefined || propDef._def === undefined) - return acc; - const propertyPath = [...refs.currentPath, 'properties', propName]; - const parsedDef = parseDef_parseDef(propDef._def, { - ...refs, - currentPath: propertyPath, - propertyPath, - }); - if (parsedDef === undefined) - return acc; - if (refs.openaiStrictMode && - propDef.isOptional() && - !propDef.isNullable() && - typeof propDef._def?.defaultValue === 'undefined') { - throw new Error(`Zod field at \`${propertyPath.join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`); - } - return { - properties: { - ...acc.properties, - [propName]: parsedDef, - }, - required: propDef.isOptional() && !refs.openaiStrictMode ? acc.required : [...acc.required, propName], - }; - }, { properties: {}, required: [] }), - additionalProperties: object_decideAdditionalProperties(def, refs), - }; - if (!result.required.length) - delete result.required; - return result; -} -//# sourceMappingURL=object.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/optional.mjs - -const optional_parseOptionalDef = (def, refs) => { - if (refs.propertyPath && - refs.currentPath.slice(0, refs.propertyPath.length).toString() === refs.propertyPath.toString()) { - return parseDef_parseDef(def.innerType._def, { ...refs, currentPath: refs.currentPath }); - } - const innerSchema = parseDef_parseDef(def.innerType._def, { - ...refs, - currentPath: [...refs.currentPath, 'anyOf', '1'], - }); - return innerSchema ? - { - anyOf: [ - { - not: {}, - }, - innerSchema, - ], - } - : {}; -}; -//# sourceMappingURL=optional.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/pipeline.mjs - -const pipeline_parsePipelineDef = (def, refs) => { - if (refs.pipeStrategy === 'input') { - return parseDef_parseDef(def.in._def, refs); - } - else if (refs.pipeStrategy === 'output') { - return parseDef_parseDef(def.out._def, refs); - } - const a = parseDef_parseDef(def.in._def, { - ...refs, - currentPath: [...refs.currentPath, 'allOf', '0'], - }); - const b = parseDef_parseDef(def.out._def, { - ...refs, - currentPath: [...refs.currentPath, 'allOf', a ? '1' : '0'], - }); - return { - allOf: [a, b].filter((x) => x !== undefined), - }; -}; -//# sourceMappingURL=pipeline.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/promise.mjs - -function promise_parsePromiseDef(def, refs) { - return parseDef_parseDef(def.type._def, refs); -} -//# sourceMappingURL=promise.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/set.mjs - - -function set_parseSetDef(def, refs) { - const items = parseDef_parseDef(def.valueType._def, { - ...refs, - currentPath: [...refs.currentPath, 'items'], - }); - const schema = { - type: 'array', - uniqueItems: true, - items, - }; - if (def.minSize) { - errorMessages_setResponseValueAndErrors(schema, 'minItems', def.minSize.value, def.minSize.message, refs); - } - if (def.maxSize) { - errorMessages_setResponseValueAndErrors(schema, 'maxItems', def.maxSize.value, def.maxSize.message, refs); - } - return schema; -} -//# sourceMappingURL=set.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/tuple.mjs - -function tuple_parseTupleDef(def, refs) { - if (def.rest) { - return { - type: 'array', - minItems: def.items.length, - items: def.items - .map((x, i) => parseDef_parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, 'items', `${i}`], - })) - .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), - additionalItems: parseDef_parseDef(def.rest._def, { - ...refs, - currentPath: [...refs.currentPath, 'additionalItems'], - }), - }; - } - else { - return { - type: 'array', - minItems: def.items.length, - maxItems: def.items.length, - items: def.items - .map((x, i) => parseDef_parseDef(x._def, { - ...refs, - currentPath: [...refs.currentPath, 'items', `${i}`], - })) - .reduce((acc, x) => (x === undefined ? acc : [...acc, x]), []), - }; - } -} -//# sourceMappingURL=tuple.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/undefined.mjs -function undefined_parseUndefinedDef() { - return { - not: {}, - }; -} -//# sourceMappingURL=undefined.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/unknown.mjs -function unknown_parseUnknownDef() { - return {}; -} -//# sourceMappingURL=unknown.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parsers/readonly.mjs - -const readonly_parseReadonlyDef = (def, refs) => { - return parseDef_parseDef(def.innerType._def, refs); -}; -//# sourceMappingURL=readonly.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/parseDef.mjs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -function parseDef_parseDef(def, refs, forceResolution = false) { - const seenItem = refs.seen.get(def); - if (refs.override) { - const overrideResult = refs.override?.(def, refs, seenItem, forceResolution); - if (overrideResult !== Options_ignoreOverride) { - return overrideResult; - } - } - if (seenItem && !forceResolution) { - const seenSchema = parseDef_get$ref(seenItem, refs); - if (seenSchema !== undefined) { - if ('$ref' in seenSchema) { - refs.seenRefs.add(seenSchema.$ref); - } - return seenSchema; - } - } - const newItem = { def, path: refs.currentPath, jsonSchema: undefined }; - refs.seen.set(def, newItem); - const jsonSchema = parseDef_selectParser(def, def.typeName, refs, forceResolution); - if (jsonSchema) { - parseDef_addMeta(def, refs, jsonSchema); - } - newItem.jsonSchema = jsonSchema; - return jsonSchema; -} -const parseDef_get$ref = (item, refs) => { - switch (refs.$refStrategy) { - case 'root': - return { $ref: item.path.join('/') }; - // this case is needed as OpenAI strict mode doesn't support top-level `$ref`s, i.e. - // the top-level schema *must* be `{"type": "object", "properties": {...}}` but if we ever - // need to define a `$ref`, relative `$ref`s aren't supported, so we need to extract - // the schema to `#/definitions/` and reference that. - // - // e.g. if we need to reference a schema at - // `["#","definitions","contactPerson","properties","person1","properties","name"]` - // then we'll extract it out to `contactPerson_properties_person1_properties_name` - case 'extract-to-root': - const name = item.path.slice(refs.basePath.length + 1).join('_'); - // we don't need to extract the root schema in this case, as it's already - // been added to the definitions - if (name !== refs.name && refs.nameStrategy === 'duplicate-ref') { - refs.definitions[name] = item.def; - } - return { $ref: [...refs.basePath, refs.definitionPath, name].join('/') }; - case 'relative': - return { $ref: parseDef_getRelativePath(refs.currentPath, item.path) }; - case 'none': - case 'seen': { - if (item.path.length < refs.currentPath.length && - item.path.every((value, index) => refs.currentPath[index] === value)) { - console.warn(`Recursive reference detected at ${refs.currentPath.join('/')}! Defaulting to any`); - return {}; - } - return refs.$refStrategy === 'seen' ? {} : undefined; - } - } -}; -const parseDef_getRelativePath = (pathA, pathB) => { - let i = 0; - for (; i < pathA.length && i < pathB.length; i++) { - if (pathA[i] !== pathB[i]) - break; - } - return [(pathA.length - i).toString(), ...pathB.slice(i)].join('/'); -}; -const parseDef_selectParser = (def, typeName, refs, forceResolution) => { - switch (typeName) { - case ZodFirstPartyTypeKind.ZodString: - return string_parseStringDef(def, refs); - case ZodFirstPartyTypeKind.ZodNumber: - return number_parseNumberDef(def, refs); - case ZodFirstPartyTypeKind.ZodObject: - return object_parseObjectDef(def, refs); - case ZodFirstPartyTypeKind.ZodBigInt: - return bigint_parseBigintDef(def, refs); - case ZodFirstPartyTypeKind.ZodBoolean: - return boolean_parseBooleanDef(); - case ZodFirstPartyTypeKind.ZodDate: - return date_parseDateDef(def, refs); - case ZodFirstPartyTypeKind.ZodUndefined: - return undefined_parseUndefinedDef(); - case ZodFirstPartyTypeKind.ZodNull: - return null_parseNullDef(refs); - case ZodFirstPartyTypeKind.ZodArray: - return array_parseArrayDef(def, refs); - case ZodFirstPartyTypeKind.ZodUnion: - case ZodFirstPartyTypeKind.ZodDiscriminatedUnion: - return union_parseUnionDef(def, refs); - case ZodFirstPartyTypeKind.ZodIntersection: - return intersection_parseIntersectionDef(def, refs); - case ZodFirstPartyTypeKind.ZodTuple: - return tuple_parseTupleDef(def, refs); - case ZodFirstPartyTypeKind.ZodRecord: - return record_parseRecordDef(def, refs); - case ZodFirstPartyTypeKind.ZodLiteral: - return literal_parseLiteralDef(def, refs); - case ZodFirstPartyTypeKind.ZodEnum: - return enum_parseEnumDef(def); - case ZodFirstPartyTypeKind.ZodNativeEnum: - return nativeEnum_parseNativeEnumDef(def); - case ZodFirstPartyTypeKind.ZodNullable: - return nullable_parseNullableDef(def, refs); - case ZodFirstPartyTypeKind.ZodOptional: - return optional_parseOptionalDef(def, refs); - case ZodFirstPartyTypeKind.ZodMap: - return map_parseMapDef(def, refs); - case ZodFirstPartyTypeKind.ZodSet: - return set_parseSetDef(def, refs); - case ZodFirstPartyTypeKind.ZodLazy: - return parseDef_parseDef(def.getter()._def, refs); - case ZodFirstPartyTypeKind.ZodPromise: - return promise_parsePromiseDef(def, refs); - case ZodFirstPartyTypeKind.ZodNaN: - case ZodFirstPartyTypeKind.ZodNever: - return never_parseNeverDef(); - case ZodFirstPartyTypeKind.ZodEffects: - return effects_parseEffectsDef(def, refs, forceResolution); - case ZodFirstPartyTypeKind.ZodAny: - return any_parseAnyDef(); - case ZodFirstPartyTypeKind.ZodUnknown: - return unknown_parseUnknownDef(); - case ZodFirstPartyTypeKind.ZodDefault: - return default_parseDefaultDef(def, refs); - case ZodFirstPartyTypeKind.ZodBranded: - return branded_parseBrandedDef(def, refs); - case ZodFirstPartyTypeKind.ZodReadonly: - return readonly_parseReadonlyDef(def, refs); - case ZodFirstPartyTypeKind.ZodCatch: - return catch_parseCatchDef(def, refs); - case ZodFirstPartyTypeKind.ZodPipeline: - return pipeline_parsePipelineDef(def, refs); - case ZodFirstPartyTypeKind.ZodFunction: - case ZodFirstPartyTypeKind.ZodVoid: - case ZodFirstPartyTypeKind.ZodSymbol: - return undefined; - default: - return ((_) => undefined)(typeName); - } -}; -const parseDef_addMeta = (def, refs, jsonSchema) => { - if (def.description) { - jsonSchema.description = def.description; - if (refs.markdownDescription) { - jsonSchema.markdownDescription = def.description; - } - } - return jsonSchema; -}; -//# sourceMappingURL=parseDef.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/zodToJsonSchema.mjs - - - -const zod_to_json_schema_zodToJsonSchema_zodToJsonSchema = (schema, options) => { - const refs = Refs_getRefs(options); - const name = typeof options === 'string' ? options - : options?.nameStrategy === 'title' ? undefined - : options?.name; - const main = parseDef_parseDef(schema._def, name === undefined ? refs : ({ - ...refs, - currentPath: [...refs.basePath, refs.definitionPath, name], - }), false) ?? {}; - const title = typeof options === 'object' && options.name !== undefined && options.nameStrategy === 'title' ? - options.name - : undefined; - if (title !== undefined) { - main.title = title; - } - const definitions = (() => { - if (util_isEmptyObj(refs.definitions)) { - return undefined; - } - const definitions = {}; - const processedDefinitions = new Set(); - // the call to `parseDef()` here might itself add more entries to `.definitions` - // so we need to continually evaluate definitions until we've resolved all of them - // - // we have a generous iteration limit here to avoid blowing up the stack if there - // are any bugs that would otherwise result in us iterating indefinitely - for (let i = 0; i < 500; i++) { - const newDefinitions = Object.entries(refs.definitions).filter(([key]) => !processedDefinitions.has(key)); - if (newDefinitions.length === 0) - break; - for (const [key, schema] of newDefinitions) { - definitions[key] = - parseDef_parseDef(zodDef(schema), { ...refs, currentPath: [...refs.basePath, refs.definitionPath, key] }, true) ?? {}; - processedDefinitions.add(key); - } - } - return definitions; - })(); - const combined = name === undefined ? - definitions ? - { - ...main, - [refs.definitionPath]: definitions, - } - : main - : refs.nameStrategy === 'duplicate-ref' ? - { - ...main, - ...(definitions || refs.seenRefs.size ? - { - [refs.definitionPath]: { - ...definitions, - // only actually duplicate the schema definition if it was ever referenced - // otherwise the duplication is completely pointless - ...(refs.seenRefs.size ? { [name]: main } : undefined), - }, - } - : undefined), - } - : { - $ref: [...(refs.$refStrategy === 'relative' ? [] : refs.basePath), refs.definitionPath, name].join('/'), - [refs.definitionPath]: { - ...definitions, - [name]: main, - }, - }; - if (refs.target === 'jsonSchema7') { - combined.$schema = 'http://json-schema.org/draft-07/schema#'; - } - else if (refs.target === 'jsonSchema2019-09') { - combined.$schema = 'https://json-schema.org/draft/2019-09/schema#'; - } - return combined; -}; - -//# sourceMappingURL=zodToJsonSchema.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/_vendor/zod-to-json-schema/index.mjs - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -/* harmony default export */ const zod_to_json_schema = ((/* unused pure expression or super */ null && (zodToJsonSchema))); -//# sourceMappingURL=index.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/lib/transform.mjs -function toStrictJsonSchema(schema) { - if (schema.type !== 'object') { - throw new Error(`Root schema must have type: 'object' but got type: ${schema.type ? `'${schema.type}'` : 'undefined'}`); - } - const schemaCopy = structuredClone(schema); - return ensureStrictJsonSchema(schemaCopy, [], schemaCopy); -} -function isNullable(schema) { - if (typeof schema === 'boolean') { - return false; - } - if (schema.type === 'null') { - return true; - } - for (const oneOfVariant of schema.oneOf ?? []) { - if (isNullable(oneOfVariant)) { - return true; - } - } - for (const allOfVariant of schema.anyOf ?? []) { - if (isNullable(allOfVariant)) { - return true; - } - } - return false; -} -/** - * Mutates the given JSON schema to ensure it conforms to the `strict` standard - * that the API expects. - */ -function ensureStrictJsonSchema(jsonSchema, path, root) { - if (typeof jsonSchema === 'boolean') { - throw new TypeError(`Expected object schema but got boolean; path=${path.join('/')}`); - } - if (!transform_isObject(jsonSchema)) { - throw new TypeError(`Expected ${JSON.stringify(jsonSchema)} to be an object; path=${path.join('/')}`); - } - // Handle $defs (non-standard but sometimes used) - const defs = jsonSchema.$defs; - if (transform_isObject(defs)) { - for (const [defName, defSchema] of Object.entries(defs)) { - ensureStrictJsonSchema(defSchema, [...path, '$defs', defName], root); - } - } - // Handle definitions (draft-04 style, deprecated in draft-07 but still used) - const definitions = jsonSchema.definitions; - if (transform_isObject(definitions)) { - for (const [definitionName, definitionSchema] of Object.entries(definitions)) { - ensureStrictJsonSchema(definitionSchema, [...path, 'definitions', definitionName], root); - } - } - // Add additionalProperties: false to object types - const typ = jsonSchema.type; - if (typ === 'object' && !('additionalProperties' in jsonSchema)) { - jsonSchema.additionalProperties = false; - } - const required = jsonSchema.required ?? []; - // Handle object properties - const properties = jsonSchema.properties; - if (transform_isObject(properties)) { - for (const [key, value] of Object.entries(properties)) { - if (!isNullable(value) && !required.includes(key)) { - throw new Error(`Zod field at \`${[...path, 'properties', key].join('/')}\` uses \`.optional()\` without \`.nullable()\` which is not supported by the API. See: https://platform.openai.com/docs/guides/structured-outputs?api-mode=responses#all-fields-must-be-required`); - } - } - jsonSchema.required = Object.keys(properties); - jsonSchema.properties = Object.fromEntries(Object.entries(properties).map(([key, propSchema]) => [ - key, - ensureStrictJsonSchema(propSchema, [...path, 'properties', key], root), - ])); - } - // Handle arrays - const items = jsonSchema.items; - if (transform_isObject(items)) { - jsonSchema.items = ensureStrictJsonSchema(items, [...path, 'items'], root); - } - // Handle unions (anyOf) - const anyOf = jsonSchema.anyOf; - if (Array.isArray(anyOf)) { - jsonSchema.anyOf = anyOf.map((variant, i) => ensureStrictJsonSchema(variant, [...path, 'anyOf', String(i)], root)); - } - // Handle intersections (allOf) - const allOf = jsonSchema.allOf; - if (Array.isArray(allOf)) { - if (allOf.length === 1) { - const resolved = ensureStrictJsonSchema(allOf[0], [...path, 'allOf', '0'], root); - Object.assign(jsonSchema, resolved); - delete jsonSchema.allOf; - } - else { - jsonSchema.allOf = allOf.map((entry, i) => ensureStrictJsonSchema(entry, [...path, 'allOf', String(i)], root)); - } - } - // Strip `null` defaults as there's no meaningful distinction - if (jsonSchema.default === null) { - delete jsonSchema.default; - } - // Handle $ref with additional properties - const ref = jsonSchema.$ref; - if (ref && hasMoreThanNKeys(jsonSchema, 1)) { - if (typeof ref !== 'string') { - throw new TypeError(`Received non-string $ref - ${ref}; path=${path.join('/')}`); - } - const resolved = transform_resolveRef(root, ref); - if (typeof resolved === 'boolean') { - throw new Error(`Expected \`$ref: ${ref}\` to resolve to an object schema but got boolean`); - } - if (!transform_isObject(resolved)) { - throw new Error(`Expected \`$ref: ${ref}\` to resolve to an object but got ${JSON.stringify(resolved)}`); - } - // Properties from the json schema take priority over the ones on the `$ref` - Object.assign(jsonSchema, { ...resolved, ...jsonSchema }); - delete jsonSchema.$ref; - // Since the schema expanded from `$ref` might not have `additionalProperties: false` applied, - // we call `ensureStrictJsonSchema` again to fix the inlined schema and ensure it's valid. - return ensureStrictJsonSchema(jsonSchema, path, root); - } - return jsonSchema; -} -function transform_resolveRef(root, ref) { - if (!ref.startsWith('#/')) { - throw new Error(`Unexpected $ref format ${JSON.stringify(ref)}; Does not start with #/`); - } - const pathParts = ref.slice(2).split('/'); - let resolved = root; - for (const key of pathParts) { - if (!transform_isObject(resolved)) { - throw new Error(`encountered non-object entry while resolving ${ref} - ${JSON.stringify(resolved)}`); - } - const value = resolved[key]; - if (value === undefined) { - throw new Error(`Key ${key} not found while resolving ${ref}`); - } - resolved = value; - } - return resolved; -} -function transform_isObject(obj) { - return typeof obj === 'object' && obj !== null && !Array.isArray(obj); -} -function hasMoreThanNKeys(obj, n) { - let i = 0; - for (const _ in obj) { - i++; - if (i > n) { - return true; - } - } - return false; -} -//# sourceMappingURL=transform.mjs.map -;// CONCATENATED MODULE: ./node_modules/openai/helpers/zod.mjs - - - - - -function zodV3ToJsonSchema(schema, options) { - return zod_to_json_schema_zodToJsonSchema_zodToJsonSchema(schema, { - openaiStrictMode: true, - name: options.name, - nameStrategy: 'duplicate-ref', - $refStrategy: 'extract-to-root', - nullableStrategy: 'property', - }); -} -function zodV4ToJsonSchema(schema) { - return toStrictJsonSchema(toJSONSchema(schema, { - target: 'draft-7', - })); -} -function isZodV4(zodObject) { - return '_zod' in zodObject; -} -/** - * Creates a chat completion `JSONSchema` response format object from - * the given Zod schema. - * - * If this is passed to the `.parse()`, `.stream()` or `.runTools()` - * chat completion methods then the response message will contain a - * `.parsed` property that is the result of parsing the content with - * the given Zod object. - * - * ```ts - * const completion = await client.chat.completions.parse({ - * model: 'gpt-4o-2024-08-06', - * messages: [ - * { role: 'system', content: 'You are a helpful math tutor.' }, - * { role: 'user', content: 'solve 8x + 31 = 2' }, - * ], - * response_format: zodResponseFormat( - * z.object({ - * steps: z.array(z.object({ - * explanation: z.string(), - * answer: z.string(), - * })), - * final_answer: z.string(), - * }), - * 'math_answer', - * ), - * }); - * const message = completion.choices[0]?.message; - * if (message?.parsed) { - * console.log(message.parsed); - * console.log(message.parsed.final_answer); - * } - * ``` - * - * This can be passed directly to the `.create()` method but will not - * result in any automatic parsing, you'll have to parse the response yourself. - */ -function zodResponseFormat(zodObject, name, props) { - return makeParseableResponseFormat({ - type: 'json_schema', - json_schema: { - ...props, - name, - strict: true, - schema: isZodV4(zodObject) ? zodV4ToJsonSchema(zodObject) : zodV3ToJsonSchema(zodObject, { name }), - }, - }, (content) => zodObject.parse(JSON.parse(content))); -} -function zodTextFormat(zodObject, name, props) { - return makeParseableTextFormat({ - type: 'json_schema', - ...props, - name, - strict: true, - schema: isZodV4(zodObject) ? zodV4ToJsonSchema(zodObject) : zodV3ToJsonSchema(zodObject, { name }), - }, (content) => zodObject.parse(JSON.parse(content))); -} -/** - * Creates a chat completion `function` tool that can be invoked - * automatically by the chat completion `.runTools()` method or automatically - * parsed by `.parse()` / `.stream()`. - */ -function zodFunction(options) { - // @ts-expect-error TODO - return makeParseableTool({ - type: 'function', - function: { - name: options.name, - parameters: isZodV4(options.parameters) ? - zodV4ToJsonSchema(options.parameters) - : zodV3ToJsonSchema(options.parameters, { name: options.name }), - strict: true, - ...(options.description ? { description: options.description } : undefined), - }, - }, { - callback: options.function, - parser: (args) => options.parameters.parse(JSON.parse(args)), - }); -} -function zodResponsesFunction(options) { - return makeParseableResponseTool({ - type: 'function', - name: options.name, - parameters: isZodV4(options.parameters) ? - zodV4ToJsonSchema(options.parameters) - : zodV3ToJsonSchema(options.parameters, { name: options.name }), - strict: true, - ...(options.description ? { description: options.description } : undefined), - }, { - callback: options.function, - parser: (args) => options.parameters.parse(JSON.parse(args)), - }); -} -//# sourceMappingURL=zod.mjs.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/output.js - - - - - -//#region src/utils/output.ts -const SUPPORTED_METHODS = [ - "jsonSchema", - "functionCalling", - "jsonMode" -]; -/** -* Get the structured output method for a given model. By default, it uses -* `jsonSchema` if the model supports it, otherwise it uses `functionCalling`. -* -* @throws if the method is invalid, e.g. is not a string or invalid method is provided. -* @param model - The model name. -* @param config - The structured output method options. -* @returns The structured output method. -*/ -function getStructuredOutputMethod(model, method) { - /** - * If a method is provided, validate it. - */ - if (typeof method !== "undefined" && !SUPPORTED_METHODS.includes(method)) throw new Error(`Invalid method: ${method}. Supported methods are: ${SUPPORTED_METHODS.join(", ")}`); - const hasSupportForJsonSchema = !model.startsWith("gpt-3") && !model.startsWith("gpt-4-") && model !== "gpt-4"; - /** - * If the model supports JSON Schema, use it by default. - */ - if (hasSupportForJsonSchema && !method) return "jsonSchema"; - if (!hasSupportForJsonSchema && method === "jsonSchema") throw new Error(`JSON Schema is not supported for model "${model}". Please use a different method, e.g. "functionCalling" or "jsonMode".`); - /** - * If the model does not support JSON Schema, use function calling by default. - */ - return method ?? "functionCalling"; -} -function output_makeParseableResponseFormat(response_format, parser) { - const obj = { ...response_format }; - Object.defineProperties(obj, { - $brand: { - value: "auto-parseable-response-format", - enumerable: false - }, - $parseRaw: { - value: parser, - enumerable: false - } - }); - return obj; -} -function interopZodResponseFormat(zodSchema, name, props) { - if (isZodSchemaV3(zodSchema)) return zodResponseFormat(zodSchema, name, props); - if (isZodSchemaV4(zodSchema)) return output_makeParseableResponseFormat({ - type: "json_schema", - json_schema: { - ...props, - name, - strict: true, - schema: toJsonSchema(zodSchema, { - cycles: "ref", - reused: "ref", - override(ctx) { - ctx.jsonSchema.title = name; - } - }) - } - }, (content) => parse_parse(zodSchema, JSON.parse(content))); - throw new Error("Unsupported schema response format"); -} -/** -* Handle multi modal response content. -* -* @param content The content of the message. -* @param messages The messages of the response. -* @returns The new content of the message. -*/ -function handleMultiModalOutput(content, messages) { - /** - * Handle OpenRouter image responses - * @see https://openrouter.ai/docs/features/multimodal/image-generation#api-usage - */ - if (messages && typeof messages === "object" && "images" in messages && Array.isArray(messages.images)) { - const images = messages.images.filter((image) => typeof image?.image_url?.url === "string").map((image) => ({ - type: "image", - url: image.image_url.url - })); - return [{ - type: "text", - text: content - }, ...images]; - } - return content; -} - -//#endregion - -//# sourceMappingURL=output.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/profiles.js -//#region src/chat_models/profiles.ts -const profiles_PROFILES = { - "gpt-4.1-nano": { - maxInputTokens: 1047576, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32768, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "text-embedding-3-small": { - maxInputTokens: 8191, - imageInputs: false, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 1536, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: false, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-4": { - maxInputTokens: 8192, - imageInputs: false, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "o1-pro": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 1e5, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-4o-2024-05-13": { - maxInputTokens: 128e3, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 4096, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-4o-2024-08-06": { - maxInputTokens: 128e3, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 16384, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-4.1-mini": { - maxInputTokens: 1047576, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32768, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "o3-deep-research": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 1e5, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-3.5-turbo": { - maxInputTokens: 16385, - imageInputs: false, - audioInputs: false, - pdfInputs: false, - videoInputs: false, - maxOutputTokens: 4096, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: false, - structuredOutput: false, - imageUrlInputs: false, - pdfToolMessage: false, - imageToolMessage: false, - toolChoice: true - }, - "text-embedding-3-large": { - maxInputTokens: 8191, - imageInputs: false, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 3072, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: false, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-4-turbo": { - maxInputTokens: 128e3, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 4096, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "o1-preview": { - maxInputTokens: 128e3, - imageInputs: false, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32768, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: false, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "o3-mini": { - maxInputTokens: 2e5, - imageInputs: false, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 1e5, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "codex-mini-latest": { - maxInputTokens: 2e5, - imageInputs: false, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 1e5, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-5-nano": { - maxInputTokens: 4e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 128e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-5-codex": { - maxInputTokens: 4e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 128e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-4o": { - maxInputTokens: 128e3, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 16384, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-4.1": { - maxInputTokens: 1047576, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 32768, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "o4-mini": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 1e5, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - o1: { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 1e5, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-5-mini": { - maxInputTokens: 4e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 128e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "o1-mini": { - maxInputTokens: 128e3, - imageInputs: false, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: false, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "text-embedding-ada-002": { - maxInputTokens: 8192, - imageInputs: false, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 1536, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: false, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "o3-pro": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 1e5, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-4o-2024-11-20": { - maxInputTokens: 128e3, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 16384, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - o3: { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 1e5, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "o4-mini-deep-research": { - maxInputTokens: 2e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 1e5, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-5-chat-latest": { - maxInputTokens: 4e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 128e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: false, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-4o-mini": { - maxInputTokens: 128e3, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 16384, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-5": { - maxInputTokens: 4e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 128e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - }, - "gpt-5-pro": { - maxInputTokens: 4e5, - imageInputs: true, - audioInputs: false, - pdfInputs: true, - videoInputs: false, - maxOutputTokens: 272e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true, - imageUrlInputs: true, - pdfToolMessage: true, - imageToolMessage: true, - toolChoice: true - } -}; -var profiles_profiles_default = profiles_PROFILES; - -//#endregion - -//# sourceMappingURL=profiles.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/base.js - - - - - - - - - - - - - - - - -//#region src/chat_models/base.ts -/** @internal */ -var BaseChatOpenAI = class extends BaseChatModel { - temperature; - topP; - frequencyPenalty; - presencePenalty; - n; - logitBias; - model = "gpt-3.5-turbo"; - modelKwargs; - stop; - stopSequences; - user; - timeout; - streaming = false; - streamUsage = true; - maxTokens; - logprobs; - topLogprobs; - apiKey; - organization; - __includeRawResponse; - /** @internal */ - client; - /** @internal */ - clientConfig; - /** - * Whether the model supports the `strict` argument when passing in tools. - * If `undefined` the `strict` argument will not be passed to OpenAI. - */ - supportsStrictToolCalling; - audio; - modalities; - reasoning; - /** - * Must be set to `true` in tenancies with Zero Data Retention. Setting to `true` will disable - * output storage in the Responses API, but this DOES NOT enable Zero Data Retention in your - * OpenAI organization or project. This must be configured directly with OpenAI. - * - * See: - * https://platform.openai.com/docs/guides/your-data - * https://platform.openai.com/docs/api-reference/responses/create#responses-create-store - * - * @default false - */ - zdrEnabled; - /** - * Service tier to use for this request. Can be "auto", "default", or "flex" or "priority". - * Specifies the service tier for prioritization and latency optimization. - */ - service_tier; - /** - * Used by OpenAI to cache responses for similar requests to optimize your cache - * hit rates. - * [Learn more](https://platform.openai.com/docs/guides/prompt-caching). - */ - promptCacheKey; - /** - * Used by OpenAI to set cache retention time - */ - promptCacheRetention; - /** - * The verbosity of the model's response. - */ - verbosity; - defaultOptions; - _llmType() { - return "openai"; - } - static lc_name() { - return "ChatOpenAI"; - } - get callKeys() { - return [ - ...super.callKeys, - "options", - "function_call", - "functions", - "tools", - "tool_choice", - "promptIndex", - "response_format", - "seed", - "reasoning", - "service_tier" - ]; - } - lc_serializable = true; - get lc_secrets() { - return { - apiKey: "OPENAI_API_KEY", - organization: "OPENAI_ORGANIZATION" - }; - } - get lc_aliases() { - return { - apiKey: "openai_api_key", - modelName: "model" - }; - } - get lc_serializable_keys() { - return [ - "configuration", - "logprobs", - "topLogprobs", - "prefixMessages", - "supportsStrictToolCalling", - "modalities", - "audio", - "temperature", - "maxTokens", - "topP", - "frequencyPenalty", - "presencePenalty", - "n", - "logitBias", - "user", - "streaming", - "streamUsage", - "model", - "modelName", - "modelKwargs", - "stop", - "stopSequences", - "timeout", - "apiKey", - "cache", - "maxConcurrency", - "maxRetries", - "verbose", - "callbacks", - "tags", - "metadata", - "disableStreaming", - "zdrEnabled", - "reasoning", - "promptCacheKey", - "promptCacheRetention", - "verbosity" - ]; - } - getLsParams(options) { - const params = this.invocationParams(options); - return { - ls_provider: "openai", - ls_model_name: this.model, - ls_model_type: "chat", - ls_temperature: params.temperature ?? void 0, - ls_max_tokens: params.max_tokens ?? void 0, - ls_stop: options.stop - }; - } - /** @ignore */ - _identifyingParams() { - return { - model_name: this.model, - ...this.invocationParams(), - ...this.clientConfig - }; - } - /** - * Get the identifying parameters for the model - */ - identifyingParams() { - return this._identifyingParams(); - } - constructor(fields) { - super(fields ?? {}); - const configApiKey = typeof fields?.configuration?.apiKey === "string" || typeof fields?.configuration?.apiKey === "function" ? fields?.configuration?.apiKey : void 0; - this.apiKey = fields?.apiKey ?? configApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); - this.organization = fields?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); - this.model = fields?.model ?? fields?.modelName ?? this.model; - this.modelKwargs = fields?.modelKwargs ?? {}; - this.timeout = fields?.timeout; - this.temperature = fields?.temperature ?? this.temperature; - this.topP = fields?.topP ?? this.topP; - this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; - this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; - this.logprobs = fields?.logprobs; - this.topLogprobs = fields?.topLogprobs; - this.n = fields?.n ?? this.n; - this.logitBias = fields?.logitBias; - this.stop = fields?.stopSequences ?? fields?.stop; - this.stopSequences = this.stop; - this.user = fields?.user; - this.__includeRawResponse = fields?.__includeRawResponse; - this.audio = fields?.audio; - this.modalities = fields?.modalities; - this.reasoning = fields?.reasoning; - this.maxTokens = fields?.maxCompletionTokens ?? fields?.maxTokens; - this.promptCacheKey = fields?.promptCacheKey ?? this.promptCacheKey; - this.promptCacheRetention = fields?.promptCacheRetention ?? this.promptCacheRetention; - this.verbosity = fields?.verbosity ?? this.verbosity; - this.disableStreaming = fields?.disableStreaming === true; - this.streaming = fields?.streaming === true; - if (this.disableStreaming) this.streaming = false; - if (fields?.streaming === false) this.disableStreaming = true; - this.streamUsage = fields?.streamUsage ?? this.streamUsage; - if (this.disableStreaming) this.streamUsage = false; - this.clientConfig = { - apiKey: this.apiKey, - organization: this.organization, - dangerouslyAllowBrowser: true, - ...fields?.configuration - }; - if (fields?.supportsStrictToolCalling !== void 0) this.supportsStrictToolCalling = fields.supportsStrictToolCalling; - if (fields?.service_tier !== void 0) this.service_tier = fields.service_tier; - this.zdrEnabled = fields?.zdrEnabled ?? false; - } - /** - * Returns backwards compatible reasoning parameters from constructor params and call options - * @internal - */ - _getReasoningParams(options) { - if (!isReasoningModel(this.model)) return; - let reasoning; - if (this.reasoning !== void 0) reasoning = { - ...reasoning, - ...this.reasoning - }; - if (options?.reasoning !== void 0) reasoning = { - ...reasoning, - ...options.reasoning - }; - return reasoning; - } - /** - * Returns an openai compatible response format from a set of options - * @internal - */ - _getResponseFormat(resFormat) { - if (resFormat && resFormat.type === "json_schema" && resFormat.json_schema.schema && isInteropZodSchema(resFormat.json_schema.schema)) return interopZodResponseFormat(resFormat.json_schema.schema, resFormat.json_schema.name, { description: resFormat.json_schema.description }); - return resFormat; - } - _combineCallOptions(additionalOptions) { - return { - ...this.defaultOptions, - ...additionalOptions ?? {} - }; - } - /** @internal */ - _getClientOptions(options) { - if (!this.client) { - const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL }; - const endpoint = getEndpoint(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!params.baseURL) delete params.baseURL; - params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders); - this.client = new OpenAI(params); - } - const requestOptions = { - ...this.clientConfig, - ...options - }; - return requestOptions; - } - _convertChatOpenAIToolToCompletionsTool(tool, fields) { - if (isCustomTool(tool)) return convertResponsesCustomTool(tool.metadata.customTool); - if (isOpenAITool(tool)) { - if (fields?.strict !== void 0) return { - ...tool, - function: { - ...tool.function, - strict: fields.strict - } - }; - return tool; - } - return _convertToOpenAITool(tool, fields); - } - bindTools(tools, kwargs) { - let strict; - if (kwargs?.strict !== void 0) strict = kwargs.strict; - else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; - return this.withConfig({ - tools: tools.map((tool) => { - if (isBuiltInTool(tool) || isCustomTool(tool)) return tool; - if (hasProviderToolDefinition(tool)) return tool.extras.providerToolDefinition; - return this._convertChatOpenAIToolToCompletionsTool(tool, { strict }); - }), - ...kwargs - }); - } - async stream(input, options) { - return super.stream(input, this._combineCallOptions(options)); - } - async invoke(input, options) { - return super.invoke(input, this._combineCallOptions(options)); - } - /** @ignore */ - _combineLLMOutput(...llmOutputs) { - return llmOutputs.reduce((acc, llmOutput) => { - if (llmOutput && llmOutput.tokenUsage) { - acc.tokenUsage.completionTokens += llmOutput.tokenUsage.completionTokens ?? 0; - acc.tokenUsage.promptTokens += llmOutput.tokenUsage.promptTokens ?? 0; - acc.tokenUsage.totalTokens += llmOutput.tokenUsage.totalTokens ?? 0; - } - return acc; - }, { tokenUsage: { - completionTokens: 0, - promptTokens: 0, - totalTokens: 0 - } }); - } - async getNumTokensFromMessages(messages) { - let totalCount = 0; - let tokensPerMessage = 0; - let tokensPerName = 0; - if (this.model === "gpt-3.5-turbo-0301") { - tokensPerMessage = 4; - tokensPerName = -1; - } else { - tokensPerMessage = 3; - tokensPerName = 1; - } - const countPerMessage = await Promise.all(messages.map(async (message) => { - const textCount = await this.getNumTokens(message.content); - const roleCount = await this.getNumTokens(messageToOpenAIRole(message)); - const nameCount = message.name !== void 0 ? tokensPerName + await this.getNumTokens(message.name) : 0; - let count = textCount + tokensPerMessage + roleCount + nameCount; - const openAIMessage = message; - if (openAIMessage._getType() === "function") count -= 2; - if (openAIMessage.additional_kwargs?.function_call) count += 3; - if (openAIMessage?.additional_kwargs.function_call?.name) count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.name); - if (openAIMessage.additional_kwargs.function_call?.arguments) try { - count += await this.getNumTokens(JSON.stringify(JSON.parse(openAIMessage.additional_kwargs.function_call?.arguments))); - } catch (error) { - console.error("Error parsing function arguments", error, JSON.stringify(openAIMessage.additional_kwargs.function_call)); - count += await this.getNumTokens(openAIMessage.additional_kwargs.function_call?.arguments); - } - totalCount += count; - return count; - })); - totalCount += 3; - return { - totalCount, - countPerMessage - }; - } - /** @internal */ - async _getNumTokensFromGenerations(generations) { - const generationUsages = await Promise.all(generations.map(async (generation) => { - if (generation.message.additional_kwargs?.function_call) return (await this.getNumTokensFromMessages([generation.message])).countPerMessage[0]; - else return await this.getNumTokens(generation.message.content); - })); - return generationUsages.reduce((a, b) => a + b, 0); - } - /** @internal */ - async _getEstimatedTokenCountFromPrompt(messages, functions, function_call) { - let tokens = (await this.getNumTokensFromMessages(messages)).totalCount; - if (functions && function_call !== "auto") { - const promptDefinitions = formatFunctionDefinitions(functions); - tokens += await this.getNumTokens(promptDefinitions); - tokens += 9; - } - if (functions && messages.find((m) => m._getType() === "system")) tokens -= 4; - if (function_call === "none") tokens += 1; - else if (typeof function_call === "object") tokens += await this.getNumTokens(function_call.name) + 4; - return tokens; - } - /** - * Moderate content using OpenAI's Moderation API. - * - * This method checks whether content violates OpenAI's content policy by - * analyzing text for categories such as hate, harassment, self-harm, - * sexual content, violence, and more. - * - * @param input - The text or array of texts to moderate - * @param params - Optional parameters for the moderation request - * @param params.model - The moderation model to use. Defaults to "omni-moderation-latest". - * @param params.options - Additional options to pass to the underlying request - * @returns A promise that resolves to the moderation response containing results for each input - * - * @example - * ```typescript - * const model = new ChatOpenAI({ model: "gpt-4o-mini" }); - * - * // Moderate a single text - * const result = await model.moderateContent("This is a test message"); - * console.log(result.results[0].flagged); // false - * console.log(result.results[0].categories); // { hate: false, harassment: false, ... } - * - * // Moderate multiple texts - * const results = await model.moderateContent([ - * "Hello, how are you?", - * "This is inappropriate content" - * ]); - * results.results.forEach((result, index) => { - * console.log(`Text ${index + 1} flagged:`, result.flagged); - * }); - * - * // Use a specific moderation model - * const stableResult = await model.moderateContent( - * "Test content", - * { model: "omni-moderation-latest" } - * ); - * ``` - */ - async moderateContent(input, params) { - const clientOptions = this._getClientOptions(params?.options); - const moderationModel = params?.model ?? "omni-moderation-latest"; - const moderationRequest = { - input, - model: moderationModel - }; - return this.caller.call(async () => { - try { - const response = await this.client.moderations.create(moderationRequest, clientOptions); - return response; - } catch (e) { - const error = wrapOpenAIClientError(e); - throw error; - } - }); - } - /** - * Return profiling information for the model. - * - * Provides information about the model's capabilities and constraints, - * including token limits, multimodal support, and advanced features like - * tool calling and structured output. - * - * @returns {ModelProfile} An object describing the model's capabilities and constraints - * - * @example - * ```typescript - * const model = new ChatOpenAI({ model: "gpt-4o" }); - * const profile = model.profile; - * console.log(profile.maxInputTokens); // 128000 - * console.log(profile.imageInputs); // true - * ``` - */ - get profile() { - return profiles_profiles_default[this.model] ?? {}; - } - /** @internal */ - _getStructuredOutputMethod(config) { - const ensuredConfig = { ...config }; - if (!this.model.startsWith("gpt-3") && !this.model.startsWith("gpt-4-") && this.model !== "gpt-4") { - if (ensuredConfig?.method === void 0) return "jsonSchema"; - } else if (ensuredConfig.method === "jsonSchema") console.warn(`[WARNING]: JSON Schema is not supported for model "${this.model}". Falling back to tool calling.`); - return ensuredConfig.method; - } - /** - * Add structured output to the model. - * - * The OpenAI model family supports the following structured output methods: - * - `jsonSchema`: Use the `response_format` field in the response to return a JSON schema. Only supported with the `gpt-4o-mini`, - * `gpt-4o-mini-2024-07-18`, and `gpt-4o-2024-08-06` model snapshots and later. - * - `functionCalling`: Function calling is useful when you are building an application that bridges the models and functionality - * of your application. - * - `jsonMode`: JSON mode is a more basic version of the Structured Outputs feature. While JSON mode ensures that model - * output is valid JSON, Structured Outputs reliably matches the model's output to the schema you specify. - * We recommend you use `functionCalling` or `jsonSchema` if it is supported for your use case. - * - * The default method is `functionCalling`. - * - * @see https://platform.openai.com/docs/guides/structured-outputs - * @param outputSchema - The schema to use for structured output. - * @param config - The structured output method options. - * @returns The model with structured output. - */ - withStructuredOutput(outputSchema, config) { - let llm; - let outputParser; - const { schema, name, includeRaw } = { - ...config, - schema: outputSchema - }; - if (config?.strict !== void 0 && config.method === "jsonMode") throw new Error("Argument `strict` is only supported for `method` = 'function_calling'"); - const method = getStructuredOutputMethod(this.model, config?.method); - if (method === "jsonMode") { - if (isInteropZodSchema(schema)) outputParser = StructuredOutputParser.fromZodSchema(schema); - else outputParser = new JsonOutputParser(); - const asJsonSchema = toJsonSchema(schema); - llm = this.withConfig({ - outputVersion: "v0", - response_format: { type: "json_object" }, - ls_structured_output_format: { - kwargs: { method: "json_mode" }, - schema: { - title: name ?? "extract", - ...asJsonSchema - } - } - }); - } else if (method === "jsonSchema") { - const openaiJsonSchemaParams = { - name: name ?? "extract", - description: getSchemaDescription(schema), - schema, - strict: config?.strict - }; - const asJsonSchema = toJsonSchema(openaiJsonSchemaParams.schema); - llm = this.withConfig({ - outputVersion: "v0", - response_format: { - type: "json_schema", - json_schema: openaiJsonSchemaParams - }, - ls_structured_output_format: { - kwargs: { method: "json_schema" }, - schema: { - title: openaiJsonSchemaParams.name, - description: openaiJsonSchemaParams.description, - ...asJsonSchema - } - } - }); - if (isInteropZodSchema(schema)) { - const altParser = StructuredOutputParser.fromZodSchema(schema); - outputParser = RunnableLambda.from((aiMessage) => { - if ("parsed" in aiMessage.additional_kwargs) return aiMessage.additional_kwargs.parsed; - return altParser; - }); - } else outputParser = new JsonOutputParser(); - } else { - let functionName = name ?? "extract"; - if (isInteropZodSchema(schema)) { - const asJsonSchema = toJsonSchema(schema); - llm = this.withConfig({ - outputVersion: "v0", - tools: [{ - type: "function", - function: { - name: functionName, - description: asJsonSchema.description, - parameters: asJsonSchema - } - }], - tool_choice: { - type: "function", - function: { name: functionName } - }, - ls_structured_output_format: { - kwargs: { method: "function_calling" }, - schema: { - title: functionName, - ...asJsonSchema - } - }, - ...config?.strict !== void 0 ? { strict: config.strict } : {} - }); - outputParser = new JsonOutputKeyToolsParser({ - returnSingle: true, - keyName: functionName, - zodSchema: schema - }); - } else { - let openAIFunctionDefinition; - if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) { - openAIFunctionDefinition = schema; - functionName = schema.name; - } else { - functionName = schema.title ?? functionName; - openAIFunctionDefinition = { - name: functionName, - description: schema.description ?? "", - parameters: schema - }; - } - const asJsonSchema = toJsonSchema(schema); - llm = this.withConfig({ - outputVersion: "v0", - tools: [{ - type: "function", - function: openAIFunctionDefinition - }], - tool_choice: { - type: "function", - function: { name: functionName } - }, - ls_structured_output_format: { - kwargs: { method: "function_calling" }, - schema: { - title: functionName, - ...asJsonSchema - } - }, - ...config?.strict !== void 0 ? { strict: config.strict } : {} - }); - outputParser = new JsonOutputKeyToolsParser({ - returnSingle: true, - keyName: functionName - }); - } - } - if (!includeRaw) return llm.pipe(outputParser); - const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); - const parserNone = RunnablePassthrough.assign({ parsed: () => null }); - const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); - return RunnableSequence.from([{ raw: llm }, parsedWithFallback]); - } -}; - -//#endregion - -//# sourceMappingURL=base.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/converters/completions.js - - - - - -//#region src/converters/completions.ts -/** -* @deprecated This converter is an internal detail of the OpenAI provider. Do not use it directly. This will be revisited in a future release. -*/ -const completionsApiContentBlockConverter = { - providerName: "ChatOpenAI", - fromStandardTextBlock(block) { - return { - type: "text", - text: block.text - }; - }, - fromStandardImageBlock(block) { - if (block.source_type === "url") return { - type: "image_url", - image_url: { - url: block.url, - ...block.metadata?.detail ? { detail: block.metadata.detail } : {} - } - }; - if (block.source_type === "base64") { - const url = `data:${block.mime_type ?? ""};base64,${block.data}`; - return { - type: "image_url", - image_url: { - url, - ...block.metadata?.detail ? { detail: block.metadata.detail } : {} - } - }; - } - throw new Error(`Image content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); - }, - fromStandardAudioBlock(block) { - if (block.source_type === "url") { - const data = parseBase64DataUrl({ dataUrl: block.url }); - if (!data) throw new Error(`URL audio blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`); - const rawMimeType = data.mime_type || block.mime_type || ""; - let mimeType; - try { - mimeType = parseMimeType(rawMimeType); - } catch { - throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); - } - if (mimeType.type !== "audio" || mimeType.subtype !== "wav" && mimeType.subtype !== "mp3") throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); - return { - type: "input_audio", - input_audio: { - format: mimeType.subtype, - data: data.data - } - }; - } - if (block.source_type === "base64") { - let mimeType; - try { - mimeType = parseMimeType(block.mime_type ?? ""); - } catch { - throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); - } - if (mimeType.type !== "audio" || mimeType.subtype !== "wav" && mimeType.subtype !== "mp3") throw new Error(`Audio blocks with source_type ${block.source_type} must have mime type of audio/wav or audio/mp3`); - return { - type: "input_audio", - input_audio: { - format: mimeType.subtype, - data: block.data - } - }; - } - throw new Error(`Audio content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); - }, - fromStandardFileBlock(block) { - if (block.source_type === "url") { - const data = parseBase64DataUrl({ dataUrl: block.url }); - const filename = getRequiredFilenameFromMetadata(block); - if (!data) throw new Error(`URL file blocks with source_type ${block.source_type} must be formatted as a data URL for ChatOpenAI`); - return { - type: "file", - file: { - file_data: block.url, - ...block.metadata?.filename || block.metadata?.name ? { filename } : {} - } - }; - } - if (block.source_type === "base64") { - const filename = getRequiredFilenameFromMetadata(block); - return { - type: "file", - file: { - file_data: `data:${block.mime_type ?? ""};base64,${block.data}`, - ...block.metadata?.filename || block.metadata?.name || block.metadata?.title ? { filename } : {} - } - }; - } - if (block.source_type === "id") return { - type: "file", - file: { file_id: block.id } - }; - throw new Error(`File content blocks with source_type ${block.source_type} are not supported for ChatOpenAI`); - } -}; -/** -* Converts an OpenAI Chat Completions API message to a LangChain BaseMessage. -* -* This converter transforms messages from OpenAI's Chat Completions API format into -* LangChain's internal message representation, handling various message types and -* preserving metadata, tool calls, and other relevant information. -* -* @remarks -* The converter handles the following message roles: -* - `assistant`: Converted to {@link AIMessage} with support for tool calls, function calls, -* audio content, and multi-modal outputs -* - Other roles: Converted to generic {@link ChatMessage} -* -* For assistant messages, the converter: -* - Parses and validates tool calls, separating valid and invalid calls -* - Preserves function call information in additional_kwargs -* - Includes usage statistics and system fingerprint in response_metadata -* - Handles multi-modal content (text, images, audio) -* - Optionally includes the raw API response for debugging -* -* @param params - Conversion parameters -* @param params.message - The OpenAI chat completion message to convert -* @param params.rawResponse - The complete raw response from OpenAI's API, used to extract -* metadata like model name, usage statistics, and system fingerprint -* @param params.includeRawResponse - If true, includes the raw OpenAI response in the -* message's additional_kwargs under the `__raw_response` key. Useful for debugging -* or accessing provider-specific fields. Defaults to false. -* -* @returns A LangChain BaseMessage instance: -* - {@link AIMessage} for assistant messages with tool calls, metadata, and content -* - {@link ChatMessage} for all other message types -* -* @example -* ```typescript -* const baseMessage = convertCompletionsMessageToBaseMessage({ -* message: { -* role: "assistant", -* content: "Hello! How can I help you?", -* tool_calls: [ -* { -* id: "call_123", -* type: "function", -* function: { name: "get_weather", arguments: '{"location":"NYC"}' } -* } -* ] -* }, -* rawResponse: completionResponse, -* includeRawResponse: true -* }); -* // Returns an AIMessage with parsed tool calls and metadata -* ``` -* -* @throws {Error} If tool call parsing fails, the invalid tool call is captured in -* the `invalid_tool_calls` array rather than throwing an error -* -*/ -const convertCompletionsMessageToBaseMessage = ({ message, rawResponse, includeRawResponse }) => { - const rawToolCalls = message.tool_calls; - switch (message.role) { - case "assistant": { - const toolCalls = []; - const invalidToolCalls = []; - for (const rawToolCall of rawToolCalls ?? []) try { - toolCalls.push(parseToolCall(rawToolCall, { returnId: true })); - } catch (e) { - invalidToolCalls.push(makeInvalidToolCall(rawToolCall, e.message)); - } - const additional_kwargs = { - function_call: message.function_call, - tool_calls: rawToolCalls - }; - if (includeRawResponse !== void 0) additional_kwargs.__raw_response = rawResponse; - const response_metadata = { - model_provider: "openai", - model_name: rawResponse.model, - ...rawResponse.system_fingerprint ? { - usage: { ...rawResponse.usage }, - system_fingerprint: rawResponse.system_fingerprint - } : {} - }; - if (message.audio) additional_kwargs.audio = message.audio; - const content = handleMultiModalOutput(message.content || "", rawResponse.choices?.[0]?.message); - return new AIMessage({ - content, - tool_calls: toolCalls, - invalid_tool_calls: invalidToolCalls, - additional_kwargs, - response_metadata, - id: rawResponse.id - }); - } - default: return new ChatMessage(message.content || "", message.role ?? "unknown"); - } -}; -/** -* Converts an OpenAI Chat Completions API delta (streaming chunk) to a LangChain BaseMessageChunk. -* -* This converter is used during streaming responses to transform incremental updates from OpenAI's -* Chat Completions API into LangChain message chunks. It handles various message types, tool calls, -* function calls, audio content, and role-specific message chunk creation. -* -* @param params - Conversion parameters -* @param params.delta - The delta object from an OpenAI streaming chunk containing incremental -* message updates. May include content, role, tool_calls, function_call, audio, etc. -* @param params.rawResponse - The complete raw ChatCompletionChunk response from OpenAI, -* containing metadata like model info, usage stats, and the delta -* @param params.includeRawResponse - Optional flag to include the raw OpenAI response in the -* message chunk's additional_kwargs. Useful for debugging or accessing provider-specific data -* @param params.defaultRole - Optional default role to use if the delta doesn't specify one. -* Typically used to maintain role consistency across chunks in a streaming response -* -* @returns A BaseMessageChunk subclass appropriate for the message role: -* - HumanMessageChunk for "user" role -* - AIMessageChunk for "assistant" role (includes tool call chunks) -* - SystemMessageChunk for "system" or "developer" roles -* - FunctionMessageChunk for "function" role -* - ToolMessageChunk for "tool" role -* - ChatMessageChunk for any other role -* -* @example -* Basic streaming text chunk: -* ```typescript -* const chunk = convertCompletionsDeltaToBaseMessageChunk({ -* delta: { role: "assistant", content: "Hello" }, -* rawResponse: { id: "chatcmpl-123", model: "gpt-4", ... } -* }); -* // Returns: AIMessageChunk with content "Hello" -* ``` -* -* @example -* Streaming chunk with tool call: -* ```typescript -* const chunk = convertCompletionsDeltaToBaseMessageChunk({ -* delta: { -* role: "assistant", -* tool_calls: [{ -* index: 0, -* id: "call_123", -* function: { name: "get_weather", arguments: '{"location":' } -* }] -* }, -* rawResponse: { id: "chatcmpl-123", ... } -* }); -* // Returns: AIMessageChunk with tool_call_chunks containing partial tool call data -* ``` -* -* @remarks -* - Tool calls are converted to ToolCallChunk objects with incremental data -* - Audio content includes the chunk index from the raw response -* - The "developer" role is mapped to SystemMessageChunk with a special marker -* - Response metadata includes model provider info and usage statistics -* - Function calls and tool calls are stored in additional_kwargs for compatibility -*/ -const convertCompletionsDeltaToBaseMessageChunk = ({ delta, rawResponse, includeRawResponse, defaultRole }) => { - const role = delta.role ?? defaultRole; - const content = delta.content ?? ""; - let additional_kwargs; - if (delta.function_call) additional_kwargs = { function_call: delta.function_call }; - else if (delta.tool_calls) additional_kwargs = { tool_calls: delta.tool_calls }; - else additional_kwargs = {}; - if (includeRawResponse) additional_kwargs.__raw_response = rawResponse; - if (delta.audio) additional_kwargs.audio = { - ...delta.audio, - index: rawResponse.choices[0].index - }; - const response_metadata = { - model_provider: "openai", - usage: { ...rawResponse.usage } - }; - if (role === "user") return new HumanMessageChunk({ - content, - response_metadata - }); - else if (role === "assistant") { - const toolCallChunks = []; - if (Array.isArray(delta.tool_calls)) for (const rawToolCall of delta.tool_calls) toolCallChunks.push({ - name: rawToolCall.function?.name, - args: rawToolCall.function?.arguments, - id: rawToolCall.id, - index: rawToolCall.index, - type: "tool_call_chunk" - }); - return new AIMessageChunk({ - content, - tool_call_chunks: toolCallChunks, - additional_kwargs, - id: rawResponse.id, - response_metadata - }); - } else if (role === "system") return new SystemMessageChunk({ - content, - response_metadata - }); - else if (role === "developer") return new SystemMessageChunk({ - content, - response_metadata, - additional_kwargs: { __openai_role__: "developer" } - }); - else if (role === "function") return new FunctionMessageChunk({ - content, - additional_kwargs, - name: delta.name, - response_metadata - }); - else if (role === "tool") return new ToolMessageChunk({ - content, - additional_kwargs, - tool_call_id: delta.tool_call_id, - response_metadata - }); - else return new ChatMessageChunk({ - content, - role, - response_metadata - }); -}; -/** -* Converts a standard LangChain content block to an OpenAI Completions API content part. -* -* This converter transforms LangChain's standardized content blocks (image, audio, file) -* into the format expected by OpenAI's Chat Completions API. It handles various content -* types including images (URL or base64), audio (base64), and files (data or file ID). -* -* @param block - The standard content block to convert. Can be an image, audio, or file block. -* -* @returns An OpenAI Chat Completions content part object, or undefined if the block -* cannot be converted (e.g., missing required data). -* -* @example -* Image with URL: -* ```typescript -* const block = { type: "image", url: "https://example.com/image.jpg" }; -* const part = convertStandardContentBlockToCompletionsContentPart(block); -* // Returns: { type: "image_url", image_url: { url: "https://example.com/image.jpg" } } -* ``` -* -* @example -* Image with base64 data: -* ```typescript -* const block = { type: "image", data: "iVBORw0KGgo...", mimeType: "image/png" }; -* const part = convertStandardContentBlockToCompletionsContentPart(block); -* // Returns: { type: "image_url", image_url: { url: "data:image/png;base64,iVBORw0KGgo..." } } -* ``` -*/ -const convertStandardContentBlockToCompletionsContentPart = (block) => { - if (block.type === "image") { - if (block.url) return { - type: "image_url", - image_url: { url: block.url } - }; - else if (block.data) return { - type: "image_url", - image_url: { url: `data:${block.mimeType};base64,${block.data}` } - }; - } - if (block.type === "audio") { - if (block.data) { - const format = utils_iife(() => { - const [, format$1] = block.mimeType.split("/"); - if (format$1 === "wav" || format$1 === "mp3") return format$1; - return "wav"; - }); - return { - type: "input_audio", - input_audio: { - data: block.data.toString(), - format - } - }; - } - } - if (block.type === "file") { - if (block.data) { - const filename = getRequiredFilenameFromMetadata(block); - return { - type: "file", - file: { - file_data: `data:${block.mimeType};base64,${block.data}`, - filename - } - }; - } - if (block.fileId) return { - type: "file", - file: { file_id: block.fileId } - }; - } - return void 0; -}; -/** -* Converts a LangChain BaseMessage with standard content blocks to an OpenAI Chat Completions API message parameter. -* -* This converter transforms LangChain's standardized message format (using contentBlocks) into the format -* expected by OpenAI's Chat Completions API. It handles role mapping, content filtering, and multi-modal -* content conversion for various message types. -* -* @remarks -* The converter performs the following transformations: -* - Maps LangChain message roles to OpenAI API roles (user, assistant, system, developer, tool, function) -* - For reasoning models, automatically converts "system" role to "developer" role -* - Filters content blocks based on message role (most roles only include text blocks) -* - For user messages, converts multi-modal content blocks (images, audio, files) to OpenAI format -* - Preserves tool call IDs for tool messages and function names for function messages -* -* Role-specific behavior: -* - **developer**: Returns only text content blocks (used for reasoning models) -* - **system**: Returns only text content blocks -* - **assistant**: Returns only text content blocks -* - **tool**: Returns only text content blocks with tool_call_id preserved -* - **function**: Returns text content blocks joined as a single string with function name -* - **user** (default): Returns multi-modal content including text, images, audio, and files -* -* @param params - Conversion parameters -* @param params.message - The LangChain BaseMessage to convert. Must have contentBlocks property -* containing an array of standard content blocks (text, image, audio, file, etc.) -* @param params.model - Optional model name. Used to determine if special role mapping is needed -* (e.g., "system" -> "developer" for reasoning models like o1) -* -* @returns An OpenAI ChatCompletionMessageParam object formatted for the Chat Completions API. -* The structure varies by role: -* - Developer/System/Assistant: `{ role, content: TextBlock[] }` -* - Tool: `{ role: "tool", tool_call_id, content: TextBlock[] }` -* - Function: `{ role: "function", name, content: string }` -* - User: `{ role: "user", content: Array }` -* -* @example -* Simple text message: -* ```typescript -* const message = new HumanMessage({ -* content: [{ type: "text", text: "Hello!" }] -* }); -* const param = convertStandardContentMessageToCompletionsMessage({ message }); -* // Returns: { role: "user", content: [{ type: "text", text: "Hello!" }] } -* ``` -* -* @example -* Multi-modal user message with image: -* ```typescript -* const message = new HumanMessage({ -* content: [ -* { type: "text", text: "What's in this image?" }, -* { type: "image", url: "https://example.com/image.jpg" } -* ] -* }); -* const param = convertStandardContentMessageToCompletionsMessage({ message }); -* // Returns: { -* // role: "user", -* // content: [ -* // { type: "text", text: "What's in this image?" }, -* // { type: "image_url", image_url: { url: "https://example.com/image.jpg" } } -* // ] -* // } -* ``` -*/ -const convertStandardContentMessageToCompletionsMessage = ({ message, model }) => { - let role = messageToOpenAIRole(message); - if (role === "system" && isReasoningModel(model)) role = "developer"; - if (role === "developer") return { - role: "developer", - content: message.contentBlocks.filter((block) => block.type === "text") - }; - else if (role === "system") return { - role: "system", - content: message.contentBlocks.filter((block) => block.type === "text") - }; - else if (role === "assistant") return { - role: "assistant", - content: message.contentBlocks.filter((block) => block.type === "text") - }; - else if (role === "tool" && ToolMessage.isInstance(message)) return { - role: "tool", - tool_call_id: message.tool_call_id, - content: message.contentBlocks.filter((block) => block.type === "text") - }; - else if (role === "function") return { - role: "function", - name: message.name ?? "", - content: message.contentBlocks.filter((block) => block.type === "text").join("") - }; - function* iterateUserContent(blocks) { - for (const block of blocks) { - if (block.type === "text") yield { - type: "text", - text: block.text - }; - const data = convertStandardContentBlockToCompletionsContentPart(block); - if (data) yield data; - } - } - return { - role: "user", - content: Array.from(iterateUserContent(message.contentBlocks)) - }; -}; -/** -* Converts an array of LangChain BaseMessages to OpenAI Chat Completions API message parameters. -* -* This converter transforms LangChain's internal message representation into the format required -* by OpenAI's Chat Completions API. It handles various message types, roles, content formats, -* tool calls, function calls, audio messages, and special model-specific requirements. -* -* @remarks -* The converter performs several key transformations: -* - Maps LangChain message types to OpenAI roles (user, assistant, system, tool, function, developer) -* - Converts standard content blocks (v1 format) using a specialized converter -* - Handles multimodal content including text, images, audio, and data blocks -* - Preserves tool calls and function calls with proper formatting -* - Applies model-specific role mappings (e.g., "system" → "developer" for reasoning models) -* - Splits audio messages into separate message parameters when needed -* -* @param params - Conversion parameters -* @param params.messages - Array of LangChain BaseMessages to convert. Can include any message -* type: HumanMessage, AIMessage, SystemMessage, ToolMessage, FunctionMessage, etc. -* @param params.model - Optional model name used to determine if special role mapping is needed. -* For reasoning models (o1, o3, etc.), "system" role is converted to "developer" role. -* -* @returns Array of ChatCompletionMessageParam objects formatted for OpenAI's Chat Completions API. -* Some messages may be split into multiple parameters (e.g., audio messages). -* -* @example -* Basic message conversion: -* ```typescript -* const messages = [ -* new HumanMessage("What's the weather like?"), -* new AIMessage("Let me check that for you.") -* ]; -* -* const params = convertMessagesToCompletionsMessageParams({ -* messages, -* model: "gpt-4" -* }); -* // Returns: -* // [ -* // { role: "user", content: "What's the weather like?" }, -* // { role: "assistant", content: "Let me check that for you." } -* // ] -* ``` -* -* @example -* Message with tool calls: -* ```typescript -* const messages = [ -* new AIMessage({ -* content: "", -* tool_calls: [{ -* id: "call_123", -* name: "get_weather", -* args: { location: "San Francisco" } -* }] -* }) -* ]; -* -* const params = convertMessagesToCompletionsMessageParams({ messages }); -* // Returns: -* // [{ -* // role: "assistant", -* // content: "", -* // tool_calls: [{ -* // id: "call_123", -* // type: "function", -* // function: { name: "get_weather", arguments: '{"location":"San Francisco"}' } -* // }] -* // }] -* ``` -*/ -const completions_convertMessagesToCompletionsMessageParams = ({ messages, model }) => { - return messages.flatMap((message) => { - if ("output_version" in message.response_metadata && message.response_metadata?.output_version === "v1") return convertStandardContentMessageToCompletionsMessage({ message }); - let role = messageToOpenAIRole(message); - if (role === "system" && isReasoningModel(model)) role = "developer"; - const content = typeof message.content === "string" ? message.content : message.content.map((m) => { - if (isDataContentBlock(m)) return convertToProviderContentBlock(m, completionsApiContentBlockConverter); - return m; - }); - const completionParam = { - role, - content - }; - if (message.name != null) completionParam.name = message.name; - if (message.additional_kwargs.function_call != null) completionParam.function_call = message.additional_kwargs.function_call; - if (AIMessage.isInstance(message) && !!message.tool_calls?.length) completionParam.tool_calls = message.tool_calls.map(convertLangChainToolCallToOpenAI); - else { - if (message.additional_kwargs.tool_calls != null) completionParam.tool_calls = message.additional_kwargs.tool_calls; - if (ToolMessage.isInstance(message) && message.tool_call_id != null) completionParam.tool_call_id = message.tool_call_id; - } - if (message.additional_kwargs.audio && typeof message.additional_kwargs.audio === "object" && "id" in message.additional_kwargs.audio) { - const audioMessage = { - role: "assistant", - audio: { id: message.additional_kwargs.audio.id } - }; - return [completionParam, audioMessage]; - } - return completionParam; - }); -}; - -//#endregion - -//# sourceMappingURL=completions.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/completions.js - - - - - - - - -//#region src/chat_models/completions.ts -/** -* OpenAI Completions API implementation. -* @internal -*/ -var ChatOpenAICompletions = class extends BaseChatOpenAI { - /** @internal */ - invocationParams(options, extra) { - let strict; - if (options?.strict !== void 0) strict = options.strict; - else if (this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; - let streamOptionsConfig = {}; - if (options?.stream_options !== void 0) streamOptionsConfig = { stream_options: options.stream_options }; - else if (this.streamUsage && (this.streaming || extra?.streaming)) streamOptionsConfig = { stream_options: { include_usage: true } }; - const params = { - model: this.model, - temperature: this.temperature, - top_p: this.topP, - frequency_penalty: this.frequencyPenalty, - presence_penalty: this.presencePenalty, - logprobs: this.logprobs, - top_logprobs: this.topLogprobs, - n: this.n, - logit_bias: this.logitBias, - stop: options?.stop ?? this.stopSequences, - user: this.user, - stream: this.streaming, - functions: options?.functions, - function_call: options?.function_call, - tools: options?.tools?.length ? options.tools.map((tool) => this._convertChatOpenAIToolToCompletionsTool(tool, { strict })) : void 0, - tool_choice: formatToOpenAIToolChoice(options?.tool_choice), - response_format: this._getResponseFormat(options?.response_format), - seed: options?.seed, - ...streamOptionsConfig, - parallel_tool_calls: options?.parallel_tool_calls, - ...this.audio || options?.audio ? { audio: this.audio || options?.audio } : {}, - ...this.modalities || options?.modalities ? { modalities: this.modalities || options?.modalities } : {}, - ...this.modelKwargs, - prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey, - prompt_cache_retention: options?.promptCacheRetention ?? this.promptCacheRetention, - verbosity: options?.verbosity ?? this.verbosity - }; - if (options?.prediction !== void 0) params.prediction = options.prediction; - if (this.service_tier !== void 0) params.service_tier = this.service_tier; - if (options?.service_tier !== void 0) params.service_tier = options.service_tier; - const reasoning = this._getReasoningParams(options); - if (reasoning !== void 0 && reasoning.effort !== void 0) params.reasoning_effort = reasoning.effort; - if (isReasoningModel(params.model)) params.max_completion_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens; - else params.max_tokens = this.maxTokens === -1 ? void 0 : this.maxTokens; - return params; - } - async _generate(messages, options, runManager) { - const usageMetadata = {}; - const params = this.invocationParams(options); - const messagesMapped = completions_convertMessagesToCompletionsMessageParams({ - messages, - model: this.model - }); - if (params.stream) { - const stream = this._streamResponseChunks(messages, options, runManager); - const finalChunks = {}; - for await (const chunk of stream) { - chunk.message.response_metadata = { - ...chunk.generationInfo, - ...chunk.message.response_metadata - }; - const index = chunk.generationInfo?.completion ?? 0; - if (finalChunks[index] === void 0) finalChunks[index] = chunk; - else finalChunks[index] = finalChunks[index].concat(chunk); - } - const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value); - const { functions, function_call } = this.invocationParams(options); - const promptTokenUsage = await this._getEstimatedTokenCountFromPrompt(messages, functions, function_call); - const completionTokenUsage = await this._getNumTokensFromGenerations(generations); - usageMetadata.input_tokens = promptTokenUsage; - usageMetadata.output_tokens = completionTokenUsage; - usageMetadata.total_tokens = promptTokenUsage + completionTokenUsage; - return { - generations, - llmOutput: { estimatedTokenUsage: { - promptTokens: usageMetadata.input_tokens, - completionTokens: usageMetadata.output_tokens, - totalTokens: usageMetadata.total_tokens - } } - }; - } else { - const data = await this.completionWithRetry({ - ...params, - stream: false, - messages: messagesMapped - }, { - signal: options?.signal, - ...options?.options - }); - const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens, prompt_tokens_details: promptTokensDetails, completion_tokens_details: completionTokensDetails } = data?.usage ?? {}; - if (completionTokens) usageMetadata.output_tokens = (usageMetadata.output_tokens ?? 0) + completionTokens; - if (promptTokens) usageMetadata.input_tokens = (usageMetadata.input_tokens ?? 0) + promptTokens; - if (totalTokens) usageMetadata.total_tokens = (usageMetadata.total_tokens ?? 0) + totalTokens; - if (promptTokensDetails?.audio_tokens !== null || promptTokensDetails?.cached_tokens !== null) usageMetadata.input_token_details = { - ...promptTokensDetails?.audio_tokens !== null && { audio: promptTokensDetails?.audio_tokens }, - ...promptTokensDetails?.cached_tokens !== null && { cache_read: promptTokensDetails?.cached_tokens } - }; - if (completionTokensDetails?.audio_tokens !== null || completionTokensDetails?.reasoning_tokens !== null) usageMetadata.output_token_details = { - ...completionTokensDetails?.audio_tokens !== null && { audio: completionTokensDetails?.audio_tokens }, - ...completionTokensDetails?.reasoning_tokens !== null && { reasoning: completionTokensDetails?.reasoning_tokens } - }; - const generations = []; - for (const part of data?.choices ?? []) { - const text = part.message?.content ?? ""; - const generation = { - text, - message: this._convertCompletionsMessageToBaseMessage(part.message ?? { role: "assistant" }, data) - }; - generation.generationInfo = { - ...part.finish_reason ? { finish_reason: part.finish_reason } : {}, - ...part.logprobs ? { logprobs: part.logprobs } : {} - }; - if (isAIMessage(generation.message)) generation.message.usage_metadata = usageMetadata; - generation.message = new AIMessage(Object.fromEntries(Object.entries(generation.message).filter(([key]) => !key.startsWith("lc_")))); - generations.push(generation); - } - return { - generations, - llmOutput: { tokenUsage: { - promptTokens: usageMetadata.input_tokens, - completionTokens: usageMetadata.output_tokens, - totalTokens: usageMetadata.total_tokens - } } - }; - } - } - async *_streamResponseChunks(messages, options, runManager) { - const messagesMapped = completions_convertMessagesToCompletionsMessageParams({ - messages, - model: this.model - }); - const params = { - ...this.invocationParams(options, { streaming: true }), - messages: messagesMapped, - stream: true - }; - let defaultRole; - const streamIterable = await this.completionWithRetry(params, options); - let usage; - for await (const data of streamIterable) { - const choice = data?.choices?.[0]; - if (data.usage) usage = data.usage; - if (!choice) continue; - const { delta } = choice; - if (!delta) continue; - const chunk = this._convertCompletionsDeltaToBaseMessageChunk(delta, data, defaultRole); - defaultRole = delta.role ?? defaultRole; - const newTokenIndices = { - prompt: options.promptIndex ?? 0, - completion: choice.index ?? 0 - }; - if (typeof chunk.content !== "string") { - console.log("[WARNING]: Received non-string content from OpenAI. This is currently not supported."); - continue; - } - const generationInfo = { ...newTokenIndices }; - if (choice.finish_reason != null) { - generationInfo.finish_reason = choice.finish_reason; - generationInfo.system_fingerprint = data.system_fingerprint; - generationInfo.model_name = data.model; - generationInfo.service_tier = data.service_tier; - } - if (this.logprobs) generationInfo.logprobs = choice.logprobs; - const generationChunk = new ChatGenerationChunk({ - message: chunk, - text: chunk.content, - generationInfo - }); - yield generationChunk; - await runManager?.handleLLMNewToken(generationChunk.text ?? "", newTokenIndices, void 0, void 0, void 0, { chunk: generationChunk }); - } - if (usage) { - const inputTokenDetails = { - ...usage.prompt_tokens_details?.audio_tokens !== null && { audio: usage.prompt_tokens_details?.audio_tokens }, - ...usage.prompt_tokens_details?.cached_tokens !== null && { cache_read: usage.prompt_tokens_details?.cached_tokens } - }; - const outputTokenDetails = { - ...usage.completion_tokens_details?.audio_tokens !== null && { audio: usage.completion_tokens_details?.audio_tokens }, - ...usage.completion_tokens_details?.reasoning_tokens !== null && { reasoning: usage.completion_tokens_details?.reasoning_tokens } - }; - const generationChunk = new ChatGenerationChunk({ - message: new AIMessageChunk({ - content: "", - response_metadata: { usage: { ...usage } }, - usage_metadata: { - input_tokens: usage.prompt_tokens, - output_tokens: usage.completion_tokens, - total_tokens: usage.total_tokens, - ...Object.keys(inputTokenDetails).length > 0 && { input_token_details: inputTokenDetails }, - ...Object.keys(outputTokenDetails).length > 0 && { output_token_details: outputTokenDetails } - } - }), - text: "" - }); - yield generationChunk; - } - if (options.signal?.aborted) throw new Error("AbortError"); - } - async completionWithRetry(request, requestOptions) { - const clientOptions = this._getClientOptions(requestOptions); - const isParseableFormat = request.response_format && request.response_format.type === "json_schema"; - return this.caller.call(async () => { - try { - if (isParseableFormat && !request.stream) return await this.client.chat.completions.parse(request, clientOptions); - else return await this.client.chat.completions.create(request, clientOptions); - } catch (e) { - const error = wrapOpenAIClientError(e); - throw error; - } - }); - } - /** - * @deprecated - * This function was hoisted into a publicly accessible function from a - * different export, but to maintain backwards compatibility with chat models - * that depend on ChatOpenAICompletions, we'll keep it here as an overridable - * method. This will be removed in a future release - */ - _convertCompletionsDeltaToBaseMessageChunk(delta, rawResponse, defaultRole) { - return convertCompletionsDeltaToBaseMessageChunk({ - delta, - rawResponse, - includeRawResponse: this.__includeRawResponse, - defaultRole - }); - } - /** - * @deprecated - * This function was hoisted into a publicly accessible function from a - * different export, but to maintain backwards compatibility with chat models - * that depend on ChatOpenAICompletions, we'll keep it here as an overridable - * method. This will be removed in a future release - */ - _convertCompletionsMessageToBaseMessage(message, rawResponse) { - return convertCompletionsMessageToBaseMessage({ - message, - rawResponse, - includeRawResponse: this.__includeRawResponse - }); - } -}; - -//#endregion - -//# sourceMappingURL=completions.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/common.js - - - - -//#region src/azure/chat_models/common.ts -const AZURE_ALIASES = { - openAIApiKey: "openai_api_key", - openAIApiVersion: "openai_api_version", - openAIBasePath: "openai_api_base", - deploymentName: "deployment_name", - azureOpenAIEndpoint: "azure_endpoint", - azureOpenAIApiVersion: "openai_api_version", - azureOpenAIBasePath: "openai_api_base", - azureOpenAIApiDeploymentName: "deployment_name" -}; -const AZURE_SECRETS = { azureOpenAIApiKey: "AZURE_OPENAI_API_KEY" }; -const AZURE_SERIALIZABLE_KEYS = [ - "azureOpenAIApiKey", - "azureOpenAIApiVersion", - "azureOpenAIBasePath", - "azureOpenAIEndpoint", - "azureOpenAIApiInstanceName", - "azureOpenAIApiDeploymentName", - "deploymentName", - "openAIApiKey", - "openAIApiVersion" -]; -function _constructAzureFields(fields) { - this.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? (typeof fields?.openAIApiKey === "string" ? fields?.openAIApiKey : void 0) ?? (typeof fields?.apiKey === "string" ? fields?.apiKey : void 0) ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); - this.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); - this.azureOpenAIApiDeploymentName = fields?.azureOpenAIApiDeploymentName ?? fields?.deploymentName ?? getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME"); - this.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); - this.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); - this.azureOpenAIEndpoint = fields?.azureOpenAIEndpoint ?? getEnvironmentVariable("AZURE_OPENAI_ENDPOINT"); - this.azureADTokenProvider = fields?.azureADTokenProvider; - if (!this.azureOpenAIApiKey && !this.apiKey && !this.azureADTokenProvider) throw new Error("Azure OpenAI API key or Token Provider not found"); -} -function _getAzureClientOptions(options) { - if (!this.client) { - const openAIEndpointConfig = { - azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, - azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, - azureOpenAIApiKey: this.azureOpenAIApiKey, - azureOpenAIBasePath: this.azureOpenAIBasePath, - azureADTokenProvider: this.azureADTokenProvider, - baseURL: this.clientConfig.baseURL, - azureOpenAIEndpoint: this.azureOpenAIEndpoint - }; - const endpoint = getEndpoint(openAIEndpointConfig); - const { apiKey: existingApiKey,...clientConfigRest } = this.clientConfig; - const params = { - ...clientConfigRest, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey; - if (!params.baseURL) delete params.baseURL; - params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders, true, "2.0.0"); - this.client = new AzureOpenAI({ - apiVersion: this.azureOpenAIApiVersion, - azureADTokenProvider: this.azureADTokenProvider, - deployment: this.azureOpenAIApiDeploymentName, - ...params - }); - } - const requestOptions = { - ...this.clientConfig, - ...options - }; - if (this.azureOpenAIApiKey) { - requestOptions.headers = { - "api-key": this.azureOpenAIApiKey, - ...requestOptions.headers - }; - requestOptions.query = { - "api-version": this.azureOpenAIApiVersion, - ...requestOptions.query - }; - } - return requestOptions; -} -function _serializeAzureChat(input) { - const json = input; - function isRecord(obj) { - return typeof obj === "object" && obj != null; - } - if (isRecord(json) && isRecord(json.kwargs)) { - delete json.kwargs.azure_openai_base_path; - delete json.kwargs.azure_openai_api_deployment_name; - delete json.kwargs.azure_openai_api_key; - delete json.kwargs.azure_openai_api_version; - delete json.kwargs.azure_open_ai_base_path; - if (!json.kwargs.azure_endpoint && this.azureOpenAIEndpoint) json.kwargs.azure_endpoint = this.azureOpenAIEndpoint; - if (!json.kwargs.azure_endpoint && this.azureOpenAIBasePath) { - const parts = this.azureOpenAIBasePath.split("/openai/deployments/"); - if (parts.length === 2 && parts[0].startsWith("http")) { - const [endpoint] = parts; - json.kwargs.azure_endpoint = endpoint; - } - } - if (!json.kwargs.azure_endpoint && this.azureOpenAIApiInstanceName) json.kwargs.azure_endpoint = `https://${this.azureOpenAIApiInstanceName}.openai.azure.com/`; - if (!json.kwargs.deployment_name && this.azureOpenAIApiDeploymentName) json.kwargs.deployment_name = this.azureOpenAIApiDeploymentName; - if (!json.kwargs.deployment_name && this.azureOpenAIBasePath) { - const parts = this.azureOpenAIBasePath.split("/openai/deployments/"); - if (parts.length === 2) { - const [, deployment] = parts; - json.kwargs.deployment_name = deployment; - } - } - if (json.kwargs.azure_endpoint && json.kwargs.deployment_name && json.kwargs.openai_api_base) delete json.kwargs.openai_api_base; - if (json.kwargs.azure_openai_api_instance_name && json.kwargs.azure_endpoint) delete json.kwargs.azure_openai_api_instance_name; - } - return json; -} - -//#endregion - -//# sourceMappingURL=common.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/completions.js - - - -//#region src/azure/chat_models/completions.ts -var AzureChatOpenAICompletions = class extends ChatOpenAICompletions { - azureOpenAIApiVersion; - azureOpenAIApiKey; - azureADTokenProvider; - azureOpenAIApiInstanceName; - azureOpenAIApiDeploymentName; - azureOpenAIBasePath; - azureOpenAIEndpoint; - _llmType() { - return "azure_openai"; - } - get lc_aliases() { - return { - ...super.lc_aliases, - ...AZURE_ALIASES - }; - } - get lc_secrets() { - return { - ...super.lc_secrets, - ...AZURE_SECRETS - }; - } - get lc_serializable_keys() { - return [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS]; - } - getLsParams(options) { - const params = super.getLsParams(options); - params.ls_provider = "azure"; - return params; - } - constructor(fields) { - super(fields); - _constructAzureFields.call(this, fields); - } - _getClientOptions(options) { - return _getAzureClientOptions.call(this, options); - } - toJSON() { - return _serializeAzureChat.call(this, super.toJSON()); - } -}; - -//#endregion - -//# sourceMappingURL=completions.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/converters/responses.js - - - - - - - -//#region src/converters/responses.ts -const _FUNCTION_CALL_IDS_MAP_KEY = "__openai_function_call_ids__"; -/** -* Converts OpenAI Responses API usage statistics to LangChain's UsageMetadata format. -* -* This converter transforms token usage information from OpenAI's Responses API into -* the standardized UsageMetadata format used throughout LangChain. It handles both -* basic token counts and detailed token breakdowns including cached tokens and -* reasoning tokens. -* -* @param usage - The usage statistics object from OpenAI's Responses API containing -* token counts and optional detailed breakdowns. -* -* @returns A UsageMetadata object containing: -* - `input_tokens`: Total number of tokens in the input/prompt (defaults to 0 if not provided) -* - `output_tokens`: Total number of tokens in the model's output (defaults to 0 if not provided) -* - `total_tokens`: Combined total of input and output tokens (defaults to 0 if not provided) -* - `input_token_details`: Object containing detailed input token information: -* - `cache_read`: Number of tokens read from cache (only included if available) -* - `output_token_details`: Object containing detailed output token information: -* - `reasoning`: Number of tokens used for reasoning (only included if available) -* -* @example -* ```typescript -* const usage = { -* input_tokens: 100, -* output_tokens: 50, -* total_tokens: 150, -* input_tokens_details: { cached_tokens: 20 }, -* output_tokens_details: { reasoning_tokens: 10 } -* }; -* -* const metadata = convertResponsesUsageToUsageMetadata(usage); -* // Returns: -* // { -* // input_tokens: 100, -* // output_tokens: 50, -* // total_tokens: 150, -* // input_token_details: { cache_read: 20 }, -* // output_token_details: { reasoning: 10 } -* // } -* ``` -* -* @remarks -* - The function safely handles undefined or null values by using optional chaining -* and nullish coalescing operators -* - Detailed token information (cache_read, reasoning) is only included in the result -* if the corresponding values are present in the input -* - Token counts default to 0 if not provided in the usage object -* - This converter is specifically designed for OpenAI's Responses API format and -* may differ from other OpenAI API endpoints -*/ -const convertResponsesUsageToUsageMetadata = (usage) => { - const inputTokenDetails = { ...usage?.input_tokens_details?.cached_tokens != null && { cache_read: usage?.input_tokens_details?.cached_tokens } }; - const outputTokenDetails = { ...usage?.output_tokens_details?.reasoning_tokens != null && { reasoning: usage?.output_tokens_details?.reasoning_tokens } }; - return { - input_tokens: usage?.input_tokens ?? 0, - output_tokens: usage?.output_tokens ?? 0, - total_tokens: usage?.total_tokens ?? 0, - input_token_details: inputTokenDetails, - output_token_details: outputTokenDetails - }; -}; -/** -* Converts an OpenAI Responses API response to a LangChain AIMessage. -* -* This converter processes the output from OpenAI's Responses API (both `create` and `parse` methods) -* and transforms it into a LangChain AIMessage object with all relevant metadata, tool calls, and content. -* -* @param response - The response object from OpenAI's Responses API. Can be either: -* - ResponsesCreateInvoke: Result from `responses.create()` -* - ResponsesParseInvoke: Result from `responses.parse()` -* -* @returns An AIMessage containing: -* - `id`: The message ID from the response output -* - `content`: Array of message content blocks (text, images, etc.) -* - `tool_calls`: Array of successfully parsed tool calls -* - `invalid_tool_calls`: Array of tool calls that failed to parse -* - `usage_metadata`: Token usage information converted to LangChain format -* - `additional_kwargs`: Extra data including: -* - `refusal`: Refusal text if the model refused to respond -* - `reasoning`: Reasoning output for reasoning models -* - `tool_outputs`: Results from built-in tools (web search, file search, etc.) -* - `parsed`: Parsed structured output when using json_schema format -* - Function call ID mappings for tracking -* - `response_metadata`: Metadata about the response including model, timestamps, status, etc. -* -* @throws Error if the response contains an error object. The error message and code are extracted -* from the response.error field. -* -* @example -* ```typescript -* const response = await client.responses.create({ -* model: "gpt-4", -* input: [{ type: "message", content: "Hello" }] -* }); -* const message = convertResponsesMessageToAIMessage(response); -* console.log(message.content); // Message content -* console.log(message.tool_calls); // Any tool calls made -* ``` -* -* @remarks -* The converter handles multiple output item types: -* - `message`: Text and structured content from the model -* - `function_call`: Tool/function calls that need to be executed -* - `reasoning`: Reasoning traces from reasoning models (o1, o3, etc.) -* - `custom_tool_call`: Custom tool invocations -* - Built-in tool outputs: web_search, file_search, code_interpreter, etc. -* -* Tool calls are parsed and validated. Invalid tool calls (malformed JSON, etc.) are captured -* in the `invalid_tool_calls` array rather than throwing errors. -*/ -const convertResponsesMessageToAIMessage = (response) => { - if (response.error) { - const error = new Error(response.error.message); - error.name = response.error.code; - throw error; - } - let messageId; - const content = []; - const tool_calls = []; - const invalid_tool_calls = []; - const response_metadata = { - model_provider: "openai", - model: response.model, - created_at: response.created_at, - id: response.id, - incomplete_details: response.incomplete_details, - metadata: response.metadata, - object: response.object, - status: response.status, - user: response.user, - service_tier: response.service_tier, - model_name: response.model - }; - const additional_kwargs = {}; - for (const item of response.output) if (item.type === "message") { - messageId = item.id; - content.push(...item.content.flatMap((part) => { - if (part.type === "output_text") { - if ("parsed" in part && part.parsed != null) additional_kwargs.parsed = part.parsed; - return { - type: "text", - text: part.text, - annotations: part.annotations - }; - } - if (part.type === "refusal") { - additional_kwargs.refusal = part.refusal; - return []; - } - return part; - })); - } else if (item.type === "function_call") { - const fnAdapter = { - function: { - name: item.name, - arguments: item.arguments - }, - id: item.call_id - }; - try { - tool_calls.push(parseToolCall(fnAdapter, { returnId: true })); - } catch (e) { - let errMessage; - if (typeof e === "object" && e != null && "message" in e && typeof e.message === "string") errMessage = e.message; - invalid_tool_calls.push(makeInvalidToolCall(fnAdapter, errMessage)); - } - additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] ??= {}; - if (item.id) additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY][item.call_id] = item.id; - } else if (item.type === "reasoning") additional_kwargs.reasoning = item; - else if (item.type === "custom_tool_call") { - const parsed = parseCustomToolCall(item); - if (parsed) tool_calls.push(parsed); - else invalid_tool_calls.push(makeInvalidToolCall(item, "Malformed custom tool call")); - } else if (item.type === "computer_call") { - const parsed = parseComputerCall(item); - if (parsed) tool_calls.push(parsed); - else invalid_tool_calls.push(makeInvalidToolCall(item, "Malformed computer call")); - } else { - additional_kwargs.tool_outputs ??= []; - additional_kwargs.tool_outputs.push(item); - } - return new AIMessage({ - id: messageId, - content, - tool_calls, - invalid_tool_calls, - usage_metadata: convertResponsesUsageToUsageMetadata(response.usage), - additional_kwargs, - response_metadata - }); -}; -/** -* Converts a LangChain ChatOpenAI reasoning summary to an OpenAI Responses API reasoning item. -* -* This converter transforms reasoning summaries that have been accumulated during streaming -* (where summary parts may arrive in multiple chunks with the same index) into the final -* consolidated format expected by OpenAI's Responses API. It combines summary parts that -* share the same index and removes the index field from the final output. -* -* @param reasoning - A ChatOpenAI reasoning summary object containing: -* - `id`: The reasoning item ID -* - `type`: The type of reasoning (typically "reasoning") -* - `summary`: Array of summary parts, each with: -* - `text`: The summary text content -* - `type`: The summary type (e.g., "summary_text") -* - `index`: The index used to group related summary parts during streaming -* -* @returns An OpenAI Responses API ResponseReasoningItem with: -* - All properties from the input reasoning object -* - `summary`: Consolidated array of summary objects with: -* - `text`: Combined text from all parts with the same index -* - `type`: The summary type -* - No `index` field (removed after consolidation) -* -* @example -* ```typescript -* // Input: Reasoning summary with multiple parts at the same index -* const reasoning = { -* id: "reasoning_123", -* type: "reasoning", -* summary: [ -* { text: "First ", type: "summary_text", index: 0 }, -* { text: "part", type: "summary_text", index: 0 }, -* { text: "Second part", type: "summary_text", index: 1 } -* ] -* }; -* -* const result = convertReasoningSummaryToResponsesReasoningItem(reasoning); -* // Returns: -* // { -* // id: "reasoning_123", -* // type: "reasoning", -* // summary: [ -* // { text: "First part", type: "summary_text" }, -* // { text: "Second part", type: "summary_text" } -* // ] -* // } -* ``` -* -* @remarks -* - This converter is primarily used when reconstructing complete reasoning items from -* streaming chunks, where summary parts may arrive incrementally with index markers -* - Summary parts with the same index are concatenated in the order they appear -* - If the reasoning summary contains only one part, no reduction is performed -* - The index field is used internally during streaming to track which summary parts -* belong together, but is removed from the final output as it's not part of the -* OpenAI Responses API schema -* - This is the inverse operation of the streaming accumulation that happens in -* `convertResponsesDeltaToChatGenerationChunk` -*/ -const convertReasoningSummaryToResponsesReasoningItem = (reasoning) => { - const summary = (reasoning.summary.length > 1 ? reasoning.summary.reduce((acc, curr) => { - const last = acc[acc.length - 1]; - if (last.index === curr.index) last.text += curr.text; - else acc.push(curr); - return acc; - }, [{ ...reasoning.summary[0] }]) : reasoning.summary).map((s) => Object.fromEntries(Object.entries(s).filter(([k]) => k !== "index"))); - return { - ...reasoning, - summary - }; -}; -/** -* Converts OpenAI Responses API stream events to LangChain ChatGenerationChunk objects. -* -* This converter processes streaming events from OpenAI's Responses API and transforms them -* into LangChain ChatGenerationChunk objects that can be used in streaming chat applications. -* It handles various event types including text deltas, tool calls, reasoning, and metadata updates. -* -* @param event - A streaming event from OpenAI's Responses API -* -* @returns A ChatGenerationChunk containing: -* - `text`: Concatenated text content from all text parts in the event -* - `message`: An AIMessageChunk with: -* - `id`: Message ID (set when a message output item is added) -* - `content`: Array of content blocks (text with optional annotations) -* - `tool_call_chunks`: Incremental tool call data (name, args, id) -* - `usage_metadata`: Token usage information (only in completion events) -* - `additional_kwargs`: Extra data including: -* - `refusal`: Refusal text if the model refused to respond -* - `reasoning`: Reasoning output for reasoning models (id, type, summary) -* - `tool_outputs`: Results from built-in tools (web search, file search, etc.) -* - `parsed`: Parsed structured output when using json_schema format -* - Function call ID mappings for tracking -* - `response_metadata`: Metadata about the response (model, id, etc.) -* - `generationInfo`: Additional generation information (e.g., tool output status) -* -* Returns `null` for events that don't produce meaningful chunks: -* - Partial image generation events (to avoid storing all partial images in history) -* - Unrecognized event types -* -* @example -* ```typescript -* const stream = await client.responses.create({ -* model: "gpt-4", -* input: [{ type: "message", content: "Hello" }], -* stream: true -* }); -* -* for await (const event of stream) { -* const chunk = convertResponsesDeltaToChatGenerationChunk(event); -* if (chunk) { -* console.log(chunk.text); // Incremental text -* console.log(chunk.message.tool_call_chunks); // Tool call updates -* } -* } -* ``` -* -* @remarks -* - Text content is accumulated in an array with index tracking for proper ordering -* - Tool call chunks include incremental arguments that need to be concatenated by the consumer -* - Reasoning summaries are built incrementally across multiple events -* - Function call IDs are tracked in `additional_kwargs` to map call_id to item id -* - The `text` field is provided for legacy compatibility with `onLLMNewToken` callbacks -* - Usage metadata is only available in `response.completed` events -* - Partial images are intentionally ignored to prevent memory bloat in conversation history -*/ -const convertResponsesDeltaToChatGenerationChunk = (event) => { - const content = []; - let generationInfo = {}; - let usage_metadata; - const tool_call_chunks = []; - const response_metadata = { model_provider: "openai" }; - const additional_kwargs = {}; - let id; - if (event.type === "response.output_text.delta") content.push({ - type: "text", - text: event.delta, - index: event.content_index - }); - else if (event.type === "response.output_text.annotation.added") content.push({ - type: "text", - text: "", - annotations: [event.annotation], - index: event.content_index - }); - else if (event.type === "response.output_item.added" && event.item.type === "message") id = event.item.id; - else if (event.type === "response.output_item.added" && event.item.type === "function_call") { - tool_call_chunks.push({ - type: "tool_call_chunk", - name: event.item.name, - args: event.item.arguments, - id: event.item.call_id, - index: event.output_index - }); - additional_kwargs[_FUNCTION_CALL_IDS_MAP_KEY] = { [event.item.call_id]: event.item.id }; - } else if (event.type === "response.output_item.done" && event.item.type === "computer_call") { - tool_call_chunks.push({ - type: "tool_call_chunk", - name: "computer_use", - args: JSON.stringify({ action: event.item.action }), - id: event.item.call_id, - index: event.output_index - }); - additional_kwargs.tool_outputs = [event.item]; - } else if (event.type === "response.output_item.done" && [ - "web_search_call", - "file_search_call", - "code_interpreter_call", - "mcp_call", - "mcp_list_tools", - "mcp_approval_request", - "image_generation_call", - "custom_tool_call" - ].includes(event.item.type)) additional_kwargs.tool_outputs = [event.item]; - else if (event.type === "response.created") { - response_metadata.id = event.response.id; - response_metadata.model_name = event.response.model; - response_metadata.model = event.response.model; - } else if (event.type === "response.completed") { - const msg = convertResponsesMessageToAIMessage(event.response); - usage_metadata = convertResponsesUsageToUsageMetadata(event.response.usage); - if (event.response.text?.format?.type === "json_schema") additional_kwargs.parsed ??= JSON.parse(msg.text); - for (const [key, value] of Object.entries(event.response)) if (key !== "id") response_metadata[key] = value; - } else if (event.type === "response.function_call_arguments.delta" || event.type === "response.custom_tool_call_input.delta") tool_call_chunks.push({ - type: "tool_call_chunk", - args: event.delta, - index: event.output_index - }); - else if (event.type === "response.web_search_call.completed" || event.type === "response.file_search_call.completed") generationInfo = { tool_outputs: { - id: event.item_id, - type: event.type.replace("response.", "").replace(".completed", ""), - status: "completed" - } }; - else if (event.type === "response.refusal.done") additional_kwargs.refusal = event.refusal; - else if (event.type === "response.output_item.added" && "item" in event && event.item.type === "reasoning") { - const summary = event.item.summary ? event.item.summary.map((s, index) => ({ - ...s, - index - })) : void 0; - additional_kwargs.reasoning = { - id: event.item.id, - type: event.item.type, - ...summary ? { summary } : {} - }; - } else if (event.type === "response.reasoning_summary_part.added") additional_kwargs.reasoning = { - type: "reasoning", - summary: [{ - ...event.part, - index: event.summary_index - }] - }; - else if (event.type === "response.reasoning_summary_text.delta") additional_kwargs.reasoning = { - type: "reasoning", - summary: [{ - text: event.delta, - type: "summary_text", - index: event.summary_index - }] - }; - else if (event.type === "response.image_generation_call.partial_image") return null; - else return null; - return new ChatGenerationChunk({ - text: content.map((part) => part.text).join(""), - message: new AIMessageChunk({ - id, - content, - tool_call_chunks, - usage_metadata, - additional_kwargs, - response_metadata - }), - generationInfo - }); -}; -/** -* Converts a single LangChain BaseMessage to OpenAI Responses API input format. -* -* This converter transforms a LangChain message into one or more ResponseInputItem objects -* that can be used with OpenAI's Responses API. It handles complex message structures including -* tool calls, reasoning blocks, multimodal content, and various content block types. -* -* @param message - The LangChain BaseMessage to convert. Can be any message type including -* HumanMessage, AIMessage, SystemMessage, ToolMessage, etc. -* -* @returns An array of ResponseInputItem objects. -* -* @example -* Basic text message conversion: -* ```typescript -* const message = new HumanMessage("Hello, how are you?"); -* const items = convertStandardContentMessageToResponsesInput(message); -* // Returns: [{ type: "message", role: "user", content: [{ type: "input_text", text: "Hello, how are you?" }] }] -* ``` -* -* @example -* AI message with tool calls: -* ```typescript -* const message = new AIMessage({ -* content: "I'll check the weather for you.", -* tool_calls: [{ -* id: "call_123", -* name: "get_weather", -* args: { location: "San Francisco" } -* }] -* }); -* const items = convertStandardContentMessageToResponsesInput(message); -* // Returns: -* // [ -* // { type: "message", role: "assistant", content: [{ type: "input_text", text: "I'll check the weather for you." }] }, -* // { type: "function_call", call_id: "call_123", name: "get_weather", arguments: '{"location":"San Francisco"}' } -* // ] -* ``` -*/ -const convertStandardContentMessageToResponsesInput = (message) => { - const isResponsesMessage = AIMessage.isInstance(message) && message.response_metadata?.model_provider === "openai"; - function* iterateItems() { - const messageRole = iife$1(() => { - try { - const role = messageToOpenAIRole(message); - if (role === "system" || role === "developer" || role === "assistant" || role === "user") return role; - return "assistant"; - } catch { - return "assistant"; - } - }); - let currentMessage = void 0; - const functionCallIdsWithBlocks = /* @__PURE__ */ new Set(); - const serverFunctionCallIdsWithBlocks = /* @__PURE__ */ new Set(); - const pendingFunctionChunks = /* @__PURE__ */ new Map(); - const pendingServerFunctionChunks = /* @__PURE__ */ new Map(); - function* flushMessage() { - if (!currentMessage) return; - const content = currentMessage.content; - if (typeof content === "string" && content.length > 0 || Array.isArray(content) && content.length > 0) yield currentMessage; - currentMessage = void 0; - } - const pushMessageContent = (content) => { - if (!currentMessage) currentMessage = { - type: "message", - role: messageRole, - content: [] - }; - if (typeof currentMessage.content === "string") currentMessage.content = currentMessage.content.length > 0 ? [{ - type: "input_text", - text: currentMessage.content - }, ...content] : [...content]; - else currentMessage.content.push(...content); - }; - const toJsonString = (value) => { - if (typeof value === "string") return value; - try { - return JSON.stringify(value ?? {}); - } catch { - return "{}"; - } - }; - const resolveImageItem = (block) => { - const detail = iife$1(() => { - const raw = block.metadata?.detail; - if (raw === "low" || raw === "high" || raw === "auto") return raw; - return "auto"; - }); - if (block.fileId) return { - type: "input_image", - detail, - file_id: block.fileId - }; - if (block.url) return { - type: "input_image", - detail, - image_url: block.url - }; - if (block.data) { - const base64Data = typeof block.data === "string" ? block.data : Buffer.from(block.data).toString("base64"); - const mimeType = block.mimeType ?? "image/png"; - return { - type: "input_image", - detail, - image_url: `data:${mimeType};base64,${base64Data}` - }; - } - return void 0; - }; - const resolveFileItem = (block) => { - const filename = getRequiredFilenameFromMetadata(block); - if (block.fileId && typeof filename === "string") return { - type: "input_file", - file_id: block.fileId, - ...filename ? { filename } : {} - }; - if (block.url && typeof filename === "string") return { - type: "input_file", - file_url: block.url, - ...filename ? { filename } : {} - }; - if (block.data && typeof filename === "string") { - const encoded = typeof block.data === "string" ? block.data : Buffer.from(block.data).toString("base64"); - const mimeType = block.mimeType ?? "application/octet-stream"; - return { - type: "input_file", - file_data: `data:${mimeType};base64,${encoded}`, - ...filename ? { filename } : {} - }; - } - return void 0; - }; - const convertReasoningBlock = (block) => { - const summaryEntries = iife$1(() => { - if (Array.isArray(block.summary)) { - const candidate = block.summary; - const mapped = candidate?.map((item) => item?.text).filter((text) => typeof text === "string") ?? []; - if (mapped.length > 0) return mapped; - } - return block.reasoning ? [block.reasoning] : []; - }); - const summary = summaryEntries.length > 0 ? summaryEntries.map((text) => ({ - type: "summary_text", - text - })) : [{ - type: "summary_text", - text: "" - }]; - const reasoningItem = { - type: "reasoning", - id: block.id ?? "", - summary - }; - if (block.reasoning) reasoningItem.content = [{ - type: "reasoning_text", - text: block.reasoning - }]; - return reasoningItem; - }; - const convertFunctionCall = (block) => ({ - type: "function_call", - name: block.name ?? "", - call_id: block.id ?? "", - arguments: toJsonString(block.args) - }); - const convertFunctionCallOutput = (block) => { - const output = toJsonString(block.output); - const status = block.status === "success" ? "completed" : block.status === "error" ? "incomplete" : void 0; - return { - type: "function_call_output", - call_id: block.toolCallId ?? "", - output, - ...status ? { status } : {} - }; - }; - for (const block of message.contentBlocks) if (block.type === "text") pushMessageContent([{ - type: "input_text", - text: block.text - }]); - else if (block.type === "invalid_tool_call") {} else if (block.type === "reasoning") { - yield* flushMessage(); - yield convertReasoningBlock(block); - } else if (block.type === "tool_call") { - yield* flushMessage(); - const id = block.id ?? ""; - if (id) { - functionCallIdsWithBlocks.add(id); - pendingFunctionChunks.delete(id); - } - yield convertFunctionCall(block); - } else if (block.type === "tool_call_chunk") { - if (block.id) { - const existing = pendingFunctionChunks.get(block.id) ?? { - name: block.name, - args: [] - }; - if (block.name) existing.name = block.name; - if (block.args) existing.args.push(block.args); - pendingFunctionChunks.set(block.id, existing); - } - } else if (block.type === "server_tool_call") { - yield* flushMessage(); - const id = block.id ?? ""; - if (id) { - serverFunctionCallIdsWithBlocks.add(id); - pendingServerFunctionChunks.delete(id); - } - yield convertFunctionCall(block); - } else if (block.type === "server_tool_call_chunk") { - if (block.id) { - const existing = pendingServerFunctionChunks.get(block.id) ?? { - name: block.name, - args: [] - }; - if (block.name) existing.name = block.name; - if (block.args) existing.args.push(block.args); - pendingServerFunctionChunks.set(block.id, existing); - } - } else if (block.type === "server_tool_call_result") { - yield* flushMessage(); - yield convertFunctionCallOutput(block); - } else if (block.type === "audio") {} else if (block.type === "file") { - const fileItem = resolveFileItem(block); - if (fileItem) pushMessageContent([fileItem]); - } else if (block.type === "image") { - const imageItem = resolveImageItem(block); - if (imageItem) pushMessageContent([imageItem]); - } else if (block.type === "video") { - const videoItem = resolveFileItem(block); - if (videoItem) pushMessageContent([videoItem]); - } else if (block.type === "text-plain") { - if (block.text) pushMessageContent([{ - type: "input_text", - text: block.text - }]); - } else if (block.type === "non_standard" && isResponsesMessage) { - yield* flushMessage(); - yield block.value; - } - yield* flushMessage(); - for (const [id, chunk] of pendingFunctionChunks) { - if (!id || functionCallIdsWithBlocks.has(id)) continue; - const args = chunk.args.join(""); - if (!chunk.name && !args) continue; - yield { - type: "function_call", - call_id: id, - name: chunk.name ?? "", - arguments: args - }; - } - for (const [id, chunk] of pendingServerFunctionChunks) { - if (!id || serverFunctionCallIdsWithBlocks.has(id)) continue; - const args = chunk.args.join(""); - if (!chunk.name && !args) continue; - yield { - type: "function_call", - call_id: id, - name: chunk.name ?? "", - arguments: args - }; - } - } - return Array.from(iterateItems()); -}; -/** -* - MCP (Model Context Protocol) approval responses -* - Zero Data Retention (ZDR) mode handling -* -* @param params - Conversion parameters -* @param params.messages - Array of LangChain BaseMessages to convert -* @param params.zdrEnabled - Whether Zero Data Retention mode is enabled. When true, certain -* metadata like message IDs and function call IDs are omitted from the output -* @param params.model - The model name being used. Used to determine if special role mapping -* is needed (e.g., "system" -> "developer" for reasoning models) -* -* @returns Array of ResponsesInputItem objects formatted for the OpenAI Responses API -* -* @throws {Error} When a function message is encountered (not supported) -* @throws {Error} When computer call output format is invalid -* -* @example -* ```typescript -* const messages = [ -* new HumanMessage("Hello"), -* new AIMessage({ content: "Hi there!", tool_calls: [...] }) -* ]; -* -* const input = convertMessagesToResponsesInput({ -* messages, -* zdrEnabled: false, -* model: "gpt-4" -* }); -* ``` -*/ -const convertMessagesToResponsesInput = ({ messages, zdrEnabled, model }) => { - return messages.flatMap((lcMsg) => { - const responseMetadata = lcMsg.response_metadata; - if (responseMetadata?.output_version === "v1") return convertStandardContentMessageToResponsesInput(lcMsg); - const additional_kwargs = lcMsg.additional_kwargs; - let role = messageToOpenAIRole(lcMsg); - if (role === "system" && isReasoningModel(model)) role = "developer"; - if (role === "function") throw new Error("Function messages are not supported in Responses API"); - if (role === "tool") { - const toolMessage = lcMsg; - if (additional_kwargs?.type === "computer_call_output") { - const output = (() => { - if (typeof toolMessage.content === "string") return { - type: "input_image", - image_url: toolMessage.content - }; - if (Array.isArray(toolMessage.content)) { - /** - * Check for input_image type first (computer-use-preview format) - */ - const inputImage = toolMessage.content.find((i) => i.type === "input_image"); - if (inputImage) return inputImage; - /** - * Check for computer_screenshot type (legacy format) - */ - const oaiScreenshot = toolMessage.content.find((i) => i.type === "computer_screenshot"); - if (oaiScreenshot) return oaiScreenshot; - /** - * Convert image_url content block to input_image format - */ - const lcImage = toolMessage.content.find((i) => i.type === "image_url"); - if (lcImage) return { - type: "input_image", - image_url: typeof lcImage.image_url === "string" ? lcImage.image_url : lcImage.image_url.url - }; - } - throw new Error("Invalid computer call output"); - })(); - /** - * Cast needed because OpenAI SDK types don't yet include input_image - * for computer-use-preview model output format - */ - return { - type: "computer_call_output", - output, - call_id: toolMessage.tool_call_id - }; - } - if (toolMessage.additional_kwargs?.customTool) return { - type: "custom_tool_call_output", - call_id: toolMessage.tool_call_id, - output: toolMessage.content - }; - return { - type: "function_call_output", - call_id: toolMessage.tool_call_id, - id: toolMessage.id?.startsWith("fc_") ? toolMessage.id : void 0, - output: typeof toolMessage.content !== "string" ? JSON.stringify(toolMessage.content) : toolMessage.content - }; - } - if (role === "assistant") { - if (!zdrEnabled && responseMetadata?.output != null && Array.isArray(responseMetadata?.output) && responseMetadata?.output.length > 0 && responseMetadata?.output.every((item) => "type" in item)) return responseMetadata?.output; - const input = []; - if (additional_kwargs?.reasoning && !zdrEnabled) { - const reasoningItem = convertReasoningSummaryToResponsesReasoningItem(additional_kwargs.reasoning); - input.push(reasoningItem); - } - let { content } = lcMsg; - if (additional_kwargs?.refusal) { - if (typeof content === "string") content = [{ - type: "output_text", - text: content, - annotations: [] - }]; - content = [...content, { - type: "refusal", - refusal: additional_kwargs.refusal - }]; - } - if (typeof content === "string" || content.length > 0) input.push({ - type: "message", - role: "assistant", - ...lcMsg.id && !zdrEnabled && lcMsg.id.startsWith("msg_") ? { id: lcMsg.id } : {}, - content: iife$1(() => { - if (typeof content === "string") return content; - return content.flatMap((item) => { - if (item.type === "text") return { - type: "output_text", - text: item.text, - annotations: item.annotations ?? [] - }; - if (item.type === "output_text" || item.type === "refusal") return item; - return []; - }); - }) - }); - const functionCallIds = additional_kwargs?.[_FUNCTION_CALL_IDS_MAP_KEY]; - if (AIMessage.isInstance(lcMsg) && !!lcMsg.tool_calls?.length) input.push(...lcMsg.tool_calls.map((toolCall) => { - if (isCustomToolCall(toolCall)) return { - type: "custom_tool_call", - id: toolCall.call_id, - call_id: toolCall.id ?? "", - input: toolCall.args.input, - name: toolCall.name - }; - if (isComputerToolCall(toolCall)) return { - type: "computer_call", - id: toolCall.call_id, - call_id: toolCall.id ?? "", - action: toolCall.args.action - }; - return { - type: "function_call", - name: toolCall.name, - arguments: JSON.stringify(toolCall.args), - call_id: toolCall.id, - ...!zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {} - }; - })); - else if (additional_kwargs?.tool_calls) input.push(...additional_kwargs.tool_calls.map((toolCall) => ({ - type: "function_call", - name: toolCall.function.name, - call_id: toolCall.id, - arguments: toolCall.function.arguments, - ...!zdrEnabled ? { id: functionCallIds?.[toolCall.id] } : {} - }))); - const toolOutputs = (responseMetadata?.output)?.length ? responseMetadata?.output : additional_kwargs.tool_outputs; - const fallthroughCallTypes = [ - "computer_call", - "mcp_call", - "code_interpreter_call", - "image_generation_call" - ]; - if (toolOutputs != null) { - const castToolOutputs = toolOutputs; - const fallthroughCalls = castToolOutputs?.filter((item) => fallthroughCallTypes.includes(item.type)); - if (fallthroughCalls.length > 0) input.push(...fallthroughCalls); - } - return input; - } - if (role === "user" || role === "system" || role === "developer") { - if (typeof lcMsg.content === "string") return { - type: "message", - role, - content: lcMsg.content - }; - const messages$1 = []; - const content = lcMsg.content.flatMap((item) => { - if (item.type === "mcp_approval_response") messages$1.push({ - type: "mcp_approval_response", - approval_request_id: item.approval_request_id, - approve: item.approve - }); - if (isDataContentBlock(item)) return convertToProviderContentBlock(item, completionsApiContentBlockConverter); - if (item.type === "text") return { - type: "input_text", - text: item.text - }; - if (item.type === "image_url") { - const imageUrl = iife$1(() => { - if (typeof item.image_url === "string") return item.image_url; - else if (typeof item.image_url === "object" && item.image_url !== null && "url" in item.image_url) return item.image_url.url; - return void 0; - }); - const detail = iife$1(() => { - if (typeof item.image_url === "string") return "auto"; - else if (typeof item.image_url === "object" && item.image_url !== null && "detail" in item.image_url) return item.image_url.detail; - return void 0; - }); - return { - type: "input_image", - image_url: imageUrl, - detail - }; - } - if (item.type === "input_text" || item.type === "input_image" || item.type === "input_file") return item; - return []; - }); - if (content.length > 0) messages$1.push({ - type: "message", - role, - content - }); - return messages$1; - } - console.warn(`Unsupported role found when converting to OpenAI Responses API: ${role}`); - return []; - }); -}; - -//#endregion - -//# sourceMappingURL=responses.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/responses.js - - - - - - -//#region src/chat_models/responses.ts -/** -* OpenAI Responses API implementation. -* -* Will be exported in a later version of @langchain/openai. -* -* @internal -*/ -var ChatOpenAIResponses = class extends BaseChatOpenAI { - invocationParams(options) { - let strict; - if (options?.strict !== void 0) strict = options.strict; - if (strict === void 0 && this.supportsStrictToolCalling !== void 0) strict = this.supportsStrictToolCalling; - const params = { - model: this.model, - temperature: this.temperature, - top_p: this.topP, - user: this.user, - stream: this.streaming, - previous_response_id: options?.previous_response_id, - truncation: options?.truncation, - include: options?.include, - tools: options?.tools?.length ? this._reduceChatOpenAITools(options.tools, { - stream: this.streaming, - strict - }) : void 0, - tool_choice: isBuiltInToolChoice(options?.tool_choice) ? options?.tool_choice : (() => { - const formatted = formatToOpenAIToolChoice(options?.tool_choice); - if (typeof formatted === "object" && "type" in formatted) { - if (formatted.type === "function") return { - type: "function", - name: formatted.function.name - }; - else if (formatted.type === "allowed_tools") return { - type: "allowed_tools", - mode: formatted.allowed_tools.mode, - tools: formatted.allowed_tools.tools - }; - else if (formatted.type === "custom") return { - type: "custom", - name: formatted.custom.name - }; - } - return void 0; - })(), - text: (() => { - if (options?.text) return options.text; - const format = this._getResponseFormat(options?.response_format); - if (format?.type === "json_schema") { - if (format.json_schema.schema != null) return { - format: { - type: "json_schema", - schema: format.json_schema.schema, - description: format.json_schema.description, - name: format.json_schema.name, - strict: format.json_schema.strict - }, - verbosity: options?.verbosity - }; - return void 0; - } - return { - format, - verbosity: options?.verbosity - }; - })(), - parallel_tool_calls: options?.parallel_tool_calls, - max_output_tokens: this.maxTokens === -1 ? void 0 : this.maxTokens, - prompt_cache_key: options?.promptCacheKey ?? this.promptCacheKey, - prompt_cache_retention: options?.promptCacheRetention ?? this.promptCacheRetention, - ...this.zdrEnabled ? { store: false } : {}, - ...this.modelKwargs - }; - const reasoning = this._getReasoningParams(options); - if (reasoning !== void 0) params.reasoning = reasoning; - return params; - } - async _generate(messages, options) { - const invocationParams = this.invocationParams(options); - if (invocationParams.stream) { - const stream = this._streamResponseChunks(messages, options); - let finalChunk; - for await (const chunk of stream) { - chunk.message.response_metadata = { - ...chunk.generationInfo, - ...chunk.message.response_metadata - }; - finalChunk = finalChunk?.concat(chunk) ?? chunk; - } - return { - generations: finalChunk ? [finalChunk] : [], - llmOutput: { estimatedTokenUsage: (finalChunk?.message)?.usage_metadata } - }; - } else { - const data = await this.completionWithRetry({ - input: convertMessagesToResponsesInput({ - messages, - zdrEnabled: this.zdrEnabled ?? false, - model: this.model - }), - ...invocationParams, - stream: false - }, { - signal: options?.signal, - ...options?.options - }); - return { - generations: [{ - text: data.output_text, - message: convertResponsesMessageToAIMessage(data) - }], - llmOutput: { - id: data.id, - estimatedTokenUsage: data.usage ? { - promptTokens: data.usage.input_tokens, - completionTokens: data.usage.output_tokens, - totalTokens: data.usage.total_tokens - } : void 0 - } - }; - } - } - async *_streamResponseChunks(messages, options, runManager) { - const streamIterable = await this.completionWithRetry({ - ...this.invocationParams(options), - input: convertMessagesToResponsesInput({ - messages, - zdrEnabled: this.zdrEnabled ?? false, - model: this.model - }), - stream: true - }, options); - for await (const data of streamIterable) { - const chunk = convertResponsesDeltaToChatGenerationChunk(data); - if (chunk == null) continue; - yield chunk; - await runManager?.handleLLMNewToken(chunk.text || "", { - prompt: options.promptIndex ?? 0, - completion: 0 - }, void 0, void 0, void 0, { chunk }); - } - } - async completionWithRetry(request, requestOptions) { - return this.caller.call(async () => { - const clientOptions = this._getClientOptions(requestOptions); - try { - if (request.text?.format?.type === "json_schema" && !request.stream) return await this.client.responses.parse(request, clientOptions); - return await this.client.responses.create(request, clientOptions); - } catch (e) { - const error = wrapOpenAIClientError(e); - throw error; - } - }); - } - /** @internal */ - _reduceChatOpenAITools(tools, fields) { - const reducedTools = []; - for (const tool of tools) if (isBuiltInTool(tool)) { - if (tool.type === "image_generation" && fields?.stream) tool.partial_images = 1; - reducedTools.push(tool); - } else if (isCustomTool(tool)) { - const customToolData = tool.metadata.customTool; - reducedTools.push({ - type: "custom", - name: customToolData.name, - description: customToolData.description, - format: customToolData.format - }); - } else if (isOpenAITool(tool)) reducedTools.push({ - type: "function", - name: tool.function.name, - parameters: tool.function.parameters, - description: tool.function.description, - strict: fields?.strict ?? null - }); - else if (isOpenAICustomTool(tool)) reducedTools.push(convertCompletionsCustomTool(tool)); - return reducedTools; - } -}; - -//#endregion - -//# sourceMappingURL=responses.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/responses.js - - - -//#region src/azure/chat_models/responses.ts -var AzureChatOpenAIResponses = class extends ChatOpenAIResponses { - azureOpenAIApiVersion; - azureOpenAIApiKey; - azureADTokenProvider; - azureOpenAIApiInstanceName; - azureOpenAIApiDeploymentName; - azureOpenAIBasePath; - azureOpenAIEndpoint; - _llmType() { - return "azure_openai"; - } - get lc_aliases() { - return { - ...super.lc_aliases, - ...AZURE_ALIASES - }; - } - get lc_secrets() { - return { - ...super.lc_secrets, - ...AZURE_SECRETS - }; - } - get lc_serializable_keys() { - return [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS]; - } - getLsParams(options) { - const params = super.getLsParams(options); - params.ls_provider = "azure"; - return params; - } - constructor(fields) { - super(fields); - _constructAzureFields.call(this, fields); - } - _getClientOptions(options) { - return _getAzureClientOptions.call(this, options); - } - toJSON() { - return _serializeAzureChat.call(this, super.toJSON()); - } -}; - -//#endregion - -//# sourceMappingURL=responses.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/chat_models/index.js - - - - - - -//#region src/chat_models/index.ts -/** -* OpenAI chat model integration. -* -* To use with Azure, import the `AzureChatOpenAI` class. -* -* Setup: -* Install `@langchain/openai` and set an environment variable named `OPENAI_API_KEY`. -* -* ```bash -* npm install @langchain/openai -* export OPENAI_API_KEY="your-api-key" -* ``` -* -* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.ChatOpenAI.html#constructor) -* -* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html) -* -* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. -* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: -* -* ```typescript -* // When calling `.withConfig`, call options should be passed via the first argument -* const llmWithArgsBound = llm.withConfig({ -* stop: ["\n"], -* tools: [...], -* }); -* -* // When calling `.bindTools`, call options should be passed via the second argument -* const llmWithTools = llm.bindTools( -* [...], -* { -* tool_choice: "auto", -* } -* ); -* ``` -* -* ## Examples -* -*
-* Instantiate -* -* ```typescript -* import { ChatOpenAI } from '@langchain/openai'; -* -* const llm = new ChatOpenAI({ -* model: "gpt-4o-mini", -* temperature: 0, -* maxTokens: undefined, -* timeout: undefined, -* maxRetries: 2, -* // apiKey: "...", -* // configuration: { -* // baseURL: "...", -* // } -* // organization: "...", -* // other params... -* }); -* ``` -*
-* -*
-* -*
-* Invoking -* -* ```typescript -* const input = `Translate "I love programming" into French.`; -* -* // Models also accept a list of chat messages or a formatted prompt -* const result = await llm.invoke(input); -* console.log(result); -* ``` -* -* ```txt -* AIMessage { -* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz", -* "content": "J'adore la programmation.", -* "response_metadata": { -* "tokenUsage": { -* "completionTokens": 5, -* "promptTokens": 28, -* "totalTokens": 33 -* }, -* "finish_reason": "stop", -* "system_fingerprint": "fp_3aa7262c27" -* }, -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Streaming Chunks -* -* ```typescript -* for await (const chunk of await llm.stream(input)) { -* console.log(chunk); -* } -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs", -* "content": "" -* } -* AIMessageChunk { -* "content": "J" -* } -* AIMessageChunk { -* "content": "'adore" -* } -* AIMessageChunk { -* "content": " la" -* } -* AIMessageChunk { -* "content": " programmation",, -* } -* AIMessageChunk { -* "content": ".",, -* } -* AIMessageChunk { -* "content": "", -* "response_metadata": { -* "finish_reason": "stop", -* "system_fingerprint": "fp_c9aa9c0491" -* }, -* } -* AIMessageChunk { -* "content": "", -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Aggregate Streamed Chunks -* -* ```typescript -* import { AIMessageChunk } from '@langchain/core/messages'; -* import { concat } from '@langchain/core/utils/stream'; -* -* const stream = await llm.stream(input); -* let full: AIMessageChunk | undefined; -* for await (const chunk of stream) { -* full = !full ? chunk : concat(full, chunk); -* } -* console.log(full); -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu", -* "content": "J'adore la programmation.", -* "response_metadata": { -* "prompt": 0, -* "completion": 0, -* "finish_reason": "stop", -* }, -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Bind tools -* -* ```typescript -* import { z } from 'zod'; -* -* const GetWeather = { -* name: "GetWeather", -* description: "Get the current weather in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const GetPopulation = { -* name: "GetPopulation", -* description: "Get the current population in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const llmWithTools = llm.bindTools( -* [GetWeather, GetPopulation], -* { -* // strict: true // enforce tool args schema is respected -* } -* ); -* const aiMsg = await llmWithTools.invoke( -* "Which city is hotter today and which is bigger: LA or NY?" -* ); -* console.log(aiMsg.tool_calls); -* ``` -* -* ```txt -* [ -* { -* name: 'GetWeather', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call', -* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK' -* }, -* { -* name: 'GetWeather', -* args: { location: 'New York, NY' }, -* type: 'tool_call', -* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call', -* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'New York, NY' }, -* type: 'tool_call', -* id: 'call_s9KQB1UWj45LLGaEnjz0179q' -* } -* ] -* ``` -*
-* -*
-* -*
-* Structured Output -* -* ```typescript -* import { z } from 'zod'; -* -* const Joke = z.object({ -* setup: z.string().describe("The setup of the joke"), -* punchline: z.string().describe("The punchline to the joke"), -* rating: z.number().nullable().describe("How funny the joke is, from 1 to 10") -* }).describe('Joke to tell user.'); -* -* const structuredLlm = llm.withStructuredOutput(Joke, { -* name: "Joke", -* strict: true, // Optionally enable OpenAI structured outputs -* }); -* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); -* console.log(jokeResult); -* ``` -* -* ```txt -* { -* setup: 'Why was the cat sitting on the computer?', -* punchline: 'Because it wanted to keep an eye on the mouse!', -* rating: 7 -* } -* ``` -*
-* -*
-* -*
-* JSON Object Response Format -* -* ```typescript -* const jsonLlm = llm.withConfig({ response_format: { type: "json_object" } }); -* const jsonLlmAiMsg = await jsonLlm.invoke( -* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]" -* ); -* console.log(jsonLlmAiMsg.content); -* ``` -* -* ```txt -* { -* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67] -* } -* ``` -*
-* -*
-* -*
-* Multimodal -* -* ```typescript -* import { HumanMessage } from '@langchain/core/messages'; -* -* const imageUrl = "https://example.com/image.jpg"; -* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); -* const base64Image = Buffer.from(imageData).toString('base64'); -* -* const message = new HumanMessage({ -* content: [ -* { type: "text", text: "describe the weather in this image" }, -* { -* type: "image_url", -* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, -* }, -* ] -* }); -* -* const imageDescriptionAiMsg = await llm.invoke([message]); -* console.log(imageDescriptionAiMsg.content); -* ``` -* -* ```txt -* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions. -* ``` -*
-* -*
-* -*
-* Usage Metadata -* -* ```typescript -* const aiMsgForMetadata = await llm.invoke(input); -* console.log(aiMsgForMetadata.usage_metadata); -* ``` -* -* ```txt -* { input_tokens: 28, output_tokens: 5, total_tokens: 33 } -* ``` -*
-* -*
-* -*
-* Logprobs -* -* ```typescript -* const logprobsLlm = new ChatOpenAI({ model: "gpt-4o-mini", logprobs: true }); -* const aiMsgForLogprobs = await logprobsLlm.invoke(input); -* console.log(aiMsgForLogprobs.response_metadata.logprobs); -* ``` -* -* ```txt -* { -* content: [ -* { -* token: 'J', -* logprob: -0.000050616763, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: "'", -* logprob: -0.01868736, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: 'ad', -* logprob: -0.0000030545007, -* bytes: [Array], -* top_logprobs: [] -* }, -* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] }, -* { -* token: ' la', -* logprob: -0.515404, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: ' programm', -* logprob: -0.0000118755715, -* bytes: [Array], -* top_logprobs: [] -* }, -* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] }, -* { -* token: '.', -* logprob: -0.0000037697225, -* bytes: [Array], -* top_logprobs: [] -* } -* ], -* refusal: null -* } -* ``` -*
-* -*
-* -*
-* Response Metadata -* -* ```typescript -* const aiMsgForResponseMetadata = await llm.invoke(input); -* console.log(aiMsgForResponseMetadata.response_metadata); -* ``` -* -* ```txt -* { -* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 }, -* finish_reason: 'stop', -* system_fingerprint: 'fp_3aa7262c27' -* } -* ``` -*
-* -*
-* -*
-* JSON Schema Structured Output -* -* ```typescript -* const llmForJsonSchema = new ChatOpenAI({ -* model: "gpt-4o-2024-08-06", -* }).withStructuredOutput( -* z.object({ -* command: z.string().describe("The command to execute"), -* expectedOutput: z.string().describe("The expected output of the command"), -* options: z -* .array(z.string()) -* .describe("The options you can pass to the command"), -* }), -* { -* method: "jsonSchema", -* strict: true, // Optional when using the `jsonSchema` method -* } -* ); -* -* const jsonSchemaRes = await llmForJsonSchema.invoke( -* "What is the command to list files in a directory?" -* ); -* console.log(jsonSchemaRes); -* ``` -* -* ```txt -* { -* command: 'ls', -* expectedOutput: 'A list of files and subdirectories within the specified directory.', -* options: [ -* '-a: include directory entries whose names begin with a dot (.).', -* '-l: use a long listing format.', -* '-h: with -l, print sizes in human readable format (e.g., 1K, 234M, 2G).', -* '-t: sort by time, newest first.', -* '-r: reverse order while sorting.', -* '-S: sort by file size, largest first.', -* '-R: list subdirectories recursively.' -* ] -* } -* ``` -*
-* -*
-* -*
-* Audio Outputs -* -* ```typescript -* import { ChatOpenAI } from "@langchain/openai"; -* -* const modelWithAudioOutput = new ChatOpenAI({ -* model: "gpt-4o-audio-preview", -* // You may also pass these fields to `.withConfig` as a call argument. -* modalities: ["text", "audio"], // Specifies that the model should output audio. -* audio: { -* voice: "alloy", -* format: "wav", -* }, -* }); -* -* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats."); -* const castMessageContent = audioOutputResult.content[0] as Record; -* -* console.log({ -* ...castMessageContent, -* data: castMessageContent.data.slice(0, 100) // Sliced for brevity -* }) -* ``` -* -* ```txt -* { -* id: 'audio_67117718c6008190a3afad3e3054b9b6', -* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg', -* expires_at: 1729201448, -* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!' -* } -* ``` -*
-* -*
-* -*
-* Audio Outputs -* -* ```typescript -* import { ChatOpenAI } from "@langchain/openai"; -* -* const modelWithAudioOutput = new ChatOpenAI({ -* model: "gpt-4o-audio-preview", -* // You may also pass these fields to `.withConfig` as a call argument. -* modalities: ["text", "audio"], // Specifies that the model should output audio. -* audio: { -* voice: "alloy", -* format: "wav", -* }, -* }); -* -* const audioOutputResult = await modelWithAudioOutput.invoke("Tell me a joke about cats."); -* const castAudioContent = audioOutputResult.additional_kwargs.audio as Record; -* -* console.log({ -* ...castAudioContent, -* data: castAudioContent.data.slice(0, 100) // Sliced for brevity -* }) -* ``` -* -* ```txt -* { -* id: 'audio_67117718c6008190a3afad3e3054b9b6', -* data: 'UklGRqYwBgBXQVZFZm10IBAAAAABAAEAwF0AAIC7AAACABAATElTVBoAAABJTkZPSVNGVA4AAABMYXZmNTguMjkuMTAwAGRhdGFg', -* expires_at: 1729201448, -* transcript: 'Sure! Why did the cat sit on the computer? Because it wanted to keep an eye on the mouse!' -* } -* ``` -*
-* -*
-*/ -var ChatOpenAI = class ChatOpenAI extends BaseChatOpenAI { - /** - * Whether to use the responses API for all requests. If `false` the responses API will be used - * only when required in order to fulfill the request. - */ - useResponsesApi = false; - responses; - completions; - get lc_serializable_keys() { - return [...super.lc_serializable_keys, "useResponsesApi"]; - } - get callKeys() { - return [...super.callKeys, "useResponsesApi"]; - } - constructor(fields) { - super(fields); - this.fields = fields; - this.useResponsesApi = fields?.useResponsesApi ?? false; - this.responses = fields?.responses ?? new ChatOpenAIResponses(fields); - this.completions = fields?.completions ?? new ChatOpenAICompletions(fields); - } - _useResponsesApi(options) { - const usesBuiltInTools = options?.tools?.some(isBuiltInTool); - const hasResponsesOnlyKwargs = options?.previous_response_id != null || options?.text != null || options?.truncation != null || options?.include != null || options?.reasoning?.summary != null || this.reasoning?.summary != null; - const hasCustomTools = options?.tools?.some(isOpenAICustomTool) || options?.tools?.some(isCustomTool); - return this.useResponsesApi || usesBuiltInTools || hasResponsesOnlyKwargs || hasCustomTools || _modelPrefersResponsesAPI(this.model); - } - getLsParams(options) { - const optionsWithDefaults = this._combineCallOptions(options); - if (this._useResponsesApi(options)) return this.responses.getLsParams(optionsWithDefaults); - return this.completions.getLsParams(optionsWithDefaults); - } - invocationParams(options) { - const optionsWithDefaults = this._combineCallOptions(options); - if (this._useResponsesApi(options)) return this.responses.invocationParams(optionsWithDefaults); - return this.completions.invocationParams(optionsWithDefaults); - } - /** @ignore */ - async _generate(messages, options, runManager) { - if (this._useResponsesApi(options)) return this.responses._generate(messages, options); - return this.completions._generate(messages, options, runManager); - } - async *_streamResponseChunks(messages, options, runManager) { - if (this._useResponsesApi(options)) { - yield* this.responses._streamResponseChunks(messages, this._combineCallOptions(options), runManager); - return; - } - yield* this.completions._streamResponseChunks(messages, this._combineCallOptions(options), runManager); - } - withConfig(config) { - const newModel = new ChatOpenAI(this.fields); - newModel.defaultOptions = { - ...this.defaultOptions, - ...config - }; - return newModel; - } -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/chat_models/index.js - - - - - -//#region src/azure/chat_models/index.ts -/** -* Azure OpenAI chat model integration. -* -* Setup: -* Install `@langchain/openai` and set the following environment variables: -* -* ```bash -* npm install @langchain/openai -* export AZURE_OPENAI_API_KEY="your-api-key" -* export AZURE_OPENAI_API_DEPLOYMENT_NAME="your-deployment-name" -* export AZURE_OPENAI_API_VERSION="your-version" -* export AZURE_OPENAI_BASE_PATH="your-base-path" -* ``` -* -* ## [Constructor args](https://api.js.langchain.com/classes/langchain_openai.AzureChatOpenAI.html#constructor) -* -* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_openai.ChatOpenAICallOptions.html) -* -* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. -* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: -* -* ```typescript -* // When calling `.withConfig`, call options should be passed via the first argument -* const llmWithArgsBound = llm.withConfig({ -* stop: ["\n"], -* tools: [...], -* }); -* -* // When calling `.bindTools`, call options should be passed via the second argument -* const llmWithTools = llm.bindTools( -* [...], -* { -* tool_choice: "auto", -* } -* ); -* ``` -* -* ## Examples -* -*
-* Instantiate -* -* ```typescript -* import { AzureChatOpenAI } from '@langchain/openai'; -* -* const llm = new AzureChatOpenAI({ -* azureOpenAIApiKey: process.env.AZURE_OPENAI_API_KEY, // In Node.js defaults to process.env.AZURE_OPENAI_API_KEY -* azureOpenAIApiInstanceName: process.env.AZURE_OPENAI_API_INSTANCE_NAME, // In Node.js defaults to process.env.AZURE_OPENAI_API_INSTANCE_NAME -* azureOpenAIApiDeploymentName: process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME, // In Node.js defaults to process.env.AZURE_OPENAI_API_DEPLOYMENT_NAME -* azureOpenAIApiVersion: process.env.AZURE_OPENAI_API_VERSION, // In Node.js defaults to process.env.AZURE_OPENAI_API_VERSION -* temperature: 0, -* maxTokens: undefined, -* timeout: undefined, -* maxRetries: 2, -* // apiKey: "...", -* // baseUrl: "...", -* // other params... -* }); -* ``` -*
-* -*
-* -*
-* Invoking -* -* ```typescript -* const input = `Translate "I love programming" into French.`; -* -* // Models also accept a list of chat messages or a formatted prompt -* const result = await llm.invoke(input); -* console.log(result); -* ``` -* -* ```txt -* AIMessage { -* "id": "chatcmpl-9u4Mpu44CbPjwYFkTbeoZgvzB00Tz", -* "content": "J'adore la programmation.", -* "response_metadata": { -* "tokenUsage": { -* "completionTokens": 5, -* "promptTokens": 28, -* "totalTokens": 33 -* }, -* "finish_reason": "stop", -* "system_fingerprint": "fp_3aa7262c27" -* }, -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Streaming Chunks -* -* ```typescript -* for await (const chunk of await llm.stream(input)) { -* console.log(chunk); -* } -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "chatcmpl-9u4NWB7yUeHCKdLr6jP3HpaOYHTqs", -* "content": "" -* } -* AIMessageChunk { -* "content": "J" -* } -* AIMessageChunk { -* "content": "'adore" -* } -* AIMessageChunk { -* "content": " la" -* } -* AIMessageChunk { -* "content": " programmation",, -* } -* AIMessageChunk { -* "content": ".",, -* } -* AIMessageChunk { -* "content": "", -* "response_metadata": { -* "finish_reason": "stop", -* "system_fingerprint": "fp_c9aa9c0491" -* }, -* } -* AIMessageChunk { -* "content": "", -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Aggregate Streamed Chunks -* -* ```typescript -* import { AIMessageChunk } from '@langchain/core/messages'; -* import { concat } from '@langchain/core/utils/stream'; -* -* const stream = await llm.stream(input); -* let full: AIMessageChunk | undefined; -* for await (const chunk of stream) { -* full = !full ? chunk : concat(full, chunk); -* } -* console.log(full); -* ``` -* -* ```txt -* AIMessageChunk { -* "id": "chatcmpl-9u4PnX6Fy7OmK46DASy0bH6cxn5Xu", -* "content": "J'adore la programmation.", -* "response_metadata": { -* "prompt": 0, -* "completion": 0, -* "finish_reason": "stop", -* }, -* "usage_metadata": { -* "input_tokens": 28, -* "output_tokens": 5, -* "total_tokens": 33 -* } -* } -* ``` -*
-* -*
-* -*
-* Bind tools -* -* ```typescript -* import { z } from 'zod'; -* -* const GetWeather = { -* name: "GetWeather", -* description: "Get the current weather in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const GetPopulation = { -* name: "GetPopulation", -* description: "Get the current population in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); -* const aiMsg = await llmWithTools.invoke( -* "Which city is hotter today and which is bigger: LA or NY?" -* ); -* console.log(aiMsg.tool_calls); -* ``` -* -* ```txt -* [ -* { -* name: 'GetWeather', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call', -* id: 'call_uPU4FiFzoKAtMxfmPnfQL6UK' -* }, -* { -* name: 'GetWeather', -* args: { location: 'New York, NY' }, -* type: 'tool_call', -* id: 'call_UNkEwuQsHrGYqgDQuH9nPAtX' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call', -* id: 'call_kL3OXxaq9OjIKqRTpvjaCH14' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'New York, NY' }, -* type: 'tool_call', -* id: 'call_s9KQB1UWj45LLGaEnjz0179q' -* } -* ] -* ``` -*
-* -*
-* -*
-* Structured Output -* -* ```typescript -* import { z } from 'zod'; -* -* const Joke = z.object({ -* setup: z.string().describe("The setup of the joke"), -* punchline: z.string().describe("The punchline to the joke"), -* rating: z.number().nullable().describe("How funny the joke is, from 1 to 10") -* }).describe('Joke to tell user.'); -* -* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); -* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); -* console.log(jokeResult); -* ``` -* -* ```txt -* { -* setup: 'Why was the cat sitting on the computer?', -* punchline: 'Because it wanted to keep an eye on the mouse!', -* rating: 7 -* } -* ``` -*
-* -*
-* -*
-* JSON Object Response Format -* -* ```typescript -* const jsonLlm = llm.withConfig({ response_format: { type: "json_object" } }); -* const jsonLlmAiMsg = await jsonLlm.invoke( -* "Return a JSON object with key 'randomInts' and a value of 10 random ints in [0-99]" -* ); -* console.log(jsonLlmAiMsg.content); -* ``` -* -* ```txt -* { -* "randomInts": [23, 87, 45, 12, 78, 34, 56, 90, 11, 67] -* } -* ``` -*
-* -*
-* -*
-* Multimodal -* -* ```typescript -* import { HumanMessage } from '@langchain/core/messages'; -* -* const imageUrl = "https://example.com/image.jpg"; -* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); -* const base64Image = Buffer.from(imageData).toString('base64'); -* -* const message = new HumanMessage({ -* content: [ -* { type: "text", text: "describe the weather in this image" }, -* { -* type: "image_url", -* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, -* }, -* ] -* }); -* -* const imageDescriptionAiMsg = await llm.invoke([message]); -* console.log(imageDescriptionAiMsg.content); -* ``` -* -* ```txt -* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions. -* ``` -*
-* -*
-* -*
-* Usage Metadata -* -* ```typescript -* const aiMsgForMetadata = await llm.invoke(input); -* console.log(aiMsgForMetadata.usage_metadata); -* ``` -* -* ```txt -* { input_tokens: 28, output_tokens: 5, total_tokens: 33 } -* ``` -*
-* -*
-* -*
-* Logprobs -* -* ```typescript -* const logprobsLlm = new ChatOpenAI({ model: "gpt-4o-mini", logprobs: true }); -* const aiMsgForLogprobs = await logprobsLlm.invoke(input); -* console.log(aiMsgForLogprobs.response_metadata.logprobs); -* ``` -* -* ```txt -* { -* content: [ -* { -* token: 'J', -* logprob: -0.000050616763, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: "'", -* logprob: -0.01868736, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: 'ad', -* logprob: -0.0000030545007, -* bytes: [Array], -* top_logprobs: [] -* }, -* { token: 'ore', logprob: 0, bytes: [Array], top_logprobs: [] }, -* { -* token: ' la', -* logprob: -0.515404, -* bytes: [Array], -* top_logprobs: [] -* }, -* { -* token: ' programm', -* logprob: -0.0000118755715, -* bytes: [Array], -* top_logprobs: [] -* }, -* { token: 'ation', logprob: 0, bytes: [Array], top_logprobs: [] }, -* { -* token: '.', -* logprob: -0.0000037697225, -* bytes: [Array], -* top_logprobs: [] -* } -* ], -* refusal: null -* } -* ``` -*
-* -*
-* -*
-* Response Metadata -* -* ```typescript -* const aiMsgForResponseMetadata = await llm.invoke(input); -* console.log(aiMsgForResponseMetadata.response_metadata); -* ``` -* -* ```txt -* { -* tokenUsage: { completionTokens: 5, promptTokens: 28, totalTokens: 33 }, -* finish_reason: 'stop', -* system_fingerprint: 'fp_3aa7262c27' -* } -* ``` -*
-*/ -var AzureChatOpenAI = class extends ChatOpenAI { - azureOpenAIApiVersion; - azureOpenAIApiKey; - azureADTokenProvider; - azureOpenAIApiInstanceName; - azureOpenAIApiDeploymentName; - azureOpenAIBasePath; - azureOpenAIEndpoint; - _llmType() { - return "azure_openai"; - } - get lc_aliases() { - return { - ...super.lc_aliases, - ...AZURE_ALIASES - }; - } - get lc_secrets() { - return { - ...super.lc_secrets, - ...AZURE_SECRETS - }; - } - get lc_serializable_keys() { - return [...super.lc_serializable_keys, ...AZURE_SERIALIZABLE_KEYS]; - } - getLsParams(options) { - const params = super.getLsParams(options); - params.ls_provider = "azure"; - return params; - } - constructor(fields) { - super({ - ...fields, - completions: new AzureChatOpenAICompletions(fields), - responses: new AzureChatOpenAIResponses(fields) - }); - _constructAzureFields.call(this, fields); - } - /** @internal */ - _getStructuredOutputMethod(config) { - const ensuredConfig = { ...config }; - if (this.model.startsWith("gpt-4o")) { - if (ensuredConfig?.method === void 0) return "functionCalling"; - } - return super._getStructuredOutputMethod(ensuredConfig); - } - toJSON() { - return _serializeAzureChat.call(this, super.toJSON()); - } -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/llms.js - - - - - - - - - -//#region src/llms.ts -/** -* Wrapper around OpenAI large language models. -* -* To use you should have the `openai` package installed, with the -* `OPENAI_API_KEY` environment variable set. -* -* To use with Azure, import the `AzureOpenAI` class. -* -* @remarks -* Any parameters that are valid to be passed to {@link -* https://platform.openai.com/docs/api-reference/completions/create | -* `openai.createCompletion`} can be passed through {@link modelKwargs}, even -* if not explicitly available on this class. -* @example -* ```typescript -* const model = new OpenAI({ -* modelName: "gpt-4", -* temperature: 0.7, -* maxTokens: 1000, -* maxRetries: 5, -* }); -* -* const res = await model.invoke( -* "Question: What would be a good company name for a company that makes colorful socks?\nAnswer:" -* ); -* console.log({ res }); -* ``` -*/ -var OpenAI$2 = class extends BaseLLM { - static lc_name() { - return "OpenAI"; - } - get callKeys() { - return [...super.callKeys, "options"]; - } - lc_serializable = true; - get lc_secrets() { - return { - openAIApiKey: "OPENAI_API_KEY", - apiKey: "OPENAI_API_KEY", - organization: "OPENAI_ORGANIZATION" - }; - } - get lc_aliases() { - return { - modelName: "model", - openAIApiKey: "openai_api_key", - apiKey: "openai_api_key" - }; - } - temperature; - maxTokens; - topP; - frequencyPenalty; - presencePenalty; - n = 1; - bestOf; - logitBias; - model = "gpt-3.5-turbo-instruct"; - /** @deprecated Use "model" instead */ - modelName; - modelKwargs; - batchSize = 20; - timeout; - stop; - stopSequences; - user; - streaming = false; - openAIApiKey; - apiKey; - organization; - client; - clientConfig; - constructor(fields) { - super(fields ?? {}); - this.openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); - this.apiKey = this.openAIApiKey; - this.organization = fields?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); - this.model = fields?.model ?? fields?.modelName ?? this.model; - if ((this.model?.startsWith("gpt-3.5-turbo") || this.model?.startsWith("gpt-4") || this.model?.startsWith("o1")) && !this.model?.includes("-instruct")) throw new Error([ - `Your chosen OpenAI model, "${this.model}", is a chat model and not a text-in/text-out LLM.`, - `Passing it into the "OpenAI" class is no longer supported.`, - `Please use the "ChatOpenAI" class instead.`, - "", - `See this page for more information:`, - "|", - `└> https://js.langchain.com/docs/integrations/chat/openai` - ].join("\n")); - this.modelName = this.model; - this.modelKwargs = fields?.modelKwargs ?? {}; - this.batchSize = fields?.batchSize ?? this.batchSize; - this.timeout = fields?.timeout; - this.temperature = fields?.temperature ?? this.temperature; - this.maxTokens = fields?.maxTokens ?? this.maxTokens; - this.topP = fields?.topP ?? this.topP; - this.frequencyPenalty = fields?.frequencyPenalty ?? this.frequencyPenalty; - this.presencePenalty = fields?.presencePenalty ?? this.presencePenalty; - this.n = fields?.n ?? this.n; - this.bestOf = fields?.bestOf ?? this.bestOf; - this.logitBias = fields?.logitBias; - this.stop = fields?.stopSequences ?? fields?.stop; - this.stopSequences = this.stop; - this.user = fields?.user; - this.streaming = fields?.streaming ?? false; - if (this.streaming && this.bestOf && this.bestOf > 1) throw new Error("Cannot stream results when bestOf > 1"); - this.clientConfig = { - apiKey: this.apiKey, - organization: this.organization, - dangerouslyAllowBrowser: true, - ...fields?.configuration - }; - } - /** - * Get the parameters used to invoke the model - */ - invocationParams(options) { - return { - model: this.model, - temperature: this.temperature, - max_tokens: this.maxTokens, - top_p: this.topP, - frequency_penalty: this.frequencyPenalty, - presence_penalty: this.presencePenalty, - n: this.n, - best_of: this.bestOf, - logit_bias: this.logitBias, - stop: options?.stop ?? this.stopSequences, - user: this.user, - stream: this.streaming, - ...this.modelKwargs - }; - } - /** @ignore */ - _identifyingParams() { - return { - model_name: this.model, - ...this.invocationParams(), - ...this.clientConfig - }; - } - /** - * Get the identifying parameters for the model - */ - identifyingParams() { - return this._identifyingParams(); - } - /** - * Call out to OpenAI's endpoint with k unique prompts - * - * @param [prompts] - The prompts to pass into the model. - * @param [options] - Optional list of stop words to use when generating. - * @param [runManager] - Optional callback manager to use when generating. - * - * @returns The full LLM output. - * - * @example - * ```ts - * import { OpenAI } from "langchain/llms/openai"; - * const openai = new OpenAI(); - * const response = await openai.generate(["Tell me a joke."]); - * ``` - */ - async _generate(prompts, options, runManager) { - const subPrompts = chunkArray(prompts, this.batchSize); - const choices = []; - const tokenUsage = {}; - const params = this.invocationParams(options); - if (params.max_tokens === -1) { - if (prompts.length !== 1) throw new Error("max_tokens set to -1 not supported for multiple inputs"); - params.max_tokens = await calculateMaxTokens({ - prompt: prompts[0], - modelName: this.model - }); - } - for (let i = 0; i < subPrompts.length; i += 1) { - const data = params.stream ? await (async () => { - const choices$1 = []; - let response; - const stream = await this.completionWithRetry({ - ...params, - stream: true, - prompt: subPrompts[i] - }, options); - for await (const message of stream) { - if (!response) response = { - id: message.id, - object: message.object, - created: message.created, - model: message.model - }; - for (const part of message.choices) { - if (!choices$1[part.index]) choices$1[part.index] = part; - else { - const choice = choices$1[part.index]; - choice.text += part.text; - choice.finish_reason = part.finish_reason; - choice.logprobs = part.logprobs; - } - runManager?.handleLLMNewToken(part.text, { - prompt: Math.floor(part.index / this.n), - completion: part.index % this.n - }); - } - } - if (options.signal?.aborted) throw new Error("AbortError"); - return { - ...response, - choices: choices$1 - }; - })() : await this.completionWithRetry({ - ...params, - stream: false, - prompt: subPrompts[i] - }, { - signal: options.signal, - ...options.options - }); - choices.push(...data.choices); - const { completion_tokens: completionTokens, prompt_tokens: promptTokens, total_tokens: totalTokens } = data.usage ? data.usage : { - completion_tokens: void 0, - prompt_tokens: void 0, - total_tokens: void 0 - }; - if (completionTokens) tokenUsage.completionTokens = (tokenUsage.completionTokens ?? 0) + completionTokens; - if (promptTokens) tokenUsage.promptTokens = (tokenUsage.promptTokens ?? 0) + promptTokens; - if (totalTokens) tokenUsage.totalTokens = (tokenUsage.totalTokens ?? 0) + totalTokens; - } - const generations = chunkArray(choices, this.n).map((promptChoices) => promptChoices.map((choice) => ({ - text: choice.text ?? "", - generationInfo: { - finishReason: choice.finish_reason, - logprobs: choice.logprobs - } - }))); - return { - generations, - llmOutput: { tokenUsage } - }; - } - async *_streamResponseChunks(input, options, runManager) { - const params = { - ...this.invocationParams(options), - prompt: input, - stream: true - }; - const stream = await this.completionWithRetry(params, options); - for await (const data of stream) { - const choice = data?.choices[0]; - if (!choice) continue; - const chunk = new GenerationChunk({ - text: choice.text, - generationInfo: { finishReason: choice.finish_reason } - }); - yield chunk; - runManager?.handleLLMNewToken(chunk.text ?? ""); - } - if (options.signal?.aborted) throw new Error("AbortError"); - } - async completionWithRetry(request, options) { - const requestOptions = this._getClientOptions(options); - return this.caller.call(async () => { - try { - const res = await this.client.completions.create(request, requestOptions); - return res; - } catch (e) { - const error = wrapOpenAIClientError(e); - throw error; - } - }); - } - /** - * Calls the OpenAI API with retry logic in case of failures. - * @param request The request to send to the OpenAI API. - * @param options Optional configuration for the API call. - * @returns The response from the OpenAI API. - */ - _getClientOptions(options) { - if (!this.client) { - const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL }; - const endpoint = getEndpoint(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!params.baseURL) delete params.baseURL; - params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders); - this.client = new OpenAI(params); - } - const requestOptions = { - ...this.clientConfig, - ...options - }; - return requestOptions; - } - _llmType() { - return "openai"; - } -}; - -//#endregion - -//# sourceMappingURL=llms.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/llms.js - - - - - -//#region src/azure/llms.ts -var AzureOpenAI$1 = class extends OpenAI$2 { - azureOpenAIApiVersion; - azureOpenAIApiKey; - azureADTokenProvider; - azureOpenAIApiInstanceName; - azureOpenAIApiDeploymentName; - azureOpenAIBasePath; - azureOpenAIEndpoint; - get lc_aliases() { - return { - ...super.lc_aliases, - openAIApiKey: "openai_api_key", - openAIApiVersion: "openai_api_version", - openAIBasePath: "openai_api_base", - deploymentName: "deployment_name", - azureOpenAIEndpoint: "azure_endpoint", - azureOpenAIApiVersion: "openai_api_version", - azureOpenAIBasePath: "openai_api_base", - azureOpenAIApiDeploymentName: "deployment_name" - }; - } - get lc_secrets() { - return { - ...super.lc_secrets, - azureOpenAIApiKey: "AZURE_OPENAI_API_KEY" - }; - } - constructor(fields) { - super(fields); - this.azureOpenAIApiDeploymentName = (fields?.azureOpenAIApiCompletionsDeploymentName || fields?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable("AZURE_OPENAI_API_COMPLETIONS_DEPLOYMENT_NAME") || getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME")); - this.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? (typeof fields?.openAIApiKey === "string" ? fields?.openAIApiKey : void 0) ?? (typeof fields?.apiKey === "string" ? fields?.apiKey : void 0) ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); - this.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); - this.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); - this.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); - this.azureOpenAIEndpoint = fields?.azureOpenAIEndpoint ?? getEnvironmentVariable("AZURE_OPENAI_ENDPOINT"); - this.azureADTokenProvider = fields?.azureADTokenProvider; - if (!this.azureOpenAIApiKey && !this.apiKey && !this.azureADTokenProvider) throw new Error("Azure OpenAI API key or Token Provider not found"); - } - _getClientOptions(options) { - if (!this.client) { - const openAIEndpointConfig = { - azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, - azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, - azureOpenAIApiKey: this.azureOpenAIApiKey, - azureOpenAIBasePath: this.azureOpenAIBasePath, - azureADTokenProvider: this.azureADTokenProvider, - baseURL: this.clientConfig.baseURL - }; - const endpoint = getEndpoint(openAIEndpointConfig); - const { apiKey: existingApiKey,...clientConfigRest } = this.clientConfig; - const params = { - ...clientConfigRest, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey; - if (!params.baseURL) delete params.baseURL; - params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders, true, "2.0.0"); - this.client = new AzureOpenAI({ - apiVersion: this.azureOpenAIApiVersion, - azureADTokenProvider: this.azureADTokenProvider, - ...params - }); - } - const requestOptions = { - ...this.clientConfig, - ...options - }; - if (this.azureOpenAIApiKey) { - requestOptions.headers = { - "api-key": this.azureOpenAIApiKey, - ...requestOptions.headers - }; - requestOptions.query = { - "api-version": this.azureOpenAIApiVersion, - ...requestOptions.query - }; - } - return requestOptions; - } - toJSON() { - const json = super.toJSON(); - function isRecord(obj) { - return typeof obj === "object" && obj != null; - } - if (isRecord(json) && isRecord(json.kwargs)) { - delete json.kwargs.azure_openai_base_path; - delete json.kwargs.azure_openai_api_deployment_name; - delete json.kwargs.azure_openai_api_key; - delete json.kwargs.azure_openai_api_version; - delete json.kwargs.azure_open_ai_base_path; - } - return json; - } -}; - -//#endregion - -//# sourceMappingURL=llms.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/embeddings.js - - - - - - - -//#region src/embeddings.ts -/** -* Class for generating embeddings using the OpenAI API. -* -* To use with Azure, import the `AzureOpenAIEmbeddings` class. -* -* @example -* ```typescript -* // Embed a query using OpenAIEmbeddings to generate embeddings for a given text -* const model = new OpenAIEmbeddings(); -* const res = await model.embedQuery( -* "What would be a good company name for a company that makes colorful socks?", -* ); -* console.log({ res }); -* -* ``` -*/ -var OpenAIEmbeddings = class extends Embeddings { - model = "text-embedding-ada-002"; - /** @deprecated Use "model" instead */ - modelName; - batchSize = 512; - stripNewLines = true; - /** - * The number of dimensions the resulting output embeddings should have. - * Only supported in `text-embedding-3` and later models. - */ - dimensions; - timeout; - organization; - encodingFormat; - client; - clientConfig; - apiKey; - constructor(fields) { - const fieldsWithDefaults = { - maxConcurrency: 2, - ...fields - }; - super(fieldsWithDefaults); - const apiKey = fieldsWithDefaults?.apiKey ?? fieldsWithDefaults?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); - this.organization = fieldsWithDefaults?.configuration?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); - this.model = fieldsWithDefaults?.model ?? fieldsWithDefaults?.modelName ?? this.model; - this.modelName = this.model; - this.batchSize = fieldsWithDefaults?.batchSize ?? this.batchSize; - this.stripNewLines = fieldsWithDefaults?.stripNewLines ?? this.stripNewLines; - this.timeout = fieldsWithDefaults?.timeout; - this.dimensions = fieldsWithDefaults?.dimensions; - this.encodingFormat = fieldsWithDefaults?.encodingFormat; - this.clientConfig = { - apiKey, - organization: this.organization, - dangerouslyAllowBrowser: true, - ...fields?.configuration - }; - } - /** - * Method to generate embeddings for an array of documents. Splits the - * documents into batches and makes requests to the OpenAI API to generate - * embeddings. - * @param texts Array of documents to generate embeddings for. - * @returns Promise that resolves to a 2D array of embeddings for each document. - */ - async embedDocuments(texts) { - const batches = chunkArray(this.stripNewLines ? texts.map((t) => t.replace(/\n/g, " ")) : texts, this.batchSize); - const batchRequests = batches.map((batch) => { - const params = { - model: this.model, - input: batch - }; - if (this.dimensions) params.dimensions = this.dimensions; - if (this.encodingFormat) params.encoding_format = this.encodingFormat; - return this.embeddingWithRetry(params); - }); - const batchResponses = await Promise.all(batchRequests); - const embeddings = []; - for (let i = 0; i < batchResponses.length; i += 1) { - const batch = batches[i]; - const { data: batchResponse } = batchResponses[i]; - for (let j = 0; j < batch.length; j += 1) embeddings.push(batchResponse[j].embedding); - } - return embeddings; - } - /** - * Method to generate an embedding for a single document. Calls the - * embeddingWithRetry method with the document as the input. - * @param text Document to generate an embedding for. - * @returns Promise that resolves to an embedding for the document. - */ - async embedQuery(text) { - const params = { - model: this.model, - input: this.stripNewLines ? text.replace(/\n/g, " ") : text - }; - if (this.dimensions) params.dimensions = this.dimensions; - if (this.encodingFormat) params.encoding_format = this.encodingFormat; - const { data } = await this.embeddingWithRetry(params); - return data[0].embedding; - } - /** - * Private method to make a request to the OpenAI API to generate - * embeddings. Handles the retry logic and returns the response from the - * API. - * @param request Request to send to the OpenAI API. - * @returns Promise that resolves to the response from the API. - */ - async embeddingWithRetry(request) { - if (!this.client) { - const openAIEndpointConfig = { baseURL: this.clientConfig.baseURL }; - const endpoint = getEndpoint(openAIEndpointConfig); - const params = { - ...this.clientConfig, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!params.baseURL) delete params.baseURL; - params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders); - this.client = new OpenAI(params); - } - const requestOptions = {}; - return this.caller.call(async () => { - try { - const res = await this.client.embeddings.create(request, requestOptions); - return res; - } catch (e) { - const error = wrapOpenAIClientError(e); - throw error; - } - }); - } -}; - -//#endregion - -//# sourceMappingURL=embeddings.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/azure/embeddings.js - - - - - - -//#region src/azure/embeddings.ts -var AzureOpenAIEmbeddings = class extends OpenAIEmbeddings { - azureOpenAIApiVersion; - azureOpenAIApiKey; - azureADTokenProvider; - azureOpenAIApiInstanceName; - azureOpenAIApiDeploymentName; - azureOpenAIBasePath; - constructor(fields) { - super(fields); - this.batchSize = fields?.batchSize ?? 1; - this.azureOpenAIApiKey = fields?.azureOpenAIApiKey ?? (typeof fields?.apiKey === "string" ? fields?.apiKey : void 0) ?? getEnvironmentVariable("AZURE_OPENAI_API_KEY"); - this.azureOpenAIApiVersion = fields?.azureOpenAIApiVersion ?? fields?.openAIApiVersion ?? getEnvironmentVariable("AZURE_OPENAI_API_VERSION"); - this.azureOpenAIBasePath = fields?.azureOpenAIBasePath ?? getEnvironmentVariable("AZURE_OPENAI_BASE_PATH"); - this.azureOpenAIApiInstanceName = fields?.azureOpenAIApiInstanceName ?? getEnvironmentVariable("AZURE_OPENAI_API_INSTANCE_NAME"); - this.azureOpenAIApiDeploymentName = (fields?.azureOpenAIApiEmbeddingsDeploymentName || fields?.azureOpenAIApiDeploymentName) ?? (getEnvironmentVariable("AZURE_OPENAI_API_EMBEDDINGS_DEPLOYMENT_NAME") || getEnvironmentVariable("AZURE_OPENAI_API_DEPLOYMENT_NAME")); - this.azureADTokenProvider = fields?.azureADTokenProvider; - } - async embeddingWithRetry(request) { - if (!this.client) { - const openAIEndpointConfig = { - azureOpenAIApiDeploymentName: this.azureOpenAIApiDeploymentName, - azureOpenAIApiInstanceName: this.azureOpenAIApiInstanceName, - azureOpenAIApiKey: this.azureOpenAIApiKey, - azureOpenAIBasePath: this.azureOpenAIBasePath, - azureADTokenProvider: this.azureADTokenProvider, - baseURL: this.clientConfig.baseURL - }; - const endpoint = getEndpoint(openAIEndpointConfig); - const { apiKey: existingApiKey,...clientConfigRest } = this.clientConfig; - const params = { - ...clientConfigRest, - baseURL: endpoint, - timeout: this.timeout, - maxRetries: 0 - }; - if (!this.azureADTokenProvider) params.apiKey = openAIEndpointConfig.azureOpenAIApiKey; - if (!params.baseURL) delete params.baseURL; - params.defaultHeaders = getHeadersWithUserAgent(params.defaultHeaders, true, "2.0.0"); - this.client = new AzureOpenAI({ - apiVersion: this.azureOpenAIApiVersion, - azureADTokenProvider: this.azureADTokenProvider, - deployment: this.azureOpenAIApiDeploymentName, - ...params - }); - } - const requestOptions = {}; - if (this.azureOpenAIApiKey) { - requestOptions.headers = { - "api-key": this.azureOpenAIApiKey, - ...requestOptions.headers - }; - requestOptions.query = { - "api-version": this.azureOpenAIApiVersion, - ...requestOptions.query - }; - } - return this.caller.call(async () => { - try { - const res = await this.client.embeddings.create(request, requestOptions); - return res; - } catch (e) { - const error = wrapOpenAIClientError(e); - throw error; - } - }); - } -}; - -//#endregion - -//# sourceMappingURL=embeddings.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/dalle.js - - - - -//#region src/tools/dalle.ts -/** -* A tool for generating images with Open AIs Dall-E 2 or 3 API. -*/ -var DallEAPIWrapper = class extends Tool { - static lc_name() { - return "DallEAPIWrapper"; - } - name = "dalle_api_wrapper"; - description = "A wrapper around OpenAI DALL-E API. Useful for when you need to generate images from a text description. Input should be an image description."; - client; - static toolName = "dalle_api_wrapper"; - model = "dall-e-3"; - style = "vivid"; - quality = "standard"; - n = 1; - size = "1024x1024"; - dallEResponseFormat = "url"; - user; - constructor(fields) { - if (fields?.responseFormat !== void 0 && ["url", "b64_json"].includes(fields.responseFormat)) { - fields.dallEResponseFormat = fields.responseFormat; - fields.responseFormat = "content"; - } - super(fields); - const openAIApiKey = fields?.apiKey ?? fields?.openAIApiKey ?? getEnvironmentVariable("OPENAI_API_KEY"); - const organization = fields?.organization ?? getEnvironmentVariable("OPENAI_ORGANIZATION"); - const clientConfig = { - apiKey: openAIApiKey, - organization, - dangerouslyAllowBrowser: true, - baseURL: fields?.baseUrl - }; - this.client = new OpenAI(clientConfig); - this.model = fields?.model ?? fields?.modelName ?? this.model; - this.style = fields?.style ?? this.style; - this.quality = fields?.quality ?? this.quality; - this.n = fields?.n ?? this.n; - this.size = fields?.size ?? this.size; - this.dallEResponseFormat = fields?.dallEResponseFormat ?? this.dallEResponseFormat; - this.user = fields?.user; - } - /** - * Processes the API response if multiple images are generated. - * Returns a list of MessageContentImageUrl objects. If the response - * format is `url`, then the `image_url` field will contain the URL. - * If it is `b64_json`, then the `image_url` field will contain an object - * with a `url` field with the base64 encoded image. - * - * @param {OpenAIClient.Images.ImagesResponse[]} response The API response - * @returns {MessageContentImageUrl[]} - */ - processMultipleGeneratedUrls(response) { - if (this.dallEResponseFormat === "url") return response.flatMap((res) => { - const imageUrlContent = res.data?.flatMap((item) => { - if (!item.url) return []; - return { - type: "image_url", - image_url: item.url - }; - }).filter((item) => item !== void 0 && item.type === "image_url" && typeof item.image_url === "string" && item.image_url !== void 0) ?? []; - return imageUrlContent; - }); - else return response.flatMap((res) => { - const b64Content = res.data?.flatMap((item) => { - if (!item.b64_json) return []; - return { - type: "image_url", - image_url: { url: item.b64_json } - }; - }).filter((item) => item !== void 0 && item.type === "image_url" && typeof item.image_url === "object" && "url" in item.image_url && typeof item.image_url.url === "string" && item.image_url.url !== void 0) ?? []; - return b64Content; - }); - } - /** @ignore */ - async _call(input) { - const generateImageFields = { - model: this.model, - prompt: input, - n: 1, - size: this.size, - response_format: this.dallEResponseFormat, - style: this.style, - quality: this.quality, - user: this.user - }; - if (this.n > 1) { - const results = await Promise.all(Array.from({ length: this.n }).map(() => this.client.images.generate(generateImageFields))); - return this.processMultipleGeneratedUrls(results); - } - const response = await this.client.images.generate(generateImageFields); - let data = ""; - if (this.dallEResponseFormat === "url") [data] = response.data?.map((item) => item.url).filter((url) => url !== "undefined") ?? []; - else [data] = response.data?.map((item) => item.b64_json).filter((b64_json) => b64_json !== "undefined") ?? []; - return data; - } -}; - -//#endregion - -//# sourceMappingURL=dalle.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/webSearch.js -//#region src/tools/webSearch.ts -/** -* Creates a web search tool that allows OpenAI models to search the web -* for up-to-date information before generating a response. -* -* Web search supports three main types: -* 1. **Non-reasoning web search**: Quick lookups where the model passes queries -* directly to the search tool. -* 2. **Agentic search with reasoning models**: The model actively manages the -* search process, analyzing results and deciding whether to keep searching. -* 3. **Deep research**: Extended investigations using models like `o3-deep-research` -* or `gpt-5` with high reasoning effort. -* -* @see {@link https://platform.openai.com/docs/guides/tools-web-search | OpenAI Web Search Documentation} -* @param options - Configuration options for the web search tool -* @returns A web search tool definition to be passed to the OpenAI Responses API -* -* @example -* ```typescript -* import { ChatOpenAI, tools } from "@langchain/openai"; -* -* const model = new ChatOpenAI({ -* model: "gpt-4o", -* }); -* -* // Basic usage -* const response = await model.invoke("What was a positive news story from today?", { -* tools: [tools.webSearch()], -* }); -* -* // With domain filtering -* const filteredResponse = await model.invoke("Latest AI research news", { -* tools: [tools.webSearch({ -* filters: { -* allowedDomains: ["arxiv.org", "nature.com", "science.org"], -* }, -* })], -* }); -* -* // With user location for geographic relevance -* const localResponse = await model.invoke("What are the best restaurants near me?", { -* tools: [tools.webSearch({ -* userLocation: { -* type: "approximate", -* country: "US", -* city: "San Francisco", -* region: "California", -* timezone: "America/Los_Angeles", -* }, -* })], -* }); -* -* // Cache-only mode (no live internet access) -* const cachedResponse = await model.invoke("Find information about OpenAI", { -* tools: [tools.webSearch({ -* externalWebAccess: false, -* })], -* }); -* ``` -*/ -function webSearch(options) { - return { - type: "web_search", - filters: options?.filters?.allowedDomains ? { allowed_domains: options.filters.allowedDomains } : void 0, - user_location: options?.userLocation, - search_context_size: options?.search_context_size - }; -} - -//#endregion - -//# sourceMappingURL=webSearch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/mcp.js -//#region src/tools/mcp.ts -/** -* Converts a McpToolFilter to the API format. -*/ -function convertToolFilter(filter) { - return { - tool_names: filter.toolNames, - read_only: filter.readOnly - }; -} -/** -* Converts allowed_tools option to API format. -*/ -function convertAllowedTools(allowedTools) { - if (!allowedTools) return void 0; - if (Array.isArray(allowedTools)) return allowedTools; - return convertToolFilter(allowedTools); -} -/** -* Converts require_approval option to API format. -*/ -function convertRequireApproval(requireApproval) { - if (!requireApproval) return void 0; - if (typeof requireApproval === "string") return requireApproval; - return { - always: requireApproval.always ? convertToolFilter(requireApproval.always) : void 0, - never: requireApproval.never ? convertToolFilter(requireApproval.never) : void 0 - }; -} -function mcp(options) { - const baseConfig = { - type: "mcp", - server_label: options.serverLabel, - allowed_tools: convertAllowedTools(options.allowedTools), - authorization: options.authorization, - headers: options.headers, - require_approval: convertRequireApproval(options.requireApproval), - server_description: options.serverDescription - }; - if ("serverUrl" in options) return { - ...baseConfig, - server_url: options.serverUrl - }; - return { - ...baseConfig, - connector_id: options.connectorId - }; -} - -//#endregion - -//# sourceMappingURL=mcp.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/codeInterpreter.js -//#region src/tools/codeInterpreter.ts -/** -* Converts container options to the API format. -*/ -function convertContainer(container) { - if (typeof container === "string") return container; - return { - type: "auto", - file_ids: container?.fileIds, - memory_limit: container?.memoryLimit - }; -} -/** -* Creates a Code Interpreter tool that allows models to write and run Python code -* in a sandboxed environment to solve complex problems. -* -* Use Code Interpreter for: -* - **Data analysis**: Processing files with diverse data and formatting -* - **File generation**: Creating files with data and images of graphs -* - **Iterative coding**: Writing and running code iteratively to solve problems -* - **Visual intelligence**: Cropping, zooming, rotating, and transforming images -* -* The tool runs in a container, which is a fully sandboxed virtual machine. -* Containers can be created automatically (auto mode) or explicitly via the -* `/v1/containers` endpoint. -* -* @see {@link https://platform.openai.com/docs/guides/tools-code-interpreter | OpenAI Code Interpreter Documentation} -* -* @param options - Configuration options for the Code Interpreter tool -* @returns A Code Interpreter tool definition to be passed to the OpenAI Responses API -* -* @example -* ```typescript -* import { ChatOpenAI, tools } from "@langchain/openai"; -* -* const model = new ChatOpenAI({ model: "gpt-4.1" }); -* -* // Basic usage with auto container (default 1GB memory) -* const response = await model.invoke( -* "Solve the equation 3x + 11 = 14", -* { tools: [tools.codeInterpreter()] } -* ); -* -* // With increased memory limit for larger computations -* const response = await model.invoke( -* "Analyze this large dataset and create visualizations", -* { -* tools: [tools.codeInterpreter({ -* container: { memoryLimit: "4g" } -* })] -* } -* ); -* -* // With specific files available to the code -* const response = await model.invoke( -* "Process the uploaded CSV file", -* { -* tools: [tools.codeInterpreter({ -* container: { -* memoryLimit: "4g", -* fileIds: ["file-abc123", "file-def456"] -* } -* })] -* } -* ); -* -* // Using an explicit container ID (created via /v1/containers) -* const response = await model.invoke( -* "Continue working with the data", -* { -* tools: [tools.codeInterpreter({ -* container: "cntr_abc123" -* })] -* } -* ); -* ``` -* -* @remarks -* - Containers expire after 20 minutes of inactivity -* - While called "Code Interpreter", the model knows it as the "python tool" -* - For explicit prompting, ask for "the python tool" in your prompts -* - Files in model input are automatically uploaded to the container -* - Generated files are returned as `container_file_citation` annotations -*/ -function codeInterpreter(options) { - return { - type: "code_interpreter", - container: convertContainer(options?.container) - }; -} - -//#endregion - -//# sourceMappingURL=codeInterpreter.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/fileSearch.js -//#region src/tools/fileSearch.ts -/** -* Converts ranking options to the API format. -*/ -function convertRankingOptions(options) { - if (!options) return void 0; - return { - ranker: options.ranker, - score_threshold: options.scoreThreshold, - hybrid_search: options.hybridSearch ? { - embedding_weight: options.hybridSearch.embeddingWeight, - text_weight: options.hybridSearch.textWeight - } : void 0 - }; -} -/** -* Creates a File Search tool that allows models to search your files -* for relevant information using semantic and keyword search. -* -* File Search enables models to retrieve information from a knowledge base -* of previously uploaded files stored in vector stores. This is a hosted tool -* managed by OpenAI - you don't need to implement the search execution yourself. -* -* **Prerequisites**: Before using File Search, you must: -* 1. Upload files to the File API with `purpose: "assistants"` -* 2. Create a vector store -* 3. Add files to the vector store -* -* @see {@link https://platform.openai.com/docs/guides/tools-file-search | OpenAI File Search Documentation} -* -* @param options - Configuration options for the File Search tool -* @returns A File Search tool definition to be passed to the OpenAI Responses API -* -* @example -* ```typescript -* import { ChatOpenAI, tools } from "@langchain/openai"; -* -* const model = new ChatOpenAI({ model: "gpt-4.1" }); -* -* // Basic usage with a vector store -* const response = await model.invoke( -* "What is deep research by OpenAI?", -* { -* tools: [tools.fileSearch({ -* vectorStoreIds: ["vs_abc123"] -* })] -* } -* ); -* -* // Limit the number of results for lower latency -* const response = await model.invoke( -* "Find information about pricing", -* { -* tools: [tools.fileSearch({ -* vectorStoreIds: ["vs_abc123"], -* maxNumResults: 5 -* })] -* } -* ); -* -* // With metadata filtering -* const response = await model.invoke( -* "Find recent blog posts about AI", -* { -* tools: [tools.fileSearch({ -* vectorStoreIds: ["vs_abc123"], -* filters: { -* type: "eq", -* key: "category", -* value: "blog" -* } -* })] -* } -* ); -* -* // With compound filters (AND/OR) -* const response = await model.invoke( -* "Find technical docs from 2024", -* { -* tools: [tools.fileSearch({ -* vectorStoreIds: ["vs_abc123"], -* filters: { -* type: "and", -* filters: [ -* { type: "eq", key: "category", value: "technical" }, -* { type: "gte", key: "year", value: 2024 } -* ] -* } -* })] -* } -* ); -* -* // With ranking options for more relevant results -* const response = await model.invoke( -* "Find the most relevant information", -* { -* tools: [tools.fileSearch({ -* vectorStoreIds: ["vs_abc123"], -* rankingOptions: { -* scoreThreshold: 0.8, -* ranker: "auto" -* } -* })] -* } -* ); -* -* // Search multiple vector stores -* const response = await model.invoke( -* "Search across all knowledge bases", -* { -* tools: [tools.fileSearch({ -* vectorStoreIds: ["vs_abc123", "vs_def456"] -* })] -* } -* ); -* ``` -* -* @remarks -* - Vector stores must be created and populated before using this tool -* - The tool returns file citations in the response annotations -* - Use `include: ["file_search_call.results"]` in the API call to get search results -* - Supported file types include PDF, DOCX, TXT, MD, and many code file formats -*/ -function fileSearch(options) { - return { - type: "file_search", - vector_store_ids: options.vectorStoreIds, - max_num_results: options.maxNumResults, - filters: options.filters, - ranking_options: convertRankingOptions(options.rankingOptions) - }; -} - -//#endregion - -//# sourceMappingURL=fileSearch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/imageGeneration.js -//#region src/tools/imageGeneration.ts -/** -* Converts input mask options to the API format. -*/ -function convertInputImageMask(mask) { - if (!mask) return void 0; - return { - image_url: mask.imageUrl, - file_id: mask.fileId - }; -} -/** -* Creates an Image Generation tool that allows models to generate or edit images -* using text prompts and optional image inputs. -* -* The image generation tool leverages the GPT Image model and automatically -* optimizes text inputs for improved performance. When included in a request, -* the model can decide when and how to generate images as part of the conversation. -* -* **Key Features**: -* - Generate images from text descriptions -* - Edit existing images with text instructions -* - Multi-turn image editing by referencing previous responses -* - Configurable output options (size, quality, format) -* - Streaming support for partial image generation -* -* **Prompting Tips**: -* - Use terms like "draw" or "edit" in your prompt for best results -* - For combining images, say "edit the first image by adding this element" instead of "combine" -* -* @see {@link https://platform.openai.com/docs/guides/tools-image-generation | OpenAI Image Generation Documentation} -* -* @param options - Configuration options for the Image Generation tool -* @returns An Image Generation tool definition to be passed to the OpenAI Responses API -* -* @example -* ```typescript -* import { ChatOpenAI, tools } from "@langchain/openai"; -* -* const model = new ChatOpenAI({ model: "gpt-4o" }); -* -* // Basic usage - generate an image -* const response = await model.invoke( -* "Generate an image of a gray tabby cat hugging an otter with an orange scarf", -* { tools: [tools.imageGeneration()] } -* ); -* -* // Access the generated image -* const imageData = response.additional_kwargs.tool_outputs?.find( -* (output) => output.type === "image_generation_call" -* ); -* if (imageData?.result) { -* // imageData.result contains the base64-encoded image -* const fs = await import("fs"); -* fs.writeFileSync("output.png", Buffer.from(imageData.result, "base64")); -* } -* -* // With custom options -* const response = await model.invoke( -* "Draw a beautiful sunset over mountains", -* { -* tools: [tools.imageGeneration({ -* size: "1536x1024", // Landscape format -* quality: "high", // Higher quality output -* outputFormat: "jpeg", // JPEG format -* outputCompression: 90, // 90% compression -* })] -* } -* ); -* -* // With transparent background -* const response = await model.invoke( -* "Create a logo with a transparent background", -* { -* tools: [tools.imageGeneration({ -* background: "transparent", -* outputFormat: "png", -* })] -* } -* ); -* -* // Force the model to use image generation -* const response = await model.invoke( -* "A serene lake at dawn", -* { -* tools: [tools.imageGeneration()], -* tool_choice: { type: "image_generation" }, -* } -* ); -* -* // Enable streaming with partial images -* const response = await model.invoke( -* "Draw a detailed fantasy castle", -* { -* tools: [tools.imageGeneration({ -* partialImages: 2, // Get 2 partial images during generation -* })] -* } -* ); -* ``` -* -* @remarks -* - Supported models: gpt-4o, gpt-4o-mini, gpt-4.1, gpt-4.1-mini, gpt-4.1-nano, o3 -* - The image generation process always uses `gpt-image-1` model internally -* - The model will automatically revise prompts for improved performance -* - Access the revised prompt via `revised_prompt` field in the output -* - Multi-turn editing is supported by passing previous response messages -*/ -function imageGeneration(options) { - return { - type: "image_generation", - background: options?.background, - input_fidelity: options?.inputFidelity, - input_image_mask: convertInputImageMask(options?.inputImageMask), - model: options?.model, - moderation: options?.moderation, - output_compression: options?.outputCompression, - output_format: options?.outputFormat, - partial_images: options?.partialImages, - quality: options?.quality, - size: options?.size - }; -} - -//#endregion - -//# sourceMappingURL=imageGeneration.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/computerUse.js - - - - -//#region src/tools/computerUse.ts -const ComputerUseScreenshotActionSchema = object({ type: literal("screenshot") }); -const ComputerUseClickActionSchema = object({ - type: literal("click"), - x: schemas_number(), - y: schemas_number(), - button: schemas_enum([ - "left", - "right", - "wheel", - "back", - "forward" - ]).default("left") -}); -const ComputerUseDoubleClickActionSchema = object({ - type: literal("double_click"), - x: schemas_number(), - y: schemas_number(), - button: schemas_enum([ - "left", - "right", - "wheel", - "back", - "forward" - ]).default("left") -}); -const ComputerUseDragActionSchema = object({ - type: literal("drag"), - path: array(object({ - x: schemas_number(), - y: schemas_number() - })) -}); -const ComputerUseKeypressActionSchema = object({ - type: literal("keypress"), - keys: array(schemas_string()) -}); -const ComputerUseMoveActionSchema = object({ - type: literal("move"), - x: schemas_number(), - y: schemas_number() -}); -const ComputerUseScrollActionSchema = object({ - type: literal("scroll"), - x: schemas_number(), - y: schemas_number(), - scroll_x: schemas_number(), - scroll_y: schemas_number() -}); -const ComputerUseTypeActionSchema = object({ - type: literal("type"), - text: schemas_string() -}); -const ComputerUseWaitActionSchema = object({ - type: literal("wait"), - duration: schemas_number().optional() -}); -const ComputerUseActionUnionSchema = discriminatedUnion("type", [ - ComputerUseScreenshotActionSchema, - ComputerUseClickActionSchema, - ComputerUseDoubleClickActionSchema, - ComputerUseDragActionSchema, - ComputerUseKeypressActionSchema, - ComputerUseMoveActionSchema, - ComputerUseScrollActionSchema, - ComputerUseTypeActionSchema, - ComputerUseWaitActionSchema -]); -const ComputerUseActionSchema = object({ action: ComputerUseActionUnionSchema }); -const computerUse_TOOL_NAME = "computer_use"; -/** -* Creates a Computer Use tool that allows models to control computer interfaces -* and perform tasks by simulating mouse clicks, keyboard input, scrolling, and more. -* -* **Computer Use** is a practical application of OpenAI's Computer-Using Agent (CUA) -* model (`computer-use-preview`), which combines vision capabilities with advanced -* reasoning to simulate controlling computer interfaces. -* -* **How it works**: -* The tool operates in a continuous loop: -* 1. Model sends computer actions (click, type, scroll, etc.) -* 2. Your code executes these actions in a controlled environment -* 3. You capture a screenshot of the result -* 4. Send the screenshot back to the model -* 5. Repeat until the task is complete -* -* **Important**: Computer use is in beta and requires careful consideration: -* - Use in sandboxed environments only -* - Do not use for high-stakes or authenticated tasks -* - Always implement human-in-the-loop for important decisions -* - Handle safety checks appropriately -* -* @see {@link https://platform.openai.com/docs/guides/tools-computer-use | OpenAI Computer Use Documentation} -* -* @param options - Configuration options for the Computer Use tool -* @returns A Computer Use tool that can be passed to `bindTools` -* -* @example -* ```typescript -* import { ChatOpenAI, tools } from "@langchain/openai"; -* -* const model = new ChatOpenAI({ model: "computer-use-preview" }); -* -* // With execute callback for automatic action handling -* const computer = tools.computerUse({ -* displayWidth: 1024, -* displayHeight: 768, -* environment: "browser", -* execute: async (action) => { -* if (action.type === "screenshot") { -* return captureScreenshot(); -* } -* if (action.type === "click") { -* await page.mouse.click(action.x, action.y, { button: action.button }); -* return captureScreenshot(); -* } -* if (action.type === "type") { -* await page.keyboard.type(action.text); -* return captureScreenshot(); -* } -* // Handle other actions... -* return captureScreenshot(); -* }, -* }); -* -* const llmWithComputer = model.bindTools([computer]); -* const response = await llmWithComputer.invoke( -* "Check the latest news on bing.com" -* ); -* ``` -* -* @example -* ```typescript -* // Without execute callback (manual action handling) -* const computer = tools.computerUse({ -* displayWidth: 1024, -* displayHeight: 768, -* environment: "browser", -* }); -* -* const response = await model.invoke("Check the news", { -* tools: [computer], -* }); -* -* // Access the computer call from the response -* const computerCall = response.additional_kwargs.tool_outputs?.find( -* (output) => output.type === "computer_call" -* ); -* if (computerCall) { -* console.log("Action to execute:", computerCall.action); -* // Execute the action manually, then send back a screenshot -* } -* ``` -* -* @example -* ```typescript -* // For macOS desktop automation with Docker -* const computer = tools.computerUse({ -* displayWidth: 1920, -* displayHeight: 1080, -* environment: "mac", -* execute: async (action) => { -* if (action.type === "click") { -* await dockerExec( -* `DISPLAY=:99 xdotool mousemove ${action.x} ${action.y} click 1`, -* containerName -* ); -* } -* // Capture screenshot from container -* return await getDockerScreenshot(containerName); -* }, -* }); -* ``` -* -* @remarks -* - Only available through the Responses API (not Chat Completions) -* - Requires `computer-use-preview` model -* - Actions include: click, double_click, drag, keypress, move, screenshot, scroll, type, wait -* - Safety checks may be returned that require acknowledgment before proceeding -* - Use `truncation: "auto"` parameter when making requests -* - Recommended to use with `reasoning.summary` for debugging -*/ -function computerUse(options) { - const computerTool = tool(async (input, runtime) => { - /** - * get computer_use call id from runtime - */ - const aiMessage = runtime.state?.messages.at(-1); - const computerToolCall = aiMessage?.tool_calls?.find((tc) => tc.name === "computer_use"); - const computerToolCallId = computerToolCall?.id; - if (!computerToolCallId) throw new Error("Computer use call id not found"); - const result = await options.execute(input.action, runtime); - /** - * make sure {@link ToolMessage} is returned with the correct additional kwargs - */ - if (typeof result === "string") return new ToolMessage({ - content: result, - tool_call_id: computerToolCallId, - additional_kwargs: { type: "computer_call_output" } - }); - /** - * make sure {@link ToolMessage} is returned with the correct additional kwargs - */ - return new ToolMessage({ - ...result, - tool_call_id: computerToolCallId, - additional_kwargs: { - type: "computer_call_output", - ...result.additional_kwargs - } - }); - }, { - name: computerUse_TOOL_NAME, - description: "Control a computer interface by executing mouse clicks, keyboard input, scrolling, and other actions.", - schema: ComputerUseActionSchema - }); - computerTool.extras = { - ...computerTool.extras ?? {}, - providerToolDefinition: { - type: "computer_use_preview", - display_width: options.displayWidth, - display_height: options.displayHeight, - environment: options.environment - } - }; - /** - * return as typed {@link DynamicStructuredTool} so we don't get any type - * errors like "can't export tool without reference" - */ - return computerTool; -} - -//#endregion - -//# sourceMappingURL=computerUse.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/localShell.js - - - -//#region src/tools/localShell.ts -const LocalShellExecActionSchema = object({ - type: literal("exec"), - command: array(schemas_string()), - env: record(schemas_string(), schemas_string()).optional(), - working_directory: schemas_string().optional(), - timeout_ms: schemas_number().optional(), - user: schemas_string().optional() -}); -const LocalShellActionSchema = discriminatedUnion("type", [LocalShellExecActionSchema]); -const localShell_TOOL_NAME = "local_shell"; -/** -* Creates a Local Shell tool that allows models to run shell commands locally -* on a machine you provide. Commands are executed inside your own runtime— -* the API only returns the instructions, but does not execute them on OpenAI infrastructure. -* -* **Important**: The local shell tool is designed to work with -* [Codex CLI](https://github.com/openai/codex) and the `codex-mini-latest` model. -* -* **How it works**: -* The tool operates in a continuous loop: -* 1. Model sends shell commands (`local_shell_call` with `exec` action) -* 2. Your code executes the command locally -* 3. You return the output back to the model -* 4. Repeat until the task is complete -* -* **Security Warning**: Running arbitrary shell commands can be dangerous. -* Always sandbox execution or add strict allow/deny-lists before forwarding -* a command to the system shell. -* -* @see {@link https://platform.openai.com/docs/guides/tools-local-shell | OpenAI Local Shell Documentation} -* -* @param options - Optional configuration for the Local Shell tool -* @returns A Local Shell tool that can be passed to `bindTools` -* -* @example -* ```typescript -* import { ChatOpenAI, tools } from "@langchain/openai"; -* import { exec } from "child_process"; -* import { promisify } from "util"; -* -* const execAsync = promisify(exec); -* const model = new ChatOpenAI({ model: "codex-mini-latest" }); -* -* // With execute callback for automatic command handling -* const shell = tools.localShell({ -* execute: async (action) => { -* const { command, env, working_directory, timeout_ms } = action; -* const result = await execAsync(command.join(' '), { -* cwd: working_directory ?? process.cwd(), -* env: { ...process.env, ...env }, -* timeout: timeout_ms ?? undefined, -* }); -* return result.stdout + result.stderr; -* }, -* }); -* -* const llmWithShell = model.bindTools([shell]); -* const response = await llmWithShell.invoke( -* "List files in the current directory" -* ); -* ``` -* -* @example -* ```typescript -* // Without execute callback (manual handling) -* const shell = tools.localShell(); -* -* const response = await model.invoke("List files", { -* tools: [shell], -* }); -* -* // Access the shell call from the response -* const shellCall = response.additional_kwargs.tool_outputs?.find( -* (output) => output.type === "local_shell_call" -* ); -* if (shellCall) { -* console.log("Command to execute:", shellCall.action.command); -* // Execute the command manually, then send back the output -* } -* ``` -* -* @example -* ```typescript -* // Full shell loop example -* async function shellLoop(model, task) { -* let response = await model.invoke(task, { -* tools: [tools.localShell()], -* }); -* -* while (true) { -* const shellCall = response.additional_kwargs.tool_outputs?.find( -* (output) => output.type === "local_shell_call" -* ); -* -* if (!shellCall) break; -* -* // Execute command (with proper sandboxing!) -* const output = await executeCommand(shellCall.action); -* -* // Send output back to model -* response = await model.invoke([ -* response, -* { -* type: "local_shell_call_output", -* id: shellCall.call_id, -* output: output, -* }, -* ], { -* tools: [tools.localShell()], -* }); -* } -* -* return response; -* } -* ``` -* -* @remarks -* - Only available through the Responses API (not Chat Completions) -* - Designed for use with `codex-mini-latest` model -* - Commands are provided as argv tokens in `action.command` -* - Action includes: `command`, `env`, `working_directory`, `timeout_ms`, `user` -* - Always sandbox or validate commands before execution -* - The `timeout_ms` from the model is only a hint—enforce your own limits -*/ -function localShell(options) { - const shellTool = tool(options.execute, { - name: localShell_TOOL_NAME, - description: "Execute shell commands locally on the machine. Commands are provided as argv tokens.", - schema: LocalShellActionSchema - }); - shellTool.extras = { - ...shellTool.extras ?? {}, - providerToolDefinition: { type: "local_shell" } - }; - return shellTool; -} - -//#endregion - -//# sourceMappingURL=localShell.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/shell.js - - - -//#region src/tools/shell.ts -const ShellActionSchema = object({ - commands: array(schemas_string()).describe("Array of shell commands to execute"), - timeout_ms: schemas_number().optional().describe("Optional timeout in milliseconds for the commands"), - max_output_length: schemas_number().optional().describe("Optional maximum number of characters to return from each command") -}); -const shell_TOOL_NAME = "shell"; -/** -* Creates a Shell tool that allows models to run shell commands through your integration. -* -* The shell tool allows the model to interact with your local computer through a controlled -* command-line interface. The model proposes shell commands; your integration executes them -* and returns the outputs. This creates a simple plan-execute loop that lets models inspect -* the system, run utilities, and gather data until they can finish the task. -* -* **Important**: The shell tool is available through the Responses API for use with `GPT-5.1`. -* It is not available on other models, or via the Chat Completions API. -* -* **When to use**: -* - **Automating filesystem or process diagnostics** – For example, "find the largest PDF -* under ~/Documents" or "show running gunicorn processes." -* - **Extending the model's capabilities** – Using built-in UNIX utilities, python runtime -* and other CLIs in your environment. -* - **Running multi-step build and test flows** – Chaining commands like `pip install` and `pytest`. -* - **Complex agentic coding workflows** – Using other tools like `apply_patch` to complete -* workflows that involve complex file operations. -* -* **How it works**: -* The tool operates in a continuous loop: -* 1. Model sends shell commands (`shell_call` with `commands` array) -* 2. Your code executes the commands (can be concurrent) -* 3. You return stdout, stderr, and outcome for each command -* 4. Repeat until the task is complete -* -* **Security Warning**: Running arbitrary shell commands can be dangerous. -* Always sandbox execution or add strict allow/deny-lists before forwarding -* a command to the system shell. -* -* @see {@link https://platform.openai.com/docs/guides/tools-shell | OpenAI Shell Documentation} -* @see {@link https://github.com/openai/codex | Codex CLI} for reference implementation. -* -* @param options - Configuration for the Shell tool -* @returns A Shell tool that can be passed to `bindTools` -* -* @example -* ```typescript -* import { ChatOpenAI, tools } from "@langchain/openai"; -* import { exec } from "child_process/promises"; -* -* const model = new ChatOpenAI({ model: "gpt-5.1" }); -* -* // With execute callback for automatic command handling -* const shellTool = tools.shell({ -* execute: async (action) => { -* const outputs = await Promise.all( -* action.commands.map(async (cmd) => { -* try { -* const { stdout, stderr } = await exec(cmd, { -* timeout: action.timeout_ms ?? undefined, -* }); -* return { -* stdout, -* stderr, -* outcome: { type: "exit" as const, exit_code: 0 }, -* }; -* } catch (error) { -* const timedOut = error.killed && error.signal === "SIGTERM"; -* return { -* stdout: error.stdout ?? "", -* stderr: error.stderr ?? String(error), -* outcome: timedOut -* ? { type: "timeout" as const } -* : { type: "exit" as const, exit_code: error.code ?? 1 }, -* }; -* } -* }) -* ); -* return { -* output: outputs, -* maxOutputLength: action.max_output_length, -* }; -* }, -* }); -* -* const llmWithShell = model.bindTools([shellTool]); -* const response = await llmWithShell.invoke( -* "Find the largest PDF file in ~/Documents" -* ); -* ``` -* -* @example -* ```typescript -* // Full shell loop example -* async function shellLoop(model, task) { -* let response = await model.invoke(task, { -* tools: [tools.shell({ execute: myExecutor })], -* }); -* -* while (true) { -* const shellCall = response.additional_kwargs.tool_outputs?.find( -* (output) => output.type === "shell_call" -* ); -* -* if (!shellCall) break; -* -* // Execute commands (with proper sandboxing!) -* const result = await executeCommands(shellCall.action); -* -* // Send output back to model -* response = await model.invoke([ -* response, -* { -* type: "shell_call_output", -* call_id: shellCall.call_id, -* output: result.output, -* max_output_length: result.maxOutputLength, -* }, -* ], { -* tools: [tools.shell({ execute: myExecutor })], -* }); -* } -* -* return response; -* } -* ``` -* -* @remarks -* - Only available through the Responses API (not Chat Completions) -* - Designed for use with `gpt-5.1` model -* - Commands are provided as an array of strings that can be executed concurrently -* - Action includes: `commands`, `timeout_ms`, `max_output_length` -* - Always sandbox or validate commands before execution -* - The `timeout_ms` from the model is only a hint—enforce your own limits -* - If `max_output_length` exists in the action, always pass it back in the output -* - Many CLI tools return non-zero exit codes for warnings; still capture stdout/stderr -*/ -function shell(options) { - const executeWrapper = async (action) => { - const result = await options.execute(action); - return JSON.stringify({ - output: result.output, - max_output_length: result.maxOutputLength - }); - }; - const shellTool = tool(executeWrapper, { - name: shell_TOOL_NAME, - description: "Execute shell commands in a managed environment. Commands can be run concurrently.", - schema: ShellActionSchema - }); - shellTool.extras = { - ...shellTool.extras ?? {}, - providerToolDefinition: { type: "shell" } - }; - return shellTool; -} - -//#endregion - -//# sourceMappingURL=shell.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/applyPatch.js - - - -//#region src/tools/applyPatch.ts -const ApplyPatchCreateFileOperationSchema = object({ - type: literal("create_file"), - path: schemas_string(), - diff: schemas_string() -}); -const ApplyPatchUpdateFileOperationSchema = object({ - type: literal("update_file"), - path: schemas_string(), - diff: schemas_string() -}); -const ApplyPatchDeleteFileOperationSchema = object({ - type: literal("delete_file"), - path: schemas_string() -}); -const ApplyPatchOperationSchema = discriminatedUnion("type", [ - ApplyPatchCreateFileOperationSchema, - ApplyPatchUpdateFileOperationSchema, - ApplyPatchDeleteFileOperationSchema -]); -const applyPatch_TOOL_NAME = "apply_patch"; -/** -* Creates an Apply Patch tool that allows models to propose structured diffs -* that your integration applies. This enables iterative, multi-step code -* editing workflows. -* -* **Apply Patch** lets GPT-5.1 create, update, and delete files in your codebase -* using structured diffs. Instead of just suggesting edits, the model emits -* patch operations that your application applies and then reports back on. -* -* **When to use**: -* - **Multi-file refactors** – Rename symbols, extract helpers, or reorganize modules -* - **Bug fixes** – Have the model both diagnose issues and emit precise patches -* - **Tests & docs generation** – Create new test files, fixtures, and documentation -* - **Migrations & mechanical edits** – Apply repetitive, structured updates -* -* **How it works**: -* The tool operates in a continuous loop: -* 1. Model sends patch operations (`apply_patch_call` with operation type) -* 2. Your code applies the patch to your working directory or repo -* 3. You return success/failure status and optional output -* 4. Repeat until the task is complete -* -* **Security Warning**: Applying patches can modify files in your codebase. -* Always validate paths, implement backups, and consider sandboxing. -* -* @see {@link https://platform.openai.com/docs/guides/tools-apply-patch | OpenAI Apply Patch Documentation} -* -* @param options - Configuration options for the Apply Patch tool -* @returns An Apply Patch tool that can be passed to `bindTools` -* -* @example -* ```typescript -* import { ChatOpenAI, tools } from "@langchain/openai"; -* import { applyDiff } from "@openai/agents"; -* import * as fs from "fs/promises"; -* -* const model = new ChatOpenAI({ model: "gpt-5.1" }); -* -* // With execute callback for automatic patch handling -* const patchTool = tools.applyPatch({ -* execute: async (operation) => { -* if (operation.type === "create_file") { -* const content = applyDiff("", operation.diff, "create"); -* await fs.writeFile(operation.path, content); -* return `Created ${operation.path}`; -* } -* if (operation.type === "update_file") { -* const current = await fs.readFile(operation.path, "utf-8"); -* const newContent = applyDiff(current, operation.diff); -* await fs.writeFile(operation.path, newContent); -* return `Updated ${operation.path}`; -* } -* if (operation.type === "delete_file") { -* await fs.unlink(operation.path); -* return `Deleted ${operation.path}`; -* } -* return "Unknown operation type"; -* }, -* }); -* -* const llmWithPatch = model.bindTools([patchTool]); -* const response = await llmWithPatch.invoke( -* "Rename the fib() function to fibonacci() in lib/fib.py" -* ); -* ``` -* -* @remarks -* - Only available through the Responses API (not Chat Completions) -* - Designed for use with `gpt-5.1` model -* - Operations include: `create_file`, `update_file`, `delete_file` -* - Patches use V4A diff format for updates -* - Always validate paths to prevent directory traversal attacks -* - Consider backing up files before applying patches -* - Implement "all-or-nothing" semantics if atomicity is required -*/ -function applyPatch_applyPatch(options) { - const patchTool = tool(options.execute, { - name: applyPatch_TOOL_NAME, - description: "Apply structured diffs to create, update, or delete files in the codebase.", - schema: ApplyPatchOperationSchema - }); - patchTool.extras = { - ...patchTool.extras ?? {}, - providerToolDefinition: { type: "apply_patch" } - }; - return patchTool; -} - -//#endregion - -//# sourceMappingURL=applyPatch.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/index.js - - - - - - - - - - - -//#region src/tools/index.ts -const tools_tools = { - webSearch: webSearch, - mcp: mcp, - codeInterpreter: codeInterpreter, - fileSearch: fileSearch, - imageGeneration: imageGeneration, - computerUse: computerUse, - localShell: localShell, - shell: shell, - applyPatch: applyPatch_applyPatch -}; - -//#endregion - -//# sourceMappingURL=index.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/tools/custom.js - - - - -//#region src/tools/custom.ts -function customTool(func, fields) { - return new DynamicTool({ - ...fields, - description: "", - metadata: { customTool: fields }, - func: async (input, runManager, config) => new Promise((resolve, reject) => { - const childConfig = patchConfig(config, { callbacks: runManager?.getChild() }); - AsyncLocalStorageProviderSingleton.runWithConfig(pickRunnableConfigKeys(childConfig), async () => { - try { - resolve(func(input, childConfig)); - } catch (e) { - reject(e); - } - }); - }) - }); -} - -//#endregion - -//# sourceMappingURL=custom.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/utils/prompts.js - - -//#region src/utils/prompts.ts -/** -* Convert a formatted LangChain prompt (e.g. pulled from the hub) into -* a format expected by OpenAI's JS SDK. -* -* Requires the "@langchain/openai" package to be installed in addition -* to the OpenAI SDK. -* -* @example -* ```ts -* import { convertPromptToOpenAI } from "langsmith/utils/hub/openai"; -* import { pull } from "langchain/hub"; -* -* import OpenAI from 'openai'; -* -* const prompt = await pull("jacob/joke-generator"); -* const formattedPrompt = await prompt.invoke({ -* topic: "cats", -* }); -* -* const { messages } = convertPromptToOpenAI(formattedPrompt); -* -* const openAIClient = new OpenAI(); -* -* const openaiResponse = await openAIClient.chat.completions.create({ -* model: "gpt-4o-mini", -* messages, -* }); -* ``` -* @param formattedPrompt -* @returns A partial OpenAI payload. -*/ -function convertPromptToOpenAI(formattedPrompt) { - const messages = formattedPrompt.toChatMessages(); - return { messages: convertMessagesToCompletionsMessageParams({ messages }) }; -} - -//#endregion - -//# sourceMappingURL=prompts.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/converters/index.js - - - -;// CONCATENATED MODULE: ./node_modules/@langchain/openai/dist/index.js - - - - - - - - - - - - - - - - - - - - - - - - -;// CONCATENATED MODULE: ./src/providers/openai.provider.ts - -/** - * OpenAI GPT provider implementation - */ -class OpenAIProvider { - name = 'openai'; - apiKey; - constructor(apiKey) { - this.apiKey = apiKey || process.env.OPENAI_API_KEY || ''; - } - isConfigured() { - return !!this.apiKey; - } - getDefaultModel() { - return 'gpt-4-turbo-preview'; - } - getChatModel(config = {}) { - if (!this.isConfigured()) { - throw new Error('OpenAI API key is not configured'); - } - return new ChatOpenAI({ - apiKey: this.apiKey, - modelName: config.model || this.getDefaultModel(), - temperature: config.temperature ?? 0.2, - maxTokens: config.maxTokens ?? 4000, - }); - } -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/utils/zod_to_genai_parameters.js - - - -//#region src/utils/zod_to_genai_parameters.ts -function removeAdditionalProperties(obj) { - if (typeof obj === "object" && obj !== null) { - const newObj = { ...obj }; - if ("additionalProperties" in newObj) delete newObj.additionalProperties; - if ("$schema" in newObj) delete newObj.$schema; - if ("strict" in newObj) delete newObj.strict; - for (const key in newObj) if (key in newObj) { - if (Array.isArray(newObj[key])) newObj[key] = newObj[key].map(removeAdditionalProperties); - else if (typeof newObj[key] === "object" && newObj[key] !== null) newObj[key] = removeAdditionalProperties(newObj[key]); - } - return newObj; - } - return obj; -} -function schemaToGenerativeAIParameters(schema) { - const jsonSchema = removeAdditionalProperties(isInteropZodSchema(schema) ? toJsonSchema(schema) : schema); - const { $schema,...rest } = jsonSchema; - return rest; -} -function jsonSchemaToGeminiParameters(schema) { - const jsonSchema = removeAdditionalProperties(schema); - const { $schema,...rest } = jsonSchema; - return rest; -} - -//#endregion - -//# sourceMappingURL=zod_to_genai_parameters.js.map -// EXTERNAL MODULE: external "crypto" -var external_crypto_ = __nccwpck_require__(6982); -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/native.js - -/* harmony default export */ const esm_native = ({ randomUUID: external_crypto_.randomUUID }); - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/rng.js - -const rnds8Pool = new Uint8Array(256); -let poolPtr = rnds8Pool.length; -function rng() { - if (poolPtr > rnds8Pool.length - 16) { - (0,external_crypto_.randomFillSync)(rnds8Pool); - poolPtr = 0; - } - return rnds8Pool.slice(poolPtr, (poolPtr += 16)); -} - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/stringify.js - -const byteToHex = []; -for (let i = 0; i < 256; ++i) { - byteToHex.push((i + 0x100).toString(16).slice(1)); -} -function unsafeStringify(arr, offset = 0) { - return (byteToHex[arr[offset + 0]] + - byteToHex[arr[offset + 1]] + - byteToHex[arr[offset + 2]] + - byteToHex[arr[offset + 3]] + - '-' + - byteToHex[arr[offset + 4]] + - byteToHex[arr[offset + 5]] + - '-' + - byteToHex[arr[offset + 6]] + - byteToHex[arr[offset + 7]] + - '-' + - byteToHex[arr[offset + 8]] + - byteToHex[arr[offset + 9]] + - '-' + - byteToHex[arr[offset + 10]] + - byteToHex[arr[offset + 11]] + - byteToHex[arr[offset + 12]] + - byteToHex[arr[offset + 13]] + - byteToHex[arr[offset + 14]] + - byteToHex[arr[offset + 15]]).toLowerCase(); -} -function esm_stringify_stringify(arr, offset = 0) { - const uuid = unsafeStringify(arr, offset); - if (!validate(uuid)) { - throw TypeError('Stringified UUID is invalid'); - } - return uuid; -} -/* harmony default export */ const esm_stringify = ((/* unused pure expression or super */ null && (esm_stringify_stringify))); - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/node_modules/uuid/dist/esm/v4.js - - - -function v4_v4(options, buf, offset) { - if (esm_native.randomUUID && !buf && !options) { - return esm_native.randomUUID(); - } - options = options || {}; - const rnds = options.random ?? options.rng?.() ?? rng(); - if (rnds.length < 16) { - throw new Error('Random bytes length must be >= 16'); - } - rnds[6] = (rnds[6] & 0x0f) | 0x40; - rnds[8] = (rnds[8] & 0x3f) | 0x80; - if (buf) { - offset = offset || 0; - if (offset < 0 || offset + 16 > buf.length) { - throw new RangeError(`UUID byte range ${offset}:${offset + 15} is out of buffer bounds`); - } - for (let i = 0; i < 16; ++i) { - buf[offset + i] = rnds[i]; - } - return buf; - } - return unsafeStringify(rnds); -} -/* harmony default export */ const esm_v4 = (v4_v4); - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/utils/common.js - - - - - - - -//#region src/utils/common.ts -const _FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY = "__gemini_function_call_thought_signatures__"; -const DUMMY_SIGNATURE = "ErYCCrMCAdHtim9kOoOkrPiCNVsmlpMIKd7ZMxgiFbVQOkgp7nlLcDMzVsZwIzvuT7nQROivoXA72ccC2lSDvR0Gh7dkWaGuj7ctv6t7ZceHnecx0QYa+ix8tYpRfjhyWozQ49lWiws6+YGjCt10KRTyWsZ2h6O7iHTYJwKIRwGUHRKy/qK/6kFxJm5ML00gLq4D8s5Z6DBpp2ZlR+uF4G8jJgeWQgyHWVdx2wGYElaceVAc66tZdPQRdOHpWtgYSI1YdaXgVI8KHY3/EfNc2YqqMIulvkDBAnuMhkAjV9xmBa54Tq+ih3Im4+r3DzqhGqYdsSkhS0kZMwte4Hjs65dZzCw9lANxIqYi1DJ639WNPYihp/DCJCos7o+/EeSPJaio5sgWDyUnMGkY1atsJZ+m7pj7DD5tvQ=="; -const common_iife = (fn) => fn(); -function getMessageAuthor(message) { - if (ChatMessage.isInstance(message)) return message.role; - return message.type; -} -/** -* Maps a message type to a Google Generative AI chat author. -* @param message The message to map. -* @param model The model to use for mapping. -* @returns The message type mapped to a Google Generative AI chat author. -*/ -function convertAuthorToRole(author) { - switch (author) { - case "supervisor": - case "ai": - case "model": return "model"; - case "system": return "system"; - case "human": return "user"; - case "tool": - case "function": return "function"; - default: throw new Error(`Unknown / unsupported author: ${author}`); - } -} -function messageContentMedia(content) { - if ("mimeType" in content && "data" in content) return { inlineData: { - mimeType: content.mimeType, - data: content.data - } }; - if ("mimeType" in content && "fileUri" in content) return { fileData: { - mimeType: content.mimeType, - fileUri: content.fileUri - } }; - throw new Error("Invalid media content"); -} -function inferToolNameFromPreviousMessages(message, previousMessages) { - return previousMessages.map((msg) => { - if (isAIMessage(msg)) return msg.tool_calls ?? []; - return []; - }).flat().find((toolCall) => { - return toolCall.id === message.tool_call_id; - })?.name; -} -function _getStandardContentBlockConverter(isMultimodalModel) { - const standardContentBlockConverter = { - providerName: "Google Gemini", - fromStandardTextBlock(block) { - return { text: block.text }; - }, - fromStandardImageBlock(block) { - if (!isMultimodalModel) throw new Error("This model does not support images"); - if (block.source_type === "url") { - const data = parseBase64DataUrl({ dataUrl: block.url }); - if (data) return { inlineData: { - mimeType: data.mime_type, - data: data.data - } }; - else return { fileData: { - mimeType: block.mime_type ?? "", - fileUri: block.url - } }; - } - if (block.source_type === "base64") return { inlineData: { - mimeType: block.mime_type ?? "", - data: block.data - } }; - throw new Error(`Unsupported source type: ${block.source_type}`); - }, - fromStandardAudioBlock(block) { - if (!isMultimodalModel) throw new Error("This model does not support audio"); - if (block.source_type === "url") { - const data = parseBase64DataUrl({ dataUrl: block.url }); - if (data) return { inlineData: { - mimeType: data.mime_type, - data: data.data - } }; - else return { fileData: { - mimeType: block.mime_type ?? "", - fileUri: block.url - } }; - } - if (block.source_type === "base64") return { inlineData: { - mimeType: block.mime_type ?? "", - data: block.data - } }; - throw new Error(`Unsupported source type: ${block.source_type}`); - }, - fromStandardFileBlock(block) { - if (!isMultimodalModel) throw new Error("This model does not support files"); - if (block.source_type === "text") return { text: block.text }; - if (block.source_type === "url") { - const data = parseBase64DataUrl({ dataUrl: block.url }); - if (data) return { inlineData: { - mimeType: data.mime_type, - data: data.data - } }; - else return { fileData: { - mimeType: block.mime_type ?? "", - fileUri: block.url - } }; - } - if (block.source_type === "base64") return { inlineData: { - mimeType: block.mime_type ?? "", - data: block.data - } }; - throw new Error(`Unsupported source type: ${block.source_type}`); - } - }; - return standardContentBlockConverter; -} -function _convertLangChainContentToPart(content, isMultimodalModel) { - if (isDataContentBlock(content)) return convertToProviderContentBlock(content, _getStandardContentBlockConverter(isMultimodalModel)); - if (content.type === "text") return { text: content.text }; - else if (content.type === "executableCode") return { executableCode: content.executableCode }; - else if (content.type === "codeExecutionResult") return { codeExecutionResult: content.codeExecutionResult }; - else if (content.type === "image_url") { - if (!isMultimodalModel) throw new Error(`This model does not support images`); - let source; - if (typeof content.image_url === "string") source = content.image_url; - else if (typeof content.image_url === "object" && "url" in content.image_url) source = content.image_url.url; - else throw new Error("Please provide image as base64 encoded data URL"); - const [dm, data] = source.split(","); - if (!dm.startsWith("data:")) throw new Error("Please provide image as base64 encoded data URL"); - const [mimeType, encoding] = dm.replace(/^data:/, "").split(";"); - if (encoding !== "base64") throw new Error("Please provide image as base64 encoded data URL"); - return { inlineData: { - data, - mimeType - } }; - } else if (content.type === "media") return messageContentMedia(content); - else if (content.type === "tool_use") return { functionCall: { - name: content.name, - args: content.input - } }; - else if (content.type?.includes("/") && content.type.split("/").length === 2 && "data" in content && typeof content.data === "string") return { inlineData: { - mimeType: content.type, - data: content.data - } }; - else if ("functionCall" in content) return void 0; - else if ("type" in content) throw new Error(`Unknown content type ${content.type}`); - else throw new Error(`Unknown content ${JSON.stringify(content)}`); -} -function convertMessageContentToParts(message, isMultimodalModel, previousMessages, model) { - if (isToolMessage(message)) { - const messageName = message.name ?? inferToolNameFromPreviousMessages(message, previousMessages); - if (messageName === void 0) throw new Error(`Google requires a tool name for each tool call response, and we could not infer a called tool name for ToolMessage "${message.id}" from your passed messages. Please populate a "name" field on that ToolMessage explicitly.`); - const result = Array.isArray(message.content) ? message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0) : message.content; - if (message.status === "error") return [{ functionResponse: { - name: messageName, - response: { error: { details: result } } - } }]; - return [{ functionResponse: { - name: messageName, - response: { result } - } }]; - } - let functionCalls = []; - const messageParts = []; - if (typeof message.content === "string" && message.content) messageParts.push({ text: message.content }); - if (Array.isArray(message.content)) messageParts.push(...message.content.map((c) => _convertLangChainContentToPart(c, isMultimodalModel)).filter((p) => p !== void 0)); - const functionThoughtSignatures = message.additional_kwargs?.[_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]; - if (isAIMessage(message) && message.tool_calls?.length) functionCalls = message.tool_calls.map((tc) => { - const thoughtSignature = common_iife(() => { - if (tc.id) { - const signature = functionThoughtSignatures?.[tc.id]; - if (signature) return signature; - } - if (model?.includes("gemini-3")) return DUMMY_SIGNATURE; - return ""; - }); - return { - functionCall: { - name: tc.name, - args: tc.args - }, - ...thoughtSignature ? { thoughtSignature } : {} - }; - }); - return [...messageParts, ...functionCalls]; -} -function convertBaseMessagesToContent(messages, isMultimodalModel, convertSystemMessageToHumanContent = false, model) { - return messages.reduce((acc, message, index) => { - if (!isBaseMessage(message)) throw new Error("Unsupported message input"); - const author = getMessageAuthor(message); - if (author === "system" && index !== 0) throw new Error("System message should be the first one"); - const role = convertAuthorToRole(author); - const prevContent = acc.content[acc.content.length]; - if (!acc.mergeWithPreviousContent && prevContent && prevContent.role === role) throw new Error("Google Generative AI requires alternate messages between authors"); - const parts = convertMessageContentToParts(message, isMultimodalModel, messages.slice(0, index), model); - if (acc.mergeWithPreviousContent) { - const prevContent$1 = acc.content[acc.content.length - 1]; - if (!prevContent$1) throw new Error("There was a problem parsing your system message. Please try a prompt without one."); - prevContent$1.parts.push(...parts); - return { - mergeWithPreviousContent: false, - content: acc.content - }; - } - let actualRole = role; - if (actualRole === "function" || actualRole === "system" && !convertSystemMessageToHumanContent) actualRole = "user"; - const content = { - role: actualRole, - parts - }; - return { - mergeWithPreviousContent: author === "system" && !convertSystemMessageToHumanContent, - content: [...acc.content, content] - }; - }, { - content: [], - mergeWithPreviousContent: false - }).content; -} -function mapGenerateContentResultToChatResult(response, extra) { - if (!response.candidates || response.candidates.length === 0 || !response.candidates[0]) return { - generations: [], - llmOutput: { filters: response.promptFeedback } - }; - const [candidate] = response.candidates; - const { content: candidateContent,...generationInfo } = candidate; - const functionCalls = candidateContent.parts?.reduce((acc, p) => { - if ("functionCall" in p && p.functionCall) acc.push({ - ...p, - id: "id" in p.functionCall && typeof p.functionCall.id === "string" ? p.functionCall.id : esm_v4() - }); - return acc; - }, []); - let content; - if (Array.isArray(candidateContent?.parts) && candidateContent.parts.length === 1 && candidateContent.parts[0].text) content = candidateContent.parts[0].text; - else if (Array.isArray(candidateContent?.parts) && candidateContent.parts.length > 0) content = candidateContent.parts.map((p) => { - if ("text" in p) return { - type: "text", - text: p.text - }; - else if ("inlineData" in p) return { - type: "inlineData", - inlineData: p.inlineData - }; - else if ("functionCall" in p) return { - type: "functionCall", - functionCall: p.functionCall - }; - else if ("functionResponse" in p) return { - type: "functionResponse", - functionResponse: p.functionResponse - }; - else if ("fileData" in p) return { - type: "fileData", - fileData: p.fileData - }; - else if ("executableCode" in p) return { - type: "executableCode", - executableCode: p.executableCode - }; - else if ("codeExecutionResult" in p) return { - type: "codeExecutionResult", - codeExecutionResult: p.codeExecutionResult - }; - return p; - }); - else content = []; - const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => { - if ("thoughtSignature" in fc && typeof fc.thoughtSignature === "string") acc[fc.id] = fc.thoughtSignature; - return acc; - }, {}); - let text = ""; - if (typeof content === "string") text = content; - else if (Array.isArray(content) && content.length > 0) { - const block = content.find((b) => "text" in b); - text = block?.text ?? text; - } - const generation = { - text, - message: new AIMessage({ - content: content ?? "", - tool_calls: functionCalls?.map((fc) => ({ - type: "tool_call", - id: fc.id, - name: fc.functionCall.name, - args: fc.functionCall.args - })), - additional_kwargs: { - ...generationInfo, - [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures - }, - usage_metadata: extra?.usageMetadata - }), - generationInfo - }; - return { - generations: [generation], - llmOutput: { tokenUsage: { - promptTokens: extra?.usageMetadata?.input_tokens, - completionTokens: extra?.usageMetadata?.output_tokens, - totalTokens: extra?.usageMetadata?.total_tokens - } } - }; -} -function convertResponseContentToChatGenerationChunk(response, extra) { - if (!response.candidates || response.candidates.length === 0) return null; - const [candidate] = response.candidates; - const { content: candidateContent,...generationInfo } = candidate; - const functionCalls = candidateContent.parts?.reduce((acc, p) => { - if ("functionCall" in p && p.functionCall) acc.push({ - ...p, - id: "id" in p.functionCall && typeof p.functionCall.id === "string" ? p.functionCall.id : esm_v4() - }); - return acc; - }, []); - let content; - if (Array.isArray(candidateContent?.parts) && candidateContent.parts.every((p) => "text" in p)) content = candidateContent.parts.map((p) => p.text).join(""); - else if (Array.isArray(candidateContent?.parts)) content = candidateContent.parts.map((p) => { - if ("text" in p) return { - type: "text", - text: p.text - }; - else if ("inlineData" in p) return { - type: "inlineData", - inlineData: p.inlineData - }; - else if ("functionCall" in p) return { - type: "functionCall", - functionCall: p.functionCall - }; - else if ("functionResponse" in p) return { - type: "functionResponse", - functionResponse: p.functionResponse - }; - else if ("fileData" in p) return { - type: "fileData", - fileData: p.fileData - }; - else if ("executableCode" in p) return { - type: "executableCode", - executableCode: p.executableCode - }; - else if ("codeExecutionResult" in p) return { - type: "codeExecutionResult", - codeExecutionResult: p.codeExecutionResult - }; - return p; - }); - else content = []; - let text = ""; - if (content && typeof content === "string") text = content; - else if (Array.isArray(content)) { - const block = content.find((b) => "text" in b); - text = block?.text ?? ""; - } - const toolCallChunks = []; - if (functionCalls) toolCallChunks.push(...functionCalls.map((fc) => ({ - type: "tool_call_chunk", - id: fc.id, - name: fc.functionCall.name, - args: JSON.stringify(fc.functionCall.args) - }))); - const functionThoughtSignatures = functionCalls?.reduce((acc, fc) => { - if ("thoughtSignature" in fc && typeof fc.thoughtSignature === "string") acc[fc.id] = fc.thoughtSignature; - return acc; - }, {}); - return new ChatGenerationChunk({ - text, - message: new AIMessageChunk({ - content: content || "", - name: !candidateContent ? void 0 : candidateContent.role, - tool_call_chunks: toolCallChunks, - additional_kwargs: { [_FUNCTION_CALL_THOUGHT_SIGNATURES_MAP_KEY]: functionThoughtSignatures }, - response_metadata: { model_provider: "google-genai" }, - usage_metadata: extra.usageMetadata - }), - generationInfo - }); -} -function convertToGenerativeAITools(tools) { - if (tools.every((tool) => "functionDeclarations" in tool && Array.isArray(tool.functionDeclarations))) return tools; - return [{ functionDeclarations: tools.map((tool) => { - if (isLangChainTool(tool)) { - const jsonSchema = schemaToGenerativeAIParameters(tool.schema); - if (jsonSchema.type === "object" && "properties" in jsonSchema && Object.keys(jsonSchema.properties).length === 0) return { - name: tool.name, - description: tool.description - }; - return { - name: tool.name, - description: tool.description, - parameters: jsonSchema - }; - } - if (isOpenAITool(tool)) return { - name: tool.function.name, - description: tool.function.description ?? `A function available to call.`, - parameters: jsonSchemaToGeminiParameters(tool.function.parameters) - }; - return tool; - }) }]; -} -function convertUsageMetadata(usageMetadata, model) { - const output = { - input_tokens: usageMetadata?.promptTokenCount ?? 0, - output_tokens: usageMetadata?.candidatesTokenCount ?? 0, - total_tokens: usageMetadata?.totalTokenCount ?? 0 - }; - if (usageMetadata?.cachedContentTokenCount) { - output.input_token_details ??= {}; - output.input_token_details.cache_read = usageMetadata.cachedContentTokenCount; - } - if (model === "gemini-3-pro-preview") { - const over200k = Math.max(0, usageMetadata?.promptTokenCount ?? -2e5); - const cachedOver200k = Math.max(0, usageMetadata?.cachedContentTokenCount ?? -2e5); - if (over200k) output.input_token_details = { - ...output.input_token_details, - over_200k: over200k - }; - if (cachedOver200k) output.input_token_details = { - ...output.input_token_details, - cache_read_over_200k: cachedOver200k - }; - } - return output; -} - -//#endregion - -//# sourceMappingURL=common.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/output_parsers.js - - - -//#region src/output_parsers.ts -var GoogleGenerativeAIToolsOutputParser = class extends BaseLLMOutputParser { - static lc_name() { - return "GoogleGenerativeAIToolsOutputParser"; - } - lc_namespace = [ - "langchain", - "google_genai", - "output_parsers" - ]; - returnId = false; - /** The type of tool calls to return. */ - keyName; - /** Whether to return only the first tool call. */ - returnSingle = false; - zodSchema; - constructor(params) { - super(params); - this.keyName = params.keyName; - this.returnSingle = params.returnSingle ?? this.returnSingle; - this.zodSchema = params.zodSchema; - } - async _validateResult(result) { - if (this.zodSchema === void 0) return result; - const zodParsedResult = await interopSafeParseAsync(this.zodSchema, result); - if (zodParsedResult.success) return zodParsedResult.data; - else throw new OutputParserException(`Failed to parse. Text: "${JSON.stringify(result, null, 2)}". Error: ${JSON.stringify(zodParsedResult.error.issues)}`, JSON.stringify(result, null, 2)); - } - async parseResult(generations) { - const tools = generations.flatMap((generation) => { - const { message } = generation; - if (!("tool_calls" in message) || !Array.isArray(message.tool_calls)) return []; - return message.tool_calls; - }); - if (tools[0] === void 0) throw new Error("No parseable tool calls provided to GoogleGenerativeAIToolsOutputParser."); - const [tool] = tools; - const validatedResult = await this._validateResult(tool.args); - return validatedResult; - } -}; - -//#endregion - -//# sourceMappingURL=output_parsers.js.map -;// CONCATENATED MODULE: ./node_modules/@google/generative-ai/dist/index.mjs -/** - * Contains the list of OpenAPI data types - * as defined by https://swagger.io/docs/specification/data-models/data-types/ - * @public - */ -var SchemaType; -(function (SchemaType) { - /** String type. */ - SchemaType["STRING"] = "string"; - /** Number type. */ - SchemaType["NUMBER"] = "number"; - /** Integer type. */ - SchemaType["INTEGER"] = "integer"; - /** Boolean type. */ - SchemaType["BOOLEAN"] = "boolean"; - /** Array type. */ - SchemaType["ARRAY"] = "array"; - /** Object type. */ - SchemaType["OBJECT"] = "object"; -})(SchemaType || (SchemaType = {})); - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * @public - */ -var ExecutableCodeLanguage; -(function (ExecutableCodeLanguage) { - ExecutableCodeLanguage["LANGUAGE_UNSPECIFIED"] = "language_unspecified"; - ExecutableCodeLanguage["PYTHON"] = "python"; -})(ExecutableCodeLanguage || (ExecutableCodeLanguage = {})); -/** - * Possible outcomes of code execution. - * @public - */ -var Outcome; -(function (Outcome) { - /** - * Unspecified status. This value should not be used. - */ - Outcome["OUTCOME_UNSPECIFIED"] = "outcome_unspecified"; - /** - * Code execution completed successfully. - */ - Outcome["OUTCOME_OK"] = "outcome_ok"; - /** - * Code execution finished but with a failure. `stderr` should contain the - * reason. - */ - Outcome["OUTCOME_FAILED"] = "outcome_failed"; - /** - * Code execution ran for too long, and was cancelled. There may or may not - * be a partial output present. - */ - Outcome["OUTCOME_DEADLINE_EXCEEDED"] = "outcome_deadline_exceeded"; -})(Outcome || (Outcome = {})); - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Possible roles. - * @public - */ -const POSSIBLE_ROLES = ["user", "model", "function", "system"]; -/** - * Harm categories that would cause prompts or candidates to be blocked. - * @public - */ -var HarmCategory; -(function (HarmCategory) { - HarmCategory["HARM_CATEGORY_UNSPECIFIED"] = "HARM_CATEGORY_UNSPECIFIED"; - HarmCategory["HARM_CATEGORY_HATE_SPEECH"] = "HARM_CATEGORY_HATE_SPEECH"; - HarmCategory["HARM_CATEGORY_SEXUALLY_EXPLICIT"] = "HARM_CATEGORY_SEXUALLY_EXPLICIT"; - HarmCategory["HARM_CATEGORY_HARASSMENT"] = "HARM_CATEGORY_HARASSMENT"; - HarmCategory["HARM_CATEGORY_DANGEROUS_CONTENT"] = "HARM_CATEGORY_DANGEROUS_CONTENT"; - HarmCategory["HARM_CATEGORY_CIVIC_INTEGRITY"] = "HARM_CATEGORY_CIVIC_INTEGRITY"; -})(HarmCategory || (HarmCategory = {})); -/** - * Threshold above which a prompt or candidate will be blocked. - * @public - */ -var HarmBlockThreshold; -(function (HarmBlockThreshold) { - /** Threshold is unspecified. */ - HarmBlockThreshold["HARM_BLOCK_THRESHOLD_UNSPECIFIED"] = "HARM_BLOCK_THRESHOLD_UNSPECIFIED"; - /** Content with NEGLIGIBLE will be allowed. */ - HarmBlockThreshold["BLOCK_LOW_AND_ABOVE"] = "BLOCK_LOW_AND_ABOVE"; - /** Content with NEGLIGIBLE and LOW will be allowed. */ - HarmBlockThreshold["BLOCK_MEDIUM_AND_ABOVE"] = "BLOCK_MEDIUM_AND_ABOVE"; - /** Content with NEGLIGIBLE, LOW, and MEDIUM will be allowed. */ - HarmBlockThreshold["BLOCK_ONLY_HIGH"] = "BLOCK_ONLY_HIGH"; - /** All content will be allowed. */ - HarmBlockThreshold["BLOCK_NONE"] = "BLOCK_NONE"; -})(HarmBlockThreshold || (HarmBlockThreshold = {})); -/** - * Probability that a prompt or candidate matches a harm category. - * @public - */ -var HarmProbability; -(function (HarmProbability) { - /** Probability is unspecified. */ - HarmProbability["HARM_PROBABILITY_UNSPECIFIED"] = "HARM_PROBABILITY_UNSPECIFIED"; - /** Content has a negligible chance of being unsafe. */ - HarmProbability["NEGLIGIBLE"] = "NEGLIGIBLE"; - /** Content has a low chance of being unsafe. */ - HarmProbability["LOW"] = "LOW"; - /** Content has a medium chance of being unsafe. */ - HarmProbability["MEDIUM"] = "MEDIUM"; - /** Content has a high chance of being unsafe. */ - HarmProbability["HIGH"] = "HIGH"; -})(HarmProbability || (HarmProbability = {})); -/** - * Reason that a prompt was blocked. - * @public - */ -var BlockReason; -(function (BlockReason) { - // A blocked reason was not specified. - BlockReason["BLOCKED_REASON_UNSPECIFIED"] = "BLOCKED_REASON_UNSPECIFIED"; - // Content was blocked by safety settings. - BlockReason["SAFETY"] = "SAFETY"; - // Content was blocked, but the reason is uncategorized. - BlockReason["OTHER"] = "OTHER"; -})(BlockReason || (BlockReason = {})); -/** - * Reason that a candidate finished. - * @public - */ -var FinishReason; -(function (FinishReason) { - // Default value. This value is unused. - FinishReason["FINISH_REASON_UNSPECIFIED"] = "FINISH_REASON_UNSPECIFIED"; - // Natural stop point of the model or provided stop sequence. - FinishReason["STOP"] = "STOP"; - // The maximum number of tokens as specified in the request was reached. - FinishReason["MAX_TOKENS"] = "MAX_TOKENS"; - // The candidate content was flagged for safety reasons. - FinishReason["SAFETY"] = "SAFETY"; - // The candidate content was flagged for recitation reasons. - FinishReason["RECITATION"] = "RECITATION"; - // The candidate content was flagged for using an unsupported language. - FinishReason["LANGUAGE"] = "LANGUAGE"; - // Token generation stopped because the content contains forbidden terms. - FinishReason["BLOCKLIST"] = "BLOCKLIST"; - // Token generation stopped for potentially containing prohibited content. - FinishReason["PROHIBITED_CONTENT"] = "PROHIBITED_CONTENT"; - // Token generation stopped because the content potentially contains Sensitive Personally Identifiable Information (SPII). - FinishReason["SPII"] = "SPII"; - // The function call generated by the model is invalid. - FinishReason["MALFORMED_FUNCTION_CALL"] = "MALFORMED_FUNCTION_CALL"; - // Unknown reason. - FinishReason["OTHER"] = "OTHER"; -})(FinishReason || (FinishReason = {})); -/** - * Task type for embedding content. - * @public - */ -var TaskType; -(function (TaskType) { - TaskType["TASK_TYPE_UNSPECIFIED"] = "TASK_TYPE_UNSPECIFIED"; - TaskType["RETRIEVAL_QUERY"] = "RETRIEVAL_QUERY"; - TaskType["RETRIEVAL_DOCUMENT"] = "RETRIEVAL_DOCUMENT"; - TaskType["SEMANTIC_SIMILARITY"] = "SEMANTIC_SIMILARITY"; - TaskType["CLASSIFICATION"] = "CLASSIFICATION"; - TaskType["CLUSTERING"] = "CLUSTERING"; -})(TaskType || (TaskType = {})); -/** - * @public - */ -var FunctionCallingMode; -(function (FunctionCallingMode) { - // Unspecified function calling mode. This value should not be used. - FunctionCallingMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; - // Default model behavior, model decides to predict either a function call - // or a natural language repspose. - FunctionCallingMode["AUTO"] = "AUTO"; - // Model is constrained to always predicting a function call only. - // If "allowed_function_names" are set, the predicted function call will be - // limited to any one of "allowed_function_names", else the predicted - // function call will be any one of the provided "function_declarations". - FunctionCallingMode["ANY"] = "ANY"; - // Model will not predict any function call. Model behavior is same as when - // not passing any function declarations. - FunctionCallingMode["NONE"] = "NONE"; -})(FunctionCallingMode || (FunctionCallingMode = {})); -/** - * The mode of the predictor to be used in dynamic retrieval. - * @public - */ -var DynamicRetrievalMode; -(function (DynamicRetrievalMode) { - // Unspecified function calling mode. This value should not be used. - DynamicRetrievalMode["MODE_UNSPECIFIED"] = "MODE_UNSPECIFIED"; - // Run retrieval only when system decides it is necessary. - DynamicRetrievalMode["MODE_DYNAMIC"] = "MODE_DYNAMIC"; -})(DynamicRetrievalMode || (DynamicRetrievalMode = {})); - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Basic error type for this SDK. - * @public - */ -class GoogleGenerativeAIError extends Error { - constructor(message) { - super(`[GoogleGenerativeAI Error]: ${message}`); - } -} -/** - * Errors in the contents of a response from the model. This includes parsing - * errors, or responses including a safety block reason. - * @public - */ -class GoogleGenerativeAIResponseError extends GoogleGenerativeAIError { - constructor(message, response) { - super(message); - this.response = response; - } -} -/** - * Error class covering HTTP errors when calling the server. Includes HTTP - * status, statusText, and optional details, if provided in the server response. - * @public - */ -class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError { - constructor(message, status, statusText, errorDetails) { - super(message); - this.status = status; - this.statusText = statusText; - this.errorDetails = errorDetails; - } -} -/** - * Errors in the contents of a request originating from user input. - * @public - */ -class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError { -} -/** - * Error thrown when a request is aborted, either due to a timeout or - * intentional cancellation by the user. - * @public - */ -class GoogleGenerativeAIAbortError extends GoogleGenerativeAIError { -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com"; -const DEFAULT_API_VERSION = "v1beta"; -/** - * We can't `require` package.json if this runs on web. We will use rollup to - * swap in the version number here at build time. - */ -const PACKAGE_VERSION = "0.24.1"; -const PACKAGE_LOG_HEADER = "genai-js"; -var Task; -(function (Task) { - Task["GENERATE_CONTENT"] = "generateContent"; - Task["STREAM_GENERATE_CONTENT"] = "streamGenerateContent"; - Task["COUNT_TOKENS"] = "countTokens"; - Task["EMBED_CONTENT"] = "embedContent"; - Task["BATCH_EMBED_CONTENTS"] = "batchEmbedContents"; -})(Task || (Task = {})); -class RequestUrl { - constructor(model, task, apiKey, stream, requestOptions) { - this.model = model; - this.task = task; - this.apiKey = apiKey; - this.stream = stream; - this.requestOptions = requestOptions; - } - toString() { - var _a, _b; - const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION; - const baseUrl = ((_b = this.requestOptions) === null || _b === void 0 ? void 0 : _b.baseUrl) || DEFAULT_BASE_URL; - let url = `${baseUrl}/${apiVersion}/${this.model}:${this.task}`; - if (this.stream) { - url += "?alt=sse"; - } - return url; - } -} -/** - * Simple, but may become more complex if we add more versions to log. - */ -function getClientHeaders(requestOptions) { - const clientHeaders = []; - if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.apiClient) { - clientHeaders.push(requestOptions.apiClient); - } - clientHeaders.push(`${PACKAGE_LOG_HEADER}/${PACKAGE_VERSION}`); - return clientHeaders.join(" "); -} -async function getHeaders(url) { - var _a; - const headers = new Headers(); - headers.append("Content-Type", "application/json"); - headers.append("x-goog-api-client", getClientHeaders(url.requestOptions)); - headers.append("x-goog-api-key", url.apiKey); - let customHeaders = (_a = url.requestOptions) === null || _a === void 0 ? void 0 : _a.customHeaders; - if (customHeaders) { - if (!(customHeaders instanceof Headers)) { - try { - customHeaders = new Headers(customHeaders); - } - catch (e) { - throw new GoogleGenerativeAIRequestInputError(`unable to convert customHeaders value ${JSON.stringify(customHeaders)} to Headers: ${e.message}`); - } - } - for (const [headerName, headerValue] of customHeaders.entries()) { - if (headerName === "x-goog-api-key") { - throw new GoogleGenerativeAIRequestInputError(`Cannot set reserved header name ${headerName}`); - } - else if (headerName === "x-goog-api-client") { - throw new GoogleGenerativeAIRequestInputError(`Header name ${headerName} can only be set using the apiClient field`); - } - headers.append(headerName, headerValue); - } - } - return headers; -} -async function constructModelRequest(model, task, apiKey, stream, body, requestOptions) { - const url = new RequestUrl(model, task, apiKey, stream, requestOptions); - return { - url: url.toString(), - fetchOptions: Object.assign(Object.assign({}, buildFetchOptions(requestOptions)), { method: "POST", headers: await getHeaders(url), body }), - }; -} -async function makeModelRequest(model, task, apiKey, stream, body, requestOptions = {}, -// Allows this to be stubbed for tests -fetchFn = fetch) { - const { url, fetchOptions } = await constructModelRequest(model, task, apiKey, stream, body, requestOptions); - return makeRequest(url, fetchOptions, fetchFn); -} -async function makeRequest(url, fetchOptions, fetchFn = fetch) { - let response; - try { - response = await fetchFn(url, fetchOptions); - } - catch (e) { - handleResponseError(e, url); - } - if (!response.ok) { - await handleResponseNotOk(response, url); - } - return response; -} -function handleResponseError(e, url) { - let err = e; - if (err.name === "AbortError") { - err = new GoogleGenerativeAIAbortError(`Request aborted when fetching ${url.toString()}: ${e.message}`); - err.stack = e.stack; - } - else if (!(e instanceof GoogleGenerativeAIFetchError || - e instanceof GoogleGenerativeAIRequestInputError)) { - err = new GoogleGenerativeAIError(`Error fetching from ${url.toString()}: ${e.message}`); - err.stack = e.stack; - } - throw err; -} -async function handleResponseNotOk(response, url) { - let message = ""; - let errorDetails; - try { - const json = await response.json(); - message = json.error.message; - if (json.error.details) { - message += ` ${JSON.stringify(json.error.details)}`; - errorDetails = json.error.details; - } - } - catch (e) { - // ignored - } - throw new GoogleGenerativeAIFetchError(`Error fetching from ${url.toString()}: [${response.status} ${response.statusText}] ${message}`, response.status, response.statusText, errorDetails); -} -/** - * Generates the request options to be passed to the fetch API. - * @param requestOptions - The user-defined request options. - * @returns The generated request options. - */ -function buildFetchOptions(requestOptions) { - const fetchOptions = {}; - if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) !== undefined || (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) { - const controller = new AbortController(); - if ((requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.timeout) >= 0) { - setTimeout(() => controller.abort(), requestOptions.timeout); - } - if (requestOptions === null || requestOptions === void 0 ? void 0 : requestOptions.signal) { - requestOptions.signal.addEventListener("abort", () => { - controller.abort(); - }); - } - fetchOptions.signal = controller.signal; - } - return fetchOptions; -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Adds convenience helper methods to a response object, including stream - * chunks (as long as each chunk is a complete GenerateContentResponse JSON). - */ -function addHelpers(response) { - response.text = () => { - if (response.candidates && response.candidates.length > 0) { - if (response.candidates.length > 1) { - console.warn(`This response had ${response.candidates.length} ` + - `candidates. Returning text from the first candidate only. ` + - `Access response.candidates directly to use the other candidates.`); - } - if (hadBadFinishReason(response.candidates[0])) { - throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); - } - return getText(response); - } - else if (response.promptFeedback) { - throw new GoogleGenerativeAIResponseError(`Text not available. ${formatBlockErrorMessage(response)}`, response); - } - return ""; - }; - /** - * TODO: remove at next major version - */ - response.functionCall = () => { - if (response.candidates && response.candidates.length > 0) { - if (response.candidates.length > 1) { - console.warn(`This response had ${response.candidates.length} ` + - `candidates. Returning function calls from the first candidate only. ` + - `Access response.candidates directly to use the other candidates.`); - } - if (hadBadFinishReason(response.candidates[0])) { - throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); - } - console.warn(`response.functionCall() is deprecated. ` + - `Use response.functionCalls() instead.`); - return getFunctionCalls(response)[0]; - } - else if (response.promptFeedback) { - throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response); - } - return undefined; - }; - response.functionCalls = () => { - if (response.candidates && response.candidates.length > 0) { - if (response.candidates.length > 1) { - console.warn(`This response had ${response.candidates.length} ` + - `candidates. Returning function calls from the first candidate only. ` + - `Access response.candidates directly to use the other candidates.`); - } - if (hadBadFinishReason(response.candidates[0])) { - throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); - } - return getFunctionCalls(response); - } - else if (response.promptFeedback) { - throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response); - } - return undefined; - }; - return response; -} -/** - * Returns all text found in all parts of first candidate. - */ -function getText(response) { - var _a, _b, _c, _d; - const textStrings = []; - if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) { - for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) { - if (part.text) { - textStrings.push(part.text); - } - if (part.executableCode) { - textStrings.push("\n```" + - part.executableCode.language + - "\n" + - part.executableCode.code + - "\n```\n"); - } - if (part.codeExecutionResult) { - textStrings.push("\n```\n" + part.codeExecutionResult.output + "\n```\n"); - } - } - } - if (textStrings.length > 0) { - return textStrings.join(""); - } - else { - return ""; - } -} -/** - * Returns functionCall of first candidate. - */ -function getFunctionCalls(response) { - var _a, _b, _c, _d; - const functionCalls = []; - if ((_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) { - for (const part of (_d = (_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0].content) === null || _d === void 0 ? void 0 : _d.parts) { - if (part.functionCall) { - functionCalls.push(part.functionCall); - } - } - } - if (functionCalls.length > 0) { - return functionCalls; - } - else { - return undefined; - } -} -const badFinishReasons = [ - FinishReason.RECITATION, - FinishReason.SAFETY, - FinishReason.LANGUAGE, -]; -function hadBadFinishReason(candidate) { - return (!!candidate.finishReason && - badFinishReasons.includes(candidate.finishReason)); -} -function formatBlockErrorMessage(response) { - var _a, _b, _c; - let message = ""; - if ((!response.candidates || response.candidates.length === 0) && - response.promptFeedback) { - message += "Response was blocked"; - if ((_a = response.promptFeedback) === null || _a === void 0 ? void 0 : _a.blockReason) { - message += ` due to ${response.promptFeedback.blockReason}`; - } - if ((_b = response.promptFeedback) === null || _b === void 0 ? void 0 : _b.blockReasonMessage) { - message += `: ${response.promptFeedback.blockReasonMessage}`; - } - } - else if ((_c = response.candidates) === null || _c === void 0 ? void 0 : _c[0]) { - const firstCandidate = response.candidates[0]; - if (hadBadFinishReason(firstCandidate)) { - message += `Candidate was blocked due to ${firstCandidate.finishReason}`; - if (firstCandidate.finishMessage) { - message += `: ${firstCandidate.finishMessage}`; - } - } - } - return message; -} - -/****************************************************************************** -Copyright (c) Microsoft Corporation. - -Permission to use, copy, modify, and/or distribute this software for any -purpose with or without fee is hereby granted. - -THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH -REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY -AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, -INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM -LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR -OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR -PERFORMANCE OF THIS SOFTWARE. -***************************************************************************** */ -/* global Reflect, Promise, SuppressedError, Symbol */ - - -function __await(v) { - return this instanceof __await ? (this.v = v, this) : new __await(v); -} - -function __asyncGenerator(thisArg, _arguments, generator) { - if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); - var g = generator.apply(thisArg, _arguments || []), i, q = []; - return i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i; - function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; } - function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } - function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } - function fulfill(value) { resume("next", value); } - function reject(value) { resume("throw", value); } - function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } -} - -typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { - var e = new Error(message); - return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; -}; - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -const responseLineRE = /^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/; -/** - * Process a response.body stream from the backend and return an - * iterator that provides one complete GenerateContentResponse at a time - * and a promise that resolves with a single aggregated - * GenerateContentResponse. - * - * @param response - Response from a fetch call - */ -function processStream(response) { - const inputStream = response.body.pipeThrough(new TextDecoderStream("utf8", { fatal: true })); - const responseStream = getResponseStream(inputStream); - const [stream1, stream2] = responseStream.tee(); - return { - stream: generateResponseSequence(stream1), - response: getResponsePromise(stream2), - }; -} -async function getResponsePromise(stream) { - const allResponses = []; - const reader = stream.getReader(); - while (true) { - const { done, value } = await reader.read(); - if (done) { - return addHelpers(aggregateResponses(allResponses)); - } - allResponses.push(value); - } -} -function generateResponseSequence(stream) { - return __asyncGenerator(this, arguments, function* generateResponseSequence_1() { - const reader = stream.getReader(); - while (true) { - const { value, done } = yield __await(reader.read()); - if (done) { - break; - } - yield yield __await(addHelpers(value)); - } - }); -} -/** - * Reads a raw stream from the fetch response and join incomplete - * chunks, returning a new stream that provides a single complete - * GenerateContentResponse in each iteration. - */ -function getResponseStream(inputStream) { - const reader = inputStream.getReader(); - const stream = new ReadableStream({ - start(controller) { - let currentText = ""; - return pump(); - function pump() { - return reader - .read() - .then(({ value, done }) => { - if (done) { - if (currentText.trim()) { - controller.error(new GoogleGenerativeAIError("Failed to parse stream")); - return; - } - controller.close(); - return; - } - currentText += value; - let match = currentText.match(responseLineRE); - let parsedResponse; - while (match) { - try { - parsedResponse = JSON.parse(match[1]); - } - catch (e) { - controller.error(new GoogleGenerativeAIError(`Error parsing JSON response: "${match[1]}"`)); - return; - } - controller.enqueue(parsedResponse); - currentText = currentText.substring(match[0].length); - match = currentText.match(responseLineRE); - } - return pump(); - }) - .catch((e) => { - let err = e; - err.stack = e.stack; - if (err.name === "AbortError") { - err = new GoogleGenerativeAIAbortError("Request aborted when reading from the stream"); - } - else { - err = new GoogleGenerativeAIError("Error reading from the stream"); - } - throw err; - }); - } - }, - }); - return stream; -} -/** - * Aggregates an array of `GenerateContentResponse`s into a single - * GenerateContentResponse. - */ -function aggregateResponses(responses) { - const lastResponse = responses[responses.length - 1]; - const aggregatedResponse = { - promptFeedback: lastResponse === null || lastResponse === void 0 ? void 0 : lastResponse.promptFeedback, - }; - for (const response of responses) { - if (response.candidates) { - let candidateIndex = 0; - for (const candidate of response.candidates) { - if (!aggregatedResponse.candidates) { - aggregatedResponse.candidates = []; - } - if (!aggregatedResponse.candidates[candidateIndex]) { - aggregatedResponse.candidates[candidateIndex] = { - index: candidateIndex, - }; - } - // Keep overwriting, the last one will be final - aggregatedResponse.candidates[candidateIndex].citationMetadata = - candidate.citationMetadata; - aggregatedResponse.candidates[candidateIndex].groundingMetadata = - candidate.groundingMetadata; - aggregatedResponse.candidates[candidateIndex].finishReason = - candidate.finishReason; - aggregatedResponse.candidates[candidateIndex].finishMessage = - candidate.finishMessage; - aggregatedResponse.candidates[candidateIndex].safetyRatings = - candidate.safetyRatings; - /** - * Candidates should always have content and parts, but this handles - * possible malformed responses. - */ - if (candidate.content && candidate.content.parts) { - if (!aggregatedResponse.candidates[candidateIndex].content) { - aggregatedResponse.candidates[candidateIndex].content = { - role: candidate.content.role || "user", - parts: [], - }; - } - const newPart = {}; - for (const part of candidate.content.parts) { - if (part.text) { - newPart.text = part.text; - } - if (part.functionCall) { - newPart.functionCall = part.functionCall; - } - if (part.executableCode) { - newPart.executableCode = part.executableCode; - } - if (part.codeExecutionResult) { - newPart.codeExecutionResult = part.codeExecutionResult; - } - if (Object.keys(newPart).length === 0) { - newPart.text = ""; - } - aggregatedResponse.candidates[candidateIndex].content.parts.push(newPart); - } - } - } - candidateIndex++; - } - if (response.usageMetadata) { - aggregatedResponse.usageMetadata = response.usageMetadata; - } - } - return aggregatedResponse; -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -async function generateContentStream(apiKey, model, params, requestOptions) { - const response = await makeModelRequest(model, Task.STREAM_GENERATE_CONTENT, apiKey, - /* stream */ true, JSON.stringify(params), requestOptions); - return processStream(response); -} -async function generateContent(apiKey, model, params, requestOptions) { - const response = await makeModelRequest(model, Task.GENERATE_CONTENT, apiKey, - /* stream */ false, JSON.stringify(params), requestOptions); - const responseJson = await response.json(); - const enhancedResponse = addHelpers(responseJson); - return { - response: enhancedResponse, - }; -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -function formatSystemInstruction(input) { - // null or undefined - if (input == null) { - return undefined; - } - else if (typeof input === "string") { - return { role: "system", parts: [{ text: input }] }; - } - else if (input.text) { - return { role: "system", parts: [input] }; - } - else if (input.parts) { - if (!input.role) { - return { role: "system", parts: input.parts }; - } - else { - return input; - } - } -} -function formatNewContent(request) { - let newParts = []; - if (typeof request === "string") { - newParts = [{ text: request }]; - } - else { - for (const partOrString of request) { - if (typeof partOrString === "string") { - newParts.push({ text: partOrString }); - } - else { - newParts.push(partOrString); - } - } - } - return assignRoleToPartsAndValidateSendMessageRequest(newParts); -} -/** - * When multiple Part types (i.e. FunctionResponsePart and TextPart) are - * passed in a single Part array, we may need to assign different roles to each - * part. Currently only FunctionResponsePart requires a role other than 'user'. - * @private - * @param parts Array of parts to pass to the model - * @returns Array of content items - */ -function assignRoleToPartsAndValidateSendMessageRequest(parts) { - const userContent = { role: "user", parts: [] }; - const functionContent = { role: "function", parts: [] }; - let hasUserContent = false; - let hasFunctionContent = false; - for (const part of parts) { - if ("functionResponse" in part) { - functionContent.parts.push(part); - hasFunctionContent = true; - } - else { - userContent.parts.push(part); - hasUserContent = true; - } - } - if (hasUserContent && hasFunctionContent) { - throw new GoogleGenerativeAIError("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message."); - } - if (!hasUserContent && !hasFunctionContent) { - throw new GoogleGenerativeAIError("No content is provided for sending chat message."); - } - if (hasUserContent) { - return userContent; - } - return functionContent; -} -function formatCountTokensInput(params, modelParams) { - var _a; - let formattedGenerateContentRequest = { - model: modelParams === null || modelParams === void 0 ? void 0 : modelParams.model, - generationConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.generationConfig, - safetySettings: modelParams === null || modelParams === void 0 ? void 0 : modelParams.safetySettings, - tools: modelParams === null || modelParams === void 0 ? void 0 : modelParams.tools, - toolConfig: modelParams === null || modelParams === void 0 ? void 0 : modelParams.toolConfig, - systemInstruction: modelParams === null || modelParams === void 0 ? void 0 : modelParams.systemInstruction, - cachedContent: (_a = modelParams === null || modelParams === void 0 ? void 0 : modelParams.cachedContent) === null || _a === void 0 ? void 0 : _a.name, - contents: [], - }; - const containsGenerateContentRequest = params.generateContentRequest != null; - if (params.contents) { - if (containsGenerateContentRequest) { - throw new GoogleGenerativeAIRequestInputError("CountTokensRequest must have one of contents or generateContentRequest, not both."); - } - formattedGenerateContentRequest.contents = params.contents; - } - else if (containsGenerateContentRequest) { - formattedGenerateContentRequest = Object.assign(Object.assign({}, formattedGenerateContentRequest), params.generateContentRequest); - } - else { - // Array or string - const content = formatNewContent(params); - formattedGenerateContentRequest.contents = [content]; - } - return { generateContentRequest: formattedGenerateContentRequest }; -} -function formatGenerateContentInput(params) { - let formattedRequest; - if (params.contents) { - formattedRequest = params; - } - else { - // Array or string - const content = formatNewContent(params); - formattedRequest = { contents: [content] }; - } - if (params.systemInstruction) { - formattedRequest.systemInstruction = formatSystemInstruction(params.systemInstruction); - } - return formattedRequest; -} -function formatEmbedContentInput(params) { - if (typeof params === "string" || Array.isArray(params)) { - const content = formatNewContent(params); - return { content }; - } - return params; -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -// https://ai.google.dev/api/rest/v1beta/Content#part -const VALID_PART_FIELDS = [ - "text", - "inlineData", - "functionCall", - "functionResponse", - "executableCode", - "codeExecutionResult", -]; -const VALID_PARTS_PER_ROLE = { - user: ["text", "inlineData"], - function: ["functionResponse"], - model: ["text", "functionCall", "executableCode", "codeExecutionResult"], - // System instructions shouldn't be in history anyway. - system: ["text"], -}; -function validateChatHistory(history) { - let prevContent = false; - for (const currContent of history) { - const { role, parts } = currContent; - if (!prevContent && role !== "user") { - throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`); - } - if (!POSSIBLE_ROLES.includes(role)) { - throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`); - } - if (!Array.isArray(parts)) { - throw new GoogleGenerativeAIError("Content should have 'parts' property with an array of Parts"); - } - if (parts.length === 0) { - throw new GoogleGenerativeAIError("Each Content should have at least one part"); - } - const countFields = { - text: 0, - inlineData: 0, - functionCall: 0, - functionResponse: 0, - fileData: 0, - executableCode: 0, - codeExecutionResult: 0, - }; - for (const part of parts) { - for (const key of VALID_PART_FIELDS) { - if (key in part) { - countFields[key] += 1; - } - } - } - const validParts = VALID_PARTS_PER_ROLE[role]; - for (const key of VALID_PART_FIELDS) { - if (!validParts.includes(key) && countFields[key] > 0) { - throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`); - } - } - prevContent = true; - } -} -/** - * Returns true if the response is valid (could be appended to the history), flase otherwise. - */ -function isValidResponse(response) { - var _a; - if (response.candidates === undefined || response.candidates.length === 0) { - return false; - } - const content = (_a = response.candidates[0]) === null || _a === void 0 ? void 0 : _a.content; - if (content === undefined) { - return false; - } - if (content.parts === undefined || content.parts.length === 0) { - return false; - } - for (const part of content.parts) { - if (part === undefined || Object.keys(part).length === 0) { - return false; - } - if (part.text !== undefined && part.text === "") { - return false; - } - } - return true; -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Do not log a message for this error. - */ -const SILENT_ERROR = "SILENT_ERROR"; +import { PRAnalyzerAgent } from './agents/pr-analyzer-agent.js'; +const provider = (process.env.AI_PROVIDER || 'anthropic').toLowerCase(); +const apiKey = process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY || process.env.GOOGLE_API_KEY; +const model = process.env.AI_MODEL; /** - * ChatSession class that enables sending chat messages and stores - * history of sent and received messages so far. - * - * @public + * Format agent analysis result for GitHub comment */ -class ChatSession { - constructor(apiKey, model, params, _requestOptions = {}) { - this.model = model; - this.params = params; - this._requestOptions = _requestOptions; - this._history = []; - this._sendPromise = Promise.resolve(); - this._apiKey = apiKey; - if (params === null || params === void 0 ? void 0 : params.history) { - validateChatHistory(params.history); - this._history = params.history; - } - } - /** - * Gets the chat history so far. Blocked prompts are not added to history. - * Blocked candidates are not added to history, nor are the prompts that - * generated them. - */ - async getHistory() { - await this._sendPromise; - return this._history; - } - /** - * Sends a chat message and receives a non-streaming - * {@link GenerateContentResult}. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async sendMessage(request, requestOptions = {}) { - var _a, _b, _c, _d, _e, _f; - await this._sendPromise; - const newContent = formatNewContent(request); - const generateContentRequest = { - safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings, - generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig, - tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools, - toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig, - systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction, - cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent, - contents: [...this._history, newContent], - }; - const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - let finalResult; - // Add onto the chain. - this._sendPromise = this._sendPromise - .then(() => generateContent(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions)) - .then((result) => { - var _a; - if (isValidResponse(result.response)) { - this._history.push(newContent); - const responseContent = Object.assign({ parts: [], - // Response seems to come back without a role set. - role: "model" }, (_a = result.response.candidates) === null || _a === void 0 ? void 0 : _a[0].content); - this._history.push(responseContent); - } - else { - const blockErrorMessage = formatBlockErrorMessage(result.response); - if (blockErrorMessage) { - console.warn(`sendMessage() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`); - } - } - finalResult = result; - }) - .catch((e) => { - // Resets _sendPromise to avoid subsequent calls failing and throw error. - this._sendPromise = Promise.resolve(); - throw e; - }); - await this._sendPromise; - return finalResult; +function formatAnalysisForGitHub(result) { + let output = ''; + // Summary + if (result.summary) { + output += `### 📋 Summary\n${result.summary}\n\n`; } - /** - * Sends a chat message and receives the response as a - * {@link GenerateContentStreamResult} containing an iterable stream - * and a response promise. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async sendMessageStream(request, requestOptions = {}) { - var _a, _b, _c, _d, _e, _f; - await this._sendPromise; - const newContent = formatNewContent(request); - const generateContentRequest = { - safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings, - generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig, - tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools, - toolConfig: (_d = this.params) === null || _d === void 0 ? void 0 : _d.toolConfig, - systemInstruction: (_e = this.params) === null || _e === void 0 ? void 0 : _e.systemInstruction, - cachedContent: (_f = this.params) === null || _f === void 0 ? void 0 : _f.cachedContent, - contents: [...this._history, newContent], - }; - const chatSessionRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - const streamPromise = generateContentStream(this._apiKey, this.model, generateContentRequest, chatSessionRequestOptions); - // Add onto the chain. - this._sendPromise = this._sendPromise - .then(() => streamPromise) - // This must be handled to avoid unhandled rejection, but jump - // to the final catch block with a label to not log this error. - .catch((_ignored) => { - throw new Error(SILENT_ERROR); - }) - .then((streamResult) => streamResult.response) - .then((response) => { - if (isValidResponse(response)) { - this._history.push(newContent); - const responseContent = Object.assign({}, response.candidates[0].content); - // Response seems to come back without a role set. - if (!responseContent.role) { - responseContent.role = "model"; - } - this._history.push(responseContent); - } - else { - const blockErrorMessage = formatBlockErrorMessage(response); - if (blockErrorMessage) { - console.warn(`sendMessageStream() was unsuccessful. ${blockErrorMessage}. Inspect response object for details.`); - } - } - }) - .catch((e) => { - // Errors in streamPromise are already catchable by the user as - // streamPromise is returned. - // Avoid duplicating the error message in logs. - if (e.message !== SILENT_ERROR) { - // Users do not have access to _sendPromise to catch errors - // downstream from streamPromise, so they should not throw. - console.error(e); - } + // Risks + if (result.overallRisks && result.overallRisks.length > 0) { + output += `### ⚠️ Risks Identified\n`; + result.overallRisks.forEach((risk, i) => { + output += `${i + 1}. ${risk}\n`; }); - return streamPromise; - } -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -async function countTokens(apiKey, model, params, singleRequestOptions) { - const response = await makeModelRequest(model, Task.COUNT_TOKENS, apiKey, false, JSON.stringify(params), singleRequestOptions); - return response.json(); -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -async function embedContent(apiKey, model, params, requestOptions) { - const response = await makeModelRequest(model, Task.EMBED_CONTENT, apiKey, false, JSON.stringify(params), requestOptions); - return response.json(); -} -async function batchEmbedContents(apiKey, model, params, requestOptions) { - const requestsWithModel = params.requests.map((request) => { - return Object.assign(Object.assign({}, request), { model }); - }); - const response = await makeModelRequest(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, JSON.stringify({ requests: requestsWithModel }), requestOptions); - return response.json(); -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Class for generative model APIs. - * @public - */ -class GenerativeModel { - constructor(apiKey, modelParams, _requestOptions = {}) { - this.apiKey = apiKey; - this._requestOptions = _requestOptions; - if (modelParams.model.includes("/")) { - // Models may be named "models/model-name" or "tunedModels/model-name" - this.model = modelParams.model; - } - else { - // If path is not included, assume it's a non-tuned model. - this.model = `models/${modelParams.model}`; - } - this.generationConfig = modelParams.generationConfig || {}; - this.safetySettings = modelParams.safetySettings || []; - this.tools = modelParams.tools; - this.toolConfig = modelParams.toolConfig; - this.systemInstruction = formatSystemInstruction(modelParams.systemInstruction); - this.cachedContent = modelParams.cachedContent; - } - /** - * Makes a single non-streaming call to the model - * and returns an object containing a single {@link GenerateContentResponse}. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async generateContent(request, requestOptions = {}) { - var _a; - const formattedParams = formatGenerateContentInput(request); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions); - } - /** - * Makes a single streaming call to the model and returns an object - * containing an iterable stream that iterates over all chunks in the - * streaming response as well as a promise that returns the final - * aggregated response. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async generateContentStream(request, requestOptions = {}) { - var _a; - const formattedParams = formatGenerateContentInput(request); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, formattedParams), generativeModelRequestOptions); + output += '\n'; } - /** - * Gets a new {@link ChatSession} instance which can be used for - * multi-turn chats. - */ - startChat(startChatParams) { - var _a; - return new ChatSession(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools, toolConfig: this.toolConfig, systemInstruction: this.systemInstruction, cachedContent: (_a = this.cachedContent) === null || _a === void 0 ? void 0 : _a.name }, startChatParams), this._requestOptions); + // Complexity + if (result.overallComplexity) { + output += `### 📊 Complexity Score: ${result.overallComplexity}/5\n\n`; } - /** - * Counts the tokens in the provided request. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async countTokens(request, requestOptions = {}) { - const formattedParams = formatCountTokensInput(request, { - model: this.model, - generationConfig: this.generationConfig, - safetySettings: this.safetySettings, - tools: this.tools, - toolConfig: this.toolConfig, - systemInstruction: this.systemInstruction, - cachedContent: this.cachedContent, + // Recommendations + if (result.recommendations && result.recommendations.length > 0) { + output += `### 💡 Recommendations\n`; + result.recommendations.forEach((rec, i) => { + output += `${i + 1}. ${rec}\n`; }); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return countTokens(this.apiKey, this.model, formattedParams, generativeModelRequestOptions); - } - /** - * Embeds the provided content. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async embedContent(request, requestOptions = {}) { - const formattedParams = formatEmbedContentInput(request); - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return embedContent(this.apiKey, this.model, formattedParams, generativeModelRequestOptions); - } - /** - * Embeds an array of {@link EmbedContentRequest}s. - * - * Fields set in the optional {@link SingleRequestOptions} parameter will - * take precedence over the {@link RequestOptions} values provided to - * {@link GoogleGenerativeAI.getGenerativeModel }. - */ - async batchEmbedContents(batchEmbedContentRequest, requestOptions = {}) { - const generativeModelRequestOptions = Object.assign(Object.assign({}, this._requestOptions), requestOptions); - return batchEmbedContents(this.apiKey, this.model, batchEmbedContentRequest, generativeModelRequestOptions); - } -} - -/** - * @license - * Copyright 2024 Google LLC - * - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - */ -/** - * Top-level class for this SDK - * @public - */ -class GoogleGenerativeAI { - constructor(apiKey) { - this.apiKey = apiKey; - } - /** - * Gets a {@link GenerativeModel} instance for the provided model name. - */ - getGenerativeModel(modelParams, requestOptions) { - if (!modelParams.model) { - throw new GoogleGenerativeAIError(`Must provide a model name. ` + - `Example: genai.getGenerativeModel({ model: 'my-model-name' })`); - } - return new GenerativeModel(this.apiKey, modelParams, requestOptions); + output += '\n'; } - /** - * Creates a {@link GenerativeModel} instance from provided content cache. - */ - getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions) { - if (!cachedContent.name) { - throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `name` field."); - } - if (!cachedContent.model) { - throw new GoogleGenerativeAIRequestInputError("Cached content must contain a `model` field."); - } - /** - * Not checking tools and toolConfig for now as it would require a deep - * equality comparison and isn't likely to be a common case. - */ - const disallowedDuplicates = ["model", "systemInstruction"]; - for (const key of disallowedDuplicates) { - if ((modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) && - cachedContent[key] && - (modelParams === null || modelParams === void 0 ? void 0 : modelParams[key]) !== cachedContent[key]) { - if (key === "model") { - const modelParamsComp = modelParams.model.startsWith("models/") - ? modelParams.model.replace("models/", "") - : modelParams.model; - const cachedContentComp = cachedContent.model.startsWith("models/") - ? cachedContent.model.replace("models/", "") - : cachedContent.model; - if (modelParamsComp === cachedContentComp) { - continue; - } + // File-level details (top 5 most complex) + if (result.fileAnalyses && result.fileAnalyses.size > 0) { + const files = Array.from(result.fileAnalyses.entries()); + const sortedFiles = files + .sort((a, b) => b[1].complexity - a[1].complexity) + .slice(0, 5); + if (sortedFiles.length > 0) { + output += `### 📁 Files of Interest\n`; + sortedFiles.forEach(([path, analysis]) => { + output += `- **${path}** (complexity: ${analysis.complexity}/5)\n`; + if (analysis.risks && analysis.risks.length > 0) { + output += ` - ⚠️ ${analysis.risks.join(', ')}\n`; } - throw new GoogleGenerativeAIRequestInputError(`Different value for "${key}" specified in modelParams` + - ` (${modelParams[key]}) and cachedContent (${cachedContent[key]})`); - } - } - const modelParamsFromCache = Object.assign(Object.assign({}, modelParams), { model: cachedContent.model, tools: cachedContent.tools, toolConfig: cachedContent.toolConfig, systemInstruction: cachedContent.systemInstruction, cachedContent }); - return new GenerativeModel(this.apiKey, modelParamsFromCache, requestOptions); - } -} - - -//# sourceMappingURL=index.mjs.map - -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/utils/tools.js - - - - - - -//#region src/utils/tools.ts -function convertToolsToGenAI(tools, extra) { - const genAITools = processTools(tools); - const toolConfig = createToolConfig(genAITools, extra); - return { - tools: genAITools, - toolConfig - }; -} -function processTools(tools) { - let functionDeclarationTools = []; - const genAITools = []; - tools.forEach((tool) => { - if (isLangChainTool(tool)) { - const [convertedTool] = convertToGenerativeAITools([tool]); - if (convertedTool.functionDeclarations) functionDeclarationTools.push(...convertedTool.functionDeclarations); - } else if (isOpenAITool(tool)) { - const { functionDeclarations } = convertOpenAIToolToGenAI(tool); - if (functionDeclarations) functionDeclarationTools.push(...functionDeclarations); - else throw new Error("Failed to convert OpenAI structured tool to GenerativeAI tool"); - } else genAITools.push(tool); - }); - const genAIFunctionDeclaration = genAITools.find((t) => "functionDeclarations" in t); - if (genAIFunctionDeclaration) return genAITools.map((tool) => { - if (functionDeclarationTools?.length > 0 && "functionDeclarations" in tool) { - const newTool = { functionDeclarations: [...tool.functionDeclarations || [], ...functionDeclarationTools] }; - functionDeclarationTools = []; - return newTool; - } - return tool; - }); - return [...genAITools, ...functionDeclarationTools.length > 0 ? [{ functionDeclarations: functionDeclarationTools }] : []]; -} -function convertOpenAIToolToGenAI(tool) { - return { functionDeclarations: [{ - name: tool.function.name, - description: tool.function.description, - parameters: removeAdditionalProperties(tool.function.parameters) - }] }; -} -function createToolConfig(genAITools, extra) { - if (!genAITools.length || !extra) return void 0; - const { toolChoice, allowedFunctionNames } = extra; - const modeMap = { - any: FunctionCallingMode.ANY, - auto: FunctionCallingMode.AUTO, - none: FunctionCallingMode.NONE - }; - if (toolChoice && [ - "any", - "auto", - "none" - ].includes(toolChoice)) return { functionCallingConfig: { - mode: modeMap[toolChoice] ?? "MODE_UNSPECIFIED", - allowedFunctionNames - } }; - if (typeof toolChoice === "string" || allowedFunctionNames) return { functionCallingConfig: { - mode: FunctionCallingMode.ANY, - allowedFunctionNames: [...allowedFunctionNames ?? [], ...toolChoice && typeof toolChoice === "string" ? [toolChoice] : []] - } }; - return void 0; -} - -//#endregion - -//# sourceMappingURL=tools.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/profiles.js -//#region src/profiles.ts -const dist_profiles_PROFILES = { - "gemini-embedding-001": { - maxInputTokens: 2048, - imageInputs: false, - audioInputs: false, - pdfInputs: false, - videoInputs: false, - maxOutputTokens: 3072, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: false, - structuredOutput: false - }, - "gemini-2.5-flash-image": { - maxInputTokens: 32768, - imageInputs: true, - audioInputs: false, - pdfInputs: false, - videoInputs: false, - maxOutputTokens: 32768, - reasoningOutput: true, - imageOutputs: true, - audioOutputs: false, - videoOutputs: false, - toolCalling: false, - structuredOutput: false - }, - "gemini-2.5-flash-preview-05-20": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-flash-lite-latest": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-2.5-flash": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-flash-latest": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-2.5-pro-preview-05-06": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-2.5-flash-preview-tts": { - maxInputTokens: 8e3, - imageInputs: false, - audioInputs: false, - pdfInputs: false, - videoInputs: false, - maxOutputTokens: 16e3, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: true, - videoOutputs: false, - toolCalling: false, - structuredOutput: false - }, - "gemini-2.0-flash-lite": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-live-2.5-flash-preview-native-audio": { - maxInputTokens: 131072, - imageInputs: false, - audioInputs: true, - pdfInputs: false, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: true, - videoOutputs: false, - toolCalling: true, - structuredOutput: false - }, - "gemini-2.0-flash": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-2.5-flash-lite": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-2.5-pro-preview-06-05": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-live-2.5-flash": { - maxInputTokens: 128e3, - imageInputs: true, - audioInputs: true, - pdfInputs: false, - videoInputs: true, - maxOutputTokens: 8e3, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: true, - videoOutputs: false, - toolCalling: true, - structuredOutput: false - }, - "gemini-2.5-flash-lite-preview-06-17": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false - }, - "gemini-2.5-flash-image-preview": { - maxInputTokens: 32768, - imageInputs: true, - audioInputs: false, - pdfInputs: false, - videoInputs: false, - maxOutputTokens: 32768, - reasoningOutput: true, - imageOutputs: true, - audioOutputs: false, - videoOutputs: false, - toolCalling: false, - structuredOutput: false - }, - "gemini-2.5-flash-preview-09-2025": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-2.5-flash-preview-04-17": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false - }, - "gemini-2.5-pro-preview-tts": { - maxInputTokens: 8e3, - imageInputs: false, - audioInputs: false, - pdfInputs: false, - videoInputs: false, - maxOutputTokens: 16e3, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: true, - videoOutputs: false, - toolCalling: false, - structuredOutput: false - }, - "gemini-2.5-pro": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-1.5-flash": { - maxInputTokens: 1e6, - imageInputs: true, - audioInputs: true, - pdfInputs: false, - videoInputs: true, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false - }, - "gemini-1.5-flash-8b": { - maxInputTokens: 1e6, - imageInputs: true, - audioInputs: true, - pdfInputs: false, - videoInputs: true, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false - }, - "gemini-2.5-flash-lite-preview-09-2025": { - maxInputTokens: 1048576, - imageInputs: true, - audioInputs: true, - pdfInputs: true, - videoInputs: true, - maxOutputTokens: 65536, - reasoningOutput: true, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: true - }, - "gemini-1.5-pro": { - maxInputTokens: 1e6, - imageInputs: true, - audioInputs: true, - pdfInputs: false, - videoInputs: true, - maxOutputTokens: 8192, - reasoningOutput: false, - imageOutputs: false, - audioOutputs: false, - videoOutputs: false, - toolCalling: true, - structuredOutput: false - } -}; -var dist_profiles_profiles_default = dist_profiles_PROFILES; - -//#endregion - -//# sourceMappingURL=profiles.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/chat_models.js - - - - - - - - - - - - -//#region src/chat_models.ts -/** -* Google Generative AI chat model integration. -* -* Setup: -* Install `@langchain/google-genai` and set an environment variable named `GOOGLE_API_KEY`. -* -* ```bash -* npm install @langchain/google-genai -* export GOOGLE_API_KEY="your-api-key" -* ``` -* -* ## [Constructor args](https://api.js.langchain.com/classes/langchain_google_genai.ChatGoogleGenerativeAI.html#constructor) -* -* ## [Runtime args](https://api.js.langchain.com/interfaces/langchain_google_genai.GoogleGenerativeAIChatCallOptions.html) -* -* Runtime args can be passed as the second argument to any of the base runnable methods `.invoke`. `.stream`, `.batch`, etc. -* They can also be passed via `.withConfig`, or the second arg in `.bindTools`, like shown in the examples below: -* -* ```typescript -* // When calling `.withConfig`, call options should be passed via the first argument -* const llmWithArgsBound = llm.withConfig({ -* stop: ["\n"], -* }); -* -* // When calling `.bindTools`, call options should be passed via the second argument -* const llmWithTools = llm.bindTools( -* [...], -* { -* stop: ["\n"], -* } -* ); -* ``` -* -* ## Examples -* -*
-* Instantiate -* -* ```typescript -* import { ChatGoogleGenerativeAI } from '@langchain/google-genai'; -* -* const llm = new ChatGoogleGenerativeAI({ -* model: "gemini-1.5-flash", -* temperature: 0, -* maxRetries: 2, -* // apiKey: "...", -* // other params... -* }); -* ``` -*
-* -*
-* -*
-* Invoking -* -* ```typescript -* const input = `Translate "I love programming" into French.`; -* -* // Models also accept a list of chat messages or a formatted prompt -* const result = await llm.invoke(input); -* console.log(result); -* ``` -* -* ```txt -* AIMessage { -* "content": "There are a few ways to translate \"I love programming\" into French, depending on the level of formality and nuance you want to convey:\n\n**Formal:**\n\n* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and your intended audience. \n", -* "response_metadata": { -* "finishReason": "STOP", -* "index": 0, -* "safetyRatings": [ -* { -* "category": "HARM_CATEGORY_SEXUALLY_EXPLICIT", -* "probability": "NEGLIGIBLE" -* }, -* { -* "category": "HARM_CATEGORY_HATE_SPEECH", -* "probability": "NEGLIGIBLE" -* }, -* { -* "category": "HARM_CATEGORY_HARASSMENT", -* "probability": "NEGLIGIBLE" -* }, -* { -* "category": "HARM_CATEGORY_DANGEROUS_CONTENT", -* "probability": "NEGLIGIBLE" -* } -* ] -* }, -* "usage_metadata": { -* "input_tokens": 10, -* "output_tokens": 149, -* "total_tokens": 159 -* } -* } -* ``` -*
-* -*
-* -*
-* Streaming Chunks -* -* ```typescript -* for await (const chunk of await llm.stream(input)) { -* console.log(chunk); -* } -* ``` -* -* ```txt -* AIMessageChunk { -* "content": "There", -* "response_metadata": { -* "index": 0 -* } -* "usage_metadata": { -* "input_tokens": 10, -* "output_tokens": 1, -* "total_tokens": 11 -* } -* } -* AIMessageChunk { -* "content": " are a few ways to translate \"I love programming\" into French, depending on", -* } -* AIMessageChunk { -* "content": " the level of formality and nuance you want to convey:\n\n**Formal:**\n\n", -* } -* AIMessageChunk { -* "content": "* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This", -* } -* AIMessageChunk { -* "content": " is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More", -* } -* AIMessageChunk { -* "content": " specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and", -* } -* AIMessageChunk { -* "content": " your intended audience. \n", -* } -* ``` -*
-* -*
-* -*
-* Aggregate Streamed Chunks -* -* ```typescript -* import { AIMessageChunk } from '@langchain/core/messages'; -* import { concat } from '@langchain/core/utils/stream'; -* -* const stream = await llm.stream(input); -* let full: AIMessageChunk | undefined; -* for await (const chunk of stream) { -* full = !full ? chunk : concat(full, chunk); -* } -* console.log(full); -* ``` -* -* ```txt -* AIMessageChunk { -* "content": "There are a few ways to translate \"I love programming\" into French, depending on the level of formality and nuance you want to convey:\n\n**Formal:**\n\n* **J'aime la programmation.** (This is the most literal and formal translation.)\n\n**Informal:**\n\n* **J'adore programmer.** (This is a more enthusiastic and informal translation.)\n* **J'aime beaucoup programmer.** (This is a slightly less enthusiastic but still informal translation.)\n\n**More specific:**\n\n* **J'aime beaucoup coder.** (This specifically refers to writing code.)\n* **J'aime beaucoup développer des logiciels.** (This specifically refers to developing software.)\n\nThe best translation will depend on the context and your intended audience. \n", -* "usage_metadata": { -* "input_tokens": 10, -* "output_tokens": 277, -* "total_tokens": 287 -* } -* } -* ``` -*
-* -*
-* -*
-* Bind tools -* -* ```typescript -* import { z } from 'zod'; -* -* const GetWeather = { -* name: "GetWeather", -* description: "Get the current weather in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const GetPopulation = { -* name: "GetPopulation", -* description: "Get the current population in a given location", -* schema: z.object({ -* location: z.string().describe("The city and state, e.g. San Francisco, CA") -* }), -* } -* -* const llmWithTools = llm.bindTools([GetWeather, GetPopulation]); -* const aiMsg = await llmWithTools.invoke( -* "Which city is hotter today and which is bigger: LA or NY?" -* ); -* console.log(aiMsg.tool_calls); -* ``` -* -* ```txt -* [ -* { -* name: 'GetWeather', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call' -* }, -* { -* name: 'GetWeather', -* args: { location: 'New York, NY' }, -* type: 'tool_call' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'Los Angeles, CA' }, -* type: 'tool_call' -* }, -* { -* name: 'GetPopulation', -* args: { location: 'New York, NY' }, -* type: 'tool_call' -* } -* ] -* ``` -*
-* -*
-* -*
-* Structured Output -* -* ```typescript -* const Joke = z.object({ -* setup: z.string().describe("The setup of the joke"), -* punchline: z.string().describe("The punchline to the joke"), -* rating: z.number().optional().describe("How funny the joke is, from 1 to 10") -* }).describe('Joke to tell user.'); -* -* const structuredLlm = llm.withStructuredOutput(Joke, { name: "Joke" }); -* const jokeResult = await structuredLlm.invoke("Tell me a joke about cats"); -* console.log(jokeResult); -* ``` -* -* ```txt -* { -* setup: "Why don\\'t cats play poker?", -* punchline: "Why don\\'t cats play poker? Because they always have an ace up their sleeve!" -* } -* ``` -*
-* -*
-* -*
-* Multimodal -* -* ```typescript -* import { HumanMessage } from '@langchain/core/messages'; -* -* const imageUrl = "https://example.com/image.jpg"; -* const imageData = await fetch(imageUrl).then(res => res.arrayBuffer()); -* const base64Image = Buffer.from(imageData).toString('base64'); -* -* const message = new HumanMessage({ -* content: [ -* { type: "text", text: "describe the weather in this image" }, -* { -* type: "image_url", -* image_url: { url: `data:image/jpeg;base64,${base64Image}` }, -* }, -* ] -* }); -* -* const imageDescriptionAiMsg = await llm.invoke([message]); -* console.log(imageDescriptionAiMsg.content); -* ``` -* -* ```txt -* The weather in the image appears to be clear and sunny. The sky is mostly blue with a few scattered white clouds, indicating fair weather. The bright sunlight is casting shadows on the green, grassy hill, suggesting it is a pleasant day with good visibility. There are no signs of rain or stormy conditions. -* ``` -*
-* -*
-* -*
-* Usage Metadata -* -* ```typescript -* const aiMsgForMetadata = await llm.invoke(input); -* console.log(aiMsgForMetadata.usage_metadata); -* ``` -* -* ```txt -* { input_tokens: 10, output_tokens: 149, total_tokens: 159 } -* ``` -*
-* -*
-* -*
-* Response Metadata -* -* ```typescript -* const aiMsgForResponseMetadata = await llm.invoke(input); -* console.log(aiMsgForResponseMetadata.response_metadata); -* ``` -* -* ```txt -* { -* finishReason: 'STOP', -* index: 0, -* safetyRatings: [ -* { -* category: 'HARM_CATEGORY_SEXUALLY_EXPLICIT', -* probability: 'NEGLIGIBLE' -* }, -* { -* category: 'HARM_CATEGORY_HATE_SPEECH', -* probability: 'NEGLIGIBLE' -* }, -* { category: 'HARM_CATEGORY_HARASSMENT', probability: 'NEGLIGIBLE' }, -* { -* category: 'HARM_CATEGORY_DANGEROUS_CONTENT', -* probability: 'NEGLIGIBLE' -* } -* ] -* } -* ``` -*
-* -*
-* -*
-* Document Messages -* -* This example will show you how to pass documents such as PDFs to Google -* Generative AI through messages. -* -* ```typescript -* const pdfPath = "/Users/my_user/Downloads/invoice.pdf"; -* const pdfBase64 = await fs.readFile(pdfPath, "base64"); -* -* const response = await llm.invoke([ -* ["system", "Use the provided documents to answer the question"], -* [ -* "user", -* [ -* { -* type: "application/pdf", // If the `type` field includes a single slash (`/`), it will be treated as inline data. -* data: pdfBase64, -* }, -* { -* type: "text", -* text: "Summarize the contents of this PDF", -* }, -* ], -* ], -* ]); -* -* console.log(response.content); -* ``` -* -* ```txt -* This is a billing invoice from Twitter Developers for X API Basic Access. The transaction date is January 7, 2025, -* and the amount is $194.34, which has been paid. The subscription period is from January 7, 2025 21:02 to February 7, 2025 00:00 (UTC). -* The tax is $0.00, with a tax rate of 0%. The total amount is $194.34. The payment was made using a Visa card ending in 7022, -* expiring in 12/2026. The billing address is Brace Sproul, 1234 Main Street, San Francisco, CA, US 94103. The company being billed is -* X Corp, located at 865 FM 1209 Building 2, Bastrop, TX, US 78602. Terms and conditions apply. -* ``` -*
-* -*
-*/ -var ChatGoogleGenerativeAI = class extends BaseChatModel { - static lc_name() { - return "ChatGoogleGenerativeAI"; - } - lc_serializable = true; - get lc_secrets() { - return { apiKey: "GOOGLE_API_KEY" }; - } - lc_namespace = [ - "langchain", - "chat_models", - "google_genai" - ]; - get lc_aliases() { - return { apiKey: "google_api_key" }; - } - model; - temperature; - maxOutputTokens; - topP; - topK; - stopSequences = []; - safetySettings; - apiKey; - streaming = false; - json; - streamUsage = true; - convertSystemMessageToHumanContent; - thinkingConfig; - client; - get _isMultimodalModel() { - return this.model.includes("vision") || this.model.startsWith("gemini-1.5") || this.model.startsWith("gemini-2") || this.model.startsWith("gemma-3-") && !this.model.startsWith("gemma-3-1b") || this.model.startsWith("gemini-3"); - } - constructor(fields) { - super(fields); - this.model = fields.model.replace(/^models\//, ""); - this.maxOutputTokens = fields.maxOutputTokens ?? this.maxOutputTokens; - if (this.maxOutputTokens && this.maxOutputTokens < 0) throw new Error("`maxOutputTokens` must be a positive integer"); - this.temperature = fields.temperature ?? this.temperature; - if (this.temperature && (this.temperature < 0 || this.temperature > 2)) throw new Error("`temperature` must be in the range of [0.0,2.0]"); - this.topP = fields.topP ?? this.topP; - if (this.topP && this.topP < 0) throw new Error("`topP` must be a positive integer"); - if (this.topP && this.topP > 1) throw new Error("`topP` must be below 1."); - this.topK = fields.topK ?? this.topK; - if (this.topK && this.topK < 0) throw new Error("`topK` must be a positive integer"); - this.stopSequences = fields.stopSequences ?? this.stopSequences; - this.apiKey = fields.apiKey ?? getEnvironmentVariable("GOOGLE_API_KEY"); - if (!this.apiKey) throw new Error("Please set an API key for Google GenerativeAI in the environment variable GOOGLE_API_KEY or in the `apiKey` field of the ChatGoogleGenerativeAI constructor"); - this.safetySettings = fields.safetySettings ?? this.safetySettings; - if (this.safetySettings && this.safetySettings.length > 0) { - const safetySettingsSet = new Set(this.safetySettings.map((s) => s.category)); - if (safetySettingsSet.size !== this.safetySettings.length) throw new Error("The categories in `safetySettings` array must be unique"); - } - this.streaming = fields.streaming ?? this.streaming; - this.json = fields.json; - this.thinkingConfig = fields.thinkingConfig ?? this.thinkingConfig; - this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModel({ - model: this.model, - safetySettings: this.safetySettings, - generationConfig: { - stopSequences: this.stopSequences, - maxOutputTokens: this.maxOutputTokens, - temperature: this.temperature, - topP: this.topP, - topK: this.topK, - ...this.json ? { responseMimeType: "application/json" } : {}, - ...this.thinkingConfig ? { thinkingConfig: this.thinkingConfig } : {} - } - }, { - apiVersion: fields.apiVersion, - baseUrl: fields.baseUrl, - customHeaders: fields.customHeaders - }); - this.streamUsage = fields.streamUsage ?? this.streamUsage; - } - useCachedContent(cachedContent, modelParams, requestOptions) { - if (!this.apiKey) return; - this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModelFromCachedContent(cachedContent, modelParams, requestOptions); - } - get useSystemInstruction() { - return typeof this.convertSystemMessageToHumanContent === "boolean" ? !this.convertSystemMessageToHumanContent : this.computeUseSystemInstruction; - } - get computeUseSystemInstruction() { - if (this.model === "gemini-1.0-pro-001") return false; - else if (this.model.startsWith("gemini-pro-vision")) return false; - else if (this.model.startsWith("gemini-1.0-pro-vision")) return false; - else if (this.model === "gemini-pro") return false; - return true; - } - getLsParams(options) { - return { - ls_provider: "google_genai", - ls_model_name: this.model, - ls_model_type: "chat", - ls_temperature: this.client.generationConfig.temperature, - ls_max_tokens: this.client.generationConfig.maxOutputTokens, - ls_stop: options.stop - }; - } - _combineLLMOutput() { - return []; - } - _llmType() { - return "googlegenerativeai"; - } - bindTools(tools, kwargs) { - return this.withConfig({ - tools: convertToolsToGenAI(tools)?.tools, - ...kwargs - }); - } - invocationParams(options) { - const toolsAndConfig = options?.tools?.length ? convertToolsToGenAI(options.tools, { - toolChoice: options.tool_choice, - allowedFunctionNames: options.allowedFunctionNames - }) : void 0; - if (options?.responseSchema) { - this.client.generationConfig.responseSchema = options.responseSchema; - this.client.generationConfig.responseMimeType = "application/json"; - } else { - this.client.generationConfig.responseSchema = void 0; - this.client.generationConfig.responseMimeType = this.json ? "application/json" : void 0; - } - return { - ...toolsAndConfig?.tools ? { tools: toolsAndConfig.tools } : {}, - ...toolsAndConfig?.toolConfig ? { toolConfig: toolsAndConfig.toolConfig } : {} - }; - } - async _generate(messages, options, runManager) { - const prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction, this.model); - let actualPrompt = prompt; - if (prompt[0].role === "system") { - const [systemInstruction] = prompt; - this.client.systemInstruction = systemInstruction; - actualPrompt = prompt.slice(1); - } - const parameters = this.invocationParams(options); - if (this.streaming) { - const tokenUsage = {}; - const stream = this._streamResponseChunks(messages, options, runManager); - const finalChunks = {}; - for await (const chunk of stream) { - const index = chunk.generationInfo?.completion ?? 0; - if (finalChunks[index] === void 0) finalChunks[index] = chunk; - else finalChunks[index] = finalChunks[index].concat(chunk); - } - const generations = Object.entries(finalChunks).sort(([aKey], [bKey]) => parseInt(aKey, 10) - parseInt(bKey, 10)).map(([_, value]) => value); - return { - generations, - llmOutput: { estimatedTokenUsage: tokenUsage } - }; - } - const res = await this.completionWithRetry({ - ...parameters, - contents: actualPrompt - }); - let usageMetadata; - if ("usageMetadata" in res.response) usageMetadata = convertUsageMetadata(res.response.usageMetadata, this.model); - const generationResult = mapGenerateContentResultToChatResult(res.response, { usageMetadata }); - if (generationResult.generations?.length > 0) await runManager?.handleLLMNewToken(generationResult.generations[0]?.text ?? ""); - return generationResult; - } - async *_streamResponseChunks(messages, options, runManager) { - const prompt = convertBaseMessagesToContent(messages, this._isMultimodalModel, this.useSystemInstruction, this.model); - let actualPrompt = prompt; - if (prompt[0].role === "system") { - const [systemInstruction] = prompt; - this.client.systemInstruction = systemInstruction; - actualPrompt = prompt.slice(1); - } - const parameters = this.invocationParams(options); - const request = { - ...parameters, - contents: actualPrompt - }; - const stream = await this.caller.callWithOptions({ signal: options?.signal }, async () => { - const { stream: stream$1 } = await this.client.generateContentStream(request); - return stream$1; - }); - let usageMetadata; - let prevPromptTokenCount = 0; - let prevCandidatesTokenCount = 0; - let prevTotalTokenCount = 0; - let index = 0; - for await (const response of stream) { - if ("usageMetadata" in response && response.usageMetadata !== void 0 && this.streamUsage !== false && options.streamUsage !== false) { - usageMetadata = convertUsageMetadata(response.usageMetadata, this.model); - const newPromptTokenCount = response.usageMetadata.promptTokenCount ?? 0; - usageMetadata.input_tokens = Math.max(0, newPromptTokenCount - prevPromptTokenCount); - prevPromptTokenCount = newPromptTokenCount; - const newCandidatesTokenCount = response.usageMetadata.candidatesTokenCount ?? 0; - usageMetadata.output_tokens = Math.max(0, newCandidatesTokenCount - prevCandidatesTokenCount); - prevCandidatesTokenCount = newCandidatesTokenCount; - const newTotalTokenCount = response.usageMetadata.totalTokenCount ?? 0; - usageMetadata.total_tokens = Math.max(0, newTotalTokenCount - prevTotalTokenCount); - prevTotalTokenCount = newTotalTokenCount; - } - const chunk = convertResponseContentToChatGenerationChunk(response, { - usageMetadata, - index - }); - index += 1; - if (!chunk) continue; - yield chunk; - await runManager?.handleLLMNewToken(chunk.text ?? ""); - } - } - async completionWithRetry(request, options) { - return this.caller.callWithOptions({ signal: options?.signal }, async () => { - try { - return await this.client.generateContent(request); - } catch (e) { - if (e.message?.includes("400 Bad Request")) e.status = 400; - throw e; - } - }); - } - /** - * Return profiling information for the model. - * - * Provides information about the model's capabilities and constraints, - * including token limits, multimodal support, and advanced features like - * tool calling and structured output. - * - * @returns {ModelProfile} An object describing the model's capabilities and constraints - * - * @example - * ```typescript - * const model = new ChatGoogleGenerativeAI({ model: "gemini-1.5-flash" }); - * const profile = model.profile; - * console.log(profile.maxInputTokens); // 2000000 - * console.log(profile.imageInputs); // true - * ``` - */ - get profile() { - return dist_profiles_profiles_default[this.model] ?? {}; - } - withStructuredOutput(outputSchema, config) { - const schema = outputSchema; - const name = config?.name; - const method = config?.method; - const includeRaw = config?.includeRaw; - if (method === "jsonMode") throw new Error(`ChatGoogleGenerativeAI only supports "jsonSchema" or "functionCalling" as a method.`); - let llm; - let outputParser; - if (method === "functionCalling") { - let functionName = name ?? "extract"; - let tools; - if (isInteropZodSchema(schema)) { - const jsonSchema = schemaToGenerativeAIParameters(schema); - tools = [{ functionDeclarations: [{ - name: functionName, - description: jsonSchema.description ?? "A function available to call.", - parameters: jsonSchema - }] }]; - outputParser = new GoogleGenerativeAIToolsOutputParser({ - returnSingle: true, - keyName: functionName, - zodSchema: schema - }); - } else { - let geminiFunctionDefinition; - if (typeof schema.name === "string" && typeof schema.parameters === "object" && schema.parameters != null) { - geminiFunctionDefinition = schema; - geminiFunctionDefinition.parameters = removeAdditionalProperties(schema.parameters); - functionName = schema.name; - } else geminiFunctionDefinition = { - name: functionName, - description: schema.description ?? "", - parameters: removeAdditionalProperties(schema) - }; - tools = [{ functionDeclarations: [geminiFunctionDefinition] }]; - outputParser = new GoogleGenerativeAIToolsOutputParser({ - returnSingle: true, - keyName: functionName - }); - } - llm = this.bindTools(tools).withConfig({ allowedFunctionNames: [functionName] }); - } else { - const jsonSchema = schemaToGenerativeAIParameters(schema); - llm = this.withConfig({ responseSchema: jsonSchema }); - outputParser = new JsonOutputParser(); - } - if (!includeRaw) return llm.pipe(outputParser).withConfig({ runName: "ChatGoogleGenerativeAIStructuredOutput" }); - const parserAssign = RunnablePassthrough.assign({ parsed: (input, config$1) => outputParser.invoke(input.raw, config$1) }); - const parserNone = RunnablePassthrough.assign({ parsed: () => null }); - const parsedWithFallback = parserAssign.withFallbacks({ fallbacks: [parserNone] }); - return RunnableSequence.from([{ raw: llm }, parsedWithFallback]).withConfig({ runName: "StructuredOutputRunnable" }); - } -}; - -//#endregion - -//# sourceMappingURL=chat_models.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/embeddings.js - - - - - -//#region src/embeddings.ts -/** -* Class that extends the Embeddings class and provides methods for -* generating embeddings using the Google Palm API. -* @example -* ```typescript -* const model = new GoogleGenerativeAIEmbeddings({ -* apiKey: "", -* modelName: "embedding-001", -* }); -* -* // Embed a single query -* const res = await model.embedQuery( -* "What would be a good company name for a company that makes colorful socks?" -* ); -* console.log({ res }); -* -* // Embed multiple documents -* const documentRes = await model.embedDocuments(["Hello world", "Bye bye"]); -* console.log({ documentRes }); -* ``` -*/ -var GoogleGenerativeAIEmbeddings = class extends Embeddings { - apiKey; - modelName = "embedding-001"; - model = "embedding-001"; - taskType; - title; - stripNewLines = true; - maxBatchSize = 100; - client; - constructor(fields) { - super(fields ?? {}); - this.modelName = fields?.model?.replace(/^models\//, "") ?? fields?.modelName?.replace(/^models\//, "") ?? this.modelName; - this.model = this.modelName; - this.taskType = fields?.taskType ?? this.taskType; - this.title = fields?.title ?? this.title; - if (this.title && this.taskType !== "RETRIEVAL_DOCUMENT") throw new Error("title can only be sepcified with TaskType.RETRIEVAL_DOCUMENT"); - this.apiKey = fields?.apiKey ?? getEnvironmentVariable("GOOGLE_API_KEY"); - if (!this.apiKey) throw new Error("Please set an API key for Google GenerativeAI in the environmentb variable GOOGLE_API_KEY or in the `apiKey` field of the GoogleGenerativeAIEmbeddings constructor"); - this.client = new GoogleGenerativeAI(this.apiKey).getGenerativeModel({ model: this.model }, { baseUrl: fields?.baseUrl }); - } - _convertToContent(text) { - const cleanedText = this.stripNewLines ? text.replace(/\n/g, " ") : text; - return { - content: { - role: "user", - parts: [{ text: cleanedText }] - }, - taskType: this.taskType, - title: this.title - }; - } - async _embedQueryContent(text) { - const req = this._convertToContent(text); - const res = await this.client.embedContent(req); - return res.embedding.values ?? []; - } - async _embedDocumentsContent(documents) { - const batchEmbedChunks = chunkArray(documents, this.maxBatchSize); - const batchEmbedRequests = batchEmbedChunks.map((chunk) => ({ requests: chunk.map((doc) => this._convertToContent(doc)) })); - const responses = await Promise.allSettled(batchEmbedRequests.map((req) => this.client.batchEmbedContents(req))); - const embeddings = responses.flatMap((res, idx) => { - if (res.status === "fulfilled") return res.value.embeddings.map((e) => e.values || []); - else return Array(batchEmbedChunks[idx].length).fill([]); - }); - return embeddings; - } - /** - * Method that takes a document as input and returns a promise that - * resolves to an embedding for the document. It calls the _embedText - * method with the document as the input. - * @param document Document for which to generate an embedding. - * @returns Promise that resolves to an embedding for the input document. - */ - embedQuery(document) { - return this.caller.call(this._embedQueryContent.bind(this), document); - } - /** - * Method that takes an array of documents as input and returns a promise - * that resolves to a 2D array of embeddings for each document. It calls - * the _embedText method for each document in the array. - * @param documents Array of documents for which to generate embeddings. - * @returns Promise that resolves to a 2D array of embeddings for each input document. - */ - embedDocuments(documents) { - return this.caller.call(this._embedDocumentsContent.bind(this), documents); - } -}; - -//#endregion - -//# sourceMappingURL=embeddings.js.map -;// CONCATENATED MODULE: ./node_modules/@langchain/google-genai/dist/index.js - - - - -;// CONCATENATED MODULE: ./src/providers/google.provider.ts - -/** - * Google Gemini provider implementation - */ -class GoogleProvider { - name = 'google'; - apiKey; - constructor(apiKey) { - this.apiKey = apiKey || process.env.GOOGLE_API_KEY || ''; - } - isConfigured() { - return !!this.apiKey; - } - getDefaultModel() { - return 'gemini-pro'; - } - getChatModel(config = {}) { - if (!this.isConfigured()) { - throw new Error('Google API key is not configured'); - } - return new ChatGoogleGenerativeAI({ - apiKey: this.apiKey, - model: config.model || this.getDefaultModel(), - temperature: config.temperature ?? 0.2, - maxOutputTokens: config.maxTokens ?? 4000, - }); - } -} - -;// CONCATENATED MODULE: ./src/providers/provider.factory.ts - - - -/** - * Factory for creating LLM providers - */ -class ProviderFactory { - static providers = new Map(); - /** - * Get or create a provider instance - */ - static getProvider(providerName, apiKey) { - // Normalize provider names - const normalizedName = this.normalizeProviderName(providerName); - // Check if we already have an instance (unless a specific API key is provided) - if (!apiKey && this.providers.has(normalizedName)) { - return this.providers.get(normalizedName); - } - // Create new provider instance - let provider; - switch (normalizedName) { - case 'anthropic': - provider = new AnthropicProvider(apiKey); - break; - case 'openai': - provider = new OpenAIProvider(apiKey); - break; - case 'google': - provider = new GoogleProvider(apiKey); - break; - default: - throw new Error(`Unsupported provider: ${providerName}. Supported: anthropic, openai, google`); - } - // Cache the provider if no specific API key was provided - if (!apiKey) { - this.providers.set(normalizedName, provider); - } - return provider; - } - /** - * Create a chat model with the specified options - */ - static createChatModel(options = {}) { - const providerName = options.provider || 'anthropic'; - const provider = this.getProvider(providerName, options.apiKey); - if (!provider.isConfigured()) { - throw new Error(`Provider ${providerName} is not configured. Please set the API key.`); - } - const config = { - model: options.model, - temperature: options.temperature, - maxTokens: options.maxTokens, - }; - return provider.getChatModel(config); - } - /** - * Get the default model for a provider - */ - static getDefaultModel(providerName) { - const provider = this.getProvider(providerName); - return provider.getDefaultModel(); - } - /** - * Check if a provider is configured - */ - static isProviderConfigured(providerName) { - try { - const provider = this.getProvider(providerName); - return provider.isConfigured(); - } - catch { - return false; - } - } - /** - * Normalize provider name (handle aliases) - */ - static normalizeProviderName(name) { - const normalized = name.toLowerCase(); - if (normalized === 'claude') - return 'anthropic'; - if (normalized === 'gemini') - return 'google'; - return normalized; - } - /** - * Get list of available providers - */ - static getAvailableProviders() { - return ['anthropic', 'openai', 'google']; - } -} - -;// CONCATENATED MODULE: ./src/providers/index.ts - - - - - - -;// CONCATENATED MODULE: ./src/agents/pr-analyzer-agent.ts -/** - * PR Analyzer Agent - * LangChain-based agent for intelligent PR analysis - */ - - - - - -/** - * PR Analysis Agent using LangChain and LangGraph - */ -class PRAnalyzerAgent extends BasePRAgentWorkflow { - constructor(options = {}) { - const model = ProviderFactory.createChatModel({ - provider: options.provider || 'anthropic', - apiKey: options.apiKey, - model: options.model, - temperature: options.temperature ?? 0.2, - maxTokens: options.maxTokens ?? 4000, - }); - super(model); - } - /** - * Get agent metadata - */ - getMetadata() { - return { - name: 'pr-analyzer', - version: '1.0.0', - description: 'AI-powered pull request analyzer using LangChain agent workflow', - capabilities: [ - 'file-level analysis', - 'risk detection', - 'complexity scoring', - 'intelligent recommendations', - 'self-refinement workflow', - ], - }; - } - /** - * Analyze a PR with full agent workflow - */ - async analyze(diff, title, mode, options) { - // Parse diff into files - const files = parseDiff(diff); - // Build arch-docs context if enabled - let archDocsContext = undefined; - if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) { - const docs = parseAllArchDocs(options?.repoPath); - archDocsContext = buildArchDocsContext(docs, { title, files, diff }); - } - // Create context - const context = { - diff, - title, - files, - tokenBudget: 100000, - maxCost: 5.0, - mode: mode || { summary: true, risks: true, complexity: true }, - archDocs: archDocsContext, - }; - // Execute workflow - const result = await this.execute(context, { - skipSelfRefinement: files.length < 5 || diff.length < 10000, // Skip for small PRs - }); - return result; - } - /** - * Quick analysis without refinement - */ - async quickAnalyze(diff, title, options) { - const files = parseDiff(diff); - // Build arch-docs context if enabled - let archDocsContext = undefined; - if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) { - const docs = parseAllArchDocs(options?.repoPath); - archDocsContext = buildArchDocsContext(docs, { title, files, diff }); - } - const context = { - diff, - title, - files, - tokenBudget: 50000, - maxCost: 2.0, - mode: { summary: true, risks: true, complexity: true }, - archDocs: archDocsContext, - }; - return this.execute(context, { - skipSelfRefinement: true, - }); - } - /** - * Analyze specific files only - */ - async analyzeFiles(diff, filePaths, options) { - const allFiles = parseDiff(diff); - const files = allFiles.filter(f => filePaths.includes(f.path)); - // Build arch-docs context if enabled - let archDocsContext = undefined; - if (options?.useArchDocs !== false && archDocsExists(options?.repoPath)) { - const docs = parseAllArchDocs(options?.repoPath); - archDocsContext = buildArchDocsContext(docs, { files, diff }); + }); } - const context = { - diff, - files, - tokenBudget: 50000, - maxCost: 2.0, - mode: { summary: true, risks: true, complexity: true }, - archDocs: archDocsContext, - }; - return this.execute(context, { - skipSelfRefinement: true, - }); - } - /** - * Check if agent can execute with given context - */ - async canExecute(context) { - return context.files.length > 0 && context.diff.length > 0; - } - /** - * Estimate tokens for this analysis - */ - async estimateTokens(context) { - const baseTokens = 2000; - const diffTokens = Math.ceil(context.diff.length / 4); // ~4 chars per token - const filesTokens = context.files.length * 100; - return baseTokens + diffTokens + filesTokens; } + return output; } -/** - * Factory function to create PR analyzer agent - */ -function createPRAnalyzerAgent(options = {}) { - return new PRAnalyzerAgent(options); -} -/** - * Legacy factory function for backward compatibility - * @deprecated Use PRAnalyzerAgent constructor with ProviderOptions instead - */ -function createPRAnalyzerAgentLegacy(apiKey, modelName) { - return new PRAnalyzerAgent({ - apiKey, - model: modelName, - provider: 'anthropic' - }); -} - -;// CONCATENATED MODULE: ./src/action.ts - - - -async function run() { - try { - // Get provider configuration from environment - const provider = (process.env.AI_PROVIDER || 'anthropic').toLowerCase(); - const apiKey = process.env.ANTHROPIC_API_KEY || process.env.OPENAI_API_KEY || process.env.GOOGLE_API_KEY; - const model = process.env.AI_MODEL; - const ghToken = process.env.GITHUB_TOKEN; - if (!apiKey) { - core.setFailed('AI provider API key is required (ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY)'); - return; - } - if (!ghToken) { - core.setFailed('GITHUB_TOKEN environment variable is required'); - return; - } - core.info(`Using AI provider: ${provider}${model ? ` with model: ${model}` : ''}`); - const { context } = github; +export default (app) => { + app.log.info('🤖 PR Agent (LangChain) started'); + app.on(['pull_request.opened', 'pull_request.synchronize'], async (context) => { const { pull_request: pr, repository } = context.payload; - if (!pr) { - core.setFailed('This action can only be run on pull request events'); - return; - } - core.info(`Analyzing PR #${pr.number} in ${repository?.full_name}`); - // Get PR diffs - const diff = await getPRDiffs(context, ghToken); - if (!diff) { - core.warning('No changes found in the pull request'); - return; - } - core.info(`Diff size: ${diff.length} characters`); - if (!repository) { - core.setFailed('Repository information not available'); - return; - } - // Use LangChain PRAnalyzerAgent - core.info('Running LangChain agent analysis...'); - const agent = new PRAnalyzerAgent({ - provider, - apiKey, - model, - }); - // Analyze with the LangChain agent - core.info('Parsing diff and analyzing...'); - const result = await agent.analyze(diff, pr.title); - core.info(`Analysis complete: ${result.fileAnalyses.size} files analyzed`); - // Format the summary - let summary = ''; - if (result.summary) { - summary += `### Summary\n${result.summary}\n\n`; - } - if (result.overallRisks.length > 0) { - summary += `### Potential Risks\n`; - result.overallRisks.forEach((risk) => { - if (typeof risk === 'string') { - summary += `- ${risk}\n`; - } - else if (typeof risk === 'object' && risk.description) { - summary += `- **${risk.description}**\n`; - if (risk.archDocsReference) { - summary += ` - 📚 *From ${risk.archDocsReference.source}*: "${risk.archDocsReference.excerpt}"\n`; - summary += ` - *Reason*: ${risk.archDocsReference.reason}\n`; - } - } + app.log.info(`Analyzing PR #${pr.number} in ${repository.full_name}`); + try { + app.log.info('Getting PR diffs'); + const diff = await getPRDiffs(context); + if (!apiKey) { + throw new Error('AI provider API key is not set (ANTHROPIC_API_KEY, OPENAI_API_KEY, or GOOGLE_API_KEY)'); + } + // Use LangChain agent for intelligent analysis + app.log.info(`Running LangChain agent analysis with ${provider}...`); + const agent = new PRAnalyzerAgent({ + provider: provider, + apiKey, + model, }); - summary += '\n'; - } - else { - summary += `### Potential Risks\nNone\n\n`; - } - summary += `### Complexity: ${result.overallComplexity}/5\n`; - if (result.recommendations && result.recommendations.length > 0) { - summary += `\n### Recommendations\n`; - result.recommendations.forEach((rec) => { - summary += `- ${rec}\n`; + const result = await agent.analyze(diff, pr.title); + // Format the analysis for GitHub comment + const summary = formatAnalysisForGitHub(result); + await context.octokit.issues.createComment({ + owner: repository.owner.login, + repo: repository.name, + issue_number: pr.number, + body: `## 🤖 AI Analysis (LangChain Agent)\n\n${summary}` }); + app.log.info(`Analysis posted for PR #${pr.number}`); } - // Post comment - await postComment(pr.number, summary, repository, ghToken); - core.info('Analysis complete!'); - } - catch (error) { - core.setFailed(`Action failed with error: ${error}`); - } -} -async function getPRDiffs(context, ghToken) { + catch (error) { + app.log.error('Error analyzing PR:', error); + } + }); + // TODO: Re-implement code suggestions using the new agent's code suggestion tool + // The old code suggestion implementation has been removed + // To implement this feature: + // 1. Use the agent's createCodeSuggestionTool() from tools/pr-analysis-tools.ts + // 2. Call the agent with the tool to generate code fixes based on reviewer comments + // + // app.on(['pull_request_review_comment.created', 'pull_request_review_comment.edited'], async (context) => { + // // Implementation goes here + // }); +}; +async function getPRDiffs(context) { try { const { pull_request: pr, repository } = context.payload; - const octokit = github.getOctokit(ghToken); - const { data: files } = await octokit.rest.pulls.listFiles({ + const { data: files } = await context.octokit.pulls.listFiles({ owner: repository.owner.login, repo: repository.name, pull_number: pr.number }); - // Format as proper git diff that parseDiff expects - return files.map((f) => { - const status = f.status === 'added' ? 'new file mode 100644' : - f.status === 'removed' ? 'deleted file mode 100644' : ''; - const patch = f.patch || ''; - return `diff --git a/${f.filename} b/${f.filename} -${status ? status + '\n' : ''}--- ${f.status === 'added' ? '/dev/null' : 'a/' + f.filename} -+++ ${f.status === 'removed' ? '/dev/null' : 'b/' + f.filename} -${patch}`; - }).join('\n'); + const diff = files.map((f) => `--- ${f.filename}\n${f.patch}`).join('\n'); + return diff; } catch (error) { - core.error('Error fetching PR diff:'); - core.error(String(error)); + console.error('Error fetching PR diff:', error); throw new Error('Failed to fetch PR diff'); } } -async function postComment(prNumber, summary, repository, ghToken) { - try { - const octokit = github.getOctokit(ghToken); - await octokit.rest.issues.createComment({ - owner: repository.owner.login, - repo: repository.name, - issue_number: prNumber, - body: `## 🤖 AI Analysis (PR Agent by TechDebtGPT)\n\n${summary}` - }); - } - catch (error) { - core.error('Error posting comment:'); - core.error(String(error)); - throw new Error('Failed to post comment'); - } -} -run(); - +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/licenses.txt b/dist/licenses.txt index 7febf81..f2cb43d 100644 --- a/dist/licenses.txt +++ b/dist/licenses.txt @@ -108,6 +108,212 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +@google/generative-ai +Apache-2.0 + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + @langchain/anthropic MIT MIT License @@ -158,6 +364,31 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +@langchain/google-genai +MIT +MIT License + +Copyright (c) LangChain, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + @langchain/langgraph MIT The MIT License @@ -206,6 +437,31 @@ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +@langchain/openai +MIT +MIT License + +Copyright (c) LangChain, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + + @octokit/auth-token MIT The MIT License @@ -743,6 +999,211 @@ ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +openai +Apache-2.0 + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright 2025 OpenAI + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + + p-finally MIT The MIT License (MIT) @@ -781,19 +1242,6 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -p-retry -MIT -MIT License - -Copyright (c) Sindre Sorhus (sindresorhus.com) - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. - - p-timeout MIT MIT License @@ -807,31 +1255,6 @@ The above copyright notice and this permission notice shall be included in all c THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -retry -MIT -Copyright (c) 2011: -Tim Koschützki (tim@debuggable.com) -Felix Geisendörfer (felix@debuggable.com) - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights - to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - copies of the Software, and to permit persons to whom the Software is - furnished to do so, subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. - - semver ISC The ISC License diff --git a/dist/providers/index.d.ts b/dist/providers/index.d.ts index 197c43e..abcb958 100644 --- a/dist/providers/index.d.ts +++ b/dist/providers/index.d.ts @@ -3,3 +3,4 @@ export * from './provider.factory.js'; export * from './anthropic.provider.js'; export * from './openai.provider.js'; export * from './google.provider.js'; +export * from './zhipu.provider.js'; diff --git a/dist/providers/index.js b/dist/providers/index.js index 11dbd8e..3d54524 100644 --- a/dist/providers/index.js +++ b/dist/providers/index.js @@ -3,4 +3,5 @@ export * from './provider.factory.js'; export * from './anthropic.provider.js'; export * from './openai.provider.js'; export * from './google.provider.js'; +export * from './zhipu.provider.js'; //# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dist/providers/index.js.map b/dist/providers/index.js.map index 7e81376..8a72121 100644 --- a/dist/providers/index.js.map +++ b/dist/providers/index.js.map @@ -1 +1 @@ -{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/providers/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AACxC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC"} \ No newline at end of file +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/providers/index.ts"],"names":[],"mappings":"AAAA,cAAc,yBAAyB,CAAC;AACxC,cAAc,uBAAuB,CAAC;AACtC,cAAc,yBAAyB,CAAC;AACxC,cAAc,sBAAsB,CAAC;AACrC,cAAc,sBAAsB,CAAC;AACrC,cAAc,qBAAqB,CAAC"} \ No newline at end of file diff --git a/dist/providers/provider.factory.d.ts b/dist/providers/provider.factory.d.ts index ca4916a..e38f90e 100644 --- a/dist/providers/provider.factory.d.ts +++ b/dist/providers/provider.factory.d.ts @@ -1,6 +1,6 @@ import { ILLMProvider } from './provider.interface.js'; import { BaseChatModel } from '@langchain/core/language_models/chat_models'; -export type SupportedProvider = 'anthropic' | 'openai' | 'google'; +export type SupportedProvider = 'anthropic' | 'openai' | 'google' | 'zhipu'; export interface ProviderOptions { provider?: SupportedProvider; apiKey?: string; diff --git a/dist/providers/provider.factory.js b/dist/providers/provider.factory.js index dd2fde9..4d1a3da 100644 --- a/dist/providers/provider.factory.js +++ b/dist/providers/provider.factory.js @@ -1,6 +1,7 @@ import { AnthropicProvider } from './anthropic.provider.js'; import { OpenAIProvider } from './openai.provider.js'; import { GoogleProvider } from './google.provider.js'; +import { ZhipuProvider } from './zhipu.provider.js'; /** * Factory for creating LLM providers */ @@ -28,8 +29,11 @@ export class ProviderFactory { case 'google': provider = new GoogleProvider(apiKey); break; + case 'zhipu': + provider = new ZhipuProvider(apiKey); + break; default: - throw new Error(`Unsupported provider: ${providerName}. Supported: anthropic, openai, google`); + throw new Error(`Unsupported provider: ${providerName}. Supported: anthropic, openai, google, zhipu`); } // Cache the provider if no specific API key was provided if (!apiKey) { @@ -81,13 +85,15 @@ export class ProviderFactory { return 'anthropic'; if (normalized === 'gemini') return 'google'; + if (normalized === 'glm' || normalized === 'zhipuai') + return 'zhipu'; return normalized; } /** * Get list of available providers */ static getAvailableProviders() { - return ['anthropic', 'openai', 'google']; + return ['anthropic', 'openai', 'google', 'zhipu']; } } //# sourceMappingURL=provider.factory.js.map \ No newline at end of file diff --git a/dist/providers/provider.factory.js.map b/dist/providers/provider.factory.js.map index 2926111..5bc47b1 100644 --- a/dist/providers/provider.factory.js.map +++ b/dist/providers/provider.factory.js.map @@ -1 +1 @@ -{"version":3,"file":"provider.factory.js","sourceRoot":"","sources":["../../src/providers/provider.factory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AAatD;;GAEG;AACH,MAAM,OAAO,eAAe;IAClB,MAAM,CAAC,SAAS,GAA8B,IAAI,GAAG,EAAE,CAAC;IAEhE;;OAEG;IACI,MAAM,CAAC,WAAW,CACvB,YAA+B,EAC/B,MAAe;QAEf,2BAA2B;QAC3B,MAAM,cAAc,GAAG,IAAI,CAAC,qBAAqB,CAAC,YAAY,CAAC,CAAC;QAEhE,+EAA+E;QAC/E,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,CAAC;YAClD,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,cAAc,CAAE,CAAC;QAC7C,CAAC;QAED,+BAA+B;QAC/B,IAAI,QAAsB,CAAC;QAE3B,QAAQ,cAAc,EAAE,CAAC;YACvB,KAAK,WAAW;gBACd,QAAQ,GAAG,IAAI,iBAAiB,CAAC,MAAM,CAAC,CAAC;gBACzC,MAAM;YACR,KAAK,QAAQ;gBACX,QAAQ,GAAG,IAAI,cAAc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CAAC;YAChD,OAAO,QAAQ,CAAC,YAAY,EAAE,CAAC;QACjC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED;;OAEG;IACK,MAAM,CAAC,qBAAqB,CAAC,IAAuB;QAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACtC,IAAI,UAAU,KAAK,QAAQ;YAAE,OAAO,WAAW,CAAC;QAChD,IAAI,UAAU,KAAK,QAAQ;YAAE,OAAO,QAAQ,CAAC;QAC7C,OAAO,UAAU,CAAC;IACpB,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,qBAAqB;QACjC,OAAO,CAAC,WAAW,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC;IAC3C,CAAC"} \ No newline at end of file +{"version":3,"file":"provider.factory.js","sourceRoot":"","sources":["../../src/providers/provider.factory.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,iBAAiB,EAAE,MAAM,yBAAyB,CAAC;AAC5D,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,cAAc,EAAE,MAAM,sBAAsB,CAAC;AACtD,OAAO,EAAE,aAAa,EAAE,MAAM,qBAAqB,CAAC;AAapD;;GAEG;AACH,MAAM,OAAO,eAAe;IAClB,MAAM,CAAC,SAAS,GAA8B,IAAI,GAAG,EAAE,CAAC;IAEhE;;OAEG;IACI,MAAM,CAAC,WAAW,CACvB,YAA+B,EAC/B,MAAe;QAEf,2BAA2B;QAC3B,MAAM,cAAc,GAAG,IAAI,CAAC,qBAAqB,CAAC,YAAY,CAAC,CAAC;QAEhE,+EAA+E;QAC/E,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,cAAc,CAAC,EAAE,CAAC;YAClD,OAAO,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,cAAc,CAAE,CAAC;QAC7C,CAAC;QAED,+BAA+B;QAC/B,IAAI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AAe,CAAC,YAA+B;QAC3D,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC,CAAC;QAChD,OAAO,QAAQ,CAAC,eAAe,EAAE,CAAC;IACpC,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,oBAAoB,CAAC,YAA+B;QAChE,IAAI,CAAC;YACH,MAAM,QAAQ,GAAG,IAAI,CAAC,WAAW,CAAC,YAAY,CAAC,CAAC;YAChD,OAAO,QAAQ,CAAC,YAAY,EAAE,CAAC;QACjC,CAAC;QAAC,MAAM,CAAC;YACP,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IAED;;OAEG;IACK,MAAM,CAAC,qBAAqB,CAAC,IAAuB;QAC1D,MAAM,UAAU,GAAG,IAAI,CAAC,WAAW,EAAE,CAAC;QACtC,IAAI,UAAU,KAAK,QAAQ;YAAE,OAAO,WAAW,CAAC;QAChD,IAAI,UAAU,KAAK,QAAQ;YAAE,OAAO,QAAQ,CAAC;QAC7C,IAAI,UAAU,KAAK,KAAK,IAAI,UAAU,KAAK,SAAS;YAAE,OAAO,OAAO,CAAC;QACrE,OAAO,UAAU,CAAC;IACpB,CAAC;IAED;;OAEG;IACI,MAAM,CAAC,qBAAqB;QACjC,OAAO,CAAC,WAAW,EAAE,QAAQ,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IACpD,CAAC"} \ No newline at end of file diff --git a/dist/providers/zhipu.provider.d.ts b/dist/providers/zhipu.provider.d.ts new file mode 100644 index 0000000..d46c5af --- /dev/null +++ b/dist/providers/zhipu.provider.d.ts @@ -0,0 +1,16 @@ +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; +import { ILLMProvider, ProviderConfig } from './provider.interface.js'; +/** + * Zhipu AI (智谱AI) provider implementation + * Uses Anthropic-compatible API endpoint + * Docs: https://docs.z.ai/ + */ +export declare class ZhipuProvider implements ILLMProvider { + readonly name = "zhipu"; + private readonly apiKey; + private readonly baseUrl; + constructor(apiKey?: string); + isConfigured(): boolean; + getDefaultModel(): string; + getChatModel(config?: ProviderConfig): BaseChatModel; +} diff --git a/dist/providers/zhipu.provider.js b/dist/providers/zhipu.provider.js new file mode 100644 index 0000000..2d9351b --- /dev/null +++ b/dist/providers/zhipu.provider.js @@ -0,0 +1,34 @@ +import { ChatAnthropic } from '@langchain/anthropic'; +/** + * Zhipu AI (智谱AI) provider implementation + * Uses Anthropic-compatible API endpoint + * Docs: https://docs.z.ai/ + */ +export class ZhipuProvider { + name = 'zhipu'; + apiKey; + baseUrl = 'https://api.z.ai/api/anthropic'; + constructor(apiKey) { + this.apiKey = apiKey || process.env.ZHIPU_API_KEY || ''; + } + isConfigured() { + return !!this.apiKey; + } + getDefaultModel() { + // GLM-4.7 is mapped to claude-sonnet-4-20250514 in Zhipu's Anthropic-compatible API + return 'claude-sonnet-4-20250514'; + } + getChatModel(config = {}) { + if (!this.isConfigured()) { + throw new Error('Zhipu API key is not configured. Set ZHIPU_API_KEY environment variable.'); + } + return new ChatAnthropic({ + anthropicApiKey: this.apiKey, + anthropicApiUrl: this.baseUrl, + modelName: config.model || this.getDefaultModel(), + temperature: config.temperature ?? 0.2, + maxTokens: config.maxTokens ?? 4000, + }); + } +} +//# sourceMappingURL=zhipu.provider.js.map \ No newline at end of file diff --git a/dist/providers/zhipu.provider.js.map b/dist/providers/zhipu.provider.js.map new file mode 100644 index 0000000..3adf977 --- /dev/null +++ b/dist/providers/zhipu.provider.js.map @@ -0,0 +1 @@ +{"version":3,"file":"zhipu.provider.js","sourceRoot":"","sources":["../../src/providers/zhipu.provider.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,aAAa,EAAE,MAAM,sBAAsB,CAAC;AAIrD;;;;GAIG;AACH,MAAM,OAAO,aAAa;IACR,IAAI,GAAG,OAAO,CAAC;IACd,MAAM,CAAS;IACf,OAAO,GAAG,gCAAgC,CAAC;IAE5D,YAAY,MAAe;QACzB,IAAI,CAAC,MAAM,GAAG,MAAM,IAAI,OAAO,CAAC,GAAG,CAAC,aAAa,IAAI,EAAE,CAAC;IAC1D,CAAC;IAEM,YAAY;QACjB,OAAO,CAAC,CAAC,IAAI,CAAC,MAAM,CAAC;IACvB,CAAC;IAEM,eAAe;QACpB,oFAAoF;QACpF,OAAO,0BAA0B,CAAC;IACpC,CAAC;IAEM,YAAY,CAAC,SAAyB,EAAE;QAC7C,IAAI,CAAC,IAAI,CAAC,YAAY,EAAE,EAAE,CAAC;YACzB,MAAM,IAAI,KAAK,CAAC,0EAA0E,CAAC,CAAC;QAC9F,CAAC;QAED,OAAO,IAAI,aAAa,CAAC;YACvB,eAAe,EAAE,IAAI,CAAC,MAAM;YAC5B,eAAe,EAAE,IAAI,CAAC,OAAO;YAC7B,SAAS,EAAE,MAAM,CAAC,KAAK,IAAI,IAAI,CAAC,eAAe,EAAE;YACjD,WAAW,EAAE,MAAM,CAAC,WAAW,IAAI,GAAG;YACtC,SAAS,EAAE,MAAM,CAAC,SAAS,IAAI,IAAI;SACpC,CAAC,CAAC;IACL,CAAC;CACF"} \ No newline at end of file diff --git a/dist/types.d.ts b/dist/types.d.ts index a0c746d..50ee2ce 100644 --- a/dist/types.d.ts +++ b/dist/types.d.ts @@ -1,4 +1,4 @@ -export type AIProviderType = 'anthropic' | 'openai' | 'google'; +export type AIProviderType = 'anthropic' | 'openai' | 'google' | 'zhipu'; export interface PRInfo { number: number; title: string; diff --git a/dist/utils/config-validator.d.ts b/dist/utils/config-validator.d.ts index 3043a25..ad03d5e 100644 --- a/dist/utils/config-validator.d.ts +++ b/dist/utils/config-validator.d.ts @@ -11,12 +11,14 @@ export declare const UserConfigSchema: z.ZodObject<{ anthropic: z.ZodOptional; openai: z.ZodOptional; google: z.ZodOptional; + zhipu: z.ZodOptional; }, z.core.$strip>>; ai: z.ZodOptional>; model: z.ZodOptional; temperature: z.ZodOptional; @@ -43,6 +45,24 @@ export declare const UserConfigSchema: z.ZodObject<{ showStrategy: z.ZodOptional; showRecommendations: z.ZodOptional; }, z.core.$strip>>; + peerReview: z.ZodOptional; + provider: z.ZodOptional; + useMcp: z.ZodOptional; + instanceUrl: z.ZodOptional; + email: z.ZodOptional; + apiToken: z.ZodOptional; + defaultProject: z.ZodOptional; + acceptanceCriteriaField: z.ZodOptional; + storyPointsField: z.ZodOptional; + ticketPatterns: z.ZodOptional>; + analyzeAcceptanceCriteria: z.ZodOptional; + rateTicketQuality: z.ZodOptional; + generateTestSuggestions: z.ZodOptional; + checkScopeCreep: z.ZodOptional; + includeTicketDetails: z.ZodOptional; + verbose: z.ZodOptional; + }, z.core.$strip>>; }, z.core.$strip>; /** * Validate configuration object diff --git a/dist/utils/config-validator.js b/dist/utils/config-validator.js index 9fb780a..d5bccbd 100644 --- a/dist/utils/config-validator.js +++ b/dist/utils/config-validator.js @@ -12,11 +12,12 @@ export const UserConfigSchema = z.object({ anthropic: z.string().optional(), openai: z.string().optional(), google: z.string().optional(), + zhipu: z.string().optional(), }) .optional(), ai: z .object({ - provider: z.enum(['anthropic', 'openai', 'google']).optional(), + provider: z.enum(['anthropic', 'openai', 'google', 'zhipu']).optional(), model: z.string().optional(), temperature: z.number().min(0).max(2).optional(), maxTokens: z.number().positive().int().optional(), @@ -59,6 +60,26 @@ export const UserConfigSchema = z.object({ showRecommendations: z.boolean().optional(), }) .optional(), + peerReview: z + .object({ + enabled: z.boolean().optional(), + provider: z.string().optional(), + useMcp: z.boolean().optional(), + instanceUrl: z.string().url().optional(), + email: z.string().email().optional(), + apiToken: z.string().optional(), + defaultProject: z.string().optional(), + acceptanceCriteriaField: z.string().optional(), + storyPointsField: z.string().optional(), + ticketPatterns: z.array(z.string()).optional(), + analyzeAcceptanceCriteria: z.boolean().optional(), + rateTicketQuality: z.boolean().optional(), + generateTestSuggestions: z.boolean().optional(), + checkScopeCreep: z.boolean().optional(), + includeTicketDetails: z.boolean().optional(), + verbose: z.boolean().optional(), + }) + .optional(), }); /** * Validate configuration object diff --git a/dist/utils/config-validator.js.map b/dist/utils/config-validator.js.map index 4afe478..d2a514f 100644 --- a/dist/utils/config-validator.js.map +++ b/dist/utils/config-validator.js.map @@ -1 +1 @@ -{"version":3,"file":"config-validator.js","sourceRoot":"","sources":["../../src/utils/config-validator.ts"],"names":[],"mappings":"AAAA;;GAEG;AAEH,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAC;AACxB,OAAO,EAAE,kBAAkB,EAAE,MAAM,aAAa,CAAC;AAGjD;;GAEG;AACH,MAAM,CAAC,MAAM,gBAAgB,GAAG,CAAC,CAAC,MAAM,CAAC;IACvC,OAAO,EAAE,CAAC;SACP,MAAM,CAAC;QACN,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;QAChC,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;QAC7B,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;KAC9B,CAAC;SACD,QAAQ,EAAE;IACb,EAAE,EAAE,CAAC;SACF,MAAM,CAAC;QACN,QAAQ,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,WAAW,EAAE,QAAQ,EAAE,QAAQ,CAAC,CAAC,CAAC,QAAQ,EAAE;QAC9D,KAAK,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE;QAC5B,WAAW,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,QAAQ,EAAE;QAChD,SAAS,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,QAAQ,EAAE,CAAC,GAAG,EAAE,CAAC,QAAQ,EAAE;KAClD,CAAC;SACD,QAAQ,EAAE;IACb,QAAQ,EAAE,CAAC;SACR,MAAM,CAAC;QACN,WAAW,EAAE,CAAC,CAAC,IAAI,CAAC,CAAC,MAAM,EAAE,SAAS,EAAE,OAAO,EAAE,YAAY,CAAC,CAAC,CAAC,QAAQ,EAAE;QAC1E,OAAO,EAAE,CAAC,CAAC,MA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O,CAAC,EAAE,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,uDAAuD,CAAC;QACnM,MAAM,IAAI,kBAAkB,CAAC,YAAY,EAAE,QAAQ,CAAC,CAAC;IACvD,CAAC;IAED,OAAO,UAAU,CAAC,eAAgB,CAAC;AACrC,CAAC"} \ No newline at end of file diff --git a/package-lock.json b/package-lock.json index 36d9467..0475d8b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -635,9 +635,9 @@ "license": "MIT" }, "node_modules/@esbuild/aix-ppc64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.0.tgz", - "integrity": "sha512-KuZrd2hRjz01y5JK9mEBSD3Vj3mbCvemhT466rSuJYeE/hjuBrHfjjcjMdTm/sz7au+++sdbJZJmuBwQLuw68A==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.27.2.tgz", + "integrity": "sha512-GZMB+a0mOMZs4MpDbj8RJp4cw+w1WV5NYD6xzgvzUJ5Ek2jerwfO2eADyI6ExDSUED+1X8aMbegahsJi+8mgpw==", "cpu": [ "ppc64" ], @@ -652,9 +652,9 @@ } }, "node_modules/@esbuild/android-arm": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.0.tgz", - "integrity": "sha512-j67aezrPNYWJEOHUNLPj9maeJte7uSMM6gMoxfPC9hOg8N02JuQi/T7ewumf4tNvJadFkvLZMlAq73b9uwdMyQ==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm/-/android-arm-0.27.2.tgz", + "integrity": "sha512-DVNI8jlPa7Ujbr1yjU2PfUSRtAUZPG9I1RwW4F4xFB1Imiu2on0ADiI/c3td+KmDtVKNbi+nffGDQMfcIMkwIA==", "cpu": [ "arm" ], @@ -669,9 +669,9 @@ } }, "node_modules/@esbuild/android-arm64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.0.tgz", - "integrity": "sha512-CC3vt4+1xZrs97/PKDkl0yN7w8edvU2vZvAFGD16n9F0Cvniy5qvzRXjfO1l94efczkkQE6g1x0i73Qf5uthOQ==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-arm64/-/android-arm64-0.27.2.tgz", + "integrity": "sha512-pvz8ZZ7ot/RBphf8fv60ljmaoydPU12VuXHImtAs0XhLLw+EXBi2BLe3OYSBslR4rryHvweW5gmkKFwTiFy6KA==", "cpu": [ "arm64" ], @@ -686,9 +686,9 @@ } }, "node_modules/@esbuild/android-x64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.0.tgz", - "integrity": "sha512-wurMkF1nmQajBO1+0CJmcN17U4BP6GqNSROP8t0X/Jiw2ltYGLHpEksp9MpoBqkrFR3kv2/te6Sha26k3+yZ9Q==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/android-x64/-/android-x64-0.27.2.tgz", + "integrity": "sha512-z8Ank4Byh4TJJOh4wpz8g2vDy75zFL0TlZlkUkEwYXuPSgX8yzep596n6mT7905kA9uHZsf/o2OJZubl2l3M7A==", "cpu": [ "x64" ], @@ -703,9 +703,9 @@ } }, "node_modules/@esbuild/darwin-arm64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.0.tgz", - "integrity": "sha512-uJOQKYCcHhg07DL7i8MzjvS2LaP7W7Pn/7uA0B5S1EnqAirJtbyw4yC5jQ5qcFjHK9l6o/MX9QisBg12kNkdHg==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-arm64/-/darwin-arm64-0.27.2.tgz", + "integrity": "sha512-davCD2Zc80nzDVRwXTcQP/28fiJbcOwvdolL0sOiOsbwBa72kegmVU0Wrh1MYrbuCL98Omp5dVhQFWRKR2ZAlg==", "cpu": [ "arm64" ], @@ -720,9 +720,9 @@ } }, "node_modules/@esbuild/darwin-x64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.0.tgz", - "integrity": "sha512-8mG6arH3yB/4ZXiEnXof5MK72dE6zM9cDvUcPtxhUZsDjESl9JipZYW60C3JGreKCEP+p8P/72r69m4AZGJd5g==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/darwin-x64/-/darwin-x64-0.27.2.tgz", + "integrity": "sha512-ZxtijOmlQCBWGwbVmwOF/UCzuGIbUkqB1faQRf5akQmxRJ1ujusWsb3CVfk/9iZKr2L5SMU5wPBi1UWbvL+VQA==", "cpu": [ "x64" ], @@ -737,9 +737,9 @@ } }, "node_modules/@esbuild/freebsd-arm64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.0.tgz", - "integrity": "sha512-9FHtyO988CwNMMOE3YIeci+UV+x5Zy8fI2qHNpsEtSF83YPBmE8UWmfYAQg6Ux7Gsmd4FejZqnEUZCMGaNQHQw==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-arm64/-/freebsd-arm64-0.27.2.tgz", + "integrity": "sha512-lS/9CN+rgqQ9czogxlMcBMGd+l8Q3Nj1MFQwBZJyoEKI50XGxwuzznYdwcav6lpOGv5BqaZXqvBSiB/kJ5op+g==", "cpu": [ "arm64" ], @@ -754,9 +754,9 @@ } }, "node_modules/@esbuild/freebsd-x64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.0.tgz", - "integrity": "sha512-zCMeMXI4HS/tXvJz8vWGexpZj2YVtRAihHLk1imZj4efx1BQzN76YFeKqlDr3bUWI26wHwLWPd3rwh6pe4EV7g==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/freebsd-x64/-/freebsd-x64-0.27.2.tgz", + "integrity": "sha512-tAfqtNYb4YgPnJlEFu4c212HYjQWSO/w/h/lQaBK7RbwGIkBOuNKQI9tqWzx7Wtp7bTPaGC6MJvWI608P3wXYA==", "cpu": [ "x64" ], @@ -771,9 +771,9 @@ } }, "node_modules/@esbuild/linux-arm": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.0.tgz", - "integrity": "sha512-t76XLQDpxgmq2cNXKTVEB7O7YMb42atj2Re2Haf45HkaUpjM2J0UuJZDuaGbPbamzZ7bawyGFUkodL+zcE+jvQ==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm/-/linux-arm-0.27.2.tgz", + "integrity": "sha512-vWfq4GaIMP9AIe4yj1ZUW18RDhx6EPQKjwe7n8BbIecFtCQG4CfHGaHuh7fdfq+y3LIA2vGS/o9ZBGVxIDi9hw==", "cpu": [ "arm" ], @@ -788,9 +788,9 @@ } }, "node_modules/@esbuild/linux-arm64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.0.tgz", - "integrity": "sha512-AS18v0V+vZiLJyi/4LphvBE+OIX682Pu7ZYNsdUHyUKSoRwdnOsMf6FDekwoAFKej14WAkOef3zAORJgAtXnlQ==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-arm64/-/linux-arm64-0.27.2.tgz", + "integrity": "sha512-hYxN8pr66NsCCiRFkHUAsxylNOcAQaxSSkHMMjcpx0si13t1LHFphxJZUiGwojB1a/Hd5OiPIqDdXONia6bhTw==", "cpu": [ "arm64" ], @@ -805,9 +805,9 @@ } }, "node_modules/@esbuild/linux-ia32": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.0.tgz", - "integrity": "sha512-Mz1jxqm/kfgKkc/KLHC5qIujMvnnarD9ra1cEcrs7qshTUSksPihGrWHVG5+osAIQ68577Zpww7SGapmzSt4Nw==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ia32/-/linux-ia32-0.27.2.tgz", + "integrity": "sha512-MJt5BRRSScPDwG2hLelYhAAKh9imjHK5+NE/tvnRLbIqUWa+0E9N4WNMjmp/kXXPHZGqPLxggwVhz7QP8CTR8w==", "cpu": [ "ia32" ], @@ -822,9 +822,9 @@ } }, "node_modules/@esbuild/linux-loong64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.0.tgz", - "integrity": "sha512-QbEREjdJeIreIAbdG2hLU1yXm1uu+LTdzoq1KCo4G4pFOLlvIspBm36QrQOar9LFduavoWX2msNFAAAY9j4BDg==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-loong64/-/linux-loong64-0.27.2.tgz", + "integrity": "sha512-lugyF1atnAT463aO6KPshVCJK5NgRnU4yb3FUumyVz+cGvZbontBgzeGFO1nF+dPueHD367a2ZXe1NtUkAjOtg==", "cpu": [ "loong64" ], @@ -839,9 +839,9 @@ } }, "node_modules/@esbuild/linux-mips64el": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.0.tgz", - "integrity": "sha512-sJz3zRNe4tO2wxvDpH/HYJilb6+2YJxo/ZNbVdtFiKDufzWq4JmKAiHy9iGoLjAV7r/W32VgaHGkk35cUXlNOg==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-mips64el/-/linux-mips64el-0.27.2.tgz", + "integrity": "sha512-nlP2I6ArEBewvJ2gjrrkESEZkB5mIoaTswuqNFRv/WYd+ATtUpe9Y09RnJvgvdag7he0OWgEZWhviS1OTOKixw==", "cpu": [ "mips64el" ], @@ -856,9 +856,9 @@ } }, "node_modules/@esbuild/linux-ppc64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.0.tgz", - "integrity": "sha512-z9N10FBD0DCS2dmSABDBb5TLAyF1/ydVb+N4pi88T45efQ/w4ohr/F/QYCkxDPnkhkp6AIpIcQKQ8F0ANoA2JA==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-ppc64/-/linux-ppc64-0.27.2.tgz", + "integrity": "sha512-C92gnpey7tUQONqg1n6dKVbx3vphKtTHJaNG2Ok9lGwbZil6DrfyecMsp9CrmXGQJmZ7iiVXvvZH6Ml5hL6XdQ==", "cpu": [ "ppc64" ], @@ -873,9 +873,9 @@ } }, "node_modules/@esbuild/linux-riscv64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.0.tgz", - "integrity": "sha512-pQdyAIZ0BWIC5GyvVFn5awDiO14TkT/19FTmFcPdDec94KJ1uZcmFs21Fo8auMXzD4Tt+diXu1LW1gHus9fhFQ==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-riscv64/-/linux-riscv64-0.27.2.tgz", + "integrity": "sha512-B5BOmojNtUyN8AXlK0QJyvjEZkWwy/FKvakkTDCziX95AowLZKR6aCDhG7LeF7uMCXEJqwa8Bejz5LTPYm8AvA==", "cpu": [ "riscv64" ], @@ -890,9 +890,9 @@ } }, "node_modules/@esbuild/linux-s390x": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.0.tgz", - "integrity": "sha512-hPlRWR4eIDDEci953RI1BLZitgi5uqcsjKMxwYfmi4LcwyWo2IcRP+lThVnKjNtk90pLS8nKdroXYOqW+QQH+w==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-s390x/-/linux-s390x-0.27.2.tgz", + "integrity": "sha512-p4bm9+wsPwup5Z8f4EpfN63qNagQ47Ua2znaqGH6bqLlmJ4bx97Y9JdqxgGZ6Y8xVTixUnEkoKSHcpRlDnNr5w==", "cpu": [ "s390x" ], @@ -907,9 +907,9 @@ } }, "node_modules/@esbuild/linux-x64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.0.tgz", - "integrity": "sha512-1hBWx4OUJE2cab++aVZ7pObD6s+DK4mPGpemtnAORBvb5l/g5xFGk0vc0PjSkrDs0XaXj9yyob3d14XqvnQ4gw==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/linux-x64/-/linux-x64-0.27.2.tgz", + "integrity": "sha512-uwp2Tip5aPmH+NRUwTcfLb+W32WXjpFejTIOWZFw/v7/KnpCDKG66u4DLcurQpiYTiYwQ9B7KOeMJvLCu/OvbA==", "cpu": [ "x64" ], @@ -924,9 +924,9 @@ } }, "node_modules/@esbuild/netbsd-arm64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.0.tgz", - "integrity": "sha512-6m0sfQfxfQfy1qRuecMkJlf1cIzTOgyaeXaiVaaki8/v+WB+U4hc6ik15ZW6TAllRlg/WuQXxWj1jx6C+dfy3w==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-arm64/-/netbsd-arm64-0.27.2.tgz", + "integrity": "sha512-Kj6DiBlwXrPsCRDeRvGAUb/LNrBASrfqAIok+xB0LxK8CHqxZ037viF13ugfsIpePH93mX7xfJp97cyDuTZ3cw==", "cpu": [ "arm64" ], @@ -941,9 +941,9 @@ } }, "node_modules/@esbuild/netbsd-x64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.0.tgz", - "integrity": "sha512-xbbOdfn06FtcJ9d0ShxxvSn2iUsGd/lgPIO2V3VZIPDbEaIj1/3nBBe1AwuEZKXVXkMmpr6LUAgMkLD/4D2PPA==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/netbsd-x64/-/netbsd-x64-0.27.2.tgz", + "integrity": "sha512-HwGDZ0VLVBY3Y+Nw0JexZy9o/nUAWq9MlV7cahpaXKW6TOzfVno3y3/M8Ga8u8Yr7GldLOov27xiCnqRZf0tCA==", "cpu": [ "x64" ], @@ -958,9 +958,9 @@ } }, "node_modules/@esbuild/openbsd-arm64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.0.tgz", - "integrity": "sha512-fWgqR8uNbCQ/GGv0yhzttj6sU/9Z5/Sv/VGU3F5OuXK6J6SlriONKrQ7tNlwBrJZXRYk5jUhuWvF7GYzGguBZQ==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-arm64/-/openbsd-arm64-0.27.2.tgz", + "integrity": "sha512-DNIHH2BPQ5551A7oSHD0CKbwIA/Ox7+78/AWkbS5QoRzaqlev2uFayfSxq68EkonB+IKjiuxBFoV8ESJy8bOHA==", "cpu": [ "arm64" ], @@ -975,9 +975,9 @@ } }, "node_modules/@esbuild/openbsd-x64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.0.tgz", - "integrity": "sha512-aCwlRdSNMNxkGGqQajMUza6uXzR/U0dIl1QmLjPtRbLOx3Gy3otfFu/VjATy4yQzo9yFDGTxYDo1FfAD9oRD2A==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openbsd-x64/-/openbsd-x64-0.27.2.tgz", + "integrity": "sha512-/it7w9Nb7+0KFIzjalNJVR5bOzA9Vay+yIPLVHfIQYG/j+j9VTH84aNB8ExGKPU4AzfaEvN9/V4HV+F+vo8OEg==", "cpu": [ "x64" ], @@ -992,9 +992,9 @@ } }, "node_modules/@esbuild/openharmony-arm64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.0.tgz", - "integrity": "sha512-nyvsBccxNAsNYz2jVFYwEGuRRomqZ149A39SHWk4hV0jWxKM0hjBPm3AmdxcbHiFLbBSwG6SbpIcUbXjgyECfA==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/openharmony-arm64/-/openharmony-arm64-0.27.2.tgz", + "integrity": "sha512-LRBbCmiU51IXfeXk59csuX/aSaToeG7w48nMwA6049Y4J4+VbWALAuXcs+qcD04rHDuSCSRKdmY63sruDS5qag==", "cpu": [ "arm64" ], @@ -1009,9 +1009,9 @@ } }, "node_modules/@esbuild/sunos-x64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.0.tgz", - "integrity": "sha512-Q1KY1iJafM+UX6CFEL+F4HRTgygmEW568YMqDA5UV97AuZSm21b7SXIrRJDwXWPzr8MGr75fUZPV67FdtMHlHA==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/sunos-x64/-/sunos-x64-0.27.2.tgz", + "integrity": "sha512-kMtx1yqJHTmqaqHPAzKCAkDaKsffmXkPHThSfRwZGyuqyIeBvf08KSsYXl+abf5HDAPMJIPnbBfXvP2ZC2TfHg==", "cpu": [ "x64" ], @@ -1026,9 +1026,9 @@ } }, "node_modules/@esbuild/win32-arm64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.0.tgz", - "integrity": "sha512-W1eyGNi6d+8kOmZIwi/EDjrL9nxQIQ0MiGqe/AWc6+IaHloxHSGoeRgDRKHFISThLmsewZ5nHFvGFWdBYlgKPg==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-arm64/-/win32-arm64-0.27.2.tgz", + "integrity": "sha512-Yaf78O/B3Kkh+nKABUF++bvJv5Ijoy9AN1ww904rOXZFLWVc5OLOfL56W+C8F9xn5JQZa3UX6m+IktJnIb1Jjg==", "cpu": [ "arm64" ], @@ -1043,9 +1043,9 @@ } }, "node_modules/@esbuild/win32-ia32": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.0.tgz", - "integrity": "sha512-30z1aKL9h22kQhilnYkORFYt+3wp7yZsHWus+wSKAJR8JtdfI76LJ4SBdMsCopTR3z/ORqVu5L1vtnHZWVj4cQ==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-ia32/-/win32-ia32-0.27.2.tgz", + "integrity": "sha512-Iuws0kxo4yusk7sw70Xa2E2imZU5HoixzxfGCdxwBdhiDgt9vX9VUCBhqcwY7/uh//78A1hMkkROMJq9l27oLQ==", "cpu": [ "ia32" ], @@ -1060,9 +1060,9 @@ } }, "node_modules/@esbuild/win32-x64": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.0.tgz", - "integrity": "sha512-aIitBcjQeyOhMTImhLZmtxfdOcuNRpwlPNmlFKPcHQYPhEssw75Cl1TSXJXpMkzaua9FUetx/4OQKq7eJul5Cg==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/@esbuild/win32-x64/-/win32-x64-0.27.2.tgz", + "integrity": "sha512-sRdU18mcKf7F+YgheI/zGf5alZatMUTKj/jNS6l744f9u3WFu4v7twcUI9vu4mknF4Y9aDlblIie0IM+5xxaqQ==", "cpu": [ "x64" ], @@ -1820,24 +1820,25 @@ } }, "node_modules/@langchain/anthropic": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@langchain/anthropic/-/anthropic-1.1.3.tgz", - "integrity": "sha512-vJN7Rfl+8lDO+aVFfccDUFxIMwGtf8xHSWvqmeytOB5UBzGxNMRW2Zdu6Gv8vWrKlS6Ca7/8oB1suw1SN0FKGA==", + "version": "1.3.3", + "resolved": "https://registry.npmjs.org/@langchain/anthropic/-/anthropic-1.3.3.tgz", + "integrity": "sha512-c8K8zEIaD99HxWbAfFD45j6D72viNXX4z4bJjaIEgY9gPtGhJ7YWh80UCa6cHg/cnlEyyUSwLbcl6A5GPVAaPA==", "license": "MIT", "dependencies": { - "@anthropic-ai/sdk": "^0.71.0" + "@anthropic-ai/sdk": "^0.71.0", + "zod": "^3.25.76 || ^4" }, "engines": { "node": ">=20" }, "peerDependencies": { - "@langchain/core": "^1.0.0" + "@langchain/core": "1.1.8" } }, "node_modules/@langchain/anthropic/node_modules/@anthropic-ai/sdk": { - "version": "0.71.0", - "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.71.0.tgz", - "integrity": "sha512-go1XeWXmpxuiTkosSXpb8tokLk2ZLkIRcXpbWVwJM6gH5OBtHOVsfPfGuqI1oW7RRt4qc59EmYbrXRZ0Ng06Jw==", + "version": "0.71.2", + "resolved": "https://registry.npmjs.org/@anthropic-ai/sdk/-/sdk-0.71.2.tgz", + "integrity": "sha512-TGNDEUuEstk/DKu0/TflXAEt+p+p/WhTlFzEnoosvbaDU2LTjm42igSdlL0VijrKpWejtOKxX0b8A7uc+XiSAQ==", "license": "MIT", "dependencies": { "json-schema-to-ts": "^3.1.1" @@ -1855,9 +1856,9 @@ } }, "node_modules/@langchain/core": { - "version": "1.1.0", - "resolved": "https://registry.npmjs.org/@langchain/core/-/core-1.1.0.tgz", - "integrity": "sha512-yJ6JHcU9psjnQbzRFkXjIdNTA+3074dA+2pHdH8ewvQCSleSk6JcjkCMIb5+NASjeMoi1ZuntlLKVsNqF38YxA==", + "version": "1.1.8", + "resolved": "https://registry.npmjs.org/@langchain/core/-/core-1.1.8.tgz", + "integrity": "sha512-kIUidOgc0ZdyXo4Ahn9Zas+OayqOfk4ZoKPi7XaDipNSWSApc2+QK5BVcjvwtzxstsNOrmXJiJWEN6WPF/MvAw==", "license": "MIT", "dependencies": { "@cfworker/json-schema": "^4.0.2", @@ -1865,10 +1866,9 @@ "camelcase": "6", "decamelize": "1.2.0", "js-tiktoken": "^1.0.12", - "langsmith": "^0.3.64", + "langsmith": ">=0.4.0 <1.0.0", "mustache": "^4.2.0", "p-queue": "^6.6.2", - "p-retry": "^7.0.0", "uuid": "^10.0.0", "zod": "^3.25.76 || ^4" }, @@ -1877,9 +1877,9 @@ } }, "node_modules/@langchain/google-genai": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/@langchain/google-genai/-/google-genai-2.0.0.tgz", - "integrity": "sha512-PaAWkogQdF+Y2bhhXWXUrC2nO7sTgWLtobBbZl/0V8Aa1F/KG2wrMECie3S17bAdFu/6VmQOuFFrlgSMwQC5KA==", + "version": "2.1.3", + "resolved": "https://registry.npmjs.org/@langchain/google-genai/-/google-genai-2.1.3.tgz", + "integrity": "sha512-ZdlFK/N10GyU6ATzkM01Sk1rlHBoy36Q/MawGD1SyXdD2lQxZxuQZjFWewj6uzWQ2Nnjj70EvU/kmmHVPn6sfQ==", "license": "MIT", "dependencies": { "@google/generative-ai": "^0.24.0", @@ -1889,7 +1889,7 @@ "node": ">=20" }, "peerDependencies": { - "@langchain/core": "1.1.0" + "@langchain/core": "1.1.8" } }, "node_modules/@langchain/google-genai/node_modules/uuid": { @@ -1906,13 +1906,13 @@ } }, "node_modules/@langchain/langgraph": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/@langchain/langgraph/-/langgraph-1.0.2.tgz", - "integrity": "sha512-syxzzWTnmpCL+RhUEvalUeOXFoZy/KkzHa2Da2gKf18zsf9Dkbh3rfnRDrTyUGS1XSTejq07s4rg1qntdEDs2A==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/@langchain/langgraph/-/langgraph-1.0.7.tgz", + "integrity": "sha512-EBGqNOWoRiEoLUaeuiXRpUM8/DE6QcwiirNyd97XhezStebBoTTilWH8CUt6S94JRGl5zwfBBRHfzotDnZS/eA==", "license": "MIT", "dependencies": { "@langchain/langgraph-checkpoint": "^1.0.0", - "@langchain/langgraph-sdk": "~1.0.0", + "@langchain/langgraph-sdk": "~1.3.1", "uuid": "^10.0.0" }, "engines": { @@ -1945,9 +1945,9 @@ } }, "node_modules/@langchain/langgraph-sdk": { - "version": "1.0.3", - "resolved": "https://registry.npmjs.org/@langchain/langgraph-sdk/-/langgraph-sdk-1.0.3.tgz", - "integrity": "sha512-6M4i0XsVO5Eb2vv/3OtIPHW3UqO4zYyXl6AOfS0Jf6d7JiWiSXqzLN8UoS0hpu1ItkcW1j575CRiP/6jn6XXFg==", + "version": "1.3.1", + "resolved": "https://registry.npmjs.org/@langchain/langgraph-sdk/-/langgraph-sdk-1.3.1.tgz", + "integrity": "sha512-zTi7DZHwqtMEzapvm3I1FL4Q7OZsxtq9tTXy6s2gcCxyIU3sphqRboqytqVN7dNHLdTCLb8nXy49QKurs2MIBg==", "license": "MIT", "dependencies": { "p-queue": "^6.6.2", @@ -1971,19 +1971,6 @@ } } }, - "node_modules/@langchain/langgraph-sdk/node_modules/p-retry": { - "version": "4.6.2", - "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", - "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", - "license": "MIT", - "dependencies": { - "@types/retry": "0.12.0", - "retry": "^0.13.1" - }, - "engines": { - "node": ">=8" - } - }, "node_modules/@langchain/langgraph-sdk/node_modules/uuid": { "version": "9.0.1", "resolved": "https://registry.npmjs.org/uuid/-/uuid-9.0.1.tgz", @@ -1998,13 +1985,13 @@ } }, "node_modules/@langchain/openai": { - "version": "1.1.3", - "resolved": "https://registry.npmjs.org/@langchain/openai/-/openai-1.1.3.tgz", - "integrity": "sha512-p+xR+4HRms5Ozjf5miC6U2AYRyNVSTdO7AMBkMYs1Tp6DWHBd+mQ72H8Ogd2dKrPuS5UDJ5dbpI1fS+OrTbgQQ==", + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/@langchain/openai/-/openai-1.2.0.tgz", + "integrity": "sha512-r2g5Be3Sygw7VTJ89WVM/M94RzYToNTwXf8me1v+kgKxzdHbd/8XPYDFxpXEp3REyPgUrtJs+Oplba9pkTH5ug==", "license": "MIT", "dependencies": { "js-tiktoken": "^1.0.12", - "openai": "^6.9.0", + "openai": "^6.10.0", "zod": "^3.25.76 || ^4" }, "engines": { @@ -2586,6 +2573,18 @@ "@octokit/openapi-types": "^20.0.0" } }, + "node_modules/@octokit/plugin-request-log": { + "version": "6.0.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-6.0.0.tgz", + "integrity": "sha512-UkOzeEN3W91/eBq9sPZNQ7sUBvYCqYbrrD8gTbBuGtHEuycE4/awMXcYvx6sVYo7LypPhmQwwpUe4Yyu4QZN5Q==", + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "peerDependencies": { + "@octokit/core": ">=6" + } + }, "node_modules/@octokit/plugin-rest-endpoint-methods": { "version": "10.4.1", "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-10.4.1.tgz", @@ -2641,6 +2640,34 @@ "@octokit/openapi-types": "^12.11.0" } }, + "node_modules/@octokit/plugin-throttling": { + "version": "3.7.0", + "resolved": "https://registry.npmjs.org/@octokit/plugin-throttling/-/plugin-throttling-3.7.0.tgz", + "integrity": "sha512-qrKT1Yl/KuwGSC6/oHpLBot3ooC9rq0/ryDYBCpkRtoj+R8T47xTMDT6Tk2CxWopFota/8Pi/2SqArqwC0JPow==", + "license": "MIT", + "dependencies": { + "@octokit/types": "^6.0.1", + "bottleneck": "^2.15.3" + }, + "peerDependencies": { + "@octokit/core": "^3.5.0" + } + }, + "node_modules/@octokit/plugin-throttling/node_modules/@octokit/openapi-types": { + "version": "12.11.0", + "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", + "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", + "license": "MIT" + }, + "node_modules/@octokit/plugin-throttling/node_modules/@octokit/types": { + "version": "6.41.0", + "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", + "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", + "license": "MIT", + "dependencies": { + "@octokit/openapi-types": "^12.11.0" + } + }, "node_modules/@octokit/request": { "version": "8.4.1", "resolved": "https://registry.npmjs.org/@octokit/request/-/request-8.4.1.tgz", @@ -2760,18 +2787,6 @@ "@octokit/core": ">=6" } }, - "node_modules/@octokit/rest/node_modules/@octokit/plugin-request-log": { - "version": "6.0.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-request-log/-/plugin-request-log-6.0.0.tgz", - "integrity": "sha512-UkOzeEN3W91/eBq9sPZNQ7sUBvYCqYbrrD8gTbBuGtHEuycE4/awMXcYvx6sVYo7LypPhmQwwpUe4Yyu4QZN5Q==", - "license": "MIT", - "engines": { - "node": ">= 20" - }, - "peerDependencies": { - "@octokit/core": ">=6" - } - }, "node_modules/@octokit/rest/node_modules/@octokit/plugin-rest-endpoint-methods": { "version": "17.0.0", "resolved": "https://registry.npmjs.org/@octokit/plugin-rest-endpoint-methods/-/plugin-rest-endpoint-methods-17.0.0.tgz", @@ -3240,9 +3255,9 @@ "license": "MIT" }, "node_modules/@types/node": { - "version": "24.10.1", - "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.1.tgz", - "integrity": "sha512-GNWcUTRBgIRJD5zj+Tq0fKOJ5XZajIiBroOF0yvj2bSU1WvNdYS/dn9UxwsujGW4JX06dnHyjV2y9rRaybH0iQ==", + "version": "24.10.4", + "resolved": "https://registry.npmjs.org/@types/node/-/node-24.10.4.tgz", + "integrity": "sha512-vnDVpYPMzs4wunl27jHrfmwojOGKya0xyM3sH+UE5iv5uPS6vX7UIoh6m+vQc5LGBq52HBKPIn/zcSZVzeDEZg==", "license": "MIT", "dependencies": { "undici-types": "~7.16.0" @@ -3749,9 +3764,9 @@ "license": "MIT" }, "node_modules/baseline-browser-mapping": { - "version": "2.8.32", - "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.8.32.tgz", - "integrity": "sha512-OPz5aBThlyLFgxyhdwf/s2+8ab3OvT7AdTNvKHBwpXomIYeXqpUUuT8LrdtxZSsWJ4R4CU1un4XGh5Ez3nlTpw==", + "version": "2.9.11", + "resolved": "https://registry.npmjs.org/baseline-browser-mapping/-/baseline-browser-mapping-2.9.11.tgz", + "integrity": "sha512-Sg0xJUNDU1sJNGdfGWhVHX0kkZ+HWcvmVymJbj6NSgZZmW/8S9Y2HQ5euytnIgakgxN6papOAWiwDo1ctFDcoQ==", "dev": true, "license": "Apache-2.0", "bin": { @@ -3765,23 +3780,23 @@ "license": "Apache-2.0" }, "node_modules/body-parser": { - "version": "1.20.3", - "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.3.tgz", - "integrity": "sha512-7rAxByjUMqQ3/bHJy7D6OGXvx/MMc4IqBn/X0fcM1QUcAItpZrBEYhWGem+tzXH90c+G01ypMcYJBO9Y30203g==", + "version": "1.20.4", + "resolved": "https://registry.npmjs.org/body-parser/-/body-parser-1.20.4.tgz", + "integrity": "sha512-ZTgYYLMOXY9qKU/57FAo8F+HA2dGX7bqGc71txDRC1rS4frdFI5R7NhluHxH6M0YItAP0sHB4uqAOcYKxO6uGA==", "license": "MIT", "dependencies": { - "bytes": "3.1.2", + "bytes": "~3.1.2", "content-type": "~1.0.5", "debug": "2.6.9", "depd": "2.0.0", - "destroy": "1.2.0", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "on-finished": "2.4.1", - "qs": "6.13.0", - "raw-body": "2.5.2", + "destroy": "~1.2.0", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "on-finished": "~2.4.1", + "qs": "~6.14.0", + "raw-body": "~2.5.3", "type-is": "~1.6.18", - "unpipe": "1.0.0" + "unpipe": "~1.0.0" }, "engines": { "node": ">= 0.8", @@ -3846,9 +3861,9 @@ } }, "node_modules/browserslist": { - "version": "4.28.0", - "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.0.tgz", - "integrity": "sha512-tbydkR/CxfMwelN0vwdP/pLkDwyAASZ+VfWm4EOwlB6SWhx1sYnWLqo8N5j0rAzPfzfRaxt0mM/4wPU/Su84RQ==", + "version": "4.28.1", + "resolved": "https://registry.npmjs.org/browserslist/-/browserslist-4.28.1.tgz", + "integrity": "sha512-ZC5Bd0LgJXgwGqUknZY/vkUQ04r8NXnJZ3yYi4vDmSiZmC/pdSN0NbNRPxZpbtO4uAfDUAFffO8IZoM3Gj8IkA==", "dev": true, "funding": [ { @@ -3866,11 +3881,11 @@ ], "license": "MIT", "dependencies": { - "baseline-browser-mapping": "^2.8.25", - "caniuse-lite": "^1.0.30001754", - "electron-to-chromium": "^1.5.249", + "baseline-browser-mapping": "^2.9.0", + "caniuse-lite": "^1.0.30001759", + "electron-to-chromium": "^1.5.263", "node-releases": "^2.0.27", - "update-browserslist-db": "^1.1.4" + "update-browserslist-db": "^1.2.0" }, "bin": { "browserslist": "cli.js" @@ -3982,9 +3997,9 @@ } }, "node_modules/caniuse-lite": { - "version": "1.0.30001757", - "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001757.tgz", - "integrity": "sha512-r0nnL/I28Zi/yjk1el6ilj27tKcdjLsNqAOZr0yVjWPrSQyHgKI2INaEWw21bAQSv2LXRt1XuCS/GomNpWOxsQ==", + "version": "1.0.30001761", + "resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001761.tgz", + "integrity": "sha512-JF9ptu1vP2coz98+5051jZ4PwQgd2ni8A+gYSN7EA7dPKIMf0pDlSUxhdmVOaV3/fYK5uWBkgSXJaRLr4+3A6g==", "dev": true, "funding": [ { @@ -4333,18 +4348,18 @@ "license": "MIT" }, "node_modules/cookie": { - "version": "0.7.1", - "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.1.tgz", - "integrity": "sha512-6DnInpx7SJ2AK3+CTUE/ZM0vWTUboZCegxhC2xiIydHR9jNuTAASBrfEpHhiGOZw/nX51bHt6YQl8jsGo4y/0w==", + "version": "0.7.2", + "resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz", + "integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==", "license": "MIT", "engines": { "node": ">= 0.6" } }, "node_modules/cookie-signature": { - "version": "1.0.6", - "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.6.tgz", - "integrity": "sha512-QADzlaHc8icV8I7vbaJXJwod9HWYp8uCqf1xa4OfNu1T7JVxQIrUgOWtHdNDtPiywmFbiS12VjotIXLrKM3orQ==", + "version": "1.0.7", + "resolved": "https://registry.npmjs.org/cookie-signature/-/cookie-signature-1.0.7.tgz", + "integrity": "sha512-NXdYc3dLr47pBkpUCHtKSwIOQXLVn8dZEuywboCOJY/osA0wFSLlSawr3KN8qXJEyX66FcONTH8EIlVuK0yyFA==", "license": "MIT" }, "node_modules/create-jest": { @@ -4420,9 +4435,9 @@ } }, "node_modules/dedent": { - "version": "1.7.0", - "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.0.tgz", - "integrity": "sha512-HGFtf8yhuhGhqO07SV79tRp+br4MnbdjeVxotpn1QBl30pcLLCQjX5b2295ll0fv8RKDKsmWYrl05usHM9CewQ==", + "version": "1.7.1", + "resolved": "https://registry.npmjs.org/dedent/-/dedent-1.7.1.tgz", + "integrity": "sha512-9JmrhGZpOlEgOLdQgSm0zxFaYoQon408V1v49aqTWuXENVlnCuY9JBZcXZiCsZQWDjTm5Qf/nIvAy77mXDAjEg==", "dev": true, "license": "MIT", "peerDependencies": { @@ -4545,9 +4560,9 @@ "license": "MIT" }, "node_modules/electron-to-chromium": { - "version": "1.5.262", - "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.262.tgz", - "integrity": "sha512-NlAsMteRHek05jRUxUR0a5jpjYq9ykk6+kO0yRaMi5moe7u0fVIOeQ3Y30A8dIiWFBNUoQGi1ljb1i5VtS9WQQ==", + "version": "1.5.267", + "resolved": "https://registry.npmjs.org/electron-to-chromium/-/electron-to-chromium-1.5.267.tgz", + "integrity": "sha512-0Drusm6MVRXSOJpGbaSVgcQsuB4hEkMpHXaVstcPmhu5LIedxs1xNK/nIxmQIU/RPC0+1/o0AVZfBTkTNJOdUw==", "dev": true, "license": "ISC" }, @@ -4643,9 +4658,9 @@ } }, "node_modules/esbuild": { - "version": "0.27.0", - "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.0.tgz", - "integrity": "sha512-jd0f4NHbD6cALCyGElNpGAOtWxSq46l9X/sWB0Nzd5er4Kz2YTm+Vl0qKFT9KUJvD8+fiO8AvoHhFvEatfVixA==", + "version": "0.27.2", + "resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.27.2.tgz", + "integrity": "sha512-HyNQImnsOC7X9PMNaCIeAm4ISCQXs5a5YasTXVliKv4uuBo1dKrG0A+uQS8M5eXjVMnLg3WgXaKvprHlFJQffw==", "dev": true, "hasInstallScript": true, "license": "MIT", @@ -4656,32 +4671,32 @@ "node": ">=18" }, "optionalDependencies": { - "@esbuild/aix-ppc64": "0.27.0", - "@esbuild/android-arm": "0.27.0", - "@esbuild/android-arm64": "0.27.0", - "@esbuild/android-x64": "0.27.0", - "@esbuild/darwin-arm64": "0.27.0", - "@esbuild/darwin-x64": "0.27.0", - "@esbuild/freebsd-arm64": "0.27.0", - "@esbuild/freebsd-x64": "0.27.0", - "@esbuild/linux-arm": "0.27.0", - "@esbuild/linux-arm64": "0.27.0", - "@esbuild/linux-ia32": "0.27.0", - "@esbuild/linux-loong64": "0.27.0", - "@esbuild/linux-mips64el": "0.27.0", - "@esbuild/linux-ppc64": "0.27.0", - "@esbuild/linux-riscv64": "0.27.0", - "@esbuild/linux-s390x": "0.27.0", - "@esbuild/linux-x64": "0.27.0", - "@esbuild/netbsd-arm64": "0.27.0", - "@esbuild/netbsd-x64": "0.27.0", - "@esbuild/openbsd-arm64": "0.27.0", - "@esbuild/openbsd-x64": "0.27.0", - "@esbuild/openharmony-arm64": "0.27.0", - "@esbuild/sunos-x64": "0.27.0", - "@esbuild/win32-arm64": "0.27.0", - "@esbuild/win32-ia32": "0.27.0", - "@esbuild/win32-x64": "0.27.0" + "@esbuild/aix-ppc64": "0.27.2", + "@esbuild/android-arm": "0.27.2", + "@esbuild/android-arm64": "0.27.2", + "@esbuild/android-x64": "0.27.2", + "@esbuild/darwin-arm64": "0.27.2", + "@esbuild/darwin-x64": "0.27.2", + "@esbuild/freebsd-arm64": "0.27.2", + "@esbuild/freebsd-x64": "0.27.2", + "@esbuild/linux-arm": "0.27.2", + "@esbuild/linux-arm64": "0.27.2", + "@esbuild/linux-ia32": "0.27.2", + "@esbuild/linux-loong64": "0.27.2", + "@esbuild/linux-mips64el": "0.27.2", + "@esbuild/linux-ppc64": "0.27.2", + "@esbuild/linux-riscv64": "0.27.2", + "@esbuild/linux-s390x": "0.27.2", + "@esbuild/linux-x64": "0.27.2", + "@esbuild/netbsd-arm64": "0.27.2", + "@esbuild/netbsd-x64": "0.27.2", + "@esbuild/openbsd-arm64": "0.27.2", + "@esbuild/openbsd-x64": "0.27.2", + "@esbuild/openharmony-arm64": "0.27.2", + "@esbuild/sunos-x64": "0.27.2", + "@esbuild/win32-arm64": "0.27.2", + "@esbuild/win32-ia32": "0.27.2", + "@esbuild/win32-x64": "0.27.2" } }, "node_modules/escalade": { @@ -4814,39 +4829,39 @@ } }, "node_modules/express": { - "version": "4.21.2", - "resolved": "https://registry.npmjs.org/express/-/express-4.21.2.tgz", - "integrity": "sha512-28HqgMZAmih1Czt9ny7qr6ek2qddF4FclbMzwhCREB6OFfH+rXAnuNCwo1/wFvrtbgsQDb4kSbX9de9lFbrXnA==", + "version": "4.22.1", + "resolved": "https://registry.npmjs.org/express/-/express-4.22.1.tgz", + "integrity": "sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==", "license": "MIT", "dependencies": { "accepts": "~1.3.8", "array-flatten": "1.1.1", - "body-parser": "1.20.3", - "content-disposition": "0.5.4", + "body-parser": "~1.20.3", + "content-disposition": "~0.5.4", "content-type": "~1.0.4", - "cookie": "0.7.1", - "cookie-signature": "1.0.6", + "cookie": "~0.7.1", + "cookie-signature": "~1.0.6", "debug": "2.6.9", "depd": "2.0.0", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", - "finalhandler": "1.3.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", + "finalhandler": "~1.3.1", + "fresh": "~0.5.2", + "http-errors": "~2.0.0", "merge-descriptors": "1.0.3", "methods": "~1.1.2", - "on-finished": "2.4.1", + "on-finished": "~2.4.1", "parseurl": "~1.3.3", - "path-to-regexp": "0.1.12", + "path-to-regexp": "~0.1.12", "proxy-addr": "~2.0.7", - "qs": "6.13.0", + "qs": "~6.14.0", "range-parser": "~1.2.1", "safe-buffer": "5.2.1", - "send": "0.19.0", - "serve-static": "1.16.2", + "send": "~0.19.0", + "serve-static": "~1.16.2", "setprototypeof": "1.2.0", - "statuses": "2.0.1", + "statuses": "~2.0.1", "type-is": "~1.6.18", "utils-merge": "1.0.1", "vary": "~1.1.2" @@ -5000,17 +5015,17 @@ } }, "node_modules/finalhandler": { - "version": "1.3.1", - "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.1.tgz", - "integrity": "sha512-6BN9trH7bp3qvnrRyzsBz+g3lZxTNZTbVO2EV1CS0WIcDbawYVdYvGflME/9QP0h0pYlCDBCTjYa9nZzMDpyxQ==", + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/finalhandler/-/finalhandler-1.3.2.tgz", + "integrity": "sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==", "license": "MIT", "dependencies": { "debug": "2.6.9", "encodeurl": "~2.0.0", "escape-html": "~1.0.3", - "on-finished": "2.4.1", + "on-finished": "~2.4.1", "parseurl": "~1.3.3", - "statuses": "2.0.1", + "statuses": "~2.0.2", "unpipe": "~1.0.0" }, "engines": { @@ -5366,19 +5381,23 @@ "license": "MIT" }, "node_modules/http-errors": { - "version": "2.0.0", - "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.0.tgz", - "integrity": "sha512-FtwrG/euBzaEjYeRqOgly7G0qviiXoJWnvEH2Z1plBdXgbyjv34pHTSb9zoeHMyDy33+DWy5Wt9Wo+TURtOYSQ==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/http-errors/-/http-errors-2.0.1.tgz", + "integrity": "sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ==", "license": "MIT", "dependencies": { - "depd": "2.0.0", - "inherits": "2.0.4", - "setprototypeof": "1.2.0", - "statuses": "2.0.1", - "toidentifier": "1.0.1" + "depd": "~2.0.0", + "inherits": "~2.0.4", + "setprototypeof": "~1.2.0", + "statuses": "~2.0.2", + "toidentifier": "~1.0.1" }, "engines": { "node": ">= 0.8" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/express" } }, "node_modules/human-signals": { @@ -5401,9 +5420,9 @@ } }, "node_modules/iconv-lite": { - "version": "0.7.0", - "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.0.tgz", - "integrity": "sha512-cf6L2Ds3h57VVmkZe+Pn+5APsT7FpqJtEhhieDCvrE2MK5Qk9MyffgQyuxQTm6BChfeZNtcOLHp9IcWRVcIcBQ==", + "version": "0.7.1", + "resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.7.1.tgz", + "integrity": "sha512-2Tth85cXwGFHfvRgZWszZSvdo+0Xsqmw8k8ZwxScfcBneNUraK+dxRxRm24nszx80Y0TVio8kKLt5sLE7ZCLlw==", "license": "MIT", "dependencies": { "safer-buffer": ">= 2.1.2 < 3.0.0" @@ -5591,18 +5610,6 @@ "url": "https://github.com/sponsors/sindresorhus" } }, - "node_modules/is-network-error": { - "version": "1.3.0", - "resolved": "https://registry.npmjs.org/is-network-error/-/is-network-error-1.3.0.tgz", - "integrity": "sha512-6oIwpsgRfnDiyEDLMay/GqCl3HoAtH5+RUKW29gYkL0QA+ipzpDLA16yQs7/RHCSu+BwgbJaOUqa4A99qNVQVw==", - "license": "MIT", - "engines": { - "node": ">=16" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" - } - }, "node_modules/is-number": { "version": "7.0.0", "resolved": "https://registry.npmjs.org/is-number/-/is-number-7.0.0.tgz", @@ -6420,12 +6427,12 @@ } }, "node_modules/jsonwebtoken": { - "version": "9.0.2", - "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.2.tgz", - "integrity": "sha512-PRp66vJ865SSqOlgqS8hujT5U4AOgMfhrwYIuIhfKaoSCZcirrmASQr8CX7cUg+RMih+hgznrjp99o+W4pJLHQ==", + "version": "9.0.3", + "resolved": "https://registry.npmjs.org/jsonwebtoken/-/jsonwebtoken-9.0.3.tgz", + "integrity": "sha512-MT/xP0CrubFRNLNKvxJ2BYfy53Zkm++5bX9dtuPbqAeQpTVe0MQTFhao8+Cp//EmJp244xt6Drw/GVEGCUj40g==", "license": "MIT", "dependencies": { - "jws": "^3.2.2", + "jws": "^4.0.1", "lodash.includes": "^4.3.0", "lodash.isboolean": "^3.0.3", "lodash.isinteger": "^4.0.4", @@ -6454,9 +6461,9 @@ } }, "node_modules/jwa": { - "version": "1.4.2", - "resolved": "https://registry.npmjs.org/jwa/-/jwa-1.4.2.tgz", - "integrity": "sha512-eeH5JO+21J78qMvTIDdBXidBd6nG2kZjg5Ohz/1fpa28Z4CcsWUzJ1ZZyFq/3z3N17aZy+ZuBoHljASbL1WfOw==", + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/jwa/-/jwa-2.0.1.tgz", + "integrity": "sha512-hRF04fqJIP8Abbkq5NKGN0Bbr3JxlQ+qhZufXVr0DvujKy93ZCbXZMHDL4EOtodSbCWxOqR8MS1tXA5hwqCXDg==", "license": "MIT", "dependencies": { "buffer-equal-constant-time": "^1.0.1", @@ -6465,12 +6472,12 @@ } }, "node_modules/jws": { - "version": "3.2.2", - "resolved": "https://registry.npmjs.org/jws/-/jws-3.2.2.tgz", - "integrity": "sha512-YHlZCB6lMTllWDtSPHz/ZXTsi8S00usEV6v1tjq8tOUZzw7DpSDWVXjXDre6ed1w/pd495ODpHZYSdkRTsa0HA==", + "version": "4.0.1", + "resolved": "https://registry.npmjs.org/jws/-/jws-4.0.1.tgz", + "integrity": "sha512-EKI/M/yqPncGUUh44xz0PxSidXFr/+r0pA70+gIYhjv+et7yxM+s29Y+VGDkovRofQem0fs7Uvf4+YmAdyRduA==", "license": "MIT", "dependencies": { - "jwa": "^1.4.1", + "jwa": "^2.0.1", "safe-buffer": "^5.0.1" } }, @@ -6485,14 +6492,14 @@ } }, "node_modules/langchain": { - "version": "1.1.1", - "resolved": "https://registry.npmjs.org/langchain/-/langchain-1.1.1.tgz", - "integrity": "sha512-z7cOFhLOzbu/lRlIE8GZ5rlfi7obvvHThhMdts1KsUBusJmWLmh1Yik28MHYzJRXclUbqs4u/9D2yNmr36wf0A==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/langchain/-/langchain-1.2.3.tgz", + "integrity": "sha512-3k986xJuqg4az53JxV5LnGlOzIXF1d9Kq6Y9s7XjitvzhpsbFuTDV5/kiF4cx3pkNGyw0mUXC4tLz9RxucO0hw==", "license": "MIT", "dependencies": { "@langchain/langgraph": "^1.0.0", "@langchain/langgraph-checkpoint": "^1.0.0", - "langsmith": "~0.3.74", + "langsmith": ">=0.4.0 <1.0.0", "uuid": "^10.0.0", "zod": "^3.25.76 || ^4" }, @@ -6500,13 +6507,13 @@ "node": ">=20" }, "peerDependencies": { - "@langchain/core": "1.1.0" + "@langchain/core": "1.1.8" } }, "node_modules/langsmith": { - "version": "0.3.82", - "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.3.82.tgz", - "integrity": "sha512-RTcxtRm0zp2lV+pMesMW7EZSsIlqN7OmR2F6sZ/sOFQwmcLVl+VErMPV4VkX4Sycs4/EIAFT5hpr36EqiHoikQ==", + "version": "0.4.2", + "resolved": "https://registry.npmjs.org/langsmith/-/langsmith-0.4.2.tgz", + "integrity": "sha512-BvBeFgSmR9esl8x5wsiDlALiHKKPybw2wE2Hh6x1tgSZki46H9c9KI9/06LARbPhyyDu/TZU7exfg6fnhdj1Qg==", "license": "MIT", "dependencies": { "@types/uuid": "^10.0.0", @@ -7138,9 +7145,9 @@ } }, "node_modules/openai": { - "version": "6.9.1", - "resolved": "https://registry.npmjs.org/openai/-/openai-6.9.1.tgz", - "integrity": "sha512-vQ5Rlt0ZgB3/BNmTa7bIijYFhz3YBceAA3Z4JuoMSBftBF9YqFHIEhZakSs+O/Ad7EaoEimZvHxD5ylRjN11Lg==", + "version": "6.15.0", + "resolved": "https://registry.npmjs.org/openai/-/openai-6.15.0.tgz", + "integrity": "sha512-F1Lvs5BoVvmZtzkUEVyh8mDQPPFolq4F+xdsx/DO8Hee8YF3IGAlZqUIsF+DVGhqf4aU0a3bTghsxB6OIsRy1g==", "license": "Apache-2.0", "bin": { "openai": "bin/cli" @@ -7300,18 +7307,16 @@ } }, "node_modules/p-retry": { - "version": "7.1.0", - "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-7.1.0.tgz", - "integrity": "sha512-xL4PiFRQa/f9L9ZvR4/gUCRNus4N8YX80ku8kv9Jqz+ZokkiZLM0bcvX0gm1F3PDi9SPRsww1BDsTWgE6Y1GLQ==", + "version": "4.6.2", + "resolved": "https://registry.npmjs.org/p-retry/-/p-retry-4.6.2.tgz", + "integrity": "sha512-312Id396EbJdvRONlngUx0NydfrIQ5lsYu0znKVUzVvArzEIt08V1qhtyESbGVd1FGX7UKtiFp5uwKZdM8wIuQ==", "license": "MIT", "dependencies": { - "is-network-error": "^1.1.0" + "@types/retry": "0.12.0", + "retry": "^0.13.1" }, "engines": { - "node": ">=20" - }, - "funding": { - "url": "https://github.com/sponsors/sindresorhus" + "node": ">=8" } }, "node_modules/p-timeout": { @@ -7843,34 +7848,6 @@ "@octokit/openapi-types": "^12.11.0" } }, - "node_modules/probot/node_modules/@octokit/plugin-throttling": { - "version": "3.7.0", - "resolved": "https://registry.npmjs.org/@octokit/plugin-throttling/-/plugin-throttling-3.7.0.tgz", - "integrity": "sha512-qrKT1Yl/KuwGSC6/oHpLBot3ooC9rq0/ryDYBCpkRtoj+R8T47xTMDT6Tk2CxWopFota/8Pi/2SqArqwC0JPow==", - "license": "MIT", - "dependencies": { - "@octokit/types": "^6.0.1", - "bottleneck": "^2.15.3" - }, - "peerDependencies": { - "@octokit/core": "^3.5.0" - } - }, - "node_modules/probot/node_modules/@octokit/plugin-throttling/node_modules/@octokit/openapi-types": { - "version": "12.11.0", - "resolved": "https://registry.npmjs.org/@octokit/openapi-types/-/openapi-types-12.11.0.tgz", - "integrity": "sha512-VsXyi8peyRq9PqIz/tpqiL2w3w80OgVMwBHltTml3LmVvXiphgeqmY9mvBw9Wu7e0QWk/fqD37ux8yP5uVekyQ==", - "license": "MIT" - }, - "node_modules/probot/node_modules/@octokit/plugin-throttling/node_modules/@octokit/types": { - "version": "6.41.0", - "resolved": "https://registry.npmjs.org/@octokit/types/-/types-6.41.0.tgz", - "integrity": "sha512-eJ2jbzjdijiL3B4PrSQaSjuF2sPEQPVCPzBvTHJD9Nz+9dw2SGH4K4xeQJ77YfTq5bRQ+bD8wT11JbeDPmxmGg==", - "license": "MIT", - "dependencies": { - "@octokit/openapi-types": "^12.11.0" - } - }, "node_modules/probot/node_modules/@octokit/request": { "version": "5.6.3", "resolved": "https://registry.npmjs.org/@octokit/request/-/request-5.6.3.tgz", @@ -8050,12 +8027,12 @@ "license": "MIT" }, "node_modules/qs": { - "version": "6.13.0", - "resolved": "https://registry.npmjs.org/qs/-/qs-6.13.0.tgz", - "integrity": "sha512-+38qI9SOr8tfZ4QmJNplMUxqjbe7LKvvZgWdExBOmd+egZTtjLB67Gu0HRX3u/XOq7UU2Nx6nsjvS16Z9uwfpg==", + "version": "6.14.0", + "resolved": "https://registry.npmjs.org/qs/-/qs-6.14.0.tgz", + "integrity": "sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==", "license": "BSD-3-Clause", "dependencies": { - "side-channel": "^1.0.6" + "side-channel": "^1.1.0" }, "engines": { "node": ">=0.6" @@ -8080,15 +8057,15 @@ } }, "node_modules/raw-body": { - "version": "2.5.2", - "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.2.tgz", - "integrity": "sha512-8zGqypfENjCIqGhgXToC8aB2r7YrBX+AQAfIPs/Mlk+BtPTztOvTS01NRW/3Eh60J+a48lt8qsCzirQ6loCVfA==", + "version": "2.5.3", + "resolved": "https://registry.npmjs.org/raw-body/-/raw-body-2.5.3.tgz", + "integrity": "sha512-s4VSOf6yN0rvbRZGxs8Om5CWj6seneMwK3oDb4lWDH0UPhWcxwOWw5+qk24bxq87szX1ydrwylIOp2uG1ojUpA==", "license": "MIT", "dependencies": { - "bytes": "3.1.2", - "http-errors": "2.0.0", - "iconv-lite": "0.4.24", - "unpipe": "1.0.0" + "bytes": "~3.1.2", + "http-errors": "~2.0.1", + "iconv-lite": "~0.4.24", + "unpipe": "~1.0.0" }, "engines": { "node": ">= 0.8" @@ -8322,24 +8299,24 @@ } }, "node_modules/send": { - "version": "0.19.0", - "resolved": "https://registry.npmjs.org/send/-/send-0.19.0.tgz", - "integrity": "sha512-dW41u5VfLXu8SJh5bwRmyYUbAoSB3c9uQh6L8h/KtsFREPWpbX1lrljJo186Jc4nmci/sGUZ9a0a0J2zgfq2hw==", + "version": "0.19.2", + "resolved": "https://registry.npmjs.org/send/-/send-0.19.2.tgz", + "integrity": "sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg==", "license": "MIT", "dependencies": { "debug": "2.6.9", "depd": "2.0.0", "destroy": "1.2.0", - "encodeurl": "~1.0.2", + "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "etag": "~1.8.1", - "fresh": "0.5.2", - "http-errors": "2.0.0", + "fresh": "~0.5.2", + "http-errors": "~2.0.1", "mime": "1.6.0", "ms": "2.1.3", - "on-finished": "2.4.1", + "on-finished": "~2.4.1", "range-parser": "~1.2.1", - "statuses": "2.0.1" + "statuses": "~2.0.2" }, "engines": { "node": ">= 0.8.0" @@ -8360,25 +8337,16 @@ "integrity": "sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A==", "license": "MIT" }, - "node_modules/send/node_modules/encodeurl": { - "version": "1.0.2", - "resolved": "https://registry.npmjs.org/encodeurl/-/encodeurl-1.0.2.tgz", - "integrity": "sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w==", - "license": "MIT", - "engines": { - "node": ">= 0.8" - } - }, "node_modules/serve-static": { - "version": "1.16.2", - "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.2.tgz", - "integrity": "sha512-VqpjJZKadQB/PEbEwvFdO43Ax5dFBZ2UECszz8bQ7pi7wt//PWe1P6MN7eCnjsatYtBT6EuiClbjSWP2WrIoTw==", + "version": "1.16.3", + "resolved": "https://registry.npmjs.org/serve-static/-/serve-static-1.16.3.tgz", + "integrity": "sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA==", "license": "MIT", "dependencies": { "encodeurl": "~2.0.0", "escape-html": "~1.0.3", "parseurl": "~1.3.3", - "send": "0.19.0" + "send": "~0.19.1" }, "engines": { "node": ">= 0.8.0" @@ -8584,9 +8552,9 @@ "license": "MIT" }, "node_modules/statuses": { - "version": "2.0.1", - "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.1.tgz", - "integrity": "sha512-RwNA9Z/7PrK06rYLIzFMlaF+l73iwpzsqRIFgbMLbTcLD6cOao82TaWefPXQvB2fOC4AjuYSEndS7N/mTCbkdQ==", + "version": "2.0.2", + "resolved": "https://registry.npmjs.org/statuses/-/statuses-2.0.2.tgz", + "integrity": "sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw==", "license": "MIT", "engines": { "node": ">= 0.8" @@ -8795,9 +8763,9 @@ "license": "MIT" }, "node_modules/ts-jest": { - "version": "29.4.5", - "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.4.5.tgz", - "integrity": "sha512-HO3GyiWn2qvTQA4kTgjDcXiMwYQt68a1Y8+JuLRVpdIzm+UOLSHgl/XqR4c6nzJkq5rOkjc02O2I7P7l/Yof0Q==", + "version": "29.4.6", + "resolved": "https://registry.npmjs.org/ts-jest/-/ts-jest-29.4.6.tgz", + "integrity": "sha512-fSpWtOO/1AjSNQguk43hb/JCo16oJDnMJf3CdEGNkqsEX3t0KX96xvyX1D7PfLCpVoKu4MfVrqUkFyblYoY4lA==", "dev": true, "license": "MIT", "dependencies": { @@ -9015,9 +8983,9 @@ } }, "node_modules/update-browserslist-db": { - "version": "1.1.4", - "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.1.4.tgz", - "integrity": "sha512-q0SPT4xyU84saUX+tomz1WLkxUbuaJnR1xWt17M7fJtEJigJeWUNGUqrauFXsHnqev9y9JTRGwk13tFBuKby4A==", + "version": "1.2.3", + "resolved": "https://registry.npmjs.org/update-browserslist-db/-/update-browserslist-db-1.2.3.tgz", + "integrity": "sha512-Js0m9cx+qOgDxo0eMiFGEueWztz+d4+M3rGlmKPT+T4IS/jP4ylw3Nwpu6cpTTP8R1MAC1kF4VbdLt3ARf209w==", "dev": true, "funding": [ { @@ -9350,9 +9318,9 @@ } }, "node_modules/zod": { - "version": "4.1.13", - "resolved": "https://registry.npmjs.org/zod/-/zod-4.1.13.tgz", - "integrity": "sha512-AvvthqfqrAhNH9dnfmrfKzX5upOdjUVJYFqNSlkmGf64gRaTzlPwz99IHYnVs28qYAybvAlBV+H7pn0saFY4Ig==", + "version": "4.2.1", + "resolved": "https://registry.npmjs.org/zod/-/zod-4.2.1.tgz", + "integrity": "sha512-0wZ1IRqGGhMP76gLqz8EyfBXKk0J2qo2+H3fi4mcUP/KtTocoX08nmIAHl1Z2kJIZbZee8KOpBCSNPRgauucjw==", "license": "MIT", "funding": { "url": "https://github.com/sponsors/colinhacks" diff --git a/src/agents/jira-sub-agent.ts b/src/agents/jira-sub-agent.ts index 0dfae6f..2f45d95 100644 --- a/src/agents/jira-sub-agent.ts +++ b/src/agents/jira-sub-agent.ts @@ -72,7 +72,7 @@ const AcceptanceCriteriaValidationSchema = z.object({ // Analysis of each derived requirement against the PR criteriaAnalysis: z.array( z.object({ - criteriaId: z.string(), + criteriaId: z.string().optional(), criteriaText: z.string(), status: z.enum(['met', 'unmet', 'partial', 'unclear']), confidence: z.number().min(0).max(100), diff --git a/src/cli/commands/analyze.command.ts b/src/cli/commands/analyze.command.ts index ddb6c51..56c01bc 100644 --- a/src/cli/commands/analyze.command.ts +++ b/src/cli/commands/analyze.command.ts @@ -286,6 +286,10 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { console.error(chalk.gray(' - Anthropic (Claude): export ANTHROPIC_API_KEY="your-api-key"')); console.error(chalk.gray(' - OpenAI (GPT): export OPENAI_API_KEY="your-api-key"')); console.error(chalk.gray(' - Google (Gemini): export GOOGLE_API_KEY="your-api-key"')); + console.error(chalk.gray(' - Zhipu (GLM): export ZHIPU_API_KEY="your-api-key"')); + if (options.verbose) { + console.error(chalk.gray(` Debug: Provider=${provider}, Config apiKeys=${JSON.stringify(config.apiKeys || {})}`)); + } process.exit(1); } @@ -420,6 +424,9 @@ export async function analyzePR(options: AnalyzeOptions = {}): Promise { // Run Peer Review if enabled (via flag or config) const peerReviewEnabled = options.peerReview || config.peerReview?.enabled; + if (options.verbose) { + console.log(chalk.gray(`\n Debug: peerReviewEnabled=${peerReviewEnabled}, options.peerReview=${options.peerReview}, config.peerReview?.enabled=${config.peerReview?.enabled}`)); + } if (peerReviewEnabled) { // Pass the same provider config to peer review so it uses the same LLM await runPeerReview(config, diff, title, result, options.verbose || false, { @@ -667,6 +674,9 @@ async function runPeerReview( spinner.warn('Peer Review enabled but not configured. Add Jira settings to config.'); console.log(chalk.gray(' Run: pr-agent config --set peerReview.instanceUrl=https://your.atlassian.net')); console.log(chalk.gray(' Or configure MCP: peerReview.useMcp=true')); + if (verbose) { + console.log(chalk.gray(` Debug: peerReviewConfig=${JSON.stringify(peerReviewConfig)}`)); + } return; } diff --git a/src/cli/commands/help.command.ts b/src/cli/commands/help.command.ts index 437f0e3..1fb68ed 100644 --- a/src/cli/commands/help.command.ts +++ b/src/cli/commands/help.command.ts @@ -52,7 +52,7 @@ export function displayHelp(): void { console.log(' Use --branch to override for a single analysis\n'); console.log(chalk.dim(' Advanced Options:')); - console.log(' --provider AI provider: anthropic|openai|google'); + console.log(' --provider AI provider: anthropic|openai|google|zhipu'); console.log(' --model Specific model to use'); console.log(' --title PR title (auto-detected from git)'); console.log(' --max-cost Maximum cost limit (default: $5.00)'); diff --git a/src/cli/index.ts b/src/cli/index.ts index 4c4c3d6..05b9576 100644 --- a/src/cli/index.ts +++ b/src/cli/index.ts @@ -35,7 +35,7 @@ program .option('--staged', 'Analyze staged changes (git diff --staged)') .option('--branch ', 'Analyze against specific branch') .option('--title ', 'PR title (auto-detected from git)') - .option('--provider ', 'AI provider (anthropic|openai|google)') + .option('--provider ', 'AI provider (anthropic|openai|google|zhipu)') .option('--model ', 'Specific model to use') .option('--agent', 'Force intelligent agent (recommended for large diffs)') .option('--summary', 'Show summary only') diff --git a/src/cli/utils/config-loader.ts b/src/cli/utils/config-loader.ts index d18ca2b..24c1a3e 100644 --- a/src/cli/utils/config-loader.ts +++ b/src/cli/utils/config-loader.ts @@ -11,6 +11,7 @@ export interface UserConfig { anthropic?: string; openai?: string; google?: string; + zhipu?: string; }; ai?: { provider?: string; @@ -218,6 +219,7 @@ export function getApiKey(provider: string, config?: UserConfig): string | undef anthropic: 'ANTHROPIC_API_KEY', openai: 'OPENAI_API_KEY', google: 'GOOGLE_API_KEY', + zhipu: 'ZHIPU_API_KEY', }; const envVar = envVarMap[provider.toLowerCase()]; diff --git a/src/providers/index.ts b/src/providers/index.ts index 53e97cd..3533f79 100644 --- a/src/providers/index.ts +++ b/src/providers/index.ts @@ -3,4 +3,5 @@ export * from './provider.factory.js'; export * from './anthropic.provider.js'; export * from './openai.provider.js'; export * from './google.provider.js'; +export * from './zhipu.provider.js'; diff --git a/src/providers/provider.factory.ts b/src/providers/provider.factory.ts index ee7762d..50f7f6c 100644 --- a/src/providers/provider.factory.ts +++ b/src/providers/provider.factory.ts @@ -2,9 +2,10 @@ import { ILLMProvider, ProviderConfig } from './provider.interface.js'; import { AnthropicProvider } from './anthropic.provider.js'; import { OpenAIProvider } from './openai.provider.js'; import { GoogleProvider } from './google.provider.js'; +import { ZhipuProvider } from './zhipu.provider.js'; import { BaseChatModel } from '@langchain/core/language_models/chat_models'; -export type SupportedProvider = 'anthropic' | 'openai' | 'google'; +export type SupportedProvider = 'anthropic' | 'openai' | 'google' | 'zhipu'; export interface ProviderOptions { provider?: SupportedProvider; @@ -48,8 +49,11 @@ export class ProviderFactory { case 'google': provider = new GoogleProvider(apiKey); break; + case 'zhipu': + provider = new ZhipuProvider(apiKey); + break; default: - throw new Error(`Unsupported provider: ${providerName}. Supported: anthropic, openai, google`); + throw new Error(`Unsupported provider: ${providerName}. Supported: anthropic, openai, google, zhipu`); } // Cache the provider if no specific API key was provided @@ -109,6 +113,7 @@ export class ProviderFactory { const normalized = name.toLowerCase(); if (normalized === 'claude') return 'anthropic'; if (normalized === 'gemini') return 'google'; + if (normalized === 'glm' || normalized === 'zhipuai') return 'zhipu'; return normalized; } @@ -116,7 +121,7 @@ export class ProviderFactory { * Get list of available providers */ public static getAvailableProviders(): SupportedProvider[] { - return ['anthropic', 'openai', 'google']; + return ['anthropic', 'openai', 'google', 'zhipu']; } } diff --git a/src/providers/zhipu.provider.ts b/src/providers/zhipu.provider.ts new file mode 100644 index 0000000..3aa6f29 --- /dev/null +++ b/src/providers/zhipu.provider.ts @@ -0,0 +1,41 @@ +import { ChatAnthropic } from '@langchain/anthropic'; +import { BaseChatModel } from '@langchain/core/language_models/chat_models'; +import { ILLMProvider, ProviderConfig } from './provider.interface.js'; + +/** + * Zhipu AI (智谱AI) provider implementation + * Uses Anthropic-compatible API endpoint + * Docs: https://docs.z.ai/ + */ +export class ZhipuProvider implements ILLMProvider { + public readonly name = 'zhipu'; + private readonly apiKey: string; + private readonly baseUrl = 'https://api.z.ai/api/anthropic'; + + constructor(apiKey?: string) { + this.apiKey = apiKey || process.env.ZHIPU_API_KEY || ''; + } + + public isConfigured(): boolean { + return !!this.apiKey; + } + + public getDefaultModel(): string { + // GLM-4.7 is mapped to claude-sonnet-4-20250514 in Zhipu's Anthropic-compatible API + return 'claude-sonnet-4-20250514'; + } + + public getChatModel(config: ProviderConfig = {}): BaseChatModel { + if (!this.isConfigured()) { + throw new Error('Zhipu API key is not configured. Set ZHIPU_API_KEY environment variable.'); + } + + return new ChatAnthropic({ + anthropicApiKey: this.apiKey, + anthropicApiUrl: this.baseUrl, + modelName: config.model || this.getDefaultModel(), + temperature: config.temperature ?? 0.2, + maxTokens: config.maxTokens ?? 4000, + }); + } +} diff --git a/src/types.ts b/src/types.ts index c2d1c97..136370a 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,7 +1,7 @@ // PR Agent - Basic Types // Core types for PR analysis -export type AIProviderType = 'anthropic' | 'openai' | 'google'; +export type AIProviderType = 'anthropic' | 'openai' | 'google' | 'zhipu'; export interface PRInfo { number: number; diff --git a/src/utils/config-validator.ts b/src/utils/config-validator.ts index b9b5838..fe8ace1 100644 --- a/src/utils/config-validator.ts +++ b/src/utils/config-validator.ts @@ -15,11 +15,12 @@ export const UserConfigSchema = z.object({ anthropic: z.string().optional(), openai: z.string().optional(), google: z.string().optional(), + zhipu: z.string().optional(), }) .optional(), ai: z .object({ - provider: z.enum(['anthropic', 'openai', 'google']).optional(), + provider: z.enum(['anthropic', 'openai', 'google', 'zhipu']).optional(), model: z.string().optional(), temperature: z.number().min(0).max(2).optional(), maxTokens: z.number().positive().int().optional(), @@ -63,6 +64,26 @@ export const UserConfigSchema = z.object({ showRecommendations: z.boolean().optional(), }) .optional(), + peerReview: z + .object({ + enabled: z.boolean().optional(), + provider: z.string().optional(), + useMcp: z.boolean().optional(), + instanceUrl: z.string().url().optional(), + email: z.string().email().optional(), + apiToken: z.string().optional(), + defaultProject: z.string().optional(), + acceptanceCriteriaField: z.string().optional(), + storyPointsField: z.string().optional(), + ticketPatterns: z.array(z.string()).optional(), + analyzeAcceptanceCriteria: z.boolean().optional(), + rateTicketQuality: z.boolean().optional(), + generateTestSuggestions: z.boolean().optional(), + checkScopeCreep: z.boolean().optional(), + includeTicketDetails: z.boolean().optional(), + verbose: z.boolean().optional(), + }) + .optional(), }); /**