@elizaos/plugin-twitter 1.2.2 → 1.2.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.js +57 -58
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/interactions.ts","../src/client/auth.ts","../src/client/profile.ts","../src/client/relationships.ts","../src/client/search.ts","../src/client/tweets.ts","../src/client/client.ts","../src/utils.ts","../src/constants.ts","../src/utils/error-handler.ts","../node_modules/zod/dist/esm/v3/external.js","../node_modules/zod/dist/esm/v3/helpers/util.js","../node_modules/zod/dist/esm/v3/ZodError.js","../node_modules/zod/dist/esm/v3/locales/en.js","../node_modules/zod/dist/esm/v3/errors.js","../node_modules/zod/dist/esm/v3/helpers/parseUtil.js","../node_modules/zod/dist/esm/v3/helpers/errorUtil.js","../node_modules/zod/dist/esm/v3/types.js","../src/environment.ts","../src/post.ts","../src/timeline.ts","../src/templates.ts","../src/discovery.ts","../src/base.ts","../src/services/twitter.service.ts","../src/actions/postTweet.ts"],"sourcesContent":["import { type IAgentRuntime, logger } from \"@elizaos/core\";\nimport { TwitterInteractionClient } from \"./interactions\";\nimport { TwitterPostClient } from \"./post\";\nimport { TwitterTimelineClient } from \"./timeline\";\nimport { TwitterDiscoveryClient } from \"./discovery\";\nimport { validateTwitterConfig } from \"./environment\";\nimport { ClientBase } from \"./base\";\nimport { TwitterService } from \"./services/twitter.service.js\";\nimport { postTweetAction } from \"./actions/postTweet.js\";\nimport type { ITwitterClient } from \"./types\";\n\n/**\n * A manager that orchestrates all specialized Twitter logic:\n * - client: base operations (login, timeline caching, etc.)\n * - post: autonomous posting logic\n * - interaction: handling mentions, replies, and autonomous targeting\n * - timeline: processing timeline for actions (likes, retweets, replies)\n * - discovery: autonomous content discovery and engagement\n */\nexport class TwitterClientInstance implements ITwitterClient {\n client: ClientBase;\n post: TwitterPostClient;\n interaction: TwitterInteractionClient;\n timeline?: TwitterTimelineClient;\n discovery?: TwitterDiscoveryClient;\n service: TwitterService;\n\n constructor(runtime: IAgentRuntime, state: any) {\n // Pass twitterConfig to the base client\n this.client = new ClientBase(runtime, state);\n\n // Posting logic\n const postEnabledSetting = runtime.getSetting(\"TWITTER_ENABLE_POST\");\n logger.debug(`TWITTER_ENABLE_POST setting value: ${JSON.stringify(postEnabledSetting)}, type: ${typeof postEnabledSetting}`);\n \n const postEnabled = postEnabledSetting === \"true\" || postEnabledSetting === true;\n \n if (postEnabled) {\n logger.info(\"Twitter posting is ENABLED - creating post client\");\n this.post = new TwitterPostClient(this.client, runtime, state);\n } else {\n logger.info(\"Twitter posting is DISABLED - set TWITTER_ENABLE_POST=true to enable automatic posting\");\n }\n\n // Mentions and interactions\n const repliesEnabled = runtime.getSetting(\"TWITTER_ENABLE_REPLIES\") !== \"false\";\n \n if (repliesEnabled) {\n logger.info(\"Twitter replies/interactions are ENABLED\");\n this.interaction = new TwitterInteractionClient(\n this.client,\n runtime,\n state,\n );\n } else {\n logger.info(\"Twitter replies/interactions are DISABLED\");\n }\n\n // Timeline actions (likes, retweets, replies)\n const actionsEnabled = runtime.getSetting(\"TWITTER_ENABLE_ACTIONS\") === \"true\";\n \n if (actionsEnabled) {\n logger.info(\"Twitter timeline actions are ENABLED\");\n this.timeline = new TwitterTimelineClient(this.client, runtime, state);\n } else {\n logger.info(\"Twitter timeline actions are DISABLED\");\n }\n\n // Discovery service for autonomous content discovery\n const discoveryEnabled = runtime.getSetting(\"TWITTER_ENABLE_DISCOVERY\") === \"true\" ||\n (actionsEnabled && runtime.getSetting(\"TWITTER_ENABLE_DISCOVERY\") !== \"false\");\n \n if (discoveryEnabled) {\n logger.info(\"Twitter discovery service is ENABLED\");\n this.discovery = new TwitterDiscoveryClient(this.client, runtime, state);\n } else {\n logger.info(\"Twitter discovery service is DISABLED - set TWITTER_ENABLE_DISCOVERY=true to enable\");\n }\n\n this.service = TwitterService.getInstance();\n }\n}\n\nasync function startTwitterClient(runtime: IAgentRuntime): Promise<void> {\n try {\n logger.log(\"🔧 Initializing Twitter plugin...\");\n\n await validateTwitterConfig(runtime);\n\n logger.log(\"✅ Twitter configuration validated successfully\");\n\n const twitterClient = new TwitterClientInstance(runtime, {});\n\n await twitterClient.client.init();\n\n // Add to service map\n runtime.registerService(TwitterService);\n\n // Start appropriate services based on configuration\n if (twitterClient.post) {\n logger.log(\"📮 Starting Twitter post client...\");\n await twitterClient.post.start();\n }\n\n if (twitterClient.interaction) {\n logger.log(\"💬 Starting Twitter interaction client...\");\n await twitterClient.interaction.start();\n }\n\n if (twitterClient.timeline) {\n logger.log(\"📊 Starting Twitter timeline client...\");\n await twitterClient.timeline.start();\n }\n\n if (twitterClient.discovery) {\n logger.log(\"🔍 Starting Twitter discovery client...\");\n await twitterClient.discovery.start();\n }\n\n logger.log(\"✅ Twitter plugin started successfully\");\n } catch (error) {\n logger.error(\"🚨 Failed to start Twitter plugin:\", error);\n throw error;\n }\n}\n\nexport const TwitterPlugin = {\n name: \"twitter\",\n description: \"Twitter client with posting, interactions, and timeline actions\",\n actions: [postTweetAction],\n services: [TwitterService],\n init: startTwitterClient,\n};\n\nexport default TwitterPlugin;\n","import {\n ChannelType,\n type Content,\n ContentType,\n EventType,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type MessagePayload,\n ModelType,\n createUniqueUuid,\n logger,\n} from \"@elizaos/core\";\nimport type { ClientBase } from \"./base\";\nimport { SearchMode } from \"./client/index\";\nimport type { Tweet as ClientTweet } from \"./client/tweets\";\nimport type {\n Tweet as CoreTweet,\n TwitterInteractionMemory,\n TwitterInteractionPayload,\n TwitterLikeReceivedPayload,\n TwitterMemory,\n TwitterQuoteReceivedPayload,\n TwitterRetweetReceivedPayload,\n} from \"./types\";\nimport { TwitterEventTypes } from \"./types\";\nimport { sendTweet } from \"./utils\";\nimport { shouldTargetUser, getTargetUsers } from \"./environment\";\n\n/**\n * Template for generating dialog and actions for a Twitter message handler.\n *\n * @type {string}\n */\nexport const twitterMessageHandlerTemplate = `# Task: Generate dialog and actions for {{agentName}}.\n{{providers}}\nHere is the current post text again. Remember to include an action if the current post text includes a prompt that asks for one of the available actions mentioned above (does not need to be exact)\n{{currentPost}}\n{{imageDescriptions}}\n\n# Instructions: Write the next message for {{agentName}}. Include the appropriate action from the list: {{actionNames}}\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{ \"thought\": \"<string>\", \"name\": \"{{agentName}}\", \"text\": \"<string>\", \"action\": \"<string>\" }\n\\`\\`\\`\n\nThe \"action\" field should be one of the options in [Available Actions] and the \"text\" field should be the response you want to send. Do not including any thinking or internal reflection in the \"text\" field. \"thought\" should be a short description of what the agent is thinking about before responding, inlcuding a brief justification for the response.`;\n\n/**\n * Template for generating dialog and actions for a message handler.\n * @type {string}\n */\nexport const messageHandlerTemplate = `\n{{agentName}} is replying to you:\n{{senderName}}: {{userMessage}}\n\n# Task: Generate a reply for {{agentName}}.\n{{providers}}\n\n# Instructions: Write a thoughtful response to {{senderName}} that is appropriate and relevant to their message. Do not including any thinking, self-reflection or internal dialog in your response.`;\n\n/**\n * The TwitterInteractionClient class manages Twitter interactions,\n * including handling mentions, managing timelines, and engaging with other users.\n * It extends the base Twitter client functionality to provide mention handling,\n * user interaction, and follow change detection capabilities.\n *\n * @extends ClientBase\n */\nexport class TwitterInteractionClient {\n client: ClientBase;\n runtime: IAgentRuntime;\n twitterUsername: string;\n private twitterUserId: string;\n private isDryRun: boolean;\n private state: any;\n private isRunning: boolean = false;\n private lastProcessedTimestamp: number = Date.now();\n\n /**\n * Constructor to initialize the Twitter interaction client with runtime and state management.\n *\n * @param {ClientBase} client - The client instance.\n * @param {IAgentRuntime} runtime - The runtime instance for agent operations.\n * @param {any} state - The state object containing configuration settings.\n */\n constructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n this.client = client;\n this.runtime = runtime;\n this.state = state;\n\n // Set dry run mode - checks both state and runtime settings\n this.isDryRun = this.state?.TWITTER_DRY_RUN ?? (this.runtime.getSetting(\"TWITTER_DRY_RUN\") as unknown as boolean);\n }\n\n /**\n * Asynchronously starts the process of handling Twitter interactions on a loop.\n * Uses the unified TWITTER_ENGAGEMENT_INTERVAL setting.\n */\n async start() {\n this.isRunning = true;\n \n const handleTwitterInteractionsLoop = () => {\n if (!this.isRunning) {\n logger.info(\"Twitter interaction client stopped, exiting loop\");\n return;\n }\n \n // Get interval in minutes and convert to milliseconds\n const engagementIntervalMinutes = parseInt(\n this.state?.TWITTER_ENGAGEMENT_INTERVAL ||\n this.runtime.getSetting(\"TWITTER_ENGAGEMENT_INTERVAL\") as string ||\n \"30\"\n );\n \n const interactionInterval = engagementIntervalMinutes * 60 * 1000;\n \n logger.info(`Twitter interaction client will check every ${engagementIntervalMinutes} minutes`);\n\n this.handleTwitterInteractions();\n \n if (this.isRunning) {\n setTimeout(handleTwitterInteractionsLoop, interactionInterval);\n }\n };\n handleTwitterInteractionsLoop();\n }\n\n /**\n * Stops the Twitter interaction client\n */\n async stop() {\n logger.log(\"Stopping Twitter interaction client...\");\n this.isRunning = false;\n }\n\n /**\n * Asynchronously handles Twitter interactions by checking for mentions and target user posts.\n */\n async handleTwitterInteractions() {\n logger.log(\"Checking Twitter interactions\");\n\n const twitterUsername = this.client.profile?.username;\n \n try {\n // Check for mentions first (replies enabled by default)\n const repliesEnabled = this.runtime.getSetting(\"TWITTER_ENABLE_REPLIES\") !== \"false\";\n \n if (repliesEnabled) {\n await this.handleMentions(twitterUsername);\n }\n \n // Check target users' posts for autonomous engagement\n const targetUsersConfig = this.runtime.getSetting(\"TWITTER_TARGET_USERS\") as string || \"\";\n \n if (targetUsersConfig?.trim()) {\n await this.handleTargetUserPosts(targetUsersConfig);\n }\n\n // Save the latest checked tweet ID to the file\n await this.client.cacheLatestCheckedTweetId();\n\n logger.log(\"Finished checking Twitter interactions\");\n } catch (error) {\n logger.error(\"Error handling Twitter interactions:\", error);\n }\n }\n\n /**\n * Handle mentions and replies\n */\n private async handleMentions(twitterUsername: string) {\n try {\n // Check for mentions\n const cursorKey = `twitter/${twitterUsername}/mention_cursor`;\n const cachedCursor: String = await this.runtime.getCache<string>(cursorKey);\n\n const searchResult = await this.client.fetchSearchTweets(\n `@${twitterUsername}`,\n 20,\n SearchMode.Latest,\n String(cachedCursor),\n );\n\n const mentionCandidates = searchResult.tweets;\n\n // If we got tweets and there's a valid cursor, cache it\n if (mentionCandidates.length > 0 && searchResult.previous) {\n await this.runtime.setCache(cursorKey, searchResult.previous);\n } else if (!searchResult.previous && !searchResult.next) {\n // If both previous and next are missing, clear the outdated cursor\n await this.runtime.setCache(cursorKey, \"\");\n }\n\n await this.processMentionTweets(mentionCandidates);\n } catch (error) {\n logger.error(\"Error handling mentions:\", error);\n }\n }\n\n /**\n * Handle autonomous engagement with target users' posts\n */\n private async handleTargetUserPosts(targetUsersConfig: string) {\n try {\n const targetUsers = getTargetUsers(targetUsersConfig);\n \n if (targetUsers.length === 0 && !targetUsersConfig.includes(\"*\")) {\n return; // No target users configured\n }\n \n logger.info(`Checking posts from target users: ${targetUsers.join(\", \") || \"everyone (*)\"}`);\n \n // For each target user, search their recent posts\n for (const targetUser of targetUsers) {\n try {\n const normalizedUsername = targetUser.replace(/^@/, \"\");\n \n // Search for recent posts from this user\n const searchQuery = `from:${normalizedUsername} -is:reply -is:retweet`;\n const searchResult = await this.client.fetchSearchTweets(\n searchQuery,\n 10, // Get up to 10 recent posts per user\n SearchMode.Latest\n );\n \n if (searchResult.tweets.length > 0) {\n logger.info(`Found ${searchResult.tweets.length} posts from @${normalizedUsername}`);\n \n // Process these tweets for potential engagement\n await this.processTargetUserTweets(searchResult.tweets, normalizedUsername);\n }\n } catch (error) {\n logger.error(`Error searching posts from @${targetUser}:`, error);\n }\n }\n \n // If wildcard is configured, also check timeline for any interesting posts\n if (targetUsersConfig.includes(\"*\")) {\n await this.processTimelineForEngagement();\n }\n } catch (error) {\n logger.error(\"Error handling target user posts:\", error);\n }\n }\n\n /**\n * Process tweets from target users for potential engagement\n */\n private async processTargetUserTweets(tweets: ClientTweet[], username: string) {\n const maxEngagementsPerRun = parseInt(\n this.runtime.getSetting(\"TWITTER_MAX_ENGAGEMENTS_PER_RUN\") as string || \"10\"\n );\n \n let engagementCount = 0;\n \n for (const tweet of tweets) {\n if (engagementCount >= maxEngagementsPerRun) {\n logger.info(`Reached max engagements limit (${maxEngagementsPerRun})`);\n break;\n }\n \n // Skip if already processed\n const tweetId = createUniqueUuid(this.runtime, tweet.id);\n const existingMemory = await this.runtime.getMemoryById(tweetId);\n \n if (existingMemory) {\n continue; // Already processed\n }\n \n // Skip if tweet is too old (older than 24 hours)\n const tweetAge = Date.now() - (tweet.timestamp * 1000);\n const maxAge = 24 * 60 * 60 * 1000; // 24 hours\n \n if (tweetAge > maxAge) {\n continue;\n }\n \n // Decide whether to engage with this tweet\n const shouldEngage = await this.shouldEngageWithTweet(tweet);\n \n if (shouldEngage) {\n logger.info(`Engaging with tweet from @${username}: ${tweet.text.substring(0, 50)}...`);\n \n // Create necessary context for the tweet\n await this.ensureTweetContext(tweet);\n \n // Handle the tweet (generate and send reply)\n const engaged = await this.engageWithTweet(tweet);\n \n if (engaged) {\n engagementCount++;\n }\n }\n }\n }\n\n /**\n * Process timeline for engagement when wildcard is configured\n */\n private async processTimelineForEngagement() {\n try {\n // This would use the timeline client if available, but for now\n // we'll do a general search for recent popular tweets\n const searchResult = await this.client.fetchSearchTweets(\n \"min_retweets:10 min_faves:20 -is:reply -is:retweet lang:en\",\n 20,\n SearchMode.Latest\n );\n \n const relevantTweets = searchResult.tweets.filter(tweet => {\n // Filter for tweets from the last 12 hours\n const tweetAge = Date.now() - (tweet.timestamp * 1000);\n return tweetAge < 12 * 60 * 60 * 1000;\n });\n \n if (relevantTweets.length > 0) {\n logger.info(`Found ${relevantTweets.length} relevant tweets from timeline`);\n await this.processTargetUserTweets(relevantTweets, \"timeline\");\n }\n } catch (error) {\n logger.error(\"Error processing timeline for engagement:\", error);\n }\n }\n\n /**\n * Determine if the bot should engage with a specific tweet\n */\n private async shouldEngageWithTweet(tweet: ClientTweet): Promise<boolean> {\n try {\n // Create a simple evaluation prompt\n const evaluationContext = {\n tweet: tweet.text,\n author: tweet.username,\n metrics: {\n likes: tweet.likes || 0,\n retweets: tweet.retweets || 0,\n replies: tweet.replies || 0,\n },\n };\n \n const shouldEngageMemory: Memory = {\n id: createUniqueUuid(this.runtime, `eval-${tweet.id}`),\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId: createUniqueUuid(this.runtime, tweet.conversationId),\n content: {\n text: `Should I engage with this tweet? Tweet: \"${tweet.text}\" by @${tweet.username}`,\n evaluationContext,\n },\n createdAt: Date.now(),\n };\n \n const state = await this.runtime.composeState(shouldEngageMemory);\n const context = `You are ${this.runtime.character.name}. Should you reply to this tweet based on your interests and expertise?\n \nTweet by @${tweet.username}: \"${tweet.text}\"\n\nReply with YES if:\n- The topic relates to your interests or expertise\n- You can add valuable insights or perspective\n- The conversation seems constructive\n\nReply with NO if:\n- The topic is outside your knowledge\n- The tweet is inflammatory or controversial\n- You have nothing meaningful to add\n\nResponse (YES/NO):`;\n\n const response = await this.runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: context,\n temperature: 0.3,\n maxTokens: 10,\n stop: [\"\\n\"],\n });\n \n return response.trim().toUpperCase().includes(\"YES\");\n } catch (error) {\n logger.error(\"Error determining engagement:\", error);\n return false;\n }\n }\n\n /**\n * Ensure tweet context exists (world, room, entity)\n */\n private async ensureTweetContext(tweet: ClientTweet) {\n const userId = tweet.userId;\n const conversationId = tweet.conversationId || tweet.id;\n const username = tweet.username;\n \n // Create world for user\n const worldId = createUniqueUuid(this.runtime, userId);\n await this.runtime.ensureWorldExists({\n id: worldId,\n name: `${username}'s Twitter`,\n agentId: this.runtime.agentId,\n serverId: userId,\n metadata: {\n ownership: { ownerId: userId },\n twitter: {\n username: username,\n id: userId,\n },\n },\n });\n \n // Create room for conversation\n const roomId = createUniqueUuid(this.runtime, conversationId);\n \n // Ensure entity/connection\n const entityId = createUniqueUuid(this.runtime, userId);\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: username,\n name: tweet.name,\n source: \"twitter\",\n type: ChannelType.FEED,\n worldId: worldId,\n });\n \n // Save tweet as memory\n const tweetMemory: Memory = {\n id: createUniqueUuid(this.runtime, tweet.id),\n entityId,\n content: {\n text: tweet.text,\n url: tweet.permanentUrl,\n source: \"twitter\",\n tweet,\n },\n agentId: this.runtime.agentId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n };\n \n await this.runtime.createMemory(tweetMemory, \"messages\");\n }\n\n /**\n * Engage with a tweet by generating and sending a reply\n */\n private async engageWithTweet(tweet: ClientTweet): Promise<boolean> {\n try {\n const message: Memory = {\n id: createUniqueUuid(this.runtime, tweet.id),\n entityId: createUniqueUuid(this.runtime, tweet.userId),\n content: {\n text: tweet.text,\n source: \"twitter\",\n tweet,\n },\n agentId: this.runtime.agentId,\n roomId: createUniqueUuid(this.runtime, tweet.conversationId),\n createdAt: tweet.timestamp * 1000,\n };\n \n const result = await this.handleTweet({\n tweet,\n message,\n thread: tweet.thread || [tweet],\n });\n \n return result.text && result.text.length > 0;\n } catch (error) {\n logger.error(\"Error engaging with tweet:\", error);\n return false;\n }\n }\n\n /**\n * Processes all incoming tweets that mention the bot.\n * For each new tweet:\n * - Ensures world, room, and connection exist\n * - Saves the tweet as memory\n * - Emits thread-related events (THREAD_CREATED / THREAD_UPDATED)\n * - Delegates tweet content to `handleTweet` for reply generation\n *\n * Note: MENTION_RECEIVED is currently disabled (see TODO below)\n */\n async processMentionTweets(mentionCandidates: ClientTweet[]) {\n logger.log(\n \"Completed checking mentioned tweets:\",\n mentionCandidates.length,\n );\n let uniqueTweetCandidates = [...mentionCandidates];\n\n // Sort tweet candidates by ID in ascending order\n uniqueTweetCandidates = uniqueTweetCandidates\n .sort((a, b) => a.id.localeCompare(b.id))\n .filter((tweet) => tweet.userId !== this.client.profile.id);\n\n // Get TWITTER_TARGET_USERS configuration\n const targetUsersConfig =\n (this.runtime.getSetting(\"TWITTER_TARGET_USERS\") as string) || \"\";\n\n // Filter tweets based on TWITTER_TARGET_USERS if configured\n if (targetUsersConfig?.trim()) {\n uniqueTweetCandidates = uniqueTweetCandidates.filter((tweet) => {\n const shouldTarget = shouldTargetUser(\n tweet.username || \"\",\n targetUsersConfig,\n );\n if (!shouldTarget) {\n logger.log(\n `Skipping tweet from @${tweet.username} - not in target users list`,\n );\n }\n return shouldTarget;\n });\n }\n\n // Get max interactions per run setting\n const maxInteractionsPerRun = parseInt(\n this.runtime.getSetting(\"TWITTER_MAX_ENGAGEMENTS_PER_RUN\") as string || \"10\"\n );\n \n // Limit the number of interactions per run\n const tweetsToProcess = uniqueTweetCandidates.slice(0, maxInteractionsPerRun);\n logger.info(`Processing ${tweetsToProcess.length} of ${uniqueTweetCandidates.length} mention tweets (max: ${maxInteractionsPerRun})`);\n\n // for each tweet candidate, handle the tweet\n for (const tweet of tweetsToProcess) {\n if (\n !this.client.lastCheckedTweetId ||\n BigInt(tweet.id) > this.client.lastCheckedTweetId\n ) {\n // Generate the tweetId UUID the same way it's done in handleTweet\n const tweetId = createUniqueUuid(this.runtime, tweet.id);\n\n // Check if we've already processed this tweet\n const existingResponse = await this.runtime.getMemoryById(tweetId);\n\n if (existingResponse) {\n logger.log(`Already responded to tweet ${tweet.id}, skipping`);\n continue;\n }\n\n // Also check if we've already responded to this tweet (for chunked responses)\n // by looking for any memory with inReplyTo pointing to this tweet\n const conversationRoomId = createUniqueUuid(\n this.runtime,\n tweet.conversationId,\n );\n const existingReplies = await this.runtime.getMemories({\n tableName: \"messages\",\n roomId: conversationRoomId,\n count: 10, // Check recent messages in this room\n });\n\n // Check if any of the found memories is a reply to this specific tweet\n const hasExistingReply = existingReplies.some(\n (memory) =>\n memory.content.inReplyTo === tweetId ||\n memory.content.inReplyTo === tweet.id,\n );\n\n if (hasExistingReply) {\n logger.log(\n `Already responded to tweet ${tweet.id} (found in conversation history), skipping`,\n );\n continue;\n }\n\n logger.log(\"New Tweet found\", tweet.id);\n\n const userId = tweet.userId;\n const conversationId = tweet.conversationId || tweet.id;\n const roomId = createUniqueUuid(this.runtime, conversationId);\n const username = tweet.username;\n\n logger.log(\"----\");\n logger.log(`User: ${username} (${userId})`);\n logger.log(`Tweet: ${tweet.id}`);\n logger.log(`Conversation: ${conversationId}`);\n logger.log(`Room: ${roomId}`);\n logger.log(\"----\");\n\n // 1. Ensure world exists for the user\n const worldId = createUniqueUuid(this.runtime, userId);\n await this.runtime.ensureWorldExists({\n id: worldId,\n name: `${username}'s Twitter`,\n agentId: this.runtime.agentId,\n serverId: userId,\n metadata: {\n ownership: { ownerId: userId },\n twitter: {\n username: username,\n id: userId,\n },\n },\n });\n\n // 2. Ensure entity connection\n const entityId = createUniqueUuid(this.runtime, userId);\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: username,\n name: tweet.name,\n source: \"twitter\",\n type: ChannelType.FEED,\n worldId: worldId,\n });\n\n // 3. Create a memory for the tweet\n const memory: Memory = {\n id: tweetId,\n entityId,\n content: {\n text: tweet.text,\n url: tweet.permanentUrl,\n source: \"twitter\",\n tweet,\n },\n agentId: this.runtime.agentId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n };\n\n logger.log(\"Saving tweet memory...\");\n await this.runtime.createMemory(memory, \"messages\");\n\n // TODO: This doesn't work as intended - thread events are mixed with other events\n // and need a better implementation strategy\n // this.runtime.emitEvent(TwitterEventTypes.MENTION_RECEIVED, {\n // entityId,\n // memory: {...memory, id: createUniqueUuid(this.runtime)},\n // world: {id: worldId, ...},\n // isThread: !!tweet.thread,\n // });\n\n // 4. Handle thread-specific events\n if (tweet.thread && tweet.thread.length > 0) {\n const threadStartId = tweet.thread[0].id;\n const threadMemoryId = createUniqueUuid(\n this.runtime,\n `thread-${threadStartId}`,\n );\n\n const threadPayload = {\n runtime: this.runtime,\n entityId,\n conversationId: threadStartId,\n roomId: roomId,\n memory: memory,\n tweet: tweet,\n threadId: threadStartId,\n threadMemoryId: threadMemoryId,\n };\n\n // Check if this is a reply to an existing thread\n const previousThreadMemory =\n await this.runtime.getMemoryById(threadMemoryId);\n if (previousThreadMemory) {\n // This is a reply to an existing thread\n this.runtime.emitEvent(\n TwitterEventTypes.THREAD_UPDATED,\n threadPayload,\n );\n } else if (tweet.thread[0].id === tweet.id) {\n // This is the start of a new thread\n this.runtime.emitEvent(\n TwitterEventTypes.THREAD_CREATED,\n threadPayload,\n );\n }\n }\n\n await this.handleTweet({\n tweet,\n message: memory,\n thread: tweet.thread,\n });\n\n // Update the last checked tweet ID after processing each tweet\n this.client.lastCheckedTweetId = BigInt(tweet.id);\n }\n }\n }\n\n /**\n * Handles Twitter interactions such as likes, retweets, and quotes.\n * For each interaction:\n * - Creates a memory object\n * - Emits platform-specific events (LIKE_RECEIVED, RETWEET_RECEIVED, QUOTE_RECEIVED)\n * - Emits a generic REACTION_RECEIVED event with metadata\n */\n async handleInteraction(interaction: TwitterInteractionPayload) {\n if (interaction?.targetTweet?.conversationId) {\n const memory = this.createMemoryObject(\n interaction.type,\n `${interaction.id}-${interaction.type}`,\n interaction.userId,\n interaction.targetTweet.conversationId,\n );\n\n await this.runtime.createMemory(memory, \"messages\");\n\n // Create message for reaction\n const reactionMessage: TwitterMemory = {\n id: createUniqueUuid(this.runtime, interaction.targetTweetId),\n content: {\n text: interaction.targetTweet.text,\n source: \"twitter\",\n },\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n roomId: createUniqueUuid(\n this.runtime,\n interaction.targetTweet.conversationId,\n ),\n agentId: this.runtime.agentId,\n createdAt: Date.now(),\n };\n\n // Emit specific event for each type of interaction\n switch (interaction.type) {\n case \"like\": {\n const payload: TwitterLikeReceivedPayload = {\n runtime: this.runtime,\n tweet: interaction.targetTweet,\n user: {\n id: interaction.userId,\n username: interaction.username,\n name: interaction.name,\n },\n source: \"twitter\",\n };\n this.runtime.emitEvent(TwitterEventTypes.LIKE_RECEIVED, payload);\n break;\n }\n case \"retweet\": {\n const payload: TwitterRetweetReceivedPayload = {\n runtime: this.runtime,\n tweet: interaction.targetTweet,\n retweetId: interaction.retweetId || interaction.id,\n user: {\n id: interaction.userId,\n username: interaction.username,\n name: interaction.name,\n },\n source: \"twitter\",\n };\n this.runtime.emitEvent(TwitterEventTypes.RETWEET_RECEIVED, payload);\n break;\n }\n case \"quote\": {\n const payload: TwitterQuoteReceivedPayload = {\n runtime: this.runtime,\n quotedTweet: interaction.targetTweet,\n quoteTweet: interaction.quoteTweet || interaction.targetTweet,\n user: {\n id: interaction.userId,\n username: interaction.username,\n name: interaction.name,\n },\n message: reactionMessage,\n callback: async () => [],\n reaction: {\n type: \"quote\",\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n },\n source: \"twitter\",\n };\n this.runtime.emitEvent(TwitterEventTypes.QUOTE_RECEIVED, payload);\n break;\n }\n }\n\n // Also emit generic REACTION_RECEIVED event\n this.runtime.emitEvent(EventType.REACTION_RECEIVED, {\n runtime: this.runtime,\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n roomId: createUniqueUuid(\n this.runtime,\n interaction.targetTweet.conversationId,\n ),\n world: createUniqueUuid(this.runtime, interaction.userId),\n message: reactionMessage,\n source: \"twitter\",\n metadata: {\n type: interaction.type,\n targetTweetId: interaction.targetTweetId,\n username: interaction.username,\n userId: interaction.userId,\n timestamp: Date.now(),\n quoteText: interaction.type === \"quote\" ? (interaction.quoteTweet?.text || \"\") : undefined,\n },\n callback: async () => [],\n } as MessagePayload);\n }\n }\n\n /**\n * Creates a memory object for a given Twitter interaction.\n *\n * @param {string} type - The type of interaction (e.g., 'like', 'retweet', 'quote').\n * @param {string} id - The unique identifier for the interaction.\n * @param {string} userId - The ID of the user who initiated the interaction.\n * @param {string} conversationId - The ID of the conversation context.\n * @returns {TwitterInteractionMemory} The constructed memory object.\n */\n createMemoryObject(\n type: string,\n id: string,\n userId: string,\n conversationId: string,\n ): TwitterInteractionMemory {\n return {\n id: createUniqueUuid(this.runtime, id),\n agentId: this.runtime.agentId,\n entityId: createUniqueUuid(this.runtime, userId),\n roomId: createUniqueUuid(this.runtime, conversationId),\n content: {\n type,\n source: \"twitter\",\n },\n createdAt: Date.now(),\n };\n }\n\n /**\n * Asynchronously handles a tweet by generating a response and sending it.\n * This method processes the tweet content, determines if a response is needed,\n * generates appropriate response text, and sends the tweet reply.\n *\n * @param {object} params - The parameters object containing the tweet, message, and thread.\n * @param {Tweet} params.tweet - The tweet object to handle.\n * @param {Memory} params.message - The memory object associated with the tweet.\n * @param {Tweet[]} params.thread - The array of tweets in the thread.\n * @returns {object} - An object containing the text of the response and any relevant actions.\n */\n async handleTweet({\n tweet,\n message,\n thread,\n }: {\n tweet: ClientTweet;\n message: Memory;\n thread: ClientTweet[];\n }) {\n if (!message.content.text) {\n logger.log(\"Skipping Tweet with no text\", tweet.id);\n return { text: \"\", actions: [\"IGNORE\"] };\n }\n\n // Create a callback for handling the response\n const callback: HandlerCallback = async (\n response: Content,\n tweetId?: string,\n ) => {\n try {\n if (!response.text) {\n logger.warn(\"No text content in response, skipping tweet reply\");\n return [];\n }\n\n const tweetToReplyTo = tweetId || tweet.id;\n\n if (this.isDryRun) {\n logger.info(\n `[DRY RUN] Would have replied to ${tweet.username} with: ${response.text}`,\n );\n return [];\n }\n\n logger.info(`Replying to tweet ${tweetToReplyTo}`);\n\n // Create the actual tweet using the Twitter API through the client\n const tweetResult = await sendTweet(\n this.client,\n response.text,\n [],\n tweetToReplyTo,\n );\n\n if (!tweetResult) {\n throw new Error(\"Failed to get tweet result from response\");\n }\n\n // Create memory for our response\n const responseId = createUniqueUuid(this.runtime, tweetResult.id);\n const responseMemory: Memory = {\n id: responseId,\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId: message.roomId,\n content: {\n ...response,\n source: \"twitter\",\n inReplyTo: message.id,\n },\n createdAt: Date.now(),\n };\n\n await this.runtime.createMemory(responseMemory, \"messages\");\n\n // Return the created memory\n return [responseMemory];\n } catch (error) {\n logger.error(\"Error in tweet reply callback:\", error);\n return [];\n }\n };\n\n const twitterUserId = tweet.userId;\n const entityId = createUniqueUuid(this.runtime, twitterUserId);\n const twitterUsername = tweet.username;\n\n // Emit MESSAGE_RECEIVED event\n this.runtime.emitEvent(\n [TwitterEventTypes.MESSAGE_RECEIVED, EventType.MESSAGE_RECEIVED],\n {\n runtime: this.runtime,\n world: createUniqueUuid(this.runtime, twitterUserId),\n entityId: entityId,\n roomId: message.roomId,\n userId: twitterUserId,\n message: message,\n thread: thread,\n source: \"twitter\",\n callback,\n entityName: twitterUsername,\n },\n );\n\n // For synchronous response generation\n const response = await callback(message.content, tweet.id);\n\n // Check if response is an array of memories and extract the text\n let responseText = \"\";\n if (Array.isArray(response) && response.length > 0) {\n const firstResponse = response[0];\n if (firstResponse?.content?.text) {\n responseText = firstResponse.content.text;\n }\n }\n\n return {\n text: responseText,\n actions: responseText ? [\"REPLY\"] : [\"IGNORE\"],\n };\n }\n}\n","import { TwitterApi } from \"twitter-api-v2\";\nimport { Profile } from \"./profile\";\n\n/**\n * Twitter API v2 authentication using developer credentials\n */\nexport class TwitterAuth {\n private v2Client: TwitterApi | null = null;\n private authenticated = false;\n private profile?: Profile;\n\n constructor(\n private appKey: string,\n private appSecret: string,\n private accessToken: string,\n private accessSecret: string,\n ) {\n this.initializeClient();\n }\n\n private initializeClient(): void {\n this.v2Client = new TwitterApi({\n appKey: this.appKey,\n appSecret: this.appSecret,\n accessToken: this.accessToken,\n accessSecret: this.accessSecret,\n });\n this.authenticated = true;\n }\n\n /**\n * Get the Twitter API v2 client\n */\n getV2Client(): TwitterApi {\n if (!this.v2Client) {\n throw new Error(\"Twitter API client not initialized\");\n }\n return this.v2Client;\n }\n\n /**\n * Check if authenticated\n */\n async isLoggedIn(): Promise<boolean> {\n if (!this.authenticated || !this.v2Client) {\n return false;\n }\n\n try {\n // Verify credentials by getting current user\n const me = await this.v2Client.v2.me();\n return !!me.data;\n } catch (error) {\n console.error(\"Failed to verify authentication:\", error);\n return false;\n }\n }\n\n /**\n * Get current user profile\n */\n async me(): Promise<Profile | undefined> {\n if (this.profile) {\n return this.profile;\n }\n\n if (!this.v2Client) {\n throw new Error(\"Not authenticated\");\n }\n\n try {\n const { data: user } = await this.v2Client.v2.me({\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"description\",\n \"profile_image_url\",\n \"public_metrics\",\n \"verified\",\n \"location\",\n \"created_at\",\n ],\n });\n\n this.profile = {\n userId: user.id,\n username: user.username,\n name: user.name,\n biography: user.description,\n avatar: user.profile_image_url,\n followersCount: user.public_metrics?.followers_count,\n followingCount: user.public_metrics?.following_count,\n isVerified: user.verified,\n location: user.location || \"\",\n joined: user.created_at ? new Date(user.created_at) : undefined,\n };\n\n return this.profile;\n } catch (error) {\n console.error(\"Failed to get user profile:\", error);\n return undefined;\n }\n }\n\n /**\n * Logout (clear credentials)\n */\n async logout(): Promise<void> {\n this.v2Client = null;\n this.authenticated = false;\n this.profile = undefined;\n }\n\n /**\n * For compatibility - always returns true since we use API keys\n */\n hasToken(): boolean {\n return this.authenticated;\n }\n}\n","import stringify from \"json-stable-stringify\";\nimport { type RequestApiResult } from \"./api-types\";\nimport type { TwitterAuth } from \"./auth\";\nimport type { TwitterApiErrorRaw } from \"./errors\";\n\n/**\n * Interface representing a raw user object from a legacy system.\n * @typedef {Object} LegacyUserRaw\n * @property {string} [created_at] - The date the user was created.\n * @property {string} [description] - The user's description.\n * @property {Object} [entities] - Additional entities associated with the user.\n * @property {Object} [url] - The URL associated with the user.\n * @property {Object[]} [urls] - Array of URLs associated with the user.\n * @property {string} [expanded_url] - The expanded URL.\n * @property {number} [favourites_count] - The number of favorited items.\n * @property {number} [followers_count] - The number of followers.\n * @property {number} [friends_count] - The number of friends.\n * @property {number} [media_count] - The number of media items.\n * @property {number} [statuses_count] - The number of statuses.\n * @property {string} [id_str] - The user ID as a string.\n * @property {number} [listed_count] - The number of lists the user is listed in.\n * @property {string} [name] - The user's name.\n * @property {string} location - The user's location.\n * @property {boolean} [geo_enabled] - Indicates if geo locations are enabled.\n * @property {string[]} [pinned_tweet_ids_str] - Array of pinned tweet IDs as strings.\n * @property {string} [profile_background_color] - The background color of the user's profile.\n * @property {string} [profile_banner_url] - The URL of the user's profile banner.\n * @property {string} [profile_image_url_https] - The URL of the user's profile image (HTTPS).\n * @property {boolean} [protected] - Indicates if the user's account is protected.\n * @property {string} [screen_name] - The user's screen name.\n * @property {boolean} [verified] - Indicates if the user is verified.\n * @property {boolean} [has_custom_timelines] - Indicates if the user has custom timelines.\n * @property {boolean} [has_extended_profile] - Indicates if the user has an extended profile.\n * @property {string} [url] - The user's URL.\n * @property {boolean} [can_dm] - Indicates if direct messages are enabled for the user.\n */\nexport interface LegacyUserRaw {\n created_at?: string;\n description?: string;\n entities?: {\n url?: {\n urls?: {\n expanded_url?: string;\n }[];\n };\n };\n favourites_count?: number;\n followers_count?: number;\n friends_count?: number;\n media_count?: number;\n statuses_count?: number;\n id_str?: string;\n listed_count?: number;\n name?: string;\n location: string;\n geo_enabled?: boolean;\n pinned_tweet_ids_str?: string[];\n profile_background_color?: string;\n profile_banner_url?: string;\n profile_image_url_https?: string;\n protected?: boolean;\n screen_name?: string;\n verified?: boolean;\n has_custom_timelines?: boolean;\n has_extended_profile?: boolean;\n url?: string;\n can_dm?: boolean;\n}\n\n/**\n * A parsed profile object.\n */\n/**\n * Interface representing a user profile.\n * @typedef {Object} Profile\n * @property {string} [avatar] - The URL to the user's avatar.\n * @property {string} [banner] - The URL to the user's banner image.\n * @property {string} [biography] - The user's biography.\n * @property {string} [birthday] - The user's birthday.\n * @property {number} [followersCount] - The number of followers the user has.\n * @property {number} [followingCount] - The number of users the user is following.\n * @property {number} [friendsCount] - The number of friends the user has.\n * @property {number} [mediaCount] - The number of media items the user has posted.\n * @property {number} [statusesCount] - The number of statuses the user has posted.\n * @property {boolean} [isPrivate] - Indicates if the user's profile is private.\n * @property {boolean} [isVerified] - Indicates if the user account is verified.\n * @property {boolean} [isBlueVerified] - Indicates if the user account has blue verification badge.\n * @property {Date} [joined] - The date the user joined the platform.\n * @property {number} [likesCount] - The number of likes the user has received.\n * @property {number} [listedCount] - The number of times the user has been listed.\n * @property {string} location - The user's location.\n * @property {string} [name] - The user's name.\n * @property {string[]} [pinnedTweetIds] - The IDs of the user's pinned tweets.\n * @property {number} [tweetsCount] - The number of tweets the user has posted.\n * @property {string} [url] - The user's website URL.\n * @property {string} [userId] - The unique user ID.\n * @property {string} [username] - The user's username.\n * @property {string} [website] - The user's website.\n * @property {boolean} [canDm] - Indicates if the user can receive direct messages.\n */\nexport interface Profile {\n avatar?: string;\n banner?: string;\n biography?: string;\n birthday?: string;\n followersCount?: number;\n followingCount?: number;\n friendsCount?: number;\n mediaCount?: number;\n statusesCount?: number;\n isPrivate?: boolean;\n isVerified?: boolean;\n isBlueVerified?: boolean;\n joined?: Date;\n likesCount?: number;\n listedCount?: number;\n location: string;\n name?: string;\n pinnedTweetIds?: string[];\n tweetsCount?: number;\n url?: string;\n userId?: string;\n username?: string;\n website?: string;\n canDm?: boolean;\n}\n\nexport interface UserRaw {\n data: {\n user: {\n result: {\n rest_id?: string;\n is_blue_verified?: boolean;\n legacy: LegacyUserRaw;\n };\n };\n };\n errors?: TwitterApiErrorRaw[];\n}\n\nfunction getAvatarOriginalSizeUrl(avatarUrl: string | undefined) {\n return avatarUrl ? avatarUrl.replace(\"_normal\", \"\") : undefined;\n}\n\nexport function parseProfile(\n user: LegacyUserRaw,\n isBlueVerified?: boolean,\n): Profile {\n const profile: Profile = {\n avatar: getAvatarOriginalSizeUrl(user.profile_image_url_https),\n banner: user.profile_banner_url,\n biography: user.description,\n followersCount: user.followers_count,\n followingCount: user.friends_count,\n friendsCount: user.friends_count,\n mediaCount: user.media_count,\n isPrivate: user.protected ?? false,\n isVerified: user.verified,\n likesCount: user.favourites_count,\n listedCount: user.listed_count,\n location: user.location,\n name: user.name,\n pinnedTweetIds: user.pinned_tweet_ids_str,\n tweetsCount: user.statuses_count,\n url: `https://twitter.com/${user.screen_name}`,\n userId: user.id_str,\n username: user.screen_name,\n isBlueVerified: isBlueVerified ?? false,\n canDm: user.can_dm,\n };\n\n if (user.created_at != null) {\n profile.joined = new Date(Date.parse(user.created_at));\n }\n\n const urls = user.entities?.url?.urls;\n if (urls?.length != null && urls?.length > 0) {\n profile.website = urls[0].expanded_url;\n }\n\n return profile;\n}\n\n/**\n * Convert Twitter API v2 user data to Profile format\n */\nfunction parseV2Profile(user: any): Profile {\n const profile: Profile = {\n avatar: getAvatarOriginalSizeUrl(user.profile_image_url),\n biography: user.description,\n followersCount: user.public_metrics?.followers_count,\n followingCount: user.public_metrics?.following_count,\n friendsCount: user.public_metrics?.following_count,\n tweetsCount: user.public_metrics?.tweet_count,\n isPrivate: user.protected ?? false,\n isVerified: user.verified ?? false,\n likesCount: user.public_metrics?.like_count,\n listedCount: user.public_metrics?.listed_count,\n location: user.location || \"\",\n name: user.name,\n pinnedTweetIds: user.pinned_tweet_id ? [user.pinned_tweet_id] : [],\n url: `https://twitter.com/${user.username}`,\n userId: user.id,\n username: user.username,\n isBlueVerified: user.verified_type === \"blue\",\n };\n\n if (user.created_at) {\n profile.joined = new Date(user.created_at);\n }\n\n if (user.entities?.url?.urls?.length > 0) {\n profile.website = user.entities.url.urls[0].expanded_url;\n }\n\n return profile;\n}\n\nexport async function getProfile(\n username: string,\n auth: TwitterAuth,\n): Promise<RequestApiResult<Profile>> {\n if (!auth) {\n return {\n success: false,\n err: new Error(\"Not authenticated\"),\n };\n }\n\n try {\n const client = auth.getV2Client();\n const user = await client.v2.userByUsername(username, {\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"created_at\",\n \"description\",\n \"entities\",\n \"location\",\n \"pinned_tweet_id\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"verified\",\n \"verified_type\",\n ],\n });\n\n if (!user.data) {\n return {\n success: false,\n err: new Error(`User ${username} not found`),\n };\n }\n\n return {\n success: true,\n value: parseV2Profile(user.data),\n };\n } catch (error: any) {\n return {\n success: false,\n err: new Error(error.message || \"Failed to fetch profile\"),\n };\n }\n}\n\nconst idCache = new Map<string, string>();\n\nexport async function getScreenNameByUserId(\n userId: string,\n auth: TwitterAuth,\n): Promise<RequestApiResult<string>> {\n if (!auth) {\n return {\n success: false,\n err: new Error(\"Not authenticated\"),\n };\n }\n\n try {\n const client = auth.getV2Client();\n const user = await client.v2.user(userId, {\n \"user.fields\": [\"username\"],\n });\n\n if (!user.data || !user.data.username) {\n return {\n success: false,\n err: new Error(`User with ID ${userId} not found`),\n };\n }\n\n return {\n success: true,\n value: user.data.username,\n };\n } catch (error: any) {\n return {\n success: false,\n err: new Error(error.message || \"Failed to fetch user\"),\n };\n }\n}\n\nexport async function getEntityIdByScreenName(\n screenName: string,\n auth: TwitterAuth,\n): Promise<RequestApiResult<string>> {\n const cached = idCache.get(screenName);\n if (cached != null) {\n return { success: true, value: cached };\n }\n\n const profileRes = await getProfile(screenName, auth);\n if (!profileRes.success) {\n return profileRes as any;\n }\n\n const profile = profileRes.value;\n if (profile.userId != null) {\n idCache.set(screenName, profile.userId);\n\n return {\n success: true,\n value: profile.userId,\n };\n }\n\n return {\n success: false,\n err: new Error(\"User ID is undefined.\"),\n };\n}\n","import { Headers } from \"headers-polyfill\";\nimport type { TwitterAuth } from \"./auth\";\nimport { type Profile } from \"./profile\";\nimport type { QueryProfilesResponse } from \"./api-types\";\n\n/**\n * Convert Twitter API v2 user data to Profile format\n */\nfunction parseV2UserToProfile(user: any): Profile {\n return {\n avatar: user.profile_image_url?.replace(\"_normal\", \"\"),\n biography: user.description,\n followersCount: user.public_metrics?.followers_count,\n followingCount: user.public_metrics?.following_count,\n friendsCount: user.public_metrics?.following_count,\n tweetsCount: user.public_metrics?.tweet_count,\n isPrivate: user.protected ?? false,\n isVerified: user.verified ?? false,\n likesCount: user.public_metrics?.like_count,\n listedCount: user.public_metrics?.listed_count,\n location: user.location || \"\",\n name: user.name,\n pinnedTweetIds: user.pinned_tweet_id ? [user.pinned_tweet_id] : [],\n url: `https://twitter.com/${user.username}`,\n userId: user.id,\n username: user.username,\n isBlueVerified: user.verified_type === \"blue\",\n joined: user.created_at ? new Date(user.created_at) : undefined,\n website: user.entities?.url?.urls?.[0]?.expanded_url,\n };\n}\n\n/**\n * Function to get the following profiles of a user.\n * @param {string} userId - The ID of the user to get the following profiles for.\n * @param {number} maxProfiles - The maximum number of profiles to retrieve.\n * @param {TwitterAuth} auth - The Twitter authentication credentials.\n * @returns {AsyncGenerator<Profile, void>} An async generator that yields Profile objects.\n */\nexport async function* getFollowing(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n if (!auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = auth.getV2Client();\n let count = 0;\n let paginationToken: string | undefined;\n\n try {\n while (count < maxProfiles) {\n const response = await client.v2.following(userId, {\n max_results: Math.min(maxProfiles - count, 100),\n pagination_token: paginationToken,\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"created_at\",\n \"description\",\n \"entities\",\n \"location\",\n \"pinned_tweet_id\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"verified\",\n \"verified_type\",\n ],\n });\n\n if (!response.data || response.data.length === 0) {\n break;\n }\n\n for (const user of response.data) {\n if (count >= maxProfiles) break;\n yield parseV2UserToProfile(user);\n count++;\n }\n\n paginationToken = response.meta?.next_token;\n if (!paginationToken) break;\n }\n } catch (error) {\n console.error(\"Error fetching following:\", error);\n throw error;\n }\n}\n\n/**\n * Get followers for a specific user.\n * @param {string} userId - The user ID for which to retrieve followers.\n * @param {number} maxProfiles - The maximum number of profiles to retrieve.\n * @param {TwitterAuth} auth - The authentication credentials for the Twitter API.\n * @returns {AsyncGenerator<Profile, void>} - An async generator that yields Profile objects representing followers.\n */\nexport async function* getFollowers(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n if (!auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = auth.getV2Client();\n let count = 0;\n let paginationToken: string | undefined;\n\n try {\n while (count < maxProfiles) {\n const response = await client.v2.followers(userId, {\n max_results: Math.min(maxProfiles - count, 100),\n pagination_token: paginationToken,\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"created_at\",\n \"description\",\n \"entities\",\n \"location\",\n \"pinned_tweet_id\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"verified\",\n \"verified_type\",\n ],\n });\n\n if (!response.data || response.data.length === 0) {\n break;\n }\n\n for (const user of response.data) {\n if (count >= maxProfiles) break;\n yield parseV2UserToProfile(user);\n count++;\n }\n\n paginationToken = response.meta?.next_token;\n if (!paginationToken) break;\n }\n } catch (error) {\n console.error(\"Error fetching followers:\", error);\n throw error;\n }\n}\n\n/**\n * Fetches the profiles that a user is following.\n * @param {string} userId - The ID of the user whose following profiles are to be fetched.\n * @param {number} maxProfiles - The maximum number of profiles to fetch.\n * @param {TwitterAuth} auth - The Twitter authentication details.\n * @param {string} [cursor] - Optional cursor for pagination.\n * @returns {Promise<QueryProfilesResponse>} A Promise that resolves with the response containing profiles the user is following.\n */\nexport async function fetchProfileFollowing(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth,\n cursor?: string,\n): Promise<QueryProfilesResponse> {\n if (!auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.following(userId, {\n max_results: Math.min(maxProfiles, 100),\n pagination_token: cursor,\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"created_at\",\n \"description\",\n \"entities\",\n \"location\",\n \"pinned_tweet_id\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"verified\",\n \"verified_type\",\n ],\n });\n\n const profiles = response.data?.map(parseV2UserToProfile) || [];\n\n return {\n profiles,\n next: response.meta?.next_token,\n };\n } catch (error) {\n console.error(\"Error fetching following profiles:\", error);\n throw error;\n }\n}\n\n/**\n * Fetches the profile followers for a given user ID.\n *\n * @param {string} userId - The user ID for which to fetch profile followers.\n * @param {number} maxProfiles - The maximum number of profiles to fetch.\n * @param {TwitterAuth} auth - The Twitter authentication credentials.\n * @param {string} [cursor] - Optional cursor for paginating results.\n * @returns {Promise<QueryProfilesResponse>} A promise that resolves with the parsed profile followers timeline.\n */\nexport async function fetchProfileFollowers(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth,\n cursor?: string,\n): Promise<QueryProfilesResponse> {\n if (!auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.followers(userId, {\n max_results: Math.min(maxProfiles, 100),\n pagination_token: cursor,\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"created_at\",\n \"description\",\n \"entities\",\n \"location\",\n \"pinned_tweet_id\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"verified\",\n \"verified_type\",\n ],\n });\n\n const profiles = response.data?.map(parseV2UserToProfile) || [];\n\n return {\n profiles,\n next: response.meta?.next_token,\n };\n } catch (error) {\n console.error(\"Error fetching follower profiles:\", error);\n throw error;\n }\n}\n\n/**\n * Follow a user using Twitter API v2\n *\n * @param {string} username - The username to follow\n * @param {TwitterAuth} auth - The authentication credentials\n * @returns {Promise<Response>} Response from the API\n */\nexport async function followUser(\n username: string,\n auth: TwitterAuth,\n): Promise<Response> {\n if (!auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = auth.getV2Client();\n\n try {\n // First get the user ID from username\n const userResponse = await client.v2.userByUsername(username);\n if (!userResponse.data) {\n throw new Error(`User ${username} not found`);\n }\n\n // Get the authenticated user's ID\n const meResponse = await client.v2.me();\n if (!meResponse.data) {\n throw new Error(\"Failed to get authenticated user\");\n }\n\n // Follow the user\n const result = await client.v2.follow(meResponse.data.id, userResponse.data.id);\n\n // Return a Response-like object for compatibility\n return new Response(JSON.stringify(result), {\n status: result.data?.following ? 200 : 400,\n headers: new Headers({ \"Content-Type\": \"application/json\" }),\n });\n } catch (error) {\n console.error(\"Error following user:\", error);\n throw error;\n }\n}\n","import type { TwitterAuth } from \"./auth\";\nimport type { Profile } from \"./profile\";\nimport type { Tweet } from \"./tweets\";\n\n/**\n * The categories that can be used in Twitter searches.\n */\n/**\n * Enum representing different search modes.\n * @enum {number}\n */\n\nexport enum SearchMode {\n Top = 0,\n Latest = 1,\n Photos = 2,\n Videos = 3,\n Users = 4,\n}\n\n/**\n * Search for tweets using Twitter API v2\n *\n * @param query Search query\n * @param maxTweets Maximum number of tweets to return\n * @param searchMode Search mode (not all modes are supported in v2)\n * @param auth Authentication\n * @returns Async generator of tweets\n */\nexport async function* searchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n const client = auth.getV2Client();\n\n // Build query based on search mode\n let finalQuery = query;\n switch (searchMode) {\n case SearchMode.Photos:\n finalQuery = `${query} has:media has:images`;\n break;\n case SearchMode.Videos:\n finalQuery = `${query} has:media has:videos`;\n break;\n }\n\n try {\n const searchIterator = await client.v2.search(finalQuery, {\n max_results: Math.min(maxTweets, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n });\n\n let count = 0;\n for await (const tweet of searchIterator) {\n if (count >= maxTweets) break;\n\n // Convert to Tweet format\n const convertedTweet: Tweet = {\n id: tweet.id,\n text: tweet.text || \"\",\n timestamp: tweet.created_at\n ? new Date(tweet.created_at).getTime()\n : Date.now(),\n timeParsed: tweet.created_at ? new Date(tweet.created_at) : new Date(),\n userId: tweet.author_id || \"\",\n name:\n searchIterator.includes?.users?.find((u) => u.id === tweet.author_id)\n ?.name || \"\",\n username:\n searchIterator.includes?.users?.find((u) => u.id === tweet.author_id)\n ?.username || \"\",\n conversationId: tweet.id,\n hashtags: tweet.entities?.hashtags?.map((h) => h.tag) || [],\n mentions:\n tweet.entities?.mentions?.map((m) => ({\n id: m.id || \"\",\n username: m.username || \"\",\n name: \"\",\n })) || [],\n photos: [],\n thread: [],\n urls: tweet.entities?.urls?.map((u) => u.expanded_url || u.url) || [],\n videos: [],\n isRetweet:\n tweet.referenced_tweets?.some((rt) => rt.type === \"retweeted\") ||\n false,\n isReply:\n tweet.referenced_tweets?.some((rt) => rt.type === \"replied_to\") ||\n false,\n isQuoted:\n tweet.referenced_tweets?.some((rt) => rt.type === \"quoted\") || false,\n isPin: false,\n sensitiveContent: false,\n likes: tweet.public_metrics?.like_count || undefined,\n replies: tweet.public_metrics?.reply_count || undefined,\n retweets: tweet.public_metrics?.retweet_count || undefined,\n views: tweet.public_metrics?.impression_count || undefined,\n quotes: tweet.public_metrics?.quote_count || undefined,\n };\n\n yield convertedTweet;\n count++;\n }\n } catch (error) {\n console.error(\"Search error:\", error);\n throw error;\n }\n}\n\n/**\n * Search for users using Twitter API v2\n *\n * Note: User search is limited in the standard Twitter API v2.\n * This searches for users mentioned in tweets matching the query.\n *\n * @param query Search query\n * @param maxProfiles Maximum number of profiles to return\n * @param auth Authentication\n * @returns Async generator of profiles\n */\nexport async function* searchProfiles(\n query: string,\n maxProfiles: number,\n auth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n const client = auth.getV2Client();\n const userIds = new Set<string>();\n const profiles: Profile[] = [];\n\n try {\n // Search for tweets and extract unique user IDs\n const searchIterator = await client.v2.search(query, {\n max_results: Math.min(maxProfiles * 2, 100), // Get more tweets to find more users\n \"tweet.fields\": [\"author_id\"],\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"description\",\n \"profile_image_url\",\n \"public_metrics\",\n \"verified\",\n \"location\",\n \"created_at\",\n ],\n expansions: [\"author_id\"],\n });\n\n for await (const tweet of searchIterator) {\n if (tweet.author_id) {\n userIds.add(tweet.author_id);\n }\n\n // Also get users from includes\n if (searchIterator.includes?.users) {\n for (const user of searchIterator.includes.users) {\n if (profiles.length < maxProfiles && user.id) {\n const profile: Profile = {\n userId: user.id,\n username: user.username || \"\",\n name: user.name || \"\",\n biography: user.description || \"\",\n avatar: user.profile_image_url || \"\",\n followersCount: user.public_metrics?.followers_count,\n followingCount: user.public_metrics?.following_count,\n isVerified: user.verified || false,\n location: user.location || \"\",\n joined: user.created_at ? new Date(user.created_at) : undefined,\n };\n profiles.push(profile);\n }\n }\n }\n\n if (profiles.length >= maxProfiles) break;\n }\n\n // Yield the profiles we found\n for (const profile of profiles) {\n yield profile;\n }\n } catch (error) {\n console.error(\"Profile search error:\", error);\n throw error;\n }\n}\n\n/**\n * Fetch tweets quoting a specific tweet\n *\n * @param quotedTweetId The ID of the quoted tweet\n * @param maxTweets Maximum number of tweets to return\n * @param auth Authentication\n * @returns Async generator of tweets\n */\nexport async function* searchQuotedTweets(\n quotedTweetId: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n // Twitter API v2 doesn't have a direct endpoint for quote tweets\n // We need to search for tweets that reference this tweet\n const query = `url:\"twitter.com/*/status/${quotedTweetId}\"`;\n\n yield* searchTweets(query, maxTweets, SearchMode.Latest, auth);\n}\n\n// Compatibility exports\nexport const fetchSearchTweets = async (\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n auth: TwitterAuth,\n cursor?: string,\n) => {\n throw new Error(\n \"fetchSearchTweets is deprecated. Use searchTweets generator instead.\",\n );\n};\n\nexport const fetchSearchProfiles = async (\n query: string,\n maxProfiles: number,\n auth: TwitterAuth,\n cursor?: string,\n) => {\n throw new Error(\n \"fetchSearchProfiles is deprecated. Use searchProfiles generator instead.\",\n );\n};\n","import type {\n ApiV2Includes,\n MediaObjectV2,\n PlaceV2,\n PollV2,\n TTweetv2Expansion,\n TTweetv2MediaField,\n TTweetv2PlaceField,\n TTweetv2PollField,\n TTweetv2TweetField,\n TTweetv2UserField,\n TweetV2,\n UserV2,\n} from \"twitter-api-v2\";\nimport type { TwitterAuth } from \"./auth\";\nimport { getEntityIdByScreenName } from \"./profile\";\nimport type { QueryTweetsResponse } from \"./api-types\";\n\n/**\n * Default options for Twitter API v2 request parameters.\n * @typedef {Object} defaultOptions\n * @property {TTweetv2Expansion[]} expansions - List of expansions to include in the request.\n * @property {TTweetv2TweetField[]} tweetFields - List of tweet fields to include in the request.\n * @property {TTweetv2PollField[]} pollFields - List of poll fields to include in the request.\n * @property {TTweetv2MediaField[]} mediaFields - List of media fields to include in the request.\n * @property {TTweetv2UserField[]} userFields - List of user fields to include in the request.\n * @property {TTweetv2PlaceField[]} placeFields - List of place fields to include in the request.\n */\nexport const defaultOptions = {\n expansions: [\n \"attachments.poll_ids\",\n \"attachments.media_keys\",\n \"author_id\",\n \"referenced_tweets.id\",\n \"in_reply_to_user_id\",\n \"edit_history_tweet_ids\",\n \"geo.place_id\",\n \"entities.mentions.username\",\n \"referenced_tweets.id.author_id\",\n ] as TTweetv2Expansion[],\n tweetFields: [\n \"attachments\",\n \"author_id\",\n \"context_annotations\",\n \"conversation_id\",\n \"created_at\",\n \"entities\",\n \"geo\",\n \"id\",\n \"in_reply_to_user_id\",\n \"lang\",\n \"public_metrics\",\n \"edit_controls\",\n \"possibly_sensitive\",\n \"referenced_tweets\",\n \"reply_settings\",\n \"source\",\n \"text\",\n \"withheld\",\n \"note_tweet\",\n ] as TTweetv2TweetField[],\n pollFields: [\n \"duration_minutes\",\n \"end_datetime\",\n \"id\",\n \"options\",\n \"voting_status\",\n ] as TTweetv2PollField[],\n mediaFields: [\n \"duration_ms\",\n \"height\",\n \"media_key\",\n \"preview_image_url\",\n \"type\",\n \"url\",\n \"width\",\n \"public_metrics\",\n \"alt_text\",\n \"variants\",\n ] as TTweetv2MediaField[],\n userFields: [\n \"created_at\",\n \"description\",\n \"entities\",\n \"id\",\n \"location\",\n \"name\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"username\",\n \"verified\",\n \"withheld\",\n ] as TTweetv2UserField[],\n placeFields: [\n \"contained_within\",\n \"country\",\n \"country_code\",\n \"full_name\",\n \"geo\",\n \"id\",\n \"name\",\n \"place_type\",\n ] as TTweetv2PlaceField[],\n};\n/**\n * Interface representing a mention.\n * @typedef {Object} Mention\n * @property {string} id - The unique identifier for the mention.\n * @property {string} [username] - The username associated with the mention.\n * @property {string} [name] - The name associated with the mention.\n */\nexport interface Mention {\n id: string;\n username?: string;\n name?: string;\n}\n\n/**\n * Interface representing a photo object.\n * @interface\n * @property {string} id - The unique identifier for the photo.\n * @property {string} url - The URL for the photo image.\n * @property {string} [alt_text] - The alternative text for the photo image. Optional.\n */\nexport interface Photo {\n id: string;\n url: string;\n alt_text: string | undefined;\n}\n\n/**\n * Interface representing a video object.\n * @typedef {Object} Video\n * @property {string} id - The unique identifier for the video.\n * @property {string} preview - The URL for the preview image of the video.\n * @property {string} [url] - The optional URL for the video.\n */\n\nexport interface Video {\n id: string;\n preview: string;\n url?: string;\n}\n\n/**\n * Interface representing a raw place object.\n * @typedef {Object} PlaceRaw\n * @property {string} [id] - The unique identifier of the place.\n * @property {string} [place_type] - The type of the place.\n * @property {string} [name] - The name of the place.\n * @property {string} [full_name] - The full name of the place.\n * @property {string} [country_code] - The country code of the place.\n * @property {string} [country] - The country name of the place.\n * @property {Object} [bounding_box] - The bounding box coordinates of the place.\n * @property {string} [bounding_box.type] - The type of the bounding box.\n * @property {number[][][]} [bounding_box.coordinates] - The coordinates of the bounding box in an array format.\n */\nexport interface PlaceRaw {\n id?: string;\n place_type?: string;\n name?: string;\n full_name?: string;\n country_code?: string;\n country?: string;\n bounding_box?: {\n type?: string;\n coordinates?: number[][][];\n };\n}\n\n/**\n * Interface representing poll data.\n *\n * @property {string} [id] - The unique identifier for the poll.\n * @property {string} [end_datetime] - The end date and time for the poll.\n * @property {string} [voting_status] - The status of the voting process.\n * @property {number} duration_minutes - The duration of the poll in minutes.\n * @property {PollOption[]} options - An array of poll options.\n */\nexport interface PollData {\n id?: string;\n end_datetime?: string;\n voting_status?: string;\n duration_minutes: number;\n options: PollOption[];\n}\n\n/**\n * Interface representing a poll option.\n * @typedef {Object} PollOption\n * @property {number} [position] - The position of the option.\n * @property {string} label - The label of the option.\n * @property {number} [votes] - The number of votes for the option.\n */\nexport interface PollOption {\n position?: number;\n label: string;\n votes?: number;\n}\n\n/**\n * A parsed Tweet object.\n */\n/**\n * Represents a Tweet on Twitter.\n * @typedef { Object } Tweet\n * @property { number } [bookmarkCount] - The number of times this Tweet has been bookmarked.\n * @property { string } [conversationId] - The ID of the conversation this Tweet is a part of.\n * @property {string[]} hashtags - An array of hashtags mentioned in the Tweet.\n * @property { string } [html] - The HTML content of the Tweet.\n * @property { string } [id] - The unique ID of the Tweet.\n * @property { Tweet } [inReplyToStatus] - The Tweet that this Tweet is in reply to.\n * @property { string } [inReplyToStatusId] - The ID of the Tweet that this Tweet is in reply to.\n * @property { boolean } [isQuoted] - Indicates if this Tweet is a quote of another Tweet.\n * @property { boolean } [isPin] - Indicates if this Tweet is pinned.\n * @property { boolean } [isReply] - Indicates if this Tweet is a reply to another Tweet.\n * @property { boolean } [isRetweet] - Indicates if this Tweet is a retweet.\n * @property { boolean } [isSelfThread] - Indicates if this Tweet is part of a self thread.\n * @property { string } [language] - The language of the Tweet.\n * @property { number } [likes] - The number of likes on the Tweet.\n * @property { string } [name] - The name associated with the Tweet.\n * @property {Mention[]} mentions - An array of mentions in the Tweet.\n * @property { string } [permanentUrl] - The permanent URL of the Tweet.\n * @property {Photo[]} photos - An array of photos attached to the Tweet.\n * @property { PlaceRaw } [place] - The place associated with the Tweet.\n * @property { Tweet } [quotedStatus] - The quoted Tweet.\n * @property { string } [quotedStatusId] - The ID of the quoted Tweet.\n * @property { number } [quotes] - The number of times this Tweet has been quoted.\n * @property { number } [replies] - The number of replies to the Tweet.\n * @property { number } [retweets] - The number of retweets on the Tweet.\n * @property { Tweet } [retweetedStatus] - The status that was retweeted.\n * @property { string } [retweetedStatusId] - The ID of the retweeted status.\n * @property { string } [text] - The text content of the Tweet.\n * @property {Tweet[]} thread - An array representing a Twitter thread.\n * @property { Date } [timeParsed] - The parsed timestamp of the Tweet.\n * @property { number } [timestamp] - The timestamp of the Tweet.\n * @property {string[]} urls - An array of URLs mentioned in the Tweet.\n * @property { string } [userId] - The ID of the user who posted the Tweet.\n * @property { string } [username] - The username of the user who posted the Tweet.\n * @property {Video[]} videos - An array of videos attached to the Tweet.\n * @property { number } [views] - The number of views on the Tweet.\n * @property { boolean } [sensitiveContent] - Indicates if the Tweet contains sensitive content.\n * @property {PollV2 | null} [poll] - The poll attached to the Tweet, if any.\n */\nexport interface Tweet {\n bookmarkCount?: number;\n conversationId?: string;\n hashtags: string[];\n html?: string;\n id?: string;\n inReplyToStatus?: Tweet;\n inReplyToStatusId?: string;\n isQuoted?: boolean;\n isPin?: boolean;\n isReply?: boolean;\n isRetweet?: boolean;\n isSelfThread?: boolean;\n language?: string;\n likes?: number;\n name?: string;\n mentions: Mention[];\n permanentUrl?: string;\n photos: Photo[];\n place?: PlaceRaw;\n quotedStatus?: Tweet;\n quotedStatusId?: string;\n quotes?: number;\n replies?: number;\n retweets?: number;\n retweetedStatus?: Tweet;\n retweetedStatusId?: string;\n text?: string;\n thread: Tweet[];\n timeParsed?: Date;\n timestamp?: number;\n urls: string[];\n userId?: string;\n username?: string;\n videos: Video[];\n views?: number;\n sensitiveContent?: boolean;\n poll?: PollV2 | null;\n}\n\nexport interface Retweeter {\n rest_id: string;\n screen_name: string;\n name: string;\n description?: string;\n}\n\nexport type TweetQuery =\n | Partial<Tweet>\n | ((tweet: Tweet) => boolean | Promise<boolean>);\n\nexport async function fetchTweets(\n userId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.userTimeline(userId, {\n max_results: Math.min(maxTweets, 100),\n exclude: [\"retweets\", \"replies\"],\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n pagination_token: cursor,\n });\n\n const convertedTweets: Tweet[] = [];\n\n // Use the paginator's built-in methods to access data\n for await (const tweet of response) {\n convertedTweets.push(parseTweetV2ToV1(tweet, response.includes));\n if (convertedTweets.length >= maxTweets) break;\n }\n\n return {\n tweets: convertedTweets,\n next: response.meta.next_token,\n };\n } catch (error) {\n throw new Error(`Failed to fetch tweets: ${error?.message || error}`);\n }\n}\n\nexport async function fetchTweetsAndReplies(\n userId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.userTimeline(userId, {\n max_results: Math.min(maxTweets, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n pagination_token: cursor,\n });\n\n const convertedTweets: Tweet[] = [];\n\n // Use the paginator's built-in methods to access data\n for await (const tweet of response) {\n convertedTweets.push(parseTweetV2ToV1(tweet, response.includes));\n if (convertedTweets.length >= maxTweets) break;\n }\n\n return {\n tweets: convertedTweets,\n next: response.meta.next_token,\n };\n } catch (error) {\n throw new Error(`Failed to fetch tweets and replies: ${error?.message || error}`);\n }\n}\n\nexport async function createCreateTweetRequestV2(\n text: string,\n auth: TwitterAuth,\n tweetId?: string,\n options?: {\n poll?: PollData;\n },\n) {\n const v2client = auth.getV2Client();\n if (v2client == null) {\n throw new Error(\"V2 client is not initialized\");\n }\n const { poll } = options || {};\n let tweetConfig;\n if (poll) {\n tweetConfig = {\n text,\n poll: {\n options: poll?.options.map((option) => option.label) ?? [],\n duration_minutes: poll?.duration_minutes ?? 60,\n },\n };\n } else if (tweetId) {\n tweetConfig = {\n text,\n reply: {\n in_reply_to_tweet_id: tweetId,\n },\n };\n } else {\n tweetConfig = {\n text,\n };\n }\n const tweetResponse = await v2client.v2.tweet(tweetConfig);\n let optionsConfig = {};\n if (options?.poll) {\n optionsConfig = {\n expansions: [\"attachments.poll_ids\"],\n pollFields: [\n \"options\",\n \"duration_minutes\",\n \"end_datetime\",\n \"voting_status\",\n ],\n };\n }\n return await getTweetV2(tweetResponse.data.id, auth, optionsConfig);\n}\n\nexport function parseTweetV2ToV1(\n tweetV2: TweetV2,\n includes?: ApiV2Includes,\n): Tweet {\n const parsedTweet: Tweet = {\n id: tweetV2.id,\n text: tweetV2.text ?? \"\",\n hashtags: tweetV2.entities?.hashtags?.map((tag) => tag.tag) ?? [],\n mentions: tweetV2.entities?.mentions?.map((mention) => ({\n id: mention.id,\n username: mention.username,\n })) ?? [],\n urls: tweetV2.entities?.urls?.map((url) => url.url) ?? [],\n likes: tweetV2.public_metrics?.like_count ?? 0,\n retweets: tweetV2.public_metrics?.retweet_count ?? 0,\n replies: tweetV2.public_metrics?.reply_count ?? 0,\n quotes: tweetV2.public_metrics?.quote_count ?? 0,\n views: tweetV2.public_metrics?.impression_count ?? 0,\n userId: tweetV2.author_id,\n conversationId: tweetV2.conversation_id,\n photos: [],\n videos: [],\n poll: null,\n username: \"\",\n name: \"\",\n thread: [],\n timestamp: tweetV2.created_at ? new Date(tweetV2.created_at).getTime() / 1000 : Date.now() / 1000,\n permanentUrl: `https://twitter.com/i/status/${tweetV2.id}`,\n // Check for referenced tweets\n isReply: tweetV2.referenced_tweets?.some(ref => ref.type === \"replied_to\") ?? false,\n isRetweet: tweetV2.referenced_tweets?.some(ref => ref.type === \"retweeted\") ?? false,\n isQuoted: tweetV2.referenced_tweets?.some(ref => ref.type === \"quoted\") ?? false,\n inReplyToStatusId: tweetV2.referenced_tweets?.find(ref => ref.type === \"replied_to\")?.id,\n quotedStatusId: tweetV2.referenced_tweets?.find(ref => ref.type === \"quoted\")?.id,\n retweetedStatusId: tweetV2.referenced_tweets?.find(ref => ref.type === \"retweeted\")?.id,\n };\n\n // Process Polls\n if (includes?.polls?.length) {\n const poll = includes.polls[0];\n parsedTweet.poll = {\n id: poll.id,\n end_datetime: poll.end_datetime,\n options: poll.options.map((option) => ({\n position: option.position,\n label: option.label,\n votes: option.votes,\n })),\n voting_status: poll.voting_status,\n };\n }\n\n // Process Media (photos and videos)\n if (includes?.media?.length) {\n includes.media.forEach((media: MediaObjectV2) => {\n if (media.type === \"photo\") {\n parsedTweet.photos.push({\n id: media.media_key,\n url: media.url ?? \"\",\n alt_text: media.alt_text ?? \"\",\n });\n } else if (media.type === \"video\" || media.type === \"animated_gif\") {\n parsedTweet.videos.push({\n id: media.media_key,\n preview: media.preview_image_url ?? \"\",\n url:\n media.variants?.find(\n (variant) => variant.content_type === \"video/mp4\",\n )?.url ?? \"\",\n });\n }\n });\n }\n\n // Process User (for author info)\n if (includes?.users?.length) {\n const user = includes.users.find(\n (user: UserV2) => user.id === tweetV2.author_id,\n );\n if (user) {\n parsedTweet.username = user.username ?? \"\";\n parsedTweet.name = user.name ?? \"\";\n }\n }\n\n // Process Place (if any)\n if (tweetV2?.geo?.place_id && includes?.places?.length) {\n const place = includes.places.find(\n (place: PlaceV2) => place.id === tweetV2?.geo?.place_id,\n );\n if (place) {\n parsedTweet.place = {\n id: place.id,\n full_name: place.full_name ?? \"\",\n country: place.country ?? \"\",\n country_code: place.country_code ?? \"\",\n name: place.name ?? \"\",\n place_type: place.place_type,\n };\n }\n }\n\n // TODO: Process Thread (referenced tweets) and remove reference to v1\n return parsedTweet;\n}\n\nexport async function createCreateTweetRequest(\n text: string,\n auth: TwitterAuth,\n tweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n hideLinkPreview = false,\n) {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n let tweetConfig: any = {\n text,\n };\n\n // Handle media uploads if provided\n if (mediaData && mediaData.length > 0) {\n // Note: Twitter API v2 media upload requires separate endpoint\n // For now, we'll skip media upload as it requires additional implementation\n console.warn(\"Media upload not yet implemented for Twitter API v2\");\n }\n\n // Handle reply\n if (tweetId) {\n tweetConfig.reply = {\n in_reply_to_tweet_id: tweetId,\n };\n }\n\n const result = await v2client.v2.tweet(tweetConfig);\n\n return {\n ok: true,\n json: async () => result,\n data: result,\n };\n } catch (error) {\n throw new Error(`Failed to create tweet: ${error?.message || error}`);\n }\n}\n\nexport async function createCreateNoteTweetRequest(\n text: string,\n auth: TwitterAuth,\n tweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n) {\n // Twitter API v2 doesn't have a separate endpoint for \"note tweets\"\n // Long tweets are handled automatically by the v2 tweet endpoint\n return createCreateTweetRequest(text, auth, tweetId, mediaData);\n}\n\nexport async function fetchListTweets(\n listId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.listTweets(listId, {\n max_results: Math.min(maxTweets, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n pagination_token: cursor,\n });\n\n const convertedTweets: Tweet[] = [];\n\n // Use the paginator's built-in methods to access data\n for await (const tweet of response) {\n convertedTweets.push(parseTweetV2ToV1(tweet, response.includes));\n if (convertedTweets.length >= maxTweets) break;\n }\n\n return {\n tweets: convertedTweets,\n next: response.meta.next_token,\n };\n } catch (error) {\n throw new Error(`Failed to fetch list tweets: ${error.message}`);\n }\n}\n\nexport async function deleteTweet(tweetId: string, auth: TwitterAuth) {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n const result = await v2client.v2.deleteTweet(tweetId);\n return {\n ok: true,\n json: async () => result,\n data: result,\n };\n } catch (error) {\n throw new Error(`Failed to delete tweet: ${error.message}`);\n }\n}\n\nexport async function* getTweets(\n user: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n const userIdRes = await getEntityIdByScreenName(user, auth);\n\n if (!userIdRes.success) {\n throw (userIdRes as any).err;\n }\n\n const { value: userId } = userIdRes;\n\n let cursor: string | undefined;\n let totalFetched = 0;\n\n while (totalFetched < maxTweets) {\n const response = await fetchTweets(userId, maxTweets - totalFetched, cursor, auth);\n \n for (const tweet of response.tweets) {\n yield tweet;\n totalFetched++;\n if (totalFetched >= maxTweets) break;\n }\n \n cursor = response.next;\n if (!cursor) break;\n }\n}\n\nexport async function* getTweetsByUserId(\n userId: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n let cursor: string | undefined;\n let totalFetched = 0;\n\n while (totalFetched < maxTweets) {\n const response = await fetchTweets(userId, maxTweets - totalFetched, cursor, auth);\n \n for (const tweet of response.tweets) {\n yield tweet;\n totalFetched++;\n if (totalFetched >= maxTweets) break;\n }\n \n cursor = response.next;\n if (!cursor) break;\n }\n}\n\nexport async function* getTweetsAndReplies(\n user: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n const userIdRes = await getEntityIdByScreenName(user, auth);\n\n if (!userIdRes.success) {\n throw (userIdRes as any).err;\n }\n\n const { value: userId } = userIdRes;\n\n let cursor: string | undefined;\n let totalFetched = 0;\n\n while (totalFetched < maxTweets) {\n const response = await fetchTweetsAndReplies(userId, maxTweets - totalFetched, cursor, auth);\n \n for (const tweet of response.tweets) {\n yield tweet;\n totalFetched++;\n if (totalFetched >= maxTweets) break;\n }\n \n cursor = response.next;\n if (!cursor) break;\n }\n}\n\nexport async function* getTweetsAndRepliesByUserId(\n userId: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n let cursor: string | undefined;\n let totalFetched = 0;\n\n while (totalFetched < maxTweets) {\n const response = await fetchTweetsAndReplies(userId, maxTweets - totalFetched, cursor, auth);\n \n for (const tweet of response.tweets) {\n yield tweet;\n totalFetched++;\n if (totalFetched >= maxTweets) break;\n }\n \n cursor = response.next;\n if (!cursor) break;\n }\n}\n\nexport async function fetchLikedTweets(\n userId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.userLikedTweets(userId, {\n max_results: Math.min(maxTweets, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n pagination_token: cursor,\n });\n\n const convertedTweets: Tweet[] = [];\n\n // Use the paginator's built-in methods to access data\n for await (const tweet of response) {\n convertedTweets.push(parseTweetV2ToV1(tweet, response.includes));\n if (convertedTweets.length >= maxTweets) break;\n }\n\n return {\n tweets: convertedTweets,\n next: response.meta.next_token,\n };\n } catch (error) {\n throw new Error(`Failed to fetch liked tweets: ${error.message}`);\n }\n}\n\nexport async function getTweetWhere(\n tweets: AsyncIterable<Tweet>,\n query: TweetQuery,\n): Promise<Tweet | null> {\n const isCallback = typeof query === \"function\";\n\n for await (const tweet of tweets) {\n const matches = isCallback\n ? await query(tweet)\n : checkTweetMatches(tweet, query);\n\n if (matches) {\n return tweet;\n }\n }\n\n return null;\n}\n\nexport async function getTweetsWhere(\n tweets: AsyncIterable<Tweet>,\n query: TweetQuery,\n): Promise<Tweet[]> {\n const isCallback = typeof query === \"function\";\n const filtered = [];\n\n for await (const tweet of tweets) {\n const matches = isCallback ? query(tweet) : checkTweetMatches(tweet, query);\n\n if (!matches) continue;\n filtered.push(tweet);\n }\n\n return filtered;\n}\n\nfunction checkTweetMatches(tweet: Tweet, options: Partial<Tweet>): boolean {\n return Object.keys(options).every((k) => {\n const key = k as keyof Tweet;\n return tweet[key] === options[key];\n });\n}\n\nexport async function getLatestTweet(\n user: string,\n includeRetweets: boolean,\n max: number,\n auth: TwitterAuth,\n): Promise<Tweet | null | undefined> {\n const timeline = getTweets(user, max, auth);\n\n // No point looping if max is 1, just use first entry.\n return max === 1\n ? ((await timeline.next()).value as Tweet)\n : await getTweetWhere(timeline, { isRetweet: includeRetweets });\n}\n\n// TweetResultByRestId interface removed - no longer used with v2 API\n\nexport async function getTweet(\n id: string,\n auth: TwitterAuth,\n): Promise<Tweet | null> {\n const client = auth.getV2Client();\n\n try {\n const tweet = await client.v2.singleTweet(id, {\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n \"conversation_id\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n \"poll.fields\": [\"id\", \"options\", \"end_datetime\", \"voting_status\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"attachments.poll_ids\",\n \"referenced_tweets.id\",\n ],\n });\n\n if (!tweet.data) {\n return null;\n }\n\n return parseTweetV2ToV1(tweet.data, tweet.includes);\n } catch (error) {\n console.error(`Failed to get tweet: ${error.message}`);\n return null;\n }\n}\n\nexport async function getTweetV2(\n id: string,\n auth: TwitterAuth,\n options: {\n expansions?: TTweetv2Expansion[];\n tweetFields?: TTweetv2TweetField[];\n pollFields?: TTweetv2PollField[];\n mediaFields?: TTweetv2MediaField[];\n userFields?: TTweetv2UserField[];\n placeFields?: TTweetv2PlaceField[];\n } = defaultOptions,\n): Promise<Tweet | null> {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n const tweetData = await v2client.v2.singleTweet(id, {\n expansions: options?.expansions,\n \"tweet.fields\": options?.tweetFields,\n \"poll.fields\": options?.pollFields,\n \"media.fields\": options?.mediaFields,\n \"user.fields\": options?.userFields,\n \"place.fields\": options?.placeFields,\n });\n\n if (!tweetData?.data) {\n console.warn(`Tweet data not found for ID: ${id}`);\n return null;\n }\n\n // Extract primary tweet data\n const parsedTweet = parseTweetV2ToV1(\n tweetData.data,\n tweetData?.includes,\n );\n\n return parsedTweet;\n } catch (error) {\n console.error(`Error fetching tweet ${id}:`, error);\n return null;\n }\n}\n\nexport async function getTweetsV2(\n ids: string[],\n auth: TwitterAuth,\n options: {\n expansions?: TTweetv2Expansion[];\n tweetFields?: TTweetv2TweetField[];\n pollFields?: TTweetv2PollField[];\n mediaFields?: TTweetv2MediaField[];\n userFields?: TTweetv2UserField[];\n placeFields?: TTweetv2PlaceField[];\n } = defaultOptions,\n): Promise<Tweet[]> {\n const v2client = auth.getV2Client();\n if (!v2client) {\n return [];\n }\n\n try {\n const tweetData = await v2client.v2.tweets(ids, {\n expansions: options?.expansions,\n \"tweet.fields\": options?.tweetFields,\n \"poll.fields\": options?.pollFields,\n \"media.fields\": options?.mediaFields,\n \"user.fields\": options?.userFields,\n \"place.fields\": options?.placeFields,\n });\n const tweetsV2 = tweetData.data;\n if (tweetsV2.length === 0) {\n console.warn(`No tweet data found for IDs: ${ids.join(\", \")}`);\n return [];\n }\n return (\n await Promise.all(\n tweetsV2.map(\n async (tweet) => await getTweetV2(tweet.id, auth, options),\n ),\n )\n ).filter((tweet): tweet is Tweet => tweet !== null);\n } catch (error) {\n console.error(`Error fetching tweets for IDs: ${ids.join(\", \")}`, error);\n return [];\n }\n}\n\nexport async function getTweetAnonymous(\n id: string,\n auth: TwitterAuth,\n): Promise<Tweet | null> {\n // Twitter API v2 doesn't support anonymous access\n // Use the regular getTweet method\n return getTweet(id, auth);\n}\n\ninterface MediaUploadResponse {\n media_id_string: string;\n size: number;\n expires_after_secs: number;\n image: {\n image_type: string;\n w: number;\n h: number;\n };\n}\n\nasync function uploadMedia(\n mediaData: Buffer,\n auth: TwitterAuth,\n mediaType: string,\n): Promise<string> {\n // Twitter API v2 media upload is not yet fully implemented in twitter-api-v2 library\n // This would require using the v1.1 media upload endpoint with proper OAuth\n console.warn(\"Media upload not yet implemented for Twitter API v2\");\n throw new Error(\"Media upload not yet implemented for Twitter API v2\");\n}\n\n// Function to create a quote tweet\nexport async function createQuoteTweetRequest(\n text: string,\n quotedTweetId: string,\n auth: TwitterAuth,\n mediaData?: { data: Buffer; mediaType: string }[],\n) {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n // Quote tweets in v2 are created by including the tweet URL in the text\n const quotedTweetUrl = `https://twitter.com/i/status/${quotedTweetId}`;\n const fullText = `${text} ${quotedTweetUrl}`;\n\n const result = await v2client.v2.tweet({\n text: fullText,\n });\n\n return {\n ok: true,\n json: async () => result,\n data: result,\n };\n } catch (error) {\n throw new Error(`Failed to create quote tweet: ${error.message}`);\n }\n}\n\n/**\n * Likes a tweet with the given tweet ID.\n * @param tweetId The ID of the tweet to like.\n * @param auth The authentication object.\n * @returns A promise that resolves when the tweet is liked.\n */\nexport async function likeTweet(\n tweetId: string,\n auth: TwitterAuth,\n): Promise<void> {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n await v2client.v2.like(\n (await v2client.v2.me()).data.id, // Current user ID\n tweetId,\n );\n } catch (error) {\n throw new Error(`Failed to like tweet: ${error.message}`);\n }\n}\n\n/**\n * Retweets a tweet with the given tweet ID.\n * @param tweetId The ID of the tweet to retweet.\n * @param auth The authentication object.\n * @returns A promise that resolves when the tweet is retweeted.\n */\nexport async function retweet(\n tweetId: string,\n auth: TwitterAuth,\n): Promise<void> {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n await v2client.v2.retweet(\n (await v2client.v2.me()).data.id, // Current user ID\n tweetId,\n );\n } catch (error) {\n throw new Error(`Failed to retweet: ${error.message}`);\n }\n}\n\nexport async function createCreateLongTweetRequest(\n text: string,\n auth: TwitterAuth,\n tweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n) {\n // Twitter API v2 handles long tweets automatically\n // Just use the regular tweet creation endpoint\n return createCreateTweetRequest(text, auth, tweetId, mediaData);\n}\n\n// getArticle function removed - Twitter API v2 doesn't have a separate article endpoint\n\n/**\n * Fetches a single page of retweeters for a given tweet, collecting both bottom and top cursors.\n * Logs each user's description in the process.\n * All comments must remain in English.\n */\nexport async function fetchRetweetersPage(\n tweetId: string,\n auth: TwitterAuth,\n cursor?: string,\n count = 40,\n): Promise<{\n retweeters: Retweeter[];\n bottomCursor?: string;\n topCursor?: string;\n}> {\n // Twitter API v2 does not provide an endpoint to fetch retweeters\n // This functionality would require the API v2 retweeted_by endpoint\n console.warn(\"Fetching retweeters not implemented for Twitter API v2\");\n return {\n retweeters: [],\n bottomCursor: undefined,\n topCursor: undefined,\n };\n}\n\n/**\n * Retrieves *all* retweeters by chaining requests until no next cursor is found.\n * @param tweetId The ID of the tweet.\n * @param auth The TwitterAuth object for authentication.\n * @returns A list of all users that retweeted the tweet.\n */\nexport async function getAllRetweeters(\n tweetId: string,\n auth: TwitterAuth,\n): Promise<Retweeter[]> {\n let allRetweeters: Retweeter[] = [];\n let cursor: string | undefined;\n\n while (true) {\n // Destructure bottomCursor / topCursor\n const { retweeters, bottomCursor, topCursor } = await fetchRetweetersPage(\n tweetId,\n auth,\n cursor,\n 40,\n );\n allRetweeters = allRetweeters.concat(retweeters);\n\n const newCursor = bottomCursor || topCursor;\n\n // Stop if there is no new cursor or if it's the same as the old one\n if (!newCursor || newCursor === cursor) {\n break;\n }\n\n cursor = newCursor;\n }\n\n return allRetweeters;\n}\n","import type {\n TTweetv2Expansion,\n TTweetv2MediaField,\n TTweetv2PlaceField,\n TTweetv2PollField,\n TTweetv2TweetField,\n TTweetv2UserField,\n} from \"twitter-api-v2\";\nimport {\n type FetchTransformOptions,\n type QueryProfilesResponse,\n type QueryTweetsResponse,\n type RequestApiResult,\n} from \"./api-types\";\nimport { TwitterAuth } from \"./auth\";\n// Removed messages imports - using Twitter API v2 instead\nimport {\n type Profile,\n getEntityIdByScreenName,\n getProfile,\n getScreenNameByUserId,\n} from \"./profile\";\nimport {\n fetchProfileFollowers,\n fetchProfileFollowing,\n followUser,\n getFollowers,\n getFollowing,\n} from \"./relationships\";\nimport {\n SearchMode,\n searchProfiles,\n searchTweets,\n searchQuotedTweets,\n} from \"./search\";\n\nimport {\n type PollData,\n type Retweeter,\n type Tweet,\n type TweetQuery,\n createCreateLongTweetRequest,\n createCreateNoteTweetRequest,\n createCreateTweetRequest,\n createCreateTweetRequestV2,\n createQuoteTweetRequest,\n defaultOptions,\n deleteTweet,\n fetchListTweets,\n getAllRetweeters,\n getLatestTweet,\n getTweet,\n getTweetV2,\n getTweets,\n getTweetsAndReplies,\n getTweetsAndRepliesByUserId,\n getTweetsByUserId,\n getTweetsV2,\n getTweetsWhere,\n likeTweet,\n retweet,\n getTweetWhere,\n parseTweetV2ToV1,\n} from \"./tweets\";\n\nconst twUrl = \"https://twitter.com\";\n\n/**\n * An alternative fetch function to use instead of the default fetch function. This may be useful\n * in nonstandard runtime environments, such as edge workers.\n *\n * @param {typeof fetch} fetch - The fetch function to use.\n *\n * @param {Partial<FetchTransformOptions>} transform - Additional options that control how requests\n * and responses are processed. This can be used to proxy requests through other hosts, for example.\n */\nexport interface ClientOptions {\n /**\n * An alternative fetch function to use instead of the default fetch function. This may be useful\n * in nonstandard runtime environments, such as edge workers.\n */\n fetch: typeof fetch;\n\n /**\n * Additional options that control how requests and responses are processed. This can be used to\n * proxy requests through other hosts, for example.\n */\n transform: Partial<FetchTransformOptions>;\n}\n\n/**\n * An interface to Twitter's API v2.\n * - Reusing Client objects is recommended to minimize the time spent authenticating unnecessarily.\n */\nexport class Client {\n private auth?: TwitterAuth;\n\n /**\n * Creates a new Client object.\n * - Reusing Client objects is recommended to minimize the time spent authenticating unnecessarily.\n */\n constructor(private readonly options?: Partial<ClientOptions>) {}\n\n /**\n * Fetches a Twitter profile.\n * @param username The Twitter username of the profile to fetch, without an `@` at the beginning.\n * @returns The requested {@link Profile}.\n */\n public async getProfile(username: string): Promise<Profile> {\n const res = await getProfile(username, this.auth);\n return this.handleResponse(res);\n }\n\n /**\n * Fetches the user ID corresponding to the provided screen name.\n * @param screenName The Twitter screen name of the profile to fetch.\n * @returns The ID of the corresponding account.\n */\n public async getEntityIdByScreenName(screenName: string): Promise<string> {\n const res = await getEntityIdByScreenName(screenName, this.auth);\n return this.handleResponse(res);\n }\n\n /**\n *\n * @param userId The user ID of the profile to fetch.\n * @returns The screen name of the corresponding account.\n */\n public async getScreenNameByUserId(userId: string): Promise<string> {\n const response = await getScreenNameByUserId(userId, this.auth);\n return this.handleResponse(response);\n }\n\n /**\n * Fetches tweets from Twitter.\n * @param query The search query. Any Twitter-compatible query format can be used.\n * @param maxTweets The maximum number of tweets to return.\n * @param includeReplies Whether or not replies should be included in the response.\n * @param searchMode The category filter to apply to the search. Defaults to `Top`.\n * @returns An {@link AsyncGenerator} of tweets matching the provided filters.\n */\n public searchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode = SearchMode.Top,\n ): AsyncGenerator<Tweet, void> {\n return searchTweets(query, maxTweets, searchMode, this.auth);\n }\n\n /**\n * Fetches profiles from Twitter.\n * @param query The search query. Any Twitter-compatible query format can be used.\n * @param maxProfiles The maximum number of profiles to return.\n * @returns An {@link AsyncGenerator} of tweets matching the provided filter(s).\n */\n public searchProfiles(\n query: string,\n maxProfiles: number,\n ): AsyncGenerator<Profile, void> {\n return searchProfiles(query, maxProfiles, this.auth);\n }\n\n /**\n * Fetches tweets from Twitter.\n * @param query The search query. Any Twitter-compatible query format can be used.\n * @param maxTweets The maximum number of tweets to return.\n * @param includeReplies Whether or not replies should be included in the response.\n * @param searchMode The category filter to apply to the search. Defaults to `Top`.\n * @param cursor The search cursor, which can be passed into further requests for more results.\n * @returns A page of results, containing a cursor that can be used in further requests.\n */\n public async fetchSearchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n cursor?: string,\n ): Promise<QueryTweetsResponse> {\n // Use the generator and collect results\n const tweets: Tweet[] = [];\n const generator = searchTweets(query, maxTweets, searchMode, this.auth);\n \n for await (const tweet of generator) {\n tweets.push(tweet);\n }\n \n return {\n tweets,\n // v2 API doesn't provide cursor-based pagination for search\n next: undefined,\n };\n }\n\n /**\n * Fetches profiles from Twitter.\n * @param query The search query. Any Twitter-compatible query format can be used.\n * @param maxProfiles The maximum number of profiles to return.\n * @param cursor The search cursor, which can be passed into further requests for more results.\n * @returns A page of results, containing a cursor that can be used in further requests.\n */\n public async fetchSearchProfiles(\n query: string,\n maxProfiles: number,\n cursor?: string,\n ): Promise<QueryProfilesResponse> {\n // Use the generator and collect results\n const profiles: Profile[] = [];\n const generator = searchProfiles(query, maxProfiles, this.auth);\n \n for await (const profile of generator) {\n profiles.push(profile);\n }\n \n return {\n profiles,\n // v2 API doesn't provide cursor-based pagination for search\n next: undefined,\n };\n }\n\n /**\n * Fetches list tweets from Twitter.\n * @param listId The list id\n * @param maxTweets The maximum number of tweets to return.\n * @param cursor The search cursor, which can be passed into further requests for more results.\n * @returns A page of results, containing a cursor that can be used in further requests.\n */\n public fetchListTweets(\n listId: string,\n maxTweets: number,\n cursor?: string,\n ): Promise<QueryTweetsResponse> {\n return fetchListTweets(listId, maxTweets, cursor, this.auth);\n }\n\n /**\n * Fetch the profiles a user is following\n * @param userId The user whose following should be returned\n * @param maxProfiles The maximum number of profiles to return.\n * @returns An {@link AsyncGenerator} of following profiles for the provided user.\n */\n public getFollowing(\n userId: string,\n maxProfiles: number,\n ): AsyncGenerator<Profile, void> {\n return getFollowing(userId, maxProfiles, this.auth);\n }\n\n /**\n * Fetch the profiles that follow a user\n * @param userId The user whose followers should be returned\n * @param maxProfiles The maximum number of profiles to return.\n * @returns An {@link AsyncGenerator} of profiles following the provided user.\n */\n public getFollowers(\n userId: string,\n maxProfiles: number,\n ): AsyncGenerator<Profile, void> {\n return getFollowers(userId, maxProfiles, this.auth);\n }\n\n /**\n * Fetches following profiles from Twitter.\n * @param userId The user whose following should be returned\n * @param maxProfiles The maximum number of profiles to return.\n * @param cursor The search cursor, which can be passed into further requests for more results.\n * @returns A page of results, containing a cursor that can be used in further requests.\n */\n public fetchProfileFollowing(\n userId: string,\n maxProfiles: number,\n cursor?: string,\n ): Promise<QueryProfilesResponse> {\n return fetchProfileFollowing(userId, maxProfiles, this.auth, cursor);\n }\n\n /**\n * Fetches profile followers from Twitter.\n * @param userId The user whose following should be returned\n * @param maxProfiles The maximum number of profiles to return.\n * @param cursor The search cursor, which can be passed into further requests for more results.\n * @returns A page of results, containing a cursor that can be used in further requests.\n */\n public fetchProfileFollowers(\n userId: string,\n maxProfiles: number,\n cursor?: string,\n ): Promise<QueryProfilesResponse> {\n return fetchProfileFollowers(userId, maxProfiles, this.auth, cursor);\n }\n\n /**\n * Fetches the home timeline for the current user using Twitter API v2.\n * Note: Twitter API v2 doesn't distinguish between \"For You\" and \"Following\" feeds.\n * @param count The number of tweets to fetch.\n * @param seenTweetIds An array of tweet IDs that have already been seen (not used in v2).\n * @returns A promise that resolves to an array of tweets.\n */\n public async fetchHomeTimeline(\n count: number,\n seenTweetIds: string[],\n ): Promise<Tweet[]> {\n if (!this.auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = this.auth.getV2Client();\n\n try {\n const timeline = await client.v2.homeTimeline({\n max_results: Math.min(count, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n \"conversation_id\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n });\n\n const tweets: Tweet[] = [];\n for await (const tweet of timeline) {\n tweets.push(parseTweetV2ToV1(tweet, timeline.includes));\n if (tweets.length >= count) break;\n }\n\n return tweets;\n } catch (error) {\n console.error(\"Failed to fetch home timeline:\", error);\n throw error;\n }\n }\n\n /**\n * Fetches the home timeline for the current user (same as fetchHomeTimeline in v2).\n * Twitter API v2 doesn't provide separate \"Following\" timeline endpoint.\n * @param count The number of tweets to fetch.\n * @param seenTweetIds An array of tweet IDs that have already been seen (not used in v2).\n * @returns A promise that resolves to an array of tweets.\n */\n public async fetchFollowingTimeline(\n count: number,\n seenTweetIds: string[],\n ): Promise<Tweet[]> {\n // In v2 API, there's no separate following timeline endpoint\n // Use the same home timeline endpoint\n return this.fetchHomeTimeline(count, seenTweetIds);\n }\n\n async getUserTweets(\n userId: string,\n maxTweets = 200,\n cursor?: string,\n ): Promise<{ tweets: Tweet[]; next?: string }> {\n if (!this.auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = this.auth.getV2Client();\n\n try {\n const response = await client.v2.userTimeline(userId, {\n max_results: Math.min(maxTweets, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n \"conversation_id\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n pagination_token: cursor,\n });\n\n const tweets: Tweet[] = [];\n for await (const tweet of response) {\n tweets.push(parseTweetV2ToV1(tweet, response.includes));\n if (tweets.length >= maxTweets) break;\n }\n\n return {\n tweets,\n next: response.meta?.next_token,\n };\n } catch (error) {\n console.error(\"Failed to fetch user tweets:\", error);\n throw error;\n }\n }\n\n async *getUserTweetsIterator(\n userId: string,\n maxTweets = 200,\n ): AsyncGenerator<Tweet, void> {\n let cursor: string | undefined;\n let retrievedTweets = 0;\n\n while (retrievedTweets < maxTweets) {\n const response = await this.getUserTweets(\n userId,\n maxTweets - retrievedTweets,\n cursor,\n );\n\n for (const tweet of response.tweets) {\n yield tweet;\n retrievedTweets++;\n if (retrievedTweets >= maxTweets) {\n break;\n }\n }\n\n cursor = response.next;\n\n if (!cursor) {\n break;\n }\n }\n }\n\n /**\n * Fetches the current trends from Twitter.\n * @returns The current list of trends.\n */\n public getTrends(): Promise<string[]> {\n // Trends API not available in Twitter API v2 with current implementation\n console.warn(\"Trends API not available in Twitter API v2\");\n return Promise.resolve([]);\n }\n\n /**\n * Fetches tweets from a Twitter user.\n * @param user The user whose tweets should be returned.\n * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n * @returns An {@link AsyncGenerator} of tweets from the provided user.\n */\n public getTweets(user: string, maxTweets = 200): AsyncGenerator<Tweet> {\n return getTweets(user, maxTweets, this.auth);\n }\n\n /**\n * Fetches tweets from a Twitter user using their ID.\n * @param userId The user whose tweets should be returned.\n * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n * @returns An {@link AsyncGenerator} of tweets from the provided user.\n */\n public getTweetsByUserId(\n userId: string,\n maxTweets = 200,\n ): AsyncGenerator<Tweet, void> {\n return getTweetsByUserId(userId, maxTweets, this.auth);\n }\n\n /**\n * Send a tweet\n * @param text The text of the tweet\n * @param tweetId The id of the tweet to reply to\n * @param mediaData Optional media data\n * @returns\n */\n\n async sendTweet(\n text: string,\n replyToTweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n hideLinkPreview?: boolean,\n ) {\n if (!text || text.trim().length === 0) {\n throw new Error(\"Text is required\");\n }\n if (text.toLowerCase().startsWith(\"error:\")) {\n throw new Error(\"Error sending tweet: \" + text);\n }\n return await createCreateTweetRequest(\n text,\n this.auth,\n replyToTweetId,\n mediaData,\n hideLinkPreview,\n );\n }\n\n async sendNoteTweet(\n text: string,\n replyToTweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n ) {\n if (!text || text.trim().length === 0) {\n throw new Error(\"Text is required\");\n }\n if (text.toLowerCase().startsWith(\"error:\")) {\n throw new Error(\"Error sending note tweet: \" + text);\n }\n return await createCreateNoteTweetRequest(\n text,\n this.auth,\n replyToTweetId,\n mediaData,\n );\n }\n\n /**\n * Send a long tweet (Note Tweet)\n * @param text The text of the tweet\n * @param tweetId The id of the tweet to reply to\n * @param mediaData Optional media data\n * @returns\n */\n async sendLongTweet(\n text: string,\n replyToTweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n ) {\n return await createCreateLongTweetRequest(\n text,\n this.auth,\n replyToTweetId,\n mediaData,\n );\n }\n\n /**\n * Send a tweet\n * @param text The text of the tweet\n * @param tweetId The id of the tweet to reply to\n * @param options The options for the tweet\n * @returns\n */\n\n async sendTweetV2(\n text: string,\n replyToTweetId?: string,\n options?: {\n poll?: PollData;\n },\n ) {\n return await createCreateTweetRequestV2(\n text,\n this.auth,\n replyToTweetId,\n options,\n );\n }\n\n /**\n * Fetches tweets and replies from a Twitter user.\n * @param user The user whose tweets should be returned.\n * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n * @returns An {@link AsyncGenerator} of tweets from the provided user.\n */\n public getTweetsAndReplies(\n user: string,\n maxTweets = 200,\n ): AsyncGenerator<Tweet> {\n return getTweetsAndReplies(user, maxTweets, this.auth);\n }\n\n /**\n * Fetches tweets and replies from a Twitter user using their ID.\n * @param userId The user whose tweets should be returned.\n * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n * @returns An {@link AsyncGenerator} of tweets from the provided user.\n */\n public getTweetsAndRepliesByUserId(\n userId: string,\n maxTweets = 200,\n ): AsyncGenerator<Tweet, void> {\n return getTweetsAndRepliesByUserId(userId, maxTweets, this.auth);\n }\n\n /**\n * Fetches the first tweet matching the given query.\n *\n * Example:\n * ```js\n * const timeline = client.getTweets('user', 200);\n * const retweet = await client.getTweetWhere(timeline, { isRetweet: true });\n * ```\n * @param tweets The {@link AsyncIterable} of tweets to search through.\n * @param query A query to test **all** tweets against. This may be either an\n * object of key/value pairs or a predicate. If this query is an object, all\n * key/value pairs must match a {@link Tweet} for it to be returned. If this query\n * is a predicate, it must resolve to `true` for a {@link Tweet} to be returned.\n * - All keys are optional.\n * - If specified, the key must be implemented by that of {@link Tweet}.\n */\n public getTweetWhere(\n tweets: AsyncIterable<Tweet>,\n query: TweetQuery,\n ): Promise<Tweet | null> {\n return getTweetWhere(tweets, query);\n }\n\n /**\n * Fetches all tweets matching the given query.\n *\n * Example:\n * ```js\n * const timeline = client.getTweets('user', 200);\n * const retweets = await client.getTweetsWhere(timeline, { isRetweet: true });\n * ```\n * @param tweets The {@link AsyncIterable} of tweets to search through.\n * @param query A query to test **all** tweets against. This may be either an\n * object of key/value pairs or a predicate. If this query is an object, all\n * key/value pairs must match a {@link Tweet} for it to be returned. If this query\n * is a predicate, it must resolve to `true` for a {@link Tweet} to be returned.\n * - All keys are optional.\n * - If specified, the key must be implemented by that of {@link Tweet}.\n */\n public getTweetsWhere(\n tweets: AsyncIterable<Tweet>,\n query: TweetQuery,\n ): Promise<Tweet[]> {\n return getTweetsWhere(tweets, query);\n }\n\n /**\n * Fetches the most recent tweet from a Twitter user.\n * @param user The user whose latest tweet should be returned.\n * @param includeRetweets Whether or not to include retweets. Defaults to `false`.\n * @returns The {@link Tweet} object or `null`/`undefined` if it couldn't be fetched.\n */\n public getLatestTweet(\n user: string,\n includeRetweets = false,\n max = 200,\n ): Promise<Tweet | null | undefined> {\n return getLatestTweet(user, includeRetweets, max, this.auth);\n }\n\n /**\n * Fetches a single tweet.\n * @param id The ID of the tweet to fetch.\n * @returns The {@link Tweet} object, or `null` if it couldn't be fetched.\n */\n public getTweet(id: string): Promise<Tweet | null> {\n return getTweet(id, this.auth);\n }\n\n /**\n * Fetches a single tweet by ID using the Twitter API v2.\n * Allows specifying optional expansions and fields for more detailed data.\n *\n * @param {string} id - The ID of the tweet to fetch.\n * @param {Object} [options] - Optional parameters to customize the tweet data.\n * @param {string[]} [options.expansions] - Array of expansions to include, e.g., 'attachments.poll_ids'.\n * @param {string[]} [options.tweetFields] - Array of tweet fields to include, e.g., 'created_at', 'public_metrics'.\n * @param {string[]} [options.pollFields] - Array of poll fields to include, if the tweet has a poll, e.g., 'options', 'end_datetime'.\n * @param {string[]} [options.mediaFields] - Array of media fields to include, if the tweet includes media, e.g., 'url', 'preview_image_url'.\n * @param {string[]} [options.userFields] - Array of user fields to include, if user information is requested, e.g., 'username', 'verified'.\n * @param {string[]} [options.placeFields] - Array of place fields to include, if the tweet includes location data, e.g., 'full_name', 'country'.\n * @returns {Promise<TweetV2 | null>} - The tweet data, including requested expansions and fields.\n */\n async getTweetV2(\n id: string,\n options: {\n expansions?: TTweetv2Expansion[];\n tweetFields?: TTweetv2TweetField[];\n pollFields?: TTweetv2PollField[];\n mediaFields?: TTweetv2MediaField[];\n userFields?: TTweetv2UserField[];\n placeFields?: TTweetv2PlaceField[];\n } = defaultOptions,\n ): Promise<Tweet | null> {\n return await getTweetV2(id, this.auth, options);\n }\n\n /**\n * Fetches multiple tweets by IDs using the Twitter API v2.\n * Allows specifying optional expansions and fields for more detailed data.\n *\n * @param {string[]} ids - Array of tweet IDs to fetch.\n * @param {Object} [options] - Optional parameters to customize the tweet data.\n * @param {string[]} [options.expansions] - Array of expansions to include, e.g., 'attachments.poll_ids'.\n * @param {string[]} [options.tweetFields] - Array of tweet fields to include, e.g., 'created_at', 'public_metrics'.\n * @param {string[]} [options.pollFields] - Array of poll fields to include, if tweets contain polls, e.g., 'options', 'end_datetime'.\n * @param {string[]} [options.mediaFields] - Array of media fields to include, if tweets contain media, e.g., 'url', 'preview_image_url'.\n * @param {string[]} [options.userFields] - Array of user fields to include, if user information is requested, e.g., 'username', 'verified'.\n * @param {string[]} [options.placeFields] - Array of place fields to include, if tweets contain location data, e.g., 'full_name', 'country'.\n * @returns {Promise<TweetV2[]> } - Array of tweet data, including requested expansions and fields.\n */\n async getTweetsV2(\n ids: string[],\n options: {\n expansions?: TTweetv2Expansion[];\n tweetFields?: TTweetv2TweetField[];\n pollFields?: TTweetv2PollField[];\n mediaFields?: TTweetv2MediaField[];\n userFields?: TTweetv2UserField[];\n placeFields?: TTweetv2PlaceField[];\n } = defaultOptions,\n ): Promise<Tweet[]> {\n return await getTweetsV2(ids, this.auth, options);\n }\n\n /**\n * Updates the authentication state for the client.\n * @param auth The new authentication.\n */\n public updateAuth(auth: TwitterAuth) {\n this.auth = auth;\n }\n\n /**\n * Get current authentication credentials\n * @returns {TwitterAuth | null} Current authentication or null if not authenticated\n */\n public getAuth(): TwitterAuth | null {\n return this.auth;\n }\n\n /**\n * Check if client is properly authenticated with Twitter API v2 credentials\n * @returns {boolean} True if authenticated\n */\n public isAuthenticated(): boolean {\n if (!this.auth) return false;\n return this.auth.hasToken();\n }\n\n /**\n * Returns if the client is logged in as a real user.\n * @returns `true` if the client is logged in with a real user account; otherwise `false`.\n */\n public async isLoggedIn(): Promise<boolean> {\n return await this.auth.isLoggedIn();\n }\n\n /**\n * Returns the currently logged in user\n * @returns The currently logged in user\n */\n public async me(): Promise<Profile | undefined> {\n return this.auth.me();\n }\n\n /**\n * Login to Twitter using API v2 credentials only.\n * @param appKey The API key\n * @param appSecret The API secret key\n * @param accessToken The access token\n * @param accessSecret The access token secret\n */\n public async login(\n username: string,\n password: string,\n email?: string,\n twoFactorSecret?: string,\n appKey?: string,\n appSecret?: string,\n accessToken?: string,\n accessSecret?: string,\n ): Promise<void> {\n // Only use API credentials for v2 authentication\n if (!appKey || !appSecret || !accessToken || !accessSecret) {\n throw new Error(\n \"Twitter API v2 credentials are required for authentication\",\n );\n }\n\n this.auth = new TwitterAuth(appKey, appSecret, accessToken, accessSecret);\n }\n\n /**\n * Log out of Twitter.\n * Note: With API v2, logout is not applicable as we use API credentials.\n */\n public async logout(): Promise<void> {\n // With API v2 credentials, there's no logout process\n console.warn(\n \"Logout is not applicable when using Twitter API v2 credentials\",\n );\n }\n\n\n\n /**\n * Sends a quote tweet.\n * @param text The text of the tweet.\n * @param quotedTweetId The ID of the tweet to quote.\n * @param options Optional parameters, such as media data.\n * @returns The response from the Twitter API.\n */\n public async sendQuoteTweet(\n text: string,\n quotedTweetId: string,\n options?: {\n mediaData: { data: Buffer; mediaType: string }[];\n },\n ) {\n return await createQuoteTweetRequest(\n text,\n quotedTweetId,\n this.auth,\n options?.mediaData,\n );\n }\n\n /**\n * Delete a tweet with the given ID.\n * @param tweetId The ID of the tweet to delete.\n * @returns A promise that resolves when the tweet is deleted.\n */\n public async deleteTweet(tweetId: string): Promise<any> {\n // Call the deleteTweet function from tweets.ts\n return await deleteTweet(tweetId, this.auth);\n }\n\n /**\n * Likes a tweet with the given tweet ID.\n * @param tweetId The ID of the tweet to like.\n * @returns A promise that resolves when the tweet is liked.\n */\n public async likeTweet(tweetId: string): Promise<void> {\n // Call the likeTweet function from tweets.ts\n await likeTweet(tweetId, this.auth);\n }\n\n /**\n * Retweets a tweet with the given tweet ID.\n * @param tweetId The ID of the tweet to retweet.\n * @returns A promise that resolves when the tweet is retweeted.\n */\n public async retweet(tweetId: string): Promise<void> {\n // Call the retweet function from tweets.ts\n await retweet(tweetId, this.auth);\n }\n\n /**\n * Follows a user with the given user ID.\n * @param userId The user ID of the user to follow.\n * @returns A promise that resolves when the user is followed.\n */\n public async followUser(userName: string): Promise<void> {\n // Call the followUser function from relationships.ts\n await followUser(userName, this.auth);\n }\n\n /**\n * Fetches direct message conversations\n * Note: This functionality requires additional permissions and is not implemented in the current Twitter API v2 wrapper\n * @param userId User ID\n * @param cursor Pagination cursor\n * @returns Array of DM conversations\n */\n public async getDirectMessageConversations(\n userId: string,\n cursor?: string,\n ): Promise<any> {\n console.warn(\n \"Direct message conversations not implemented for Twitter API v2\",\n );\n return { conversations: [] };\n }\n\n /**\n * Sends a direct message to a user.\n * Note: This functionality requires additional permissions and is not implemented in the current Twitter API v2 wrapper\n * @param conversationId The ID of the conversation\n * @param text The text of the message\n * @returns The response from the Twitter API\n */\n public async sendDirectMessage(\n conversationId: string,\n text: string,\n ): Promise<any> {\n console.warn(\"Sending direct messages not implemented for Twitter API v2\");\n throw new Error(\"Direct message sending not implemented\");\n }\n\n private getAuthOptions(): Partial<{ fetch?: typeof fetch; transform?: any }> {\n return {\n fetch: this.options?.fetch,\n transform: this.options?.transform,\n };\n }\n\n private handleResponse<T>(res: RequestApiResult<T>): T {\n if (!res.success) {\n throw (res as any).err;\n }\n\n return res.value;\n }\n\n\n\n /**\n * Retrieves all users who retweeted the given tweet.\n * @param tweetId The ID of the tweet.\n * @returns An array of users (retweeters).\n */\n public async getRetweetersOfTweet(tweetId: string): Promise<Retweeter[]> {\n return await getAllRetweeters(tweetId, this.auth);\n }\n\n /**\n * Fetches all quoted tweets for a given tweet ID, handling pagination automatically.\n * @param tweetId The ID of the tweet to fetch quotes for.\n * @param maxQuotes Maximum number of quotes to return (default: 100).\n * @returns An array of all quoted tweets.\n */\n public async fetchAllQuotedTweets(\n tweetId: string,\n maxQuotes: number = 100,\n ): Promise<Tweet[]> {\n const allQuotes: Tweet[] = [];\n\n try {\n let cursor: string | undefined;\n let totalFetched = 0;\n\n while (totalFetched < maxQuotes) {\n const batchSize = Math.min(40, maxQuotes - totalFetched);\n const page = await this.fetchQuotedTweetsPage(\n tweetId,\n batchSize,\n cursor,\n );\n\n if (!page.tweets || page.tweets.length === 0) {\n break;\n }\n\n allQuotes.push(...page.tweets);\n totalFetched += page.tweets.length;\n\n // Check if there's a next page\n if (!page.next) {\n break;\n }\n\n cursor = page.next;\n }\n\n return allQuotes.slice(0, maxQuotes);\n } catch (error) {\n console.error(\"Error fetching quoted tweets:\", error);\n throw error;\n }\n }\n\n /**\n * Fetches quoted tweets for a given tweet ID.\n * This method now uses a generator function internally but maintains backward compatibility.\n * @param tweetId The ID of the tweet to fetch quotes for.\n * @param maxQuotes Maximum number of quotes to return.\n * @param cursor Optional cursor for pagination.\n * @returns A promise that resolves to a QueryTweetsResponse containing tweets and the next cursor.\n */\n public async fetchQuotedTweetsPage(\n tweetId: string,\n maxQuotes: number = 40,\n cursor?: string,\n ): Promise<QueryTweetsResponse> {\n // For backward compatibility, collect quotes from the generator\n const quotes: Tweet[] = [];\n let count = 0;\n\n // searchQuotedTweets doesn't support cursor, so we'll collect all quotes up to maxQuotes\n for await (const quote of searchQuotedTweets(\n tweetId,\n maxQuotes,\n this.auth,\n )) {\n quotes.push(quote);\n count++;\n if (count >= maxQuotes) break;\n }\n\n return {\n tweets: quotes,\n next: undefined, // Twitter API v2 doesn't provide cursor for quote search\n };\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Media } from \"@elizaos/core\";\nimport {\n type Content,\n type Memory,\n type UUID,\n createUniqueUuid,\n logger,\n truncateToCompleteSentence,\n} from \"@elizaos/core\";\nimport type { ClientBase } from \"./base\";\nimport type { Tweet } from \"./client\";\n\nimport type { ActionResponse, MediaData } from \"./types\";\nimport { TWEET_MAX_LENGTH } from \"./constants\";\n\nexport const wait = (minTime = 1000, maxTime = 3000) => {\n const waitTime =\n Math.floor(Math.random() * (maxTime - minTime + 1)) + minTime;\n return new Promise((resolve) => setTimeout(resolve, waitTime));\n};\n\nexport const isValidTweet = (tweet: Tweet): boolean => {\n // Filter out tweets with too many hashtags, @s, or $ signs, probably spam or garbage\n const hashtagCount = (tweet.text?.match(/#/g) || []).length;\n const atCount = (tweet.text?.match(/@/g) || []).length;\n const dollarSignCount = (tweet.text?.match(/\\$/g) || []).length;\n const totalCount = hashtagCount + atCount + dollarSignCount;\n\n return (\n hashtagCount <= 1 && atCount <= 2 && dollarSignCount <= 1 && totalCount <= 3\n );\n};\n\n/**\n * Fetches media data from a list of attachments, supporting both HTTP URLs and local file paths.\n *\n * @param attachments Array of Media objects containing URLs or file paths to fetch media from\n * @returns Promise that resolves with an array of MediaData objects containing the fetched media data and content type\n */\nexport async function fetchMediaData(\n attachments: Media[],\n): Promise<MediaData[]> {\n return Promise.all(\n attachments.map(async (attachment: Media) => {\n if (/^(http|https):\\/\\//.test(attachment.url)) {\n // Handle HTTP URLs\n const response = await fetch(attachment.url);\n if (!response.ok) {\n throw new Error(`Failed to fetch file: ${attachment.url}`);\n }\n const mediaBuffer = Buffer.from(await response.arrayBuffer());\n const mediaType = attachment.contentType || \"image/png\";\n return { data: mediaBuffer, mediaType };\n }\n if (fs.existsSync(attachment.url)) {\n // Handle local file paths\n const mediaBuffer = await fs.promises.readFile(\n path.resolve(attachment.url),\n );\n const mediaType = attachment.contentType || \"image/png\";\n return { data: mediaBuffer, mediaType };\n }\n throw new Error(\n `File not found: ${attachment.url}. Make sure the path is correct.`,\n );\n }),\n );\n}\n\n/**\n * Handles sending a note tweet with optional media data.\n *\n * @param {ClientBase} client - The client object used for sending the note tweet.\n * @param {string} content - The content of the note tweet.\n * @param {string} [tweetId] - Optional Tweet ID to reply to.\n * @param {MediaData[]} [mediaData] - Optional media data to attach to the note tweet.\n * @returns {Promise<Object>} - The result of the note tweet operation.\n * @throws {Error} - If the note tweet operation fails.\n */\nasync function handleNoteTweet(\n client: ClientBase,\n content: string,\n tweetId?: string,\n mediaData?: MediaData[],\n) {\n // Twitter API v2 handles long tweets automatically\n // Just use the regular sendTweet method\n const result = await client.twitterClient.sendTweet(\n content,\n tweetId,\n mediaData,\n );\n\n // Check if the result was successful\n if (!result || !result.ok) {\n // Tweet failed. Falling back to truncated Tweet.\n const truncateContent = truncateToCompleteSentence(\n content,\n TWEET_MAX_LENGTH,\n );\n return await sendStandardTweet(client, truncateContent, tweetId);\n }\n\n // Return the result directly\n return result;\n}\n\n/**\n * Send a standard tweet through the client\n */\nexport async function sendStandardTweet(\n client: ClientBase,\n content: string,\n tweetId?: string,\n mediaData?: MediaData[],\n) {\n const standardTweetResult = await client.twitterClient.sendTweet(\n content,\n tweetId,\n mediaData,\n );\n\n // The result is already the response object\n return standardTweetResult;\n}\n\nexport async function sendTweet(\n client: ClientBase,\n text: string,\n mediaData: MediaData[] = [],\n tweetToReplyTo?: string,\n): Promise<any> {\n const isNoteTweet = text.length > TWEET_MAX_LENGTH;\n const postText = isNoteTweet\n ? truncateToCompleteSentence(text, TWEET_MAX_LENGTH)\n : text;\n\n let result;\n\n try {\n result = await client.twitterClient.sendTweet(\n postText,\n tweetToReplyTo,\n mediaData,\n );\n logger.log(\"Successfully posted Tweet\");\n } catch (error) {\n logger.error(\"Error posting Tweet:\", error);\n throw error;\n }\n\n try {\n // The result from sendTweet should have the tweet data\n const tweetData = result?.data || result;\n\n // Extract the tweet ID and other data\n const tweetResult = tweetData?.data || tweetData;\n\n // if we have a response\n if (tweetResult && tweetResult.id) {\n if (client.lastCheckedTweetId < BigInt(tweetResult.id)) {\n client.lastCheckedTweetId = BigInt(tweetResult.id);\n }\n await client.cacheLatestCheckedTweetId();\n\n // Cache the tweet\n await client.cacheTweet(tweetResult);\n\n logger.log(\"Successfully posted a tweet\", tweetResult.id);\n\n return tweetResult;\n }\n } catch (error) {\n logger.error(\"Error parsing tweet response:\", error);\n throw error;\n }\n\n logger.error(\"No valid response from Twitter API\");\n throw new Error(\"Failed to send tweet - no valid response\");\n}\n\n/**\n * Sends a tweet on Twitter using the given client.\n *\n * @param {ClientBase} client The client used to send the tweet.\n * @param {Content} content The content of the tweet.\n * @param {UUID} roomId The ID of the room where the tweet will be sent.\n * @param {string} twitterUsername The Twitter username of the sender.\n * @param {string} inReplyTo The ID of the tweet to which the new tweet will reply.\n * @returns {Promise<Memory[]>} An array of memories representing the sent tweets.\n */\nexport async function sendChunkedTweet(\n client: ClientBase,\n content: Content,\n roomId: UUID,\n twitterUsername: string,\n inReplyTo: string,\n): Promise<Memory[]> {\n const messages: Memory[] = [];\n const chunks = splitTweetContent(content.text, TWEET_MAX_LENGTH);\n\n let previousTweetId = inReplyTo;\n\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n const isLastChunk = i === chunks.length - 1;\n\n // Add the tweet number to the beginning of each chunk\n const tweetContent = `${chunk}`;\n\n logger.debug(`Sending tweet ${i + 1}/${chunks.length}: ${tweetContent}`);\n\n try {\n // Convert Media[] to MediaData[] if needed\n let mediaData: MediaData[] = [];\n if (content.attachments && content.attachments.length > 0) {\n mediaData = await fetchMediaData(content.attachments);\n }\n\n const result = await sendTweet(\n client,\n tweetContent,\n mediaData,\n previousTweetId,\n );\n\n const body = typeof result === \"object\" ? result : await result.json();\n\n // Twitter API v2 response format\n const tweetResult = body?.data || body;\n\n // if we have a response\n if (tweetResult && tweetResult.id) {\n const tweetId = tweetResult.id;\n const permanentUrl = `https://x.com/${twitterUsername}/status/${tweetId}`;\n\n const memory: Memory = {\n id: createUniqueUuid(client.runtime, tweetId),\n entityId: client.runtime.agentId,\n content: {\n text: chunk,\n url: permanentUrl,\n source: \"twitter\",\n },\n agentId: client.runtime.agentId,\n roomId,\n createdAt: Date.now(),\n };\n\n messages.push(memory);\n previousTweetId = tweetId;\n }\n } catch (error) {\n logger.error(`Error sending chunk ${i + 1}:`, error);\n throw error;\n }\n }\n\n return messages;\n}\n\n/**\n * Splits the given content into individual tweets based on the maximum length allowed for a tweet.\n * @param {string} content - The content to split into tweets.\n * @param {number} maxLength - The maximum length allowed for a single tweet.\n * @returns {string[]} An array of strings representing individual tweets.\n */\nfunction splitTweetContent(content: string, maxLength: number): string[] {\n const paragraphs = content.split(\"\\n\\n\").map((p) => p.trim());\n const tweets: string[] = [];\n let currentTweet = \"\";\n\n for (const paragraph of paragraphs) {\n if (!paragraph) continue;\n\n if (`${currentTweet}\\n\\n${paragraph}`.trim().length <= maxLength) {\n if (currentTweet) {\n currentTweet += `\\n\\n${paragraph}`;\n } else {\n currentTweet = paragraph;\n }\n } else {\n if (currentTweet) {\n tweets.push(currentTweet.trim());\n }\n if (paragraph.length <= maxLength) {\n currentTweet = paragraph;\n } else {\n // Split long paragraph into smaller chunks\n const chunks = splitParagraph(paragraph, maxLength);\n tweets.push(...chunks.slice(0, -1));\n currentTweet = chunks[chunks.length - 1];\n }\n }\n }\n\n if (currentTweet) {\n tweets.push(currentTweet.trim());\n }\n\n return tweets;\n}\n\n/**\n * Extracts URLs from a given paragraph and replaces them with placeholders.\n *\n * @param {string} paragraph - The paragraph containing URLs that need to be replaced\n * @returns {Object} An object containing the updated text with placeholders and a map of placeholders to original URLs\n */\nfunction extractUrls(paragraph: string): {\n textWithPlaceholders: string;\n placeholderMap: Map<string, string>;\n} {\n // replace https urls with placeholder\n const urlRegex = /https?:\\/\\/[^\\s]+/g;\n const placeholderMap = new Map<string, string>();\n\n let urlIndex = 0;\n const textWithPlaceholders = paragraph.replace(urlRegex, (match) => {\n // twitter url would be considered as 23 characters\n // <<URL_CONSIDERER_23_1>> is also 23 characters\n const placeholder = `<<URL_CONSIDERER_23_${urlIndex}>>`; // Placeholder without . ? ! etc\n placeholderMap.set(placeholder, match);\n urlIndex++;\n return placeholder;\n });\n\n return { textWithPlaceholders, placeholderMap };\n}\n\n/**\n * Splits a given text into chunks based on the specified maximum length while preserving sentence boundaries.\n *\n * @param {string} text - The text to be split into chunks\n * @param {number} maxLength - The maximum length each chunk should not exceed\n *\n * @returns {string[]} An array of chunks where each chunk is within the specified maximum length\n */\nfunction splitSentencesAndWords(text: string, maxLength: number): string[] {\n // Split by periods, question marks and exclamation marks\n // Note that URLs in text have been replaced with `<<URL_xxx>>` and won't be split by dots\n const sentences = text.match(/[^.!?]+[.!?]+|[^.!?]+$/g) || [text];\n const chunks: string[] = [];\n let currentChunk = \"\";\n\n for (const sentence of sentences) {\n if (`${currentChunk} ${sentence}`.trim().length <= maxLength) {\n if (currentChunk) {\n currentChunk += ` ${sentence}`;\n } else {\n currentChunk = sentence;\n }\n } else {\n // Can't fit more, push currentChunk to results\n if (currentChunk) {\n chunks.push(currentChunk.trim());\n }\n\n // If current sentence itself is less than or equal to maxLength\n if (sentence.length <= maxLength) {\n currentChunk = sentence;\n } else {\n // Need to split sentence by spaces\n const words = sentence.split(\" \");\n currentChunk = \"\";\n for (const word of words) {\n if (`${currentChunk} ${word}`.trim().length <= maxLength) {\n if (currentChunk) {\n currentChunk += ` ${word}`;\n } else {\n currentChunk = word;\n }\n } else {\n if (currentChunk) {\n chunks.push(currentChunk.trim());\n }\n currentChunk = word;\n }\n }\n }\n }\n }\n\n // Handle remaining content\n if (currentChunk) {\n chunks.push(currentChunk.trim());\n }\n\n return chunks;\n}\n\n/**\n * Deduplicates mentions at the beginning of a paragraph.\n *\n * @param {string} paragraph - The input paragraph containing mentions.\n * @returns {string} - The paragraph with deduplicated mentions.\n */\nfunction deduplicateMentions(paragraph: string) {\n // Regex to match mentions at the beginning of the string\n const mentionRegex = /^@(\\w+)(?:\\s+@(\\w+))*(\\s+|$)/;\n\n // Find all matches\n const matches = paragraph.match(mentionRegex);\n\n if (!matches) {\n return paragraph; // If no matches, return the original string\n }\n\n // Extract mentions from the match groups\n let mentions = matches.slice(0, 1)[0].trim().split(\" \");\n\n // Deduplicate mentions\n mentions = Array.from(new Set(mentions));\n\n // Reconstruct the string with deduplicated mentions\n const uniqueMentionsString = mentions.join(\" \");\n\n // Find where the mentions end in the original string\n const endOfMentions = paragraph.indexOf(matches[0]) + matches[0].length;\n\n // Construct the result by combining unique mentions with the rest of the string\n return `${uniqueMentionsString} ${paragraph.slice(endOfMentions)}`;\n}\n\n/**\n * Restores the original URLs in the chunks by replacing placeholder URLs.\n *\n * @param {string[]} chunks - Array of strings representing chunks of text containing placeholder URLs.\n * @param {Map<string, string>} placeholderMap - Map with placeholder URLs as keys and original URLs as values.\n * @returns {string[]} - Array of strings with original URLs restored in each chunk.\n */\nfunction restoreUrls(\n chunks: string[],\n placeholderMap: Map<string, string>,\n): string[] {\n return chunks.map((chunk) => {\n // Replace all <<URL_CONSIDERER_23_>> in chunk back to original URLs using regex\n return chunk.replace(/<<URL_CONSIDERER_23_(\\d+)>>/g, (match) => {\n const original = placeholderMap.get(match);\n return original || match; // Return placeholder if not found (theoretically won't happen)\n });\n });\n}\n\n/**\n * Splits a paragraph into chunks of text with a maximum length, while preserving URLs.\n *\n * @param {string} paragraph - The paragraph to split.\n * @param {number} maxLength - The maximum length of each chunk.\n * @returns {string[]} An array of strings representing the splitted chunks of text.\n */\nfunction splitParagraph(paragraph: string, maxLength: number): string[] {\n // 1) Extract URLs and replace with placeholders\n const { textWithPlaceholders, placeholderMap } = extractUrls(paragraph);\n\n // 2) Use first section's logic to split by sentences first, then do secondary split\n const splittedChunks = splitSentencesAndWords(\n textWithPlaceholders,\n maxLength,\n );\n\n // 3) Replace placeholders back to original URLs\n const restoredChunks = restoreUrls(splittedChunks, placeholderMap);\n\n return restoredChunks;\n}\n\n/**\n * Parses the action response from the given text.\n *\n * @param {string} text - The text to parse actions from.\n * @returns {{ actions: ActionResponse }} The parsed actions with boolean values indicating if each action is present in the text.\n */\nexport const parseActionResponseFromText = (\n text: string,\n): { actions: ActionResponse } => {\n const actions: ActionResponse = {\n like: false,\n retweet: false,\n quote: false,\n reply: false,\n };\n\n // Regex patterns\n const likePattern = /\\[LIKE\\]/i;\n const retweetPattern = /\\[RETWEET\\]/i;\n const quotePattern = /\\[QUOTE\\]/i;\n const replyPattern = /\\[REPLY\\]/i;\n\n // Check with regex\n actions.like = likePattern.test(text);\n actions.retweet = retweetPattern.test(text);\n actions.quote = quotePattern.test(text);\n actions.reply = replyPattern.test(text);\n\n // Also do line by line parsing as backup\n const lines = text.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed === \"[LIKE]\") actions.like = true;\n if (trimmed === \"[RETWEET]\") actions.retweet = true;\n if (trimmed === \"[QUOTE]\") actions.quote = true;\n if (trimmed === \"[REPLY]\") actions.reply = true;\n }\n\n return { actions };\n};\n\n// Export error handler utilities\nexport * from \"./utils/error-handler\";\n","export const TWITTER_SERVICE_NAME = \"twitter\";\nexport const TWEET_CHAR_LIMIT = 280;\nexport const TWEET_MAX_LENGTH = 4000; // Twitter API v2 supports longer tweets\n","import { logger } from \"@elizaos/core\";\n\nexport enum TwitterErrorType {\n AUTH = \"AUTH\",\n RATE_LIMIT = \"RATE_LIMIT\",\n API = \"API\",\n NETWORK = \"NETWORK\",\n MEDIA = \"MEDIA\",\n VALIDATION = \"VALIDATION\",\n UNKNOWN = \"UNKNOWN\",\n}\n\nexport class TwitterError extends Error {\n constructor(\n public type: TwitterErrorType,\n message: string,\n public originalError?: any,\n public details?: Record<string, any>\n ) {\n super(message);\n this.name = \"TwitterError\";\n }\n}\n\nexport function getErrorType(error: any): TwitterErrorType {\n const message = error?.message?.toLowerCase() || \"\";\n const code = error?.code || error?.response?.status;\n\n if (code === 401 || message.includes(\"unauthorized\") || message.includes(\"authentication\")) {\n return TwitterErrorType.AUTH;\n }\n\n if (code === 429 || message.includes(\"rate limit\") || message.includes(\"too many requests\")) {\n return TwitterErrorType.RATE_LIMIT;\n }\n\n if (message.includes(\"network\") || message.includes(\"timeout\") || message.includes(\"econnrefused\")) {\n return TwitterErrorType.NETWORK;\n }\n\n if (message.includes(\"media\") || message.includes(\"upload\")) {\n return TwitterErrorType.MEDIA;\n }\n\n if (message.includes(\"invalid\") || message.includes(\"missing\") || message.includes(\"required\")) {\n return TwitterErrorType.VALIDATION;\n }\n\n if (code >= 400 && code < 500) {\n return TwitterErrorType.API;\n }\n\n return TwitterErrorType.UNKNOWN;\n}\n\nexport function handleTwitterError(\n context: string,\n error: any,\n throwError = false\n): TwitterError | null {\n const errorType = getErrorType(error);\n const errorMessage = error?.message || String(error);\n \n const twitterError = new TwitterError(\n errorType,\n `${context}: ${errorMessage}`,\n error,\n {\n context,\n timestamp: new Date().toISOString(),\n ...(error?.response && { response: error.response }),\n }\n );\n\n // Log based on error type\n switch (errorType) {\n case TwitterErrorType.AUTH:\n logger.error(`[Twitter Auth Error] ${context}:`, errorMessage);\n break;\n case TwitterErrorType.RATE_LIMIT:\n logger.warn(`[Twitter Rate Limit] ${context}:`, errorMessage);\n break;\n case TwitterErrorType.NETWORK:\n logger.warn(`[Twitter Network Error] ${context}:`, errorMessage);\n break;\n default:\n logger.error(`[Twitter Error] ${context}:`, errorMessage);\n }\n\n if (throwError) {\n throw twitterError;\n }\n\n return twitterError;\n}\n\nexport function isRetryableError(error: TwitterError | any): boolean {\n if (error instanceof TwitterError) {\n return [\n TwitterErrorType.RATE_LIMIT,\n TwitterErrorType.NETWORK,\n ].includes(error.type);\n }\n\n const errorType = getErrorType(error);\n return [\n TwitterErrorType.RATE_LIMIT,\n TwitterErrorType.NETWORK,\n ].includes(errorType);\n}\n\nexport function getRetryDelay(error: TwitterError | any, attempt: number): number {\n const baseDelay = 1000; // 1 second\n const maxDelay = 60000; // 60 seconds\n\n if (error instanceof TwitterError || getErrorType(error) === TwitterErrorType.RATE_LIMIT) {\n // For rate limits, use longer delays\n return Math.min(baseDelay * Math.pow(2, attempt) * 5, maxDelay);\n }\n\n // Exponential backoff for other errors\n return Math.min(baseDelay * Math.pow(2, attempt), maxDelay);\n} ","export * from \"./errors.js\";\nexport * from \"./helpers/parseUtil.js\";\nexport * from \"./helpers/typeAliases.js\";\nexport * from \"./helpers/util.js\";\nexport * from \"./types.js\";\nexport * from \"./ZodError.js\";\n","export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n","import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n","import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n","import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n","export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}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0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import { type IAgentRuntime } from \"@elizaos/core\";\nimport { z } from \"zod\";\n\n/**\n * Simplified Twitter environment schema\n * All time intervals are in minutes for consistency\n */\nexport const twitterEnvSchema = z.object({\n // Required API credentials\n TWITTER_API_KEY: z.string(),\n TWITTER_API_SECRET_KEY: z.string(),\n TWITTER_ACCESS_TOKEN: z.string(),\n TWITTER_ACCESS_TOKEN_SECRET: z.string(),\n \n // Core configuration\n TWITTER_DRY_RUN: z.string().default(\"false\"),\n TWITTER_TARGET_USERS: z.string().default(\"\"), // comma-separated list, empty = all\n \n // Feature toggles\n TWITTER_ENABLE_POST: z.string().default(\"false\"),\n TWITTER_ENABLE_REPLIES: z.string().default(\"true\"),\n TWITTER_ENABLE_ACTIONS: z.string().default(\"false\"), // likes, retweets, quotes\n \n // Timing configuration (all in minutes)\n TWITTER_POST_INTERVAL: z.string().default(\"120\"), // minutes between posts\n TWITTER_ENGAGEMENT_INTERVAL: z.string().default(\"30\"), // minutes between all interactions\n \n // Limits\n TWITTER_MAX_ENGAGEMENTS_PER_RUN: z.string().default(\"10\"),\n TWITTER_MAX_TWEET_LENGTH: z.string().default(\"280\"), // standard tweet length\n \n // Advanced\n TWITTER_RETRY_LIMIT: z.string().default(\"5\"),\n});\n\n// Remove deprecated\ndelete process.env.TWITTER_SEARCH_ENABLE;\ndelete process.env.TWITTER_POST_ENABLE;\n\nexport type TwitterConfig = z.infer<typeof twitterEnvSchema>;\n\n/**\n * Parse safe integer with fallback\n */\nfunction safeParseInt(value: string | undefined, defaultValue: number): number {\n if (!value) return defaultValue;\n const parsed = parseInt(value, 10);\n return isNaN(parsed) ? defaultValue : parsed;\n}\n\n/**\n * Helper to parse a comma-separated list of Twitter usernames\n */\nfunction parseTargetUsers(targetUsersStr?: string | null): string[] {\n if (!targetUsersStr?.trim()) {\n return [];\n }\n return targetUsersStr\n .split(\",\")\n .map((user) => user.trim())\n .filter(Boolean);\n}\n\n/**\n * Check if a user should be targeted for interactions\n * Empty list means target everyone\n * \"*\" wildcard means target everyone explicitly\n */\nexport function shouldTargetUser(\n username: string,\n targetUsersConfig: string,\n): boolean {\n if (!targetUsersConfig?.trim()) {\n return true; // Empty = interact with everyone\n }\n\n const targetUsers = parseTargetUsers(targetUsersConfig);\n \n if (targetUsers.includes(\"*\")) {\n return true; // Wildcard = everyone\n }\n\n // Check if the username (without @) is in the target list\n const normalizedUsername = username.toLowerCase().replace(/^@/, \"\");\n return targetUsers.some(\n (target) => target.toLowerCase().replace(/^@/, \"\") === normalizedUsername,\n );\n}\n\n/**\n * Get parsed target users list\n */\nexport function getTargetUsers(targetUsersConfig: string): string[] {\n const users = parseTargetUsers(targetUsersConfig);\n // Filter out wildcard since it's a special case\n return users.filter(u => u !== \"*\");\n}\n\n/**\n * Validates Twitter configuration using simplified schema\n */\nexport async function validateTwitterConfig(\n runtime: IAgentRuntime,\n config: Partial<TwitterConfig> = {},\n): Promise<TwitterConfig> {\n try {\n const getConfig = (key: keyof TwitterConfig): string | undefined => {\n return (\n config[key] || runtime.getSetting(key) || process.env[key] || undefined\n );\n };\n\n const validatedConfig: TwitterConfig = {\n TWITTER_API_KEY: getConfig(\"TWITTER_API_KEY\") || \"\",\n TWITTER_API_SECRET_KEY: getConfig(\"TWITTER_API_SECRET_KEY\") || \"\",\n TWITTER_ACCESS_TOKEN: getConfig(\"TWITTER_ACCESS_TOKEN\") || \"\",\n TWITTER_ACCESS_TOKEN_SECRET: getConfig(\"TWITTER_ACCESS_TOKEN_SECRET\") || \"\",\n TWITTER_DRY_RUN: String(getConfig(\"TWITTER_DRY_RUN\")?.toLowerCase() === \"true\"),\n TWITTER_TARGET_USERS: getConfig(\"TWITTER_TARGET_USERS\") || \"\",\n TWITTER_ENABLE_POST: String(getConfig(\"TWITTER_ENABLE_POST\")?.toLowerCase() === \"true\"),\n TWITTER_ENABLE_REPLIES: String(\n getConfig(\"TWITTER_ENABLE_REPLIES\") !== undefined\n ? getConfig(\"TWITTER_ENABLE_REPLIES\")?.toLowerCase() === \"true\"\n : true // Default to true\n ),\n TWITTER_ENABLE_ACTIONS: String(getConfig(\"TWITTER_ENABLE_ACTIONS\")?.toLowerCase() === \"true\"),\n TWITTER_POST_INTERVAL: String(safeParseInt(getConfig(\"TWITTER_POST_INTERVAL\"), 120)),\n TWITTER_ENGAGEMENT_INTERVAL: String(safeParseInt(getConfig(\"TWITTER_ENGAGEMENT_INTERVAL\"), 30)),\n TWITTER_MAX_ENGAGEMENTS_PER_RUN: String(safeParseInt(getConfig(\"TWITTER_MAX_ENGAGEMENTS_PER_RUN\"), 10)),\n TWITTER_MAX_TWEET_LENGTH: String(safeParseInt(getConfig(\"TWITTER_MAX_TWEET_LENGTH\"), 280)),\n TWITTER_RETRY_LIMIT: String(safeParseInt(getConfig(\"TWITTER_RETRY_LIMIT\"), 5)),\n };\n\n // Validate required credentials\n if (\n !validatedConfig.TWITTER_API_KEY ||\n !validatedConfig.TWITTER_API_SECRET_KEY ||\n !validatedConfig.TWITTER_ACCESS_TOKEN ||\n !validatedConfig.TWITTER_ACCESS_TOKEN_SECRET\n ) {\n throw new Error(\n \"Twitter API credentials are required. Please set TWITTER_API_KEY, TWITTER_API_SECRET_KEY, TWITTER_ACCESS_TOKEN, and TWITTER_ACCESS_TOKEN_SECRET\",\n );\n }\n\n return twitterEnvSchema.parse(validatedConfig);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const errorMessages = error.errors\n .map((err) => `${err.path.join(\".\")}: ${err.message}`)\n .join(\", \");\n throw new Error(\n `Twitter configuration validation failed: ${errorMessages}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Get configuration from environment variables\n * @returns Partial<TwitterConfig>\n */\nfunction getEnvConfig(): Partial<TwitterConfig> {\n const config: Partial<TwitterConfig> = {};\n\n const getConfig = (key: keyof TwitterConfig): string | undefined => {\n if (typeof process !== \"undefined\" && process.env) {\n return process.env[key];\n }\n return undefined;\n };\n\n // Map all environment variables\n Object.keys(twitterEnvSchema.shape).forEach((key) => {\n const value = getConfig(key as keyof TwitterConfig);\n if (value !== undefined) {\n config[key as keyof TwitterConfig] = value;\n }\n });\n\n return config;\n}\n\n/**\n * Get default configuration\n * @returns TwitterConfig with default values\n */\nfunction getDefaultConfig(): TwitterConfig {\n const getConfig = (key: keyof TwitterConfig): string | undefined => {\n if (typeof process !== \"undefined\" && process.env) {\n return process.env[key];\n }\n return undefined;\n };\n\n return {\n TWITTER_API_KEY: getConfig(\"TWITTER_API_KEY\") || \"\",\n TWITTER_API_SECRET_KEY: getConfig(\"TWITTER_API_SECRET_KEY\") || \"\",\n TWITTER_ACCESS_TOKEN: getConfig(\"TWITTER_ACCESS_TOKEN\") || \"\",\n TWITTER_ACCESS_TOKEN_SECRET: getConfig(\"TWITTER_ACCESS_TOKEN_SECRET\") || \"\",\n TWITTER_DRY_RUN: getConfig(\"TWITTER_DRY_RUN\") || \"false\",\n TWITTER_TARGET_USERS: getConfig(\"TWITTER_TARGET_USERS\") || \"\",\n TWITTER_ENABLE_POST: getConfig(\"TWITTER_ENABLE_POST\") || \"false\",\n TWITTER_ENABLE_REPLIES: getConfig(\"TWITTER_ENABLE_REPLIES\") || \"true\",\n TWITTER_ENABLE_ACTIONS: getConfig(\"TWITTER_ENABLE_ACTIONS\") || \"false\",\n TWITTER_POST_INTERVAL: getConfig(\"TWITTER_POST_INTERVAL\") || \"120\",\n TWITTER_ENGAGEMENT_INTERVAL: getConfig(\"TWITTER_ENGAGEMENT_INTERVAL\") || \"30\",\n TWITTER_MAX_ENGAGEMENTS_PER_RUN: getConfig(\"TWITTER_MAX_ENGAGEMENTS_PER_RUN\") || \"10\",\n TWITTER_MAX_TWEET_LENGTH: getConfig(\"TWITTER_MAX_TWEET_LENGTH\") || \"280\",\n TWITTER_RETRY_LIMIT: getConfig(\"TWITTER_RETRY_LIMIT\") || \"5\",\n };\n}\n\n/**\n * Load configuration from file (stub for future implementation)\n * @param configPath - Path to the configuration file (optional)\n * @returns Partial TwitterConfig object\n */\nexport function loadConfigFromFile(configPath?: string): Partial<TwitterConfig> {\n // For now, return empty config as file loading is not implemented\n return {};\n}\n\n/**\n * Load merged configuration from all sources\n * @param configPath - Path to the configuration file (optional)\n * @returns Complete TwitterConfig object\n */\nexport function loadConfig(configPath?: string): TwitterConfig {\n const fileConfig = loadConfigFromFile(configPath);\n\n return {\n ...getDefaultConfig(),\n ...fileConfig,\n ...getEnvConfig(),\n };\n}\n\n\n\n/**\n * Validate configuration\n * @param config - Configuration to validate\n * @throws Error if configuration is invalid\n */\nexport function validateConfig(config: unknown): TwitterConfig {\n return twitterEnvSchema.parse(config);\n}\n","import {\n ChannelType,\n type Content,\n EventType,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type UUID,\n createUniqueUuid,\n logger,\n} from \"@elizaos/core\";\nimport type { ClientBase } from \"./base\";\nimport type { MediaData } from \"./types\";\nimport { TwitterEventTypes } from \"./types\";\nimport { sendTweet } from \"./utils\";\n/**\n * Class representing a Twitter post client for generating and posting tweets.\n */\nexport class TwitterPostClient {\n client: ClientBase;\n runtime: IAgentRuntime;\n twitterUsername: string;\n private isDryRun: boolean;\n private state: any;\n private isRunning: boolean = false;\n\n /**\n * Constructor for initializing a new Twitter client with the provided client, runtime, and state\n * @param {ClientBase} client - The client used for interacting with Twitter API\n * @param {IAgentRuntime} runtime - The runtime environment for the agent\n * @param {any} state - The state object containing configuration settings\n */\n constructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n this.client = client;\n this.state = state;\n this.runtime = runtime;\n const dryRunSetting = this.state?.TWITTER_DRY_RUN ?? this.runtime.getSetting(\"TWITTER_DRY_RUN\");\n this.isDryRun = dryRunSetting === true || dryRunSetting === \"true\" || \n (typeof dryRunSetting === \"string\" && dryRunSetting.toLowerCase() === \"true\");\n\n // Log configuration on initialization\n logger.log(\"Twitter Post Client Configuration:\");\n logger.log(`- Dry Run Mode: ${this.isDryRun ? \"Enabled\" : \"Disabled\"}`);\n\n const postInterval = parseInt(\n this.state?.TWITTER_POST_INTERVAL || \n this.runtime.getSetting(\"TWITTER_POST_INTERVAL\") as string || \n \"120\"\n );\n logger.log(`- Post Interval: ${postInterval} minutes`);\n }\n \n /**\n * Stops the Twitter post client\n */\n async stop() {\n logger.log(\"Stopping Twitter post client...\");\n this.isRunning = false;\n }\n\n /**\n * Starts the Twitter post client, setting up a loop to periodically generate new tweets.\n */\n async start() {\n logger.log(\"Starting Twitter post client...\");\n this.isRunning = true;\n\n const generateNewTweetLoop = async () => {\n if (!this.isRunning) {\n logger.log(\"Twitter post client stopped, exiting loop\");\n return;\n }\n \n // Get post interval in minutes\n const postIntervalMinutes = parseInt(\n this.state?.TWITTER_POST_INTERVAL || \n this.runtime.getSetting(\"TWITTER_POST_INTERVAL\") as string || \n \"120\"\n );\n \n // Convert to milliseconds\n const interval = postIntervalMinutes * 60 * 1000;\n \n logger.info(`Next tweet scheduled in ${postIntervalMinutes} minutes`);\n\n await this.generateNewTweet();\n \n if (this.isRunning) {\n setTimeout(generateNewTweetLoop, interval);\n }\n };\n\n // Start the loop after a 1 minute delay to allow other services to initialize\n // Always post immediately for better UX\n await new Promise((resolve) => setTimeout(resolve, 1000));\n await this.generateNewTweet();\n \n // Then start the regular interval\n const postIntervalMinutes = parseInt(\n this.state?.TWITTER_POST_INTERVAL || \n this.runtime.getSetting(\"TWITTER_POST_INTERVAL\") as string || \n \"120\"\n );\n const interval = postIntervalMinutes * 60 * 1000;\n \n if (this.isRunning) {\n setTimeout(generateNewTweetLoop, interval);\n }\n }\n\n /**\n * Handles the creation and posting of a tweet by emitting standardized events.\n * This approach aligns with our platform-independent architecture.\n */\n async generateNewTweet() {\n logger.info(\"Attempting to generate new tweet...\");\n \n try {\n // Create the timeline room ID for storing the post\n const userId = this.client.profile?.id;\n if (!userId) {\n logger.error(\"Cannot generate tweet: Twitter profile not available\");\n return;\n }\n\n logger.info(`Generating tweet for user: ${this.client.profile?.username} (${userId})`);\n\n // Create standardized world and room IDs\n const worldId = createUniqueUuid(this.runtime, userId) as UUID;\n const roomId = createUniqueUuid(this.runtime, `${userId}-home`) as UUID;\n \n // Create a callback for handling the actual posting\n const callback: HandlerCallback = async (content: Content) => {\n logger.info(\"Tweet generation callback triggered\");\n \n try {\n if (this.isDryRun) {\n logger.info(`[DRY RUN] Would post tweet: ${content.text}`);\n return [];\n }\n\n if (content.text.includes(\"Error: Missing\")) {\n logger.error(\"Error: Missing some context\", content);\n return [];\n }\n\n logger.info(`Posting tweet: ${content.text}`);\n\n // Post the tweet\n const result = await this.postToTwitter(\n content.text,\n content.mediaData as MediaData[],\n );\n\n // If result is null, it means we detected a duplicate tweet and skipped posting\n if (result === null) {\n logger.info(\"Skipped posting duplicate tweet\");\n return [];\n }\n\n const tweetId = (result as any).id;\n logger.info(`Tweet posted successfully! ID: ${tweetId}`);\n\n if (result) {\n const postedTweetId = createUniqueUuid(this.runtime, tweetId);\n\n // Create memory for the posted tweet\n const postedMemory: Memory = {\n id: postedTweetId,\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n ...content,\n source: \"twitter\",\n channelType: ChannelType.FEED,\n type: \"post\",\n metadata: {\n tweetId,\n postedAt: Date.now(),\n },\n },\n createdAt: Date.now(),\n };\n\n await this.runtime.createMemory(postedMemory, \"messages\");\n\n return [postedMemory];\n }\n\n return [];\n } catch (error) {\n logger.error(\"Error in tweet generation callback:\", error);\n return [];\n }\n };\n\n // Emit the event that will trigger the agent to generate content\n this.runtime.emitEvent(\n TwitterEventTypes.POST_GENERATED,\n {\n callback,\n entityId: this.runtime.agentId,\n userId,\n roomId,\n source: \"twitter\",\n },\n );\n \n logger.info(\"POST_GENERATED event emitted successfully\");\n } catch (error) {\n logger.error(\"Error generating tweet:\", error);\n }\n }\n\n /**\n * Posts content to Twitter\n * @param {string} text The tweet text to post\n * @param {MediaData[]} mediaData Optional media to attach to the tweet\n * @returns {Promise<any>} The result from the Twitter API\n */\n private async postToTwitter(\n text: string,\n mediaData: MediaData[] = [],\n ): Promise<any> {\n try {\n // Check if this tweet is a duplicate of the last one\n const lastPost = await this.runtime.getCache<any>(\n `twitter/${this.client.profile?.username}/lastPost`,\n );\n if (lastPost) {\n // Fetch the last tweet to compare content\n const lastTweet = await this.client.getTweet(lastPost.id);\n if (lastTweet && lastTweet.text === text) {\n logger.warn(\n \"Tweet is a duplicate of the last post. Skipping to avoid duplicate.\",\n );\n return null;\n }\n }\n\n // Handle media uploads if needed\n const mediaIds: string[] = [];\n\n if (mediaData && mediaData.length > 0) {\n for (const media of mediaData) {\n try {\n // TODO: Media upload will need to be updated to use the new API\n // For now, just log a warning that media upload is not supported\n logger.warn(\n \"Media upload not currently supported with the modern Twitter API\",\n );\n } catch (error) {\n logger.error(\"Error uploading media:\", error);\n }\n }\n }\n\n const result = await sendTweet(this.client, text, mediaData);\n\n // Cache the new post to prevent duplicates\n await this.runtime.setCache(\n `twitter/${this.client.profile?.username}/lastPost`,\n {\n id: (result as any).id,\n text: text,\n timestamp: Date.now(),\n },\n );\n\n return result;\n } catch (error) {\n logger.error(\"Error posting to Twitter:\", error);\n throw error;\n }\n }\n}\n","import type { ClientBase } from \"./base\";\nimport {\n ChannelType,\n composePromptFromState,\n createUniqueUuid,\n ModelType,\n type IAgentRuntime,\n UUID,\n State,\n Memory,\n parseKeyValueXml,\n} from \"@elizaos/core\";\nimport type { Client, Tweet } from \"./client/index\";\nimport { logger } from \"@elizaos/core\";\n\nimport {\n twitterActionTemplate,\n quoteTweetTemplate,\n replyTweetTemplate,\n} from \"./templates\";\nimport { sendTweet, parseActionResponseFromText } from \"./utils\";\nimport { ActionResponse } from \"./types\";\n\nenum TIMELINE_TYPE {\n ForYou = \"foryou\",\n Following = \"following\",\n}\n\nexport class TwitterTimelineClient {\n client: ClientBase;\n twitterClient: Client;\n runtime: IAgentRuntime;\n isDryRun: boolean;\n timelineType: TIMELINE_TYPE;\n private state: any;\n private isRunning: boolean = false;\n\n constructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n this.client = client;\n this.twitterClient = client.twitterClient;\n this.runtime = runtime;\n this.state = state;\n\n const dryRunSetting = this.state?.TWITTER_DRY_RUN ?? this.runtime.getSetting(\"TWITTER_DRY_RUN\");\n this.isDryRun = dryRunSetting === true || dryRunSetting === \"true\" || \n (typeof dryRunSetting === \"string\" && dryRunSetting.toLowerCase() === \"true\");\n\n const timelineMode = \n this.state?.TWITTER_TIMELINE_MODE ||\n this.runtime.getSetting(\"TWITTER_TIMELINE_MODE\") ||\n \"foryou\";\n \n // Convert string to enum value\n this.timelineType = timelineMode.toLowerCase() === \"following\" \n ? TIMELINE_TYPE.Following \n : TIMELINE_TYPE.ForYou;\n }\n\n async start() {\n logger.info(\"Starting Twitter timeline client...\");\n this.isRunning = true;\n \n const handleTwitterTimelineLoop = () => {\n if (!this.isRunning) {\n logger.info(\"Twitter timeline client stopped, exiting loop\");\n return;\n }\n \n // Use unified engagement interval\n const engagementIntervalMinutes = parseInt(\n this.state?.TWITTER_ENGAGEMENT_INTERVAL ||\n this.runtime.getSetting(\"TWITTER_ENGAGEMENT_INTERVAL\") as string ||\n \"30\"\n );\n const actionInterval = engagementIntervalMinutes * 60 * 1000;\n \n logger.info(`Timeline client will check every ${engagementIntervalMinutes} minutes`);\n\n this.handleTimeline();\n \n if (this.isRunning) {\n setTimeout(handleTwitterTimelineLoop, actionInterval);\n }\n };\n handleTwitterTimelineLoop();\n }\n\n async stop() {\n logger.info(\"Stopping Twitter timeline client...\");\n this.isRunning = false;\n }\n\n async getTimeline(count: number): Promise<Tweet[]> {\n const twitterUsername = this.client.profile?.username;\n const homeTimeline =\n this.timelineType === TIMELINE_TYPE.Following\n ? await this.twitterClient.fetchFollowingTimeline(count, [])\n : await this.twitterClient.fetchHomeTimeline(count, []);\n\n // The timeline methods now return Tweet objects directly from v2 API\n return homeTimeline\n .filter((tweet) => tweet.username !== twitterUsername); // do not perform action on self-tweets\n }\n\n createTweetId(runtime: IAgentRuntime, tweet: Tweet) {\n return createUniqueUuid(runtime, tweet.id);\n }\n\n formMessage(runtime: IAgentRuntime, tweet: Tweet) {\n return {\n id: this.createTweetId(runtime, tweet),\n agentId: runtime.agentId,\n content: {\n text: tweet.text,\n url: tweet.permanentUrl,\n imageUrls: tweet.photos?.map((photo) => photo.url) || [],\n inReplyTo: tweet.inReplyToStatusId\n ? createUniqueUuid(runtime, tweet.inReplyToStatusId)\n : undefined,\n source: \"twitter\",\n channelType: ChannelType.GROUP,\n tweet,\n },\n entityId: createUniqueUuid(runtime, tweet.userId),\n roomId: createUniqueUuid(runtime, tweet.conversationId),\n createdAt: tweet.timestamp * 1000,\n };\n }\n\n async handleTimeline() {\n logger.info(\"Starting Twitter timeline processing...\");\n\n const tweets = await this.getTimeline(20);\n logger.info(`Fetched ${tweets.length} tweets from timeline`);\n \n // Use max engagements per run from environment\n const maxActionsPerCycle = parseInt(\n this.runtime.getSetting(\"TWITTER_MAX_ENGAGEMENTS_PER_RUN\") as string || \"10\"\n );\n \n const tweetDecisions = [];\n for (const tweet of tweets) {\n try {\n const tweetId = this.createTweetId(this.runtime, tweet);\n // Skip if we've already processed this tweet\n const memory = await this.runtime.getMemoryById(tweetId);\n if (memory) {\n logger.log(`Already processed tweet ID: ${tweet.id}`);\n continue;\n }\n\n const roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n\n const message = this.formMessage(this.runtime, tweet);\n\n let state = await this.runtime.composeState(message);\n\n const actionRespondPrompt =\n composePromptFromState({\n state,\n template:\n this.runtime.character.templates?.twitterActionTemplate ||\n twitterActionTemplate,\n }) +\n `\nTweet:\n${tweet.text}\n\n# Respond with qualifying action tags only.\n\nChoose any combination of [LIKE], [RETWEET], [QUOTE], and [REPLY] that are appropriate. Each action must be on its own line. Your response must only include the chosen actions.`;\n\n const actionResponse = await this.runtime.useModel(\n ModelType.TEXT_SMALL,\n {\n prompt: actionRespondPrompt,\n },\n );\n const parsedResponse = parseActionResponseFromText(actionResponse);\n\n // Ensure a valid action response was generated\n if (!parsedResponse) {\n logger.debug(`No action response generated for tweet ${tweet.id}`);\n continue;\n }\n\n tweetDecisions.push({\n tweet,\n actionResponse: parsedResponse,\n tweetState: state,\n roomId,\n });\n\n // Limit the number of actions per cycle\n if (tweetDecisions.length >= maxActionsPerCycle) break;\n } catch (error) {\n logger.error(`Error processing tweet ${tweet.id}:`, error);\n }\n }\n\n // Rank by the quality of the response\n const rankByActionRelevance = (arr) => {\n return arr.sort((a, b) => {\n const countTrue = (obj: typeof a.actionResponse) =>\n Object.values(obj).filter(Boolean).length;\n\n const countA = countTrue(a.actionResponse);\n const countB = countTrue(b.actionResponse);\n\n // Primary sort by number of true values\n if (countA !== countB) {\n return countB - countA;\n }\n\n // Secondary sort by the \"like\" property\n if (a.actionResponse.like !== b.actionResponse.like) {\n return a.actionResponse.like ? -1 : 1;\n }\n\n // Tertiary sort keeps the remaining objects with equal weight\n return 0;\n });\n };\n // Sort the timeline based on the action decision score,\n const prioritizedTweets = rankByActionRelevance(tweetDecisions);\n \n logger.info(`Processing ${prioritizedTweets.length} tweets with actions`);\n if (prioritizedTweets.length > 0) {\n const actionSummary = prioritizedTweets.map(td => {\n const actions = [];\n if (td.actionResponse.like) actions.push('LIKE');\n if (td.actionResponse.retweet) actions.push('RETWEET');\n if (td.actionResponse.quote) actions.push('QUOTE');\n if (td.actionResponse.reply) actions.push('REPLY');\n return `Tweet ${td.tweet.id}: ${actions.join(', ')}`;\n });\n logger.info(`Actions to execute:\\n${actionSummary.join('\\n')}`);\n }\n\n await this.processTimelineActions(prioritizedTweets);\n logger.info(\"Timeline processing complete\");\n }\n\n private async processTimelineActions(\n tweetDecisions: {\n tweet: Tweet;\n actionResponse: ActionResponse;\n tweetState: State;\n roomId: UUID;\n }[],\n ): Promise<\n {\n tweetId: string;\n actionResponse: ActionResponse;\n executedActions: string[];\n }[]\n > {\n const results = [];\n\n for (const { tweet, actionResponse, tweetState, roomId } of tweetDecisions) {\n const tweetId = this.createTweetId(this.runtime, tweet);\n const executedActions = [];\n\n // Update memory with processed tweet\n await this.runtime.createMemory(\n {\n id: tweetId,\n entityId: createUniqueUuid(this.runtime, tweet.userId),\n content: {\n text: tweet.text,\n url: tweet.permanentUrl,\n source: \"twitter\",\n channelType: ChannelType.GROUP,\n tweet: tweet,\n },\n agentId: this.runtime.agentId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n },\n \"messages\",\n );\n\n try {\n // ensure world and rooms, connections, and worlds are created\n const userId = tweet.userId;\n const worldId = createUniqueUuid(this.runtime, userId);\n const entityId = createUniqueUuid(this.runtime, userId);\n\n await this.ensureTweetWorldContext(tweet, roomId, worldId, entityId);\n\n if (actionResponse.like) {\n await this.handleLikeAction(tweet);\n executedActions.push(\"like\");\n }\n\n if (actionResponse.retweet) {\n await this.handleRetweetAction(tweet);\n executedActions.push(\"retweet\");\n }\n\n if (actionResponse.quote) {\n await this.handleQuoteAction(tweet);\n executedActions.push(\"quote\");\n }\n\n if (actionResponse.reply) {\n await this.handleReplyAction(tweet);\n executedActions.push(\"reply\");\n }\n\n results.push({ tweetId: tweet.id, actionResponse, executedActions });\n } catch (error) {\n logger.error(`Error processing actions for tweet ${tweet.id}:`, error);\n }\n }\n\n return results;\n }\n\n private async ensureTweetWorldContext(\n tweet: Tweet,\n roomId: UUID,\n worldId: UUID,\n entityId: UUID,\n ) {\n await this.runtime.ensureWorldExists({\n id: worldId,\n name: `${tweet.name}'s Twitter`,\n agentId: this.runtime.agentId,\n serverId: tweet.userId,\n metadata: {\n ownership: { ownerId: tweet.userId },\n twitter: {\n username: tweet.username,\n id: tweet.userId,\n name: tweet.name,\n },\n },\n });\n\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: tweet.username,\n name: tweet.name,\n worldName: `${tweet.name}'s Twitter`,\n source: \"twitter\",\n type: ChannelType.GROUP,\n channelId: tweet.conversationId,\n serverId: tweet.userId,\n worldId,\n metadata: {\n ownership: { ownerId: tweet.userId },\n twitter: {\n username: tweet.username,\n id: tweet.userId,\n name: tweet.name,\n },\n },\n });\n }\n\n async handleLikeAction(tweet: Tweet) {\n try {\n if (this.isDryRun) {\n logger.log(`[DRY RUN] Would have liked tweet ${tweet.id}`);\n return;\n }\n await this.twitterClient.likeTweet(tweet.id);\n logger.log(`Liked tweet ${tweet.id}`);\n } catch (error) {\n logger.error(`Error liking tweet ${tweet.id}:`, error);\n }\n }\n\n async handleRetweetAction(tweet: Tweet) {\n try {\n if (this.isDryRun) {\n logger.log(`[DRY RUN] Would have retweeted tweet ${tweet.id}`);\n return;\n }\n await this.twitterClient.retweet(tweet.id);\n logger.log(`Retweeted tweet ${tweet.id}`);\n } catch (error) {\n logger.error(`Error retweeting tweet ${tweet.id}:`, error);\n }\n }\n\n async handleQuoteAction(tweet: Tweet) {\n try {\n const message = this.formMessage(this.runtime, tweet);\n\n let state = await this.runtime.composeState(message);\n\n const quotePrompt =\n composePromptFromState({\n state,\n template:\n this.runtime.character.templates?.quoteTweetTemplate ||\n quoteTweetTemplate,\n }) +\n `\nYou are responding to this tweet:\n${tweet.text}`;\n\n const quoteResponse = await this.runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: quotePrompt,\n });\n const responseObject = parseKeyValueXml(quoteResponse);\n\n if (responseObject.post) {\n if (this.isDryRun) {\n logger.log(`[DRY RUN] Would have quoted tweet ${tweet.id} with: ${responseObject.post}`);\n return;\n }\n \n const result = await this.client.requestQueue.add(\n async () =>\n await this.twitterClient.sendQuoteTweet(\n responseObject.post,\n tweet.id,\n ),\n );\n\n const body: any = await result.json();\n\n const tweetResult =\n body?.data?.create_tweet?.tweet_results?.result || body?.data || body;\n if (tweetResult) {\n logger.log(\"Successfully posted quote tweet\");\n } else {\n logger.error(\"Quote tweet creation failed:\", body);\n }\n\n // Create memory for our response\n const tweetId =\n tweetResult?.id || Date.now().toString();\n const responseId = createUniqueUuid(this.runtime, tweetId);\n const responseMemory: Memory = {\n id: responseId,\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId: message.roomId,\n content: {\n ...responseObject,\n inReplyTo: message.id,\n },\n createdAt: Date.now(),\n };\n\n // Save the response to memory\n await this.runtime.createMemory(responseMemory, \"messages\");\n }\n } catch (error) {\n logger.error(\"Error in quote tweet generation:\", error);\n }\n }\n\n async handleReplyAction(tweet: Tweet) {\n try {\n const message = this.formMessage(this.runtime, tweet);\n\n let state = await this.runtime.composeState(message);\n\n const replyPrompt =\n composePromptFromState({\n state,\n template:\n this.runtime.character.templates?.replyTweetTemplate ||\n replyTweetTemplate,\n }) +\n `\nYou are replying to this tweet:\n${tweet.text}`;\n\n const replyResponse = await this.runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: replyPrompt,\n });\n const responseObject = parseKeyValueXml(replyResponse);\n\n if (responseObject.post) {\n if (this.isDryRun) {\n logger.log(`[DRY RUN] Would have replied to tweet ${tweet.id} with: ${responseObject.post}`);\n return;\n }\n \n const result = await sendTweet(\n this.client,\n responseObject.post,\n [],\n tweet.id,\n );\n\n if (result) {\n logger.log(\"Successfully posted reply tweet\");\n \n // Create memory for our response\n const responseId = createUniqueUuid(this.runtime, result.id);\n const responseMemory: Memory = {\n id: responseId,\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId: message.roomId,\n content: {\n ...responseObject,\n inReplyTo: message.id,\n },\n createdAt: Date.now(),\n };\n\n // Save the response to memory\n await this.runtime.createMemory(responseMemory, \"messages\");\n }\n }\n } catch (error) {\n logger.error(\"Error in reply tweet generation:\", error);\n }\n }\n}\n","export const twitterActionTemplate = `\n# INSTRUCTIONS: Determine actions for {{agentName}} (@{{twitterUserName}}) based on:\n{{bio}}\n{{postDirections}}\n\nGuidelines:\n- ONLY engage with content that DIRECTLY relates to character's core interests\n- Direct mentions are priority IF they are on-topic\n- Skip ALL content that is:\n - Off-topic or tangentially related\n - From high-profile accounts unless explicitly relevant\n - Generic/viral content without specific relevance\n - Political/controversial unless central to character\n - Promotional/marketing unless directly relevant\n\nActions (respond only with tags):\n[LIKE] - Perfect topic match AND aligns with character (9.8/10)\n[RETWEET] - Exceptional content that embodies character's expertise (9.5/10)\n[QUOTE] - Can add substantial domain expertise (9.5/10)\n[REPLY] - Can contribute meaningful, expert-level insight (9.5/10)\n`;\n\nexport const quoteTweetTemplate = `# Task: Write a quote tweet in the voice, style, and perspective of {{agentName}} @{{twitterUserName}}.\n\n{{bio}}\n{{postDirections}}\n\n<response>\n <thought>Your thought here, explaining why the quote tweet is meaningful or how it connects to what {{agentName}} cares about</thought>\n <post>The quote tweet content here, under 280 characters, without emojis, no questions</post>\n</response>\n\nYour quote tweet should be:\n- A reaction, agreement, disagreement, or expansion of the original tweet\n- Personal and unique to {{agentName}}’s style and point of view\n- 1 to 3 sentences long, chosen at random\n- No questions, no emojis, concise\n- Use \"\\\\n\\\\n\" (double spaces) between multiple sentences\n- Max 280 characters including line breaks\n\nYour output must ONLY contain the XML block.`;\n\nexport const replyTweetTemplate = `# Task: Write a reply tweet in the voice, style, and perspective of {{agentName}} @{{twitterUserName}}.\n\n{{bio}}\n{{postDirections}}\n\n<response>\n <thought>Your thought here, explaining why this reply is meaningful or how it connects to what {{agentName}} cares about</thought>\n <post>The reply tweet content here, under 280 characters, without emojis, no questions</post>\n</response>\n\nYour reply should be:\n- A direct response, agreement, disagreement, or personal take on the original tweet\n- Reflective of {{agentName}}’s unique voice and values\n- 1 to 2 sentences long, chosen at random\n- No questions, no emojis, concise\n- Use \"\\\\n\\\\n\" (double spaces) between multiple sentences if needed\n- Max 280 characters including line breaks\n\nYour output must ONLY contain the XML block.`;\n","import type { ClientBase } from \"./base\";\nimport type { Client, Tweet } from \"./client/index\";\nimport {\n type IAgentRuntime,\n createUniqueUuid,\n logger,\n ModelType,\n} from \"@elizaos/core\";\nimport { SearchMode } from \"./client/index\";\n\ninterface DiscoveryConfig {\n // Topics from character configuration\n topics: string[];\n // Minimum follower count for accounts to consider\n minFollowerCount: number;\n // Maximum accounts to follow per cycle\n maxFollowsPerCycle: number;\n // Maximum engagements per cycle\n maxEngagementsPerCycle: number;\n // Engagement probability thresholds\n likeThreshold: number;\n replyThreshold: number;\n quoteThreshold: number;\n}\n\ninterface ScoredTweet {\n tweet: Tweet;\n relevanceScore: number;\n engagementType: 'like' | 'reply' | 'quote' | 'skip';\n}\n\ninterface ScoredAccount {\n user: {\n id: string;\n username: string;\n name: string;\n followersCount: number;\n };\n qualityScore: number;\n relevanceScore: number;\n}\n\nexport class TwitterDiscoveryClient {\n private client: ClientBase;\n private twitterClient: Client;\n private runtime: IAgentRuntime;\n private config: DiscoveryConfig;\n private isRunning: boolean = false;\n private isDryRun: boolean;\n\n constructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n this.client = client;\n this.twitterClient = client.twitterClient;\n this.runtime = runtime;\n \n // Check dry run mode\n const dryRunSetting = state?.TWITTER_DRY_RUN ?? this.runtime.getSetting(\"TWITTER_DRY_RUN\");\n this.isDryRun = dryRunSetting === true || dryRunSetting === \"true\" || \n (typeof dryRunSetting === \"string\" && dryRunSetting.toLowerCase() === \"true\");\n \n // Build config from character settings\n this.config = this.buildDiscoveryConfig();\n \n logger.info(\"Twitter Discovery Config:\", {\n topics: this.config.topics,\n isDryRun: this.isDryRun,\n minFollowerCount: this.config.minFollowerCount,\n maxFollowsPerCycle: this.config.maxFollowsPerCycle,\n maxEngagementsPerCycle: this.config.maxEngagementsPerCycle,\n });\n }\n\n private buildDiscoveryConfig(): DiscoveryConfig {\n const character = this.runtime.character;\n \n // Use character topics or extract from bio\n const topics = character.topics || this.extractTopicsFromBio(character.bio);\n \n return {\n topics,\n minFollowerCount: parseInt(\n this.runtime.getSetting(\"TWITTER_MIN_FOLLOWER_COUNT\") as string || \"100\"\n ),\n maxFollowsPerCycle: parseInt(\n this.runtime.getSetting(\"TWITTER_MAX_FOLLOWS_PER_CYCLE\") as string || \"5\"\n ),\n maxEngagementsPerCycle: parseInt(\n this.runtime.getSetting(\"TWITTER_MAX_ENGAGEMENTS_PER_RUN\") as string || \"10\"\n ),\n likeThreshold: 0.6,\n replyThreshold: 0.8,\n quoteThreshold: 0.85,\n };\n }\n\n private extractTopicsFromBio(bio: string | string[]): string[] {\n const bioText = Array.isArray(bio) ? bio.join(\" \") : bio;\n // Extract meaningful words as potential topics\n const words = bioText.toLowerCase()\n .split(/\\s+/)\n .filter(word => word.length > 4)\n .filter(word => !['about', 'helping', 'working', 'people', 'making', 'building'].includes(word));\n return [...new Set(words)].slice(0, 5); // Limit to 5 topics\n }\n\n async start() {\n logger.info(\"Starting Twitter Discovery Client...\");\n this.isRunning = true;\n \n const discoveryLoop = async () => {\n if (!this.isRunning) {\n logger.info(\"Discovery client stopped, exiting loop\");\n return;\n }\n \n try {\n await this.runDiscoveryCycle();\n } catch (error) {\n logger.error(\"Discovery cycle error:\", error);\n }\n \n // Run discovery every 20-40 minutes (with variance)\n const baseInterval = parseInt(\n this.runtime.getSetting(\"TWITTER_DISCOVERY_INTERVAL\") as string || \"30\"\n );\n const variance = Math.random() * 20 - 10; // ±10 minutes\n const nextInterval = (baseInterval + variance) * 60 * 1000;\n \n logger.info(`Next discovery cycle in ${((baseInterval + variance)).toFixed(1)} minutes`);\n \n if (this.isRunning) {\n setTimeout(discoveryLoop, nextInterval);\n }\n };\n \n // Start after a short delay\n setTimeout(discoveryLoop, 5000);\n }\n\n async stop() {\n logger.info(\"Stopping Twitter Discovery Client...\");\n this.isRunning = false;\n }\n\n private async runDiscoveryCycle() {\n logger.info(\"Starting Twitter discovery cycle...\");\n \n const discoveries = await this.discoverContent();\n const { tweets, accounts } = discoveries;\n \n logger.info(`Discovered ${tweets.length} tweets and ${accounts.length} accounts`);\n \n // Process discovered accounts (follow high-quality ones)\n const followedCount = await this.processAccounts(accounts);\n \n // Process discovered tweets (engage with relevant ones)\n const engagementCount = await this.processTweets(tweets);\n \n logger.info(\n `Discovery cycle complete: ${followedCount} follows, ${engagementCount} engagements`\n );\n }\n\n private async discoverContent(): Promise<{\n tweets: ScoredTweet[];\n accounts: ScoredAccount[];\n }> {\n const allTweets: ScoredTweet[] = [];\n const allAccounts = new Map<string, ScoredAccount>();\n \n // Note: Twitter API v2 doesn't support trends, so we skip trend-based discovery\n \n // 1. Discover from topic searches (primary discovery method)\n try {\n const topicContent = await this.discoverFromTopics();\n allTweets.push(...topicContent.tweets);\n topicContent.accounts.forEach(acc => \n allAccounts.set(acc.user.id, acc)\n );\n } catch (error) {\n logger.error(\"Failed to discover from topics:\", error);\n }\n \n // 2. Discover from conversation threads\n try {\n const threadContent = await this.discoverFromThreads();\n allTweets.push(...threadContent.tweets);\n threadContent.accounts.forEach(acc => \n allAccounts.set(acc.user.id, acc)\n );\n } catch (error) {\n logger.error(\"Failed to discover from threads:\", error);\n }\n \n // 3. Discover from popular accounts in our topics\n try {\n const popularContent = await this.discoverFromPopularAccounts();\n allTweets.push(...popularContent.tweets);\n popularContent.accounts.forEach(acc => \n allAccounts.set(acc.user.id, acc)\n );\n } catch (error) {\n logger.error(\"Failed to discover from popular accounts:\", error);\n }\n \n // Sort by relevance score\n const sortedTweets = allTweets\n .sort((a, b) => b.relevanceScore - a.relevanceScore)\n .slice(0, 50); // Top 50 tweets\n \n const sortedAccounts = Array.from(allAccounts.values())\n .sort((a, b) => (b.qualityScore * b.relevanceScore) - (a.qualityScore * a.relevanceScore))\n .slice(0, 20); // Top 20 accounts\n \n return { tweets: sortedTweets, accounts: sortedAccounts };\n }\n\n private async discoverFromTopics(): Promise<{\n tweets: ScoredTweet[];\n accounts: ScoredAccount[];\n }> {\n logger.debug(\"Discovering from character topics...\");\n \n const tweets: ScoredTweet[] = [];\n const accounts = new Map<string, ScoredAccount>();\n \n // Search for each topic with different query strategies\n for (const topic of this.config.topics.slice(0, 5)) {\n try {\n // Strategy 1: Popular recent tweets\n const popularQuery = `${topic} -is:retweet -is:reply min_faves:10 lang:en`;\n \n logger.debug(`Searching popular tweets for topic: ${topic}`);\n const popularResults = await this.twitterClient.fetchSearchTweets(\n popularQuery,\n 20,\n SearchMode.Top\n );\n \n for (const tweet of popularResults.tweets) {\n const scored = this.scoreTweet(tweet, 'topic');\n tweets.push(scored);\n }\n \n // Strategy 2: Latest tweets from verified/notable accounts\n const verifiedQuery = `${topic} -is:retweet lang:en filter:verified`;\n \n logger.debug(`Searching verified accounts for topic: ${topic}`);\n const verifiedResults = await this.twitterClient.fetchSearchTweets(\n verifiedQuery,\n 10,\n SearchMode.Latest\n );\n \n for (const tweet of verifiedResults.tweets) {\n const scored = this.scoreTweet(tweet, 'topic');\n tweets.push(scored);\n \n // Extract account info from tweet author\n const authorUsername = tweet.username;\n const authorName = tweet.name || tweet.username;\n \n // For v2 API, we don't get follower count in tweet data\n // We'll need to make a separate call or estimate quality differently\n const account = this.scoreAccount({\n id: tweet.userId,\n username: authorUsername,\n name: authorName,\n followersCount: 1000, // Default estimate for verified accounts\n });\n \n if (account.qualityScore > 0.5) {\n accounts.set(tweet.userId, account);\n }\n }\n } catch (error) {\n logger.error(`Failed to search topic ${topic}:`, error);\n }\n }\n \n return { tweets, accounts: Array.from(accounts.values()) };\n }\n\n private async discoverFromThreads(): Promise<{\n tweets: ScoredTweet[];\n accounts: ScoredAccount[];\n }> {\n logger.debug(\"Discovering from conversation threads...\");\n \n const tweets: ScoredTweet[] = [];\n const accounts = new Map<string, ScoredAccount>();\n \n // Search for viral conversations in our topics\n const topicQuery = this.config.topics\n .slice(0, 3)\n .map(t => `\"${t}\"`)\n .join(\" OR \");\n \n try {\n const viralQuery = `${topicQuery} min_replies:20 min_faves:50 -is:retweet`;\n \n logger.debug(`Searching viral threads with query: ${viralQuery}`);\n const searchResults = await this.twitterClient.fetchSearchTweets(\n viralQuery,\n 15,\n SearchMode.Top\n );\n \n for (const tweet of searchResults.tweets) {\n const scored = this.scoreTweet(tweet, 'thread');\n tweets.push(scored);\n \n // Viral thread authors are likely high-quality accounts\n const account = this.scoreAccount({\n id: tweet.userId,\n username: tweet.username,\n name: tweet.name || tweet.username,\n followersCount: 5000, // Estimate for viral content creators\n });\n \n if (account.qualityScore > 0.6) {\n accounts.set(tweet.userId, account);\n }\n }\n } catch (error) {\n logger.error(\"Failed to discover threads:\", error);\n }\n \n return { tweets, accounts: Array.from(accounts.values()) };\n }\n\n private async discoverFromPopularAccounts(): Promise<{\n tweets: ScoredTweet[];\n accounts: ScoredAccount[];\n }> {\n logger.debug(\"Discovering from popular accounts in topics...\");\n \n const tweets: ScoredTweet[] = [];\n const accounts = new Map<string, ScoredAccount>();\n \n // Search for users who frequently tweet about our topics\n for (const topic of this.config.topics.slice(0, 3)) {\n try {\n // Find tweets from accounts with high engagement\n const influencerQuery = `${topic} -is:retweet min_faves:100 min_retweets:20`;\n \n logger.debug(`Searching for influencers in topic: ${topic}`);\n const results = await this.twitterClient.fetchSearchTweets(\n influencerQuery,\n 10,\n SearchMode.Top\n );\n \n for (const tweet of results.tweets) {\n const scored = this.scoreTweet(tweet, 'topic');\n tweets.push(scored);\n \n // High engagement suggests a quality account\n const estimatedFollowers = Math.max(\n (tweet.likes || 0) * 100,\n (tweet.retweets || 0) * 200,\n 10000\n );\n \n const account = this.scoreAccount({\n id: tweet.userId,\n username: tweet.username,\n name: tweet.name || tweet.username,\n followersCount: estimatedFollowers,\n });\n \n if (account.qualityScore > 0.7) {\n accounts.set(tweet.userId, account);\n }\n }\n } catch (error) {\n logger.error(`Failed to discover popular accounts for ${topic}:`, error);\n }\n }\n \n return { tweets, accounts: Array.from(accounts.values()) };\n }\n\n // Remove the discoverFromTrends method since API v2 doesn't support it\n // Remove the isTrendRelevant method since we're not using trends\n\n private scoreTweet(tweet: Tweet, source: 'topic' | 'thread'): ScoredTweet {\n let relevanceScore = 0;\n \n // Base score by source\n const sourceScores = {\n topic: 0.5,\n thread: 0.4,\n };\n relevanceScore += sourceScores[source];\n \n // Score by engagement metrics\n const engagementScore = Math.min(\n (tweet.likes || 0) / 1000 + \n (tweet.retweets || 0) / 500 + \n (tweet.replies || 0) / 100,\n 0.3\n );\n relevanceScore += engagementScore;\n \n // Score by content relevance to topics\n const textLower = tweet.text.toLowerCase();\n const topicMatches = this.config.topics.filter(topic => \n textLower.includes(topic.toLowerCase())\n ).length;\n relevanceScore += Math.min(topicMatches * 0.1, 0.3);\n \n // Bonus for verified accounts (if available in tweet data)\n // Note: isBlueVerified might not be available in all tweet responses\n \n // Normalize score\n relevanceScore = Math.min(relevanceScore, 1);\n \n // Determine engagement type based on score\n let engagementType: ScoredTweet['engagementType'] = 'skip';\n if (relevanceScore >= this.config.quoteThreshold) {\n engagementType = 'quote';\n } else if (relevanceScore >= this.config.replyThreshold) {\n engagementType = 'reply';\n } else if (relevanceScore >= this.config.likeThreshold) {\n engagementType = 'like';\n }\n \n return {\n tweet,\n relevanceScore,\n engagementType,\n };\n }\n\n private scoreAccount(user: ScoredAccount['user']): ScoredAccount {\n let qualityScore = 0;\n let relevanceScore = 0;\n \n // Quality based on follower count\n if (user.followersCount > 10000) qualityScore += 0.4;\n else if (user.followersCount > 1000) qualityScore += 0.3;\n else if (user.followersCount > 100) qualityScore += 0.2;\n \n // Relevance based on username/name matching topics\n const userText = `${user.username} ${user.name}`.toLowerCase();\n const topicMatches = this.config.topics.filter(topic => \n userText.includes(topic.toLowerCase())\n ).length;\n relevanceScore = Math.min(topicMatches * 0.3, 1);\n \n return {\n user,\n qualityScore: Math.min(qualityScore, 1),\n relevanceScore,\n };\n }\n\n private async processAccounts(accounts: ScoredAccount[]): Promise<number> {\n let followedCount = 0;\n \n for (const scoredAccount of accounts) {\n if (followedCount >= this.config.maxFollowsPerCycle) break;\n \n try {\n // Check if already following (via memory)\n const isFollowing = await this.checkIfFollowing(scoredAccount.user.id);\n if (isFollowing) continue;\n \n if (this.isDryRun) {\n logger.info(\n `[DRY RUN] Would follow @${scoredAccount.user.username} ` +\n `(quality: ${scoredAccount.qualityScore.toFixed(2)}, ` +\n `relevance: ${scoredAccount.relevanceScore.toFixed(2)})`\n );\n } else {\n // Follow the account\n await this.twitterClient.followUser(scoredAccount.user.id);\n \n logger.info(\n `Followed @${scoredAccount.user.username} ` +\n `(quality: ${scoredAccount.qualityScore.toFixed(2)}, ` +\n `relevance: ${scoredAccount.relevanceScore.toFixed(2)})`\n );\n \n // Save follow action to memory\n await this.saveFollowMemory(scoredAccount.user);\n }\n \n followedCount++;\n \n // Add a delay to avoid rate limits\n await this.delay(2000 + Math.random() * 3000);\n } catch (error) {\n logger.error(`Failed to follow @${scoredAccount.user.username}:`, error);\n }\n }\n \n return followedCount;\n }\n\n private async processTweets(tweets: ScoredTweet[]): Promise<number> {\n let engagementCount = 0;\n \n for (const scoredTweet of tweets) {\n if (engagementCount >= this.config.maxEngagementsPerCycle) break;\n if (scoredTweet.engagementType === 'skip') continue;\n \n try {\n // Check if already engaged\n const tweetMemoryId = createUniqueUuid(this.runtime, scoredTweet.tweet.id);\n const existingMemory = await this.runtime.getMemoryById(tweetMemoryId);\n if (existingMemory) {\n logger.debug(`Already engaged with tweet ${scoredTweet.tweet.id}, skipping`);\n continue;\n }\n \n // Perform engagement\n switch (scoredTweet.engagementType) {\n case 'like':\n if (this.isDryRun) {\n logger.info(`[DRY RUN] Would like tweet: ${scoredTweet.tweet.id} (score: ${scoredTweet.relevanceScore.toFixed(2)})`);\n } else {\n await this.twitterClient.likeTweet(scoredTweet.tweet.id);\n logger.info(`Liked tweet: ${scoredTweet.tweet.id} (score: ${scoredTweet.relevanceScore.toFixed(2)})`);\n }\n break;\n \n case 'reply':\n const replyText = await this.generateReply(scoredTweet.tweet);\n if (this.isDryRun) {\n logger.info(`[DRY RUN] Would reply to tweet ${scoredTweet.tweet.id} with: \"${replyText}\"`);\n } else {\n await this.twitterClient.sendTweet(replyText, scoredTweet.tweet.id);\n logger.info(`Replied to tweet: ${scoredTweet.tweet.id}`);\n }\n break;\n \n case 'quote':\n const quoteText = await this.generateQuote(scoredTweet.tweet);\n if (this.isDryRun) {\n logger.info(`[DRY RUN] Would quote tweet ${scoredTweet.tweet.id} with: \"${quoteText}\"`);\n } else {\n await this.twitterClient.sendQuoteTweet(quoteText, scoredTweet.tweet.id);\n logger.info(`Quoted tweet: ${scoredTweet.tweet.id}`);\n }\n break;\n }\n \n // Save engagement to memory (even in dry run for tracking)\n await this.saveEngagementMemory(scoredTweet.tweet, scoredTweet.engagementType);\n \n engagementCount++;\n \n // Add delay to avoid rate limits\n await this.delay(3000 + Math.random() * 5000);\n } catch (error) {\n logger.error(`Failed to engage with tweet ${scoredTweet.tweet.id}:`, error);\n }\n }\n \n return engagementCount;\n }\n\n private async checkIfFollowing(userId: string): Promise<boolean> {\n // Check our memory to see if we've followed them\n const embedding = await this.runtime.useModel(ModelType.TEXT_EMBEDDING, {\n text: `followed twitter user ${userId}`\n });\n \n const followMemories = await this.runtime.searchMemories({\n tableName: \"messages\",\n embedding,\n match_threshold: 0.8,\n count: 1,\n });\n return followMemories.length > 0;\n }\n\n private async generateReply(tweet: Tweet): Promise<string> {\n const prompt = `You are ${this.runtime.character.name}. Generate a thoughtful reply to this tweet:\n\nTweet by @${tweet.username}: \"${tweet.text}\"\n\nYour interests: ${this.config.topics.join(\", \")}\nCharacter bio: ${Array.isArray(this.runtime.character.bio) ? this.runtime.character.bio.join(\" \") : this.runtime.character.bio}\n\nKeep the reply:\n- Relevant and adding value to the conversation\n- Under 280 characters\n- Natural and conversational\n- Related to your expertise and interests\n- Respectful and constructive\n\nReply:`;\n \n const response = await this.runtime.useModel(ModelType.TEXT_SMALL, {\n prompt,\n max_tokens: 100,\n temperature: 0.8,\n });\n \n return response.trim();\n }\n\n private async generateQuote(tweet: Tweet): Promise<string> {\n const prompt = `You are ${this.runtime.character.name}. Add your perspective to this tweet with a quote tweet:\n\nOriginal tweet by @${tweet.username}: \"${tweet.text}\"\n\nYour interests: ${this.config.topics.join(\", \")}\nCharacter bio: ${Array.isArray(this.runtime.character.bio) ? this.runtime.character.bio.join(\" \") : this.runtime.character.bio}\n\nCreate a quote tweet that:\n- Adds unique insight or perspective\n- Is under 280 characters\n- Respectfully builds on the original idea\n- Showcases your expertise\n- Encourages further discussion\n\nQuote tweet:`;\n \n const response = await this.runtime.useModel(ModelType.TEXT_SMALL, {\n prompt,\n max_tokens: 100,\n temperature: 0.8,\n });\n \n return response.trim();\n }\n\n private async saveEngagementMemory(tweet: Tweet, engagementType: string) {\n const memoryId = await this.runtime.createMemory({\n id: createUniqueUuid(this.runtime, tweet.id),\n entityId: createUniqueUuid(this.runtime, tweet.userId),\n content: {\n text: `${engagementType} tweet from @${tweet.username}: ${tweet.text}`,\n metadata: {\n tweetId: tweet.id,\n engagementType,\n source: 'discovery',\n isDryRun: this.isDryRun,\n },\n },\n roomId: createUniqueUuid(this.runtime, tweet.conversationId),\n }, \"messages\");\n }\n\n private async saveFollowMemory(user: ScoredAccount['user']) {\n const memoryId = await this.runtime.createMemory({\n entityId: createUniqueUuid(this.runtime, user.id),\n content: {\n text: `followed twitter user ${user.id} @${user.username}`,\n metadata: {\n userId: user.id,\n username: user.username,\n name: user.name,\n followersCount: user.followersCount,\n source: 'discovery',\n isDryRun: this.isDryRun,\n },\n },\n roomId: createUniqueUuid(this.runtime, `twitter-follows`),\n }, \"messages\");\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n}","import {\n ChannelType,\n type Content,\n type IAgentRuntime,\n type Memory,\n type State,\n type UUID,\n createUniqueUuid,\n logger,\n} from \"@elizaos/core\";\nimport {\n Client,\n type QueryTweetsResponse,\n SearchMode,\n type Tweet,\n} from \"./client/index\";\nimport { TwitterInteractionPayload } from \"./types\";\n\ninterface TwitterUser {\n id_str: string;\n screen_name: string;\n name: string;\n}\n\ninterface TwitterFollowersResponse {\n users: TwitterUser[];\n}\n\n/**\n * Extracts the answer from the given text.\n *\n * @param {string} text - The text containing the answer\n * @returns {string} The extracted answer\n */\nexport function extractAnswer(text: string): string {\n const startIndex = text.indexOf(\"Answer: \") + 8;\n const endIndex = text.indexOf(\"<|endoftext|>\", 11);\n return text.slice(startIndex, endIndex);\n}\n\n/**\n * Represents a Twitter Profile.\n * @typedef {Object} TwitterProfile\n * @property {string} id - The unique identifier of the profile.\n * @property {string} username - The username of the profile.\n * @property {string} screenName - The screen name of the profile.\n * @property {string} bio - The biography of the profile.\n * @property {string[]} nicknames - An array of nicknames associated with the profile.\n */\ntype TwitterProfile = {\n id: string;\n username: string;\n screenName: string;\n bio: string;\n nicknames: string[];\n};\n\n/**\n * Class representing a request queue for handling asynchronous requests in a controlled manner.\n */\n\nclass RequestQueue {\n private queue: (() => Promise<any>)[] = [];\n private processing = false;\n private maxRetries = 3;\n private retryAttempts = new Map<() => Promise<any>, number>();\n\n /**\n * Asynchronously adds a request to the queue, then processes the queue.\n *\n * @template T\n * @param {() => Promise<T>} request - The request to be added to the queue\n * @returns {Promise<T>} - A promise that resolves with the result of the request or rejects with an error\n */\n async add<T>(request: () => Promise<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n this.queue.push(async () => {\n try {\n const result = await request();\n resolve(result);\n } catch (error) {\n reject(error);\n }\n });\n this.processQueue();\n });\n }\n\n /**\n * Asynchronously processes the queue of requests.\n *\n * @returns A promise that resolves when the queue has been fully processed.\n */\n private async processQueue(): Promise<void> {\n if (this.processing || this.queue.length === 0) {\n return;\n }\n this.processing = true;\n\n while (this.queue.length > 0) {\n const request = this.queue.shift()!;\n try {\n await request();\n // Clear retry count on success\n this.retryAttempts.delete(request);\n } catch (error) {\n logger.error(\"Error processing request:\", error);\n \n const retryCount = (this.retryAttempts.get(request) || 0) + 1;\n \n if (retryCount < this.maxRetries) {\n this.retryAttempts.set(request, retryCount);\n this.queue.unshift(request);\n await this.exponentialBackoff(retryCount);\n // Break the loop to allow exponential backoff to take effect\n break;\n } else {\n logger.error(`Max retries (${this.maxRetries}) exceeded for request, skipping`);\n this.retryAttempts.delete(request);\n }\n }\n await this.randomDelay();\n }\n\n this.processing = false;\n \n // If there are still items in the queue, restart processing\n if (this.queue.length > 0) {\n this.processQueue();\n }\n }\n\n /**\n * Implements an exponential backoff strategy for retrying a task.\n * @param {number} retryCount - The number of retries attempted so far.\n * @returns {Promise<void>} - A promise that resolves after a delay based on the retry count.\n */\n private async exponentialBackoff(retryCount: number): Promise<void> {\n const delay = 2 ** retryCount * 1000;\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n /**\n * Asynchronous method that creates a random delay between 1500ms and 3500ms.\n *\n * @returns A Promise that resolves after the random delay has passed.\n */\n private async randomDelay(): Promise<void> {\n const delay = Math.floor(Math.random() * 2000) + 1500;\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n}\n\n/**\n * Class representing a base client for interacting with Twitter.\n * @extends EventEmitter\n */\nexport class ClientBase {\n static _twitterClients: { [accountIdentifier: string]: Client } = {};\n twitterClient: Client;\n runtime: IAgentRuntime;\n lastCheckedTweetId: bigint | null = null;\n temperature = 0.5;\n\n requestQueue: RequestQueue = new RequestQueue();\n\n profile: TwitterProfile | null;\n\n /**\n * Caches a tweet in the database.\n *\n * @param {Tweet} tweet - The tweet to cache.\n * @returns {Promise<void>} A promise that resolves once the tweet is cached.\n */\n async cacheTweet(tweet: Tweet): Promise<void> {\n if (!tweet) {\n logger.warn(\"Tweet is undefined, skipping cache\");\n return;\n }\n\n this.runtime.setCache<Tweet>(`twitter/tweets/${tweet.id}`, tweet);\n }\n\n /**\n * Retrieves a cached tweet by its ID.\n * @param {string} tweetId - The ID of the tweet to retrieve from the cache.\n * @returns {Promise<Tweet | undefined>} A Promise that resolves to the cached tweet, or undefined if the tweet is not found in the cache.\n */\n async getCachedTweet(tweetId: string): Promise<Tweet | undefined> {\n const cached = await this.runtime.getCache<Tweet>(\n `twitter/tweets/${tweetId}`,\n );\n\n if (!cached) {\n return undefined;\n }\n\n return cached;\n }\n\n /**\n * Asynchronously retrieves a tweet with the specified ID.\n * If the tweet is found in the cache, it is returned from the cache.\n * If not, a request is made to the Twitter API to get the tweet, which is then cached and returned.\n * @param {string} tweetId - The ID of the tweet to retrieve.\n * @returns {Promise<Tweet>} A Promise that resolves to the retrieved tweet.\n */\n async getTweet(tweetId: string): Promise<Tweet> {\n const cachedTweet = await this.getCachedTweet(tweetId);\n\n if (cachedTweet) {\n return cachedTweet;\n }\n\n const tweet = await this.requestQueue.add(() =>\n this.twitterClient.getTweet(tweetId),\n );\n\n await this.cacheTweet(tweet);\n return tweet;\n }\n\n callback: (self: ClientBase) => any = null;\n\n /**\n * This method is called when the application is ready.\n * It throws an error indicating that it is not implemented in the base class\n * and should be implemented in the subclass.\n */\n onReady() {\n throw new Error(\"Not implemented in base class, please call from subclass\");\n }\n\n /**\n * Parse the raw tweet data into a standardized Tweet object.\n */\n /**\n * Parses a raw tweet object into a structured Tweet object.\n *\n * @param {any} raw - The raw tweet object to parse.\n * @param {number} [depth=0] - The current depth of parsing nested quotes/retweets.\n * @param {number} [maxDepth=3] - The maximum depth allowed for parsing nested quotes/retweets.\n * @returns {Tweet} The parsed Tweet object.\n */\n\n\n state: any;\n\n constructor(runtime: IAgentRuntime, state: any) {\n this.runtime = runtime;\n this.state = state;\n // Use API key as the identifier for client reuse\n const apiKey =\n state?.TWITTER_API_KEY ||\n (this.runtime.getSetting(\"TWITTER_API_KEY\") as string);\n if (apiKey && ClientBase._twitterClients[apiKey]) {\n this.twitterClient = ClientBase._twitterClients[apiKey];\n } else {\n this.twitterClient = new Client();\n if (apiKey) {\n ClientBase._twitterClients[apiKey] = this.twitterClient;\n }\n }\n }\n\n async init() {\n // First ensure the agent exists in the database\n // await this.runtime.ensureAgentExists(this.runtime.character);\n\n const apiKey =\n this.state?.TWITTER_API_KEY || this.runtime.getSetting(\"TWITTER_API_KEY\");\n const apiSecretKey =\n this.state?.TWITTER_API_SECRET_KEY ||\n this.runtime.getSetting(\"TWITTER_API_SECRET_KEY\");\n const accessToken =\n this.state?.TWITTER_ACCESS_TOKEN ||\n this.runtime.getSetting(\"TWITTER_ACCESS_TOKEN\");\n const accessTokenSecret =\n this.state?.TWITTER_ACCESS_TOKEN_SECRET ||\n this.runtime.getSetting(\"TWITTER_ACCESS_TOKEN_SECRET\");\n\n // Validate required credentials\n if (!apiKey || !apiSecretKey || !accessToken || !accessTokenSecret) {\n const missing = [];\n if (!apiKey) missing.push(\"TWITTER_API_KEY\");\n if (!apiSecretKey) missing.push(\"TWITTER_API_SECRET_KEY\");\n if (!accessToken) missing.push(\"TWITTER_ACCESS_TOKEN\");\n if (!accessTokenSecret) missing.push(\"TWITTER_ACCESS_TOKEN_SECRET\");\n throw new Error(\n `Missing required Twitter API credentials: ${missing.join(\", \")}`,\n );\n }\n\n const maxRetries = process.env.MAX_RETRIES\n ? parseInt(process.env.MAX_RETRIES)\n : 3;\n let retryCount = 0;\n let lastError: Error | null = null;\n\n while (retryCount < maxRetries) {\n try {\n logger.log(\"Initializing Twitter API v2 client\");\n await this.twitterClient.login(\n \"\", // username not needed for API v2\n \"\", // password not needed for API v2\n \"\", // email not needed for API v2\n \"\", // 2FA not needed for API v2\n apiKey,\n apiSecretKey,\n accessToken,\n accessTokenSecret,\n );\n\n if (await this.twitterClient.isLoggedIn()) {\n logger.info(\"Successfully authenticated with Twitter API v2\");\n break;\n }\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n logger.error(\n `Authentication attempt ${retryCount + 1} failed: ${lastError.message}`,\n );\n retryCount++;\n\n if (retryCount < maxRetries) {\n const delay = 2 ** retryCount * 1000; // Exponential backoff\n logger.info(`Retrying in ${delay / 1000} seconds...`);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n\n if (retryCount >= maxRetries) {\n throw new Error(\n `Twitter authentication failed after ${maxRetries} attempts. Last error: ${lastError?.message}`,\n );\n }\n\n // Initialize Twitter profile from the authenticated user\n const profile = await this.twitterClient.me();\n if (profile) {\n logger.log(\"Twitter user ID:\", profile.userId);\n logger.log(\"Twitter loaded:\", JSON.stringify(profile, null, 10));\n\n const agentId = this.runtime.agentId;\n\n const entity = await this.runtime.getEntityById(agentId);\n const entityMetadata = entity?.metadata as any;\n if (entityMetadata?.twitter?.userName !== profile.username) {\n logger.log(\n \"Updating Agents known X/twitter handle\",\n profile.username,\n \"was\",\n entityMetadata?.twitter,\n );\n const names = [profile.name, profile.username];\n await this.runtime.updateEntity({\n id: agentId,\n names: [...new Set([...(entity.names || []), ...names])].filter(\n Boolean,\n ),\n metadata: {\n ...(entityMetadata || {}),\n twitter: {\n ...(entityMetadata?.twitter || {}),\n name: profile.name,\n userName: profile.username,\n },\n },\n agentId,\n });\n }\n\n // Store profile info for use in responses\n this.profile = {\n id: profile.userId,\n username: profile.username, // this is the at\n screenName: profile.name, // this is the human readable name\n bio: profile.biography || \"\",\n nicknames: [],\n };\n } else {\n throw new Error(\"Failed to load profile\");\n }\n\n await this.loadLatestCheckedTweetId();\n await this.populateTimeline();\n }\n\n async fetchOwnPosts(count: number): Promise<Tweet[]> {\n logger.debug(\"fetching own posts\");\n const homeTimeline = await this.twitterClient.getUserTweets(\n this.profile.id,\n count,\n );\n // homeTimeline.tweets already contains Tweet objects from v2 API, no parsing needed\n return homeTimeline.tweets;\n }\n\n /**\n * Fetch timeline for twitter account, optionally only from followed accounts\n */\n async fetchHomeTimeline(\n count: number,\n following?: boolean,\n ): Promise<Tweet[]> {\n logger.debug(\"fetching home timeline\");\n const homeTimeline = following\n ? await this.twitterClient.fetchFollowingTimeline(count, [])\n : await this.twitterClient.fetchHomeTimeline(count, []);\n\n // homeTimeline already contains Tweet objects from v2 API, no parsing needed\n return homeTimeline;\n }\n\n async fetchSearchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n cursor?: string,\n ): Promise<QueryTweetsResponse> {\n try {\n // Sometimes this fails because we are rate limited. in this case, we just need to return an empty array\n // if we dont get a response in 5 seconds, something is wrong\n const timeoutPromise = new Promise((resolve) =>\n setTimeout(() => resolve({ tweets: [] }), 15000),\n );\n\n try {\n const result = await this.requestQueue.add(\n async () =>\n await Promise.race([\n this.twitterClient.fetchSearchTweets(\n query,\n maxTweets,\n searchMode,\n cursor,\n ),\n timeoutPromise,\n ]),\n );\n return (result ?? { tweets: [] }) as QueryTweetsResponse;\n } catch (error) {\n logger.error(\"Error fetching search tweets:\", error);\n return { tweets: [] };\n }\n } catch (error) {\n logger.error(\"Error fetching search tweets:\", error);\n return { tweets: [] };\n }\n }\n\n private async populateTimeline() {\n logger.debug(\"populating timeline...\");\n\n const cachedTimeline = await this.getCachedTimeline();\n\n // Check if the cache file exists\n if (cachedTimeline) {\n // Read the cached search results from the file\n\n // Get the existing memories from the database\n const existingMemories = await this.runtime.getMemoriesByRoomIds({\n tableName: \"messages\",\n roomIds: cachedTimeline.map((tweet) =>\n createUniqueUuid(this.runtime, tweet.conversationId),\n ),\n });\n\n //TODO: load tweets not in cache?\n\n // Create a Set to store the IDs of existing memories\n const existingMemoryIds = new Set(\n existingMemories.map((memory) => memory.id.toString()),\n );\n\n // Check if any of the cached tweets exist in the existing memories\n const someCachedTweetsExist = cachedTimeline.some((tweet) =>\n existingMemoryIds.has(createUniqueUuid(this.runtime, tweet.id)),\n );\n\n if (someCachedTweetsExist) {\n // Filter out the cached tweets that already exist in the database\n const tweetsToSave = cachedTimeline.filter(\n (tweet) =>\n tweet.userId !== this.profile.id &&\n !existingMemoryIds.has(createUniqueUuid(this.runtime, tweet.id)),\n );\n\n // Save the missing tweets as memories\n for (const tweet of tweetsToSave) {\n logger.log(\"Saving Tweet\", tweet.id);\n\n if (tweet.userId === this.profile.id) {\n continue;\n }\n\n // Create a world for this Twitter user if it doesn't exist\n const worldId = createUniqueUuid(this.runtime, tweet.userId) as UUID;\n await this.runtime.ensureWorldExists({\n id: worldId,\n name: `${tweet.username}'s Twitter`,\n agentId: this.runtime.agentId,\n serverId: tweet.userId,\n metadata: {\n ownership: { ownerId: tweet.userId },\n twitter: {\n username: tweet.username,\n id: tweet.userId,\n },\n },\n });\n\n const roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n const entityId =\n tweet.userId === this.profile.id\n ? this.runtime.agentId\n : createUniqueUuid(this.runtime, tweet.userId);\n\n // Ensure the entity exists with proper world association\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: tweet.username,\n name: tweet.name,\n source: \"twitter\",\n type: ChannelType.FEED,\n worldId: worldId,\n });\n\n const content = {\n text: tweet.text,\n url: tweet.permanentUrl,\n source: \"twitter\",\n inReplyTo: tweet.inReplyToStatusId\n ? createUniqueUuid(this.runtime, tweet.inReplyToStatusId)\n : undefined,\n } as Content;\n\n await this.runtime.createMemory(\n {\n id: createUniqueUuid(this.runtime, tweet.id),\n entityId,\n content: content,\n agentId: this.runtime.agentId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n },\n \"messages\",\n );\n\n await this.cacheTweet(tweet);\n }\n\n logger.log(\n `Populated ${tweetsToSave.length} missing tweets from the cache.`,\n );\n return;\n }\n }\n\n const timeline = await this.fetchHomeTimeline(cachedTimeline ? 10 : 50);\n\n // Get the most recent 20 mentions and interactions\n const mentionsAndInteractions = await this.fetchSearchTweets(\n `@${this.profile.username}`,\n 20,\n SearchMode.Latest,\n );\n\n // Combine the timeline tweets and mentions/interactions\n const allTweets = [...timeline, ...mentionsAndInteractions.tweets];\n\n // Create a Set to store unique tweet IDs\n const tweetIdsToCheck = new Set<string>();\n const roomIds = new Set<UUID>();\n\n // Add tweet IDs to the Set\n for (const tweet of allTweets) {\n tweetIdsToCheck.add(tweet.id);\n roomIds.add(createUniqueUuid(this.runtime, tweet.conversationId));\n }\n\n // Check the existing memories in the database\n const existingMemories = await this.runtime.getMemoriesByRoomIds({\n tableName: \"messages\",\n roomIds: Array.from(roomIds),\n });\n\n // Create a Set to store the existing memory IDs\n const existingMemoryIds = new Set<UUID>(\n existingMemories.map((memory) => memory.id),\n );\n\n // Filter out the tweets that already exist in the database\n const tweetsToSave = allTweets.filter(\n (tweet) =>\n tweet.userId !== this.profile.id &&\n !existingMemoryIds.has(createUniqueUuid(this.runtime, tweet.id)),\n );\n\n logger.debug({\n processingTweets: tweetsToSave.map((tweet) => tweet.id).join(\",\"),\n });\n\n // Save the new tweets as memories\n for (const tweet of tweetsToSave) {\n logger.log(\"Saving Tweet\", tweet.id);\n\n if (tweet.userId === this.profile.id) {\n continue;\n }\n\n // Create a world for this Twitter user if it doesn't exist\n const worldId = createUniqueUuid(this.runtime, tweet.userId) as UUID;\n await this.runtime.ensureWorldExists({\n id: worldId,\n name: `${tweet.username}'s Twitter`,\n agentId: this.runtime.agentId,\n serverId: tweet.userId,\n metadata: {\n ownership: { ownerId: tweet.userId },\n twitter: {\n username: tweet.username,\n id: tweet.userId,\n },\n },\n });\n\n const roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n\n const entityId =\n tweet.userId === this.profile.id\n ? this.runtime.agentId\n : createUniqueUuid(this.runtime, tweet.userId);\n\n // Ensure the entity exists with proper world association\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: tweet.username,\n name: tweet.name,\n source: \"twitter\",\n type: ChannelType.FEED,\n worldId: worldId,\n });\n\n const content = {\n text: tweet.text,\n url: tweet.permanentUrl,\n source: \"twitter\",\n inReplyTo: tweet.inReplyToStatusId\n ? createUniqueUuid(this.runtime, tweet.inReplyToStatusId)\n : undefined,\n } as Content;\n\n await this.runtime.createMemory(\n {\n id: createUniqueUuid(this.runtime, tweet.id),\n entityId,\n content: content,\n agentId: this.runtime.agentId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n },\n \"messages\",\n );\n\n await this.cacheTweet(tweet);\n }\n\n // Cache\n await this.cacheTimeline(timeline);\n await this.cacheMentions(mentionsAndInteractions.tweets);\n }\n\n async saveRequestMessage(message: Memory, state: State) {\n if (message.content.text) {\n const recentMessage = await this.runtime.getMemories({\n tableName: \"messages\",\n roomId: message.roomId,\n count: 1,\n unique: false,\n });\n\n if (\n recentMessage.length > 0 &&\n recentMessage[0].content === message.content\n ) {\n logger.debug(\"Message already saved\", recentMessage[0].id);\n } else {\n await this.runtime.createMemory(message, \"messages\");\n }\n\n await this.runtime.evaluate(message, {\n ...state,\n twitterClient: this.twitterClient,\n });\n }\n }\n\n async loadLatestCheckedTweetId(): Promise<void> {\n const latestCheckedTweetId = await this.runtime.getCache<string>(\n `twitter/${this.profile.username}/latest_checked_tweet_id`,\n );\n\n if (latestCheckedTweetId) {\n this.lastCheckedTweetId = BigInt(latestCheckedTweetId);\n }\n }\n\n async cacheLatestCheckedTweetId() {\n if (this.lastCheckedTweetId) {\n await this.runtime.setCache<string>(\n `twitter/${this.profile.username}/latest_checked_tweet_id`,\n this.lastCheckedTweetId.toString(),\n );\n }\n }\n\n async getCachedTimeline(): Promise<Tweet[] | undefined> {\n const cached = await this.runtime.getCache<Tweet[]>(\n `twitter/${this.profile.username}/timeline`,\n );\n\n if (!cached) {\n return undefined;\n }\n\n return cached;\n }\n\n async cacheTimeline(timeline: Tweet[]) {\n await this.runtime.setCache<Tweet[]>(\n `twitter/${this.profile.username}/timeline`,\n timeline,\n );\n }\n\n async cacheMentions(mentions: Tweet[]) {\n await this.runtime.setCache<Tweet[]>(\n `twitter/${this.profile.username}/mentions`,\n mentions,\n );\n }\n\n async fetchProfile(username: string): Promise<TwitterProfile> {\n try {\n const profile = await this.requestQueue.add(async () => {\n const profile = await this.twitterClient.getProfile(username);\n return {\n id: profile.userId,\n username,\n screenName: profile.name || this.runtime.character.name,\n bio:\n profile.biography || typeof this.runtime.character.bio === \"string\"\n ? (this.runtime.character.bio as string)\n : this.runtime.character.bio.length > 0\n ? this.runtime.character.bio[0]\n : \"\",\n nicknames: this.profile?.nicknames || [],\n } satisfies TwitterProfile;\n });\n\n return profile;\n } catch (error) {\n logger.error(\"Error fetching Twitter profile:\", error);\n throw error;\n }\n }\n\n /**\n * Fetches recent interactions (likes, retweets, quotes) for the authenticated user's tweets\n */\n async fetchInteractions() {\n try {\n const username = this.profile.username;\n // Use fetchSearchTweets to get mentions instead of the non-existent get method\n const mentionsResponse = await this.requestQueue.add(() =>\n this.twitterClient.fetchSearchTweets(\n `@${username}`,\n 100,\n SearchMode.Latest,\n ),\n );\n\n // Process tweets directly into the expected interaction format\n return mentionsResponse.tweets.map((tweet) =>\n this.formatTweetToInteraction(tweet),\n );\n } catch (error) {\n logger.error(\"Error fetching Twitter interactions:\", error);\n return [];\n }\n }\n\n formatTweetToInteraction(tweet): TwitterInteractionPayload | null {\n if (!tweet) return null;\n\n const isQuote = tweet.isQuoted;\n const isRetweet = !!tweet.retweetedStatus;\n const type = isQuote ? \"quote\" : isRetweet ? \"retweet\" : \"like\";\n\n return {\n id: tweet.id,\n type,\n userId: tweet.userId,\n username: tweet.username,\n name: tweet.name || tweet.username,\n targetTweetId: tweet.inReplyToStatusId || tweet.quotedStatusId,\n targetTweet: tweet.quotedStatus || tweet,\n quoteTweet: isQuote ? tweet : undefined,\n retweetId: tweet.retweetedStatus?.id,\n };\n }\n}\n","import { Service, type IAgentRuntime } from \"@elizaos/core\";\n\nexport class TwitterService extends Service {\n static serviceType = \"twitter\";\n \n // Add the required abstract property\n capabilityDescription = \"The agent is able to send and receive messages on Twitter\";\n \n private static instance: TwitterService;\n\n constructor(runtime?: IAgentRuntime) {\n super(runtime);\n }\n\n static getInstance(): TwitterService {\n if (!TwitterService.instance) {\n TwitterService.instance = new TwitterService();\n }\n return TwitterService.instance;\n }\n\n static async start(runtime: IAgentRuntime): Promise<TwitterService> {\n const instance = TwitterService.getInstance();\n instance.runtime = runtime;\n return instance;\n }\n\n async stop(): Promise<void> {\n // Clean up resources if needed\n }\n} ","import {\n Action,\n type ActionExample,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type State,\n logger,\n createUniqueUuid,\n ModelType,\n} from \"@elizaos/core\";\nimport { ClientBase } from \"../base.js\";\n\nexport const postTweetAction: Action = {\n name: \"POST_TWEET\",\n similes: [\"TWEET\", \"SEND_TWEET\", \"TWITTER_POST\", \"POST_ON_TWITTER\", \"SHARE_ON_TWITTER\"],\n validate: async (runtime: IAgentRuntime, message: Memory): Promise<boolean> => {\n logger.debug(\"Validating POST_TWEET action\");\n \n // Basic validation - make sure we have content to tweet\n const text = message.content?.text?.trim();\n if (!text || text.length === 0) {\n logger.error(\"No text content for tweet\");\n return false;\n }\n \n // Check tweet length (280 characters)\n if (text.length > 280) {\n logger.warn(`Tweet too long: ${text.length} characters`);\n // Still valid, will be truncated or sent as thread\n }\n \n return true;\n },\n description: \"Post a tweet on Twitter\",\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n state: State,\n _options: { [key: string]: unknown },\n callback?: HandlerCallback\n ): Promise<boolean> => {\n logger.info(\"Executing POST_TWEET action\");\n \n try {\n // Initialize a Twitter client directly\n const client = new ClientBase(runtime, {});\n \n // Check if client is initialized\n if (!client.twitterClient) {\n await client.init();\n }\n \n // Verify we have a profile\n if (!client.profile) {\n throw new Error(\"Twitter client not properly initialized - no profile found\");\n }\n \n // Get tweet content\n const tweetText = message.content?.text?.trim() || \"\";\n \n // Generate a more natural tweet if the input is too short or generic\n let finalTweetText = tweetText;\n if (tweetText.length < 50 || tweetText.toLowerCase().includes(\"post\") || tweetText.toLowerCase().includes(\"tweet\")) {\n const tweetPrompt = `You are ${runtime.character.name}. Create an interesting tweet based on this context:\n\nContext: ${tweetText}\n\nYour interests: ${runtime.character.topics?.join(\", \") || \"technology, AI, web3\"}\nYour style: ${runtime.character.style?.all?.join(\", \") || \"thoughtful, engaging\"}\n\nGenerate a tweet that:\n- Is under 280 characters\n- Reflects your personality and interests\n- Is engaging and conversational\n- Doesn't use hashtags unless truly relevant\n- Doesn't ask questions at the end\n- Is not generic or promotional\n\nTweet:`;\n \n const response = await runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: tweetPrompt,\n max_tokens: 100,\n temperature: 0.8,\n });\n \n finalTweetText = response.trim();\n }\n \n // Post the tweet\n const result = await client.twitterClient.sendTweet(finalTweetText);\n \n if (result && result.data) {\n const tweetData = result.data.data || result.data;\n // Extract tweet ID from the response - handle different response formats\n let tweetId: string;\n if ('id' in tweetData) {\n tweetId = tweetData.id;\n } else if ((tweetData as any).data?.id) {\n tweetId = (tweetData as any).data.id;\n } else {\n tweetId = Date.now().toString();\n }\n const tweetUrl = `https://twitter.com/${client.profile.username}/status/${tweetId}`;\n \n logger.info(`Successfully posted tweet: ${tweetId}`);\n \n // Create memory of the posted tweet\n await runtime.createMemory({\n entityId: runtime.agentId,\n content: {\n text: finalTweetText,\n url: tweetUrl,\n source: \"twitter\",\n action: \"POST_TWEET\",\n },\n roomId: message.roomId,\n }, \"messages\");\n \n if (callback) {\n await callback({\n text: `I've posted a tweet: \"${finalTweetText}\"\\n\\nView it here: ${tweetUrl}`,\n metadata: {\n tweetId: tweetId,\n tweetUrl,\n }\n });\n }\n \n return true;\n } else {\n throw new Error(\"Failed to post tweet - no response data\");\n }\n } catch (error) {\n logger.error(\"Error posting tweet:\", error);\n \n if (callback) {\n await callback({\n text: `Sorry, I couldn't post the tweet. Error: ${error.message}`,\n metadata: { error: error.message }\n });\n }\n \n return false;\n }\n },\n examples: [\n [\n {\n name: \"{{user1}}\",\n content: {\n text: \"Post a tweet about the importance of open source AI\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"I'll post a tweet about open source AI for you.\",\n action: \"POST_TWEET\",\n },\n },\n ],\n [\n {\n name: \"{{user1}}\",\n content: {\n text: \"Tweet something interesting about web3\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"I'll share an interesting thought about web3 on Twitter.\",\n action: \"POST_TWEET\",\n },\n },\n ],\n [\n {\n name: \"{{user1}}\",\n content: {\n text: \"Share your thoughts on the future of technology on Twitter\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"I'll post my thoughts on the future of technology.\",\n action: \"POST_TWEET\",\n },\n },\n ],\n ],\n}; "],"mappings":";;;;;;;AAAA,SAA6B,UAAAA,eAAc;;;ACA3C;AAAA,EACE;AAAA,EAGA;AAAA,EAKA;AAAA,EACA,oBAAAC;AAAA,EACA,UAAAC;AAAA,OACK;;;ACZP,SAAS,kBAAkB;AAMpB,IAAM,cAAN,MAAkB;AAAA,EAKvB,YACU,QACA,WACA,aACA,cACR;AAJQ;AACA;AACA;AACA;AARV,SAAQ,WAA8B;AACtC,SAAQ,gBAAgB;AAStB,SAAK,iBAAiB;AAAA,EACxB;AAAA,EAEQ,mBAAyB;AAC/B,SAAK,WAAW,IAAI,WAAW;AAAA,MAC7B,QAAQ,KAAK;AAAA,MACb,WAAW,KAAK;AAAA,MAChB,aAAa,KAAK;AAAA,MAClB,cAAc,KAAK;AAAA,IACrB,CAAC;AACD,SAAK,gBAAgB;AAAA,EACvB;AAAA;AAAA;AAAA;AAAA,EAKA,cAA0B;AACxB,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,oCAAoC;AAAA,IACtD;AACA,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aAA+B;AACnC,QAAI,CAAC,KAAK,iBAAiB,CAAC,KAAK,UAAU;AACzC,aAAO;AAAA,IACT;AAEA,QAAI;AAEF,YAAM,KAAK,MAAM,KAAK,SAAS,GAAG,GAAG;AACrC,aAAO,CAAC,CAAC,GAAG;AAAA,IACd,SAAS,OAAO;AACd,cAAQ,MAAM,oCAAoC,KAAK;AACvD,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AA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AS,CAAC,CAAC;AAE3D,UAAM,cAAc,OAAO,KAAK;AAGhC,YAAQ,gBAAgB,cAAc;AAGtC,QAAI,cAAc,MAAM;AACtB,MAAAA,QAAO,IAAI,2CAAoC;AAC/C,YAAM,cAAc,KAAK,MAAM;AAAA,IACjC;AAEA,QAAI,cAAc,aAAa;AAC7B,MAAAA,QAAO,IAAI,kDAA2C;AACtD,YAAM,cAAc,YAAY,MAAM;AAAA,IACxC;AAEA,QAAI,cAAc,UAAU;AAC1B,MAAAA,QAAO,IAAI,+CAAwC;AACnD,YAAM,cAAc,SAAS,MAAM;AAAA,IACrC;AAEA,QAAI,cAAc,WAAW;AAC3B,MAAAA,QAAO,IAAI,gDAAyC;AACpD,YAAM,cAAc,UAAU,MAAM;AAAA,IACtC;AAEA,IAAAA,QAAO,IAAI,4CAAuC;AAAA,EACpD,SAAS,OAAO;AACd,IAAAA,QAAO,MAAM,6CAAsC,KAAK;AACxD,UAAM;AAAA,EACR;AACF;AAEO,IAAM,gBAAgB;AAAA,EAC3B,MAAM;AAAA,EACN,aAAa;AAAA,EACb,SAAS,CAAC,eAAe;AAAA,EACzB,UAAU,CAAC,cAAc;AAAA,EACzB,MAAM;AACR;AAEA,IAAO,gBAAQ;","names":["logger","createUniqueUuid","logger","user","place","logger","logger","util","objectUtil","path","errorUtil","path","errorMap","ctx","result","issues","elements","processed","result","r","ZodFirstPartyTypeKind","logger","createUniqueUuid","memory","response","ChannelType","createUniqueUuid","logger","logger","postIntervalMinutes","interval","createUniqueUuid","ChannelType","ChannelType","createUniqueUuid","ModelType","logger","logger","createUniqueUuid","ChannelType","ModelType","createUniqueUuid","logger","ModelType","logger","createUniqueUuid","ModelType","ChannelType","createUniqueUuid","logger","logger","existingMemories","createUniqueUuid","existingMemoryIds","tweetsToSave","ChannelType","profile","logger","ModelType","logger","ModelType","logger"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/interactions.ts","../src/client/auth.ts","../src/client/profile.ts","../src/client/relationships.ts","../src/client/search.ts","../src/client/tweets.ts","../src/client/client.ts","../src/utils.ts","../src/constants.ts","../src/utils/error-handler.ts","../node_modules/zod/dist/esm/v3/external.js","../node_modules/zod/dist/esm/v3/helpers/util.js","../node_modules/zod/dist/esm/v3/ZodError.js","../node_modules/zod/dist/esm/v3/locales/en.js","../node_modules/zod/dist/esm/v3/errors.js","../node_modules/zod/dist/esm/v3/helpers/parseUtil.js","../node_modules/zod/dist/esm/v3/helpers/errorUtil.js","../node_modules/zod/dist/esm/v3/types.js","../src/environment.ts","../src/post.ts","../src/timeline.ts","../src/templates.ts","../src/discovery.ts","../src/base.ts","../src/services/twitter.service.ts","../src/actions/postTweet.ts"],"sourcesContent":["import { type IAgentRuntime, logger } from \"@elizaos/core\";\nimport { TwitterInteractionClient } from \"./interactions\";\nimport { TwitterPostClient } from \"./post\";\nimport { TwitterTimelineClient } from \"./timeline\";\nimport { TwitterDiscoveryClient } from \"./discovery\";\nimport { validateTwitterConfig } from \"./environment\";\nimport { ClientBase } from \"./base\";\nimport { TwitterService } from \"./services/twitter.service.js\";\nimport { postTweetAction } from \"./actions/postTweet.js\";\nimport type { ITwitterClient } from \"./types\";\n\n/**\n * A manager that orchestrates all specialized Twitter logic:\n * - client: base operations (login, timeline caching, etc.)\n * - post: autonomous posting logic\n * - interaction: handling mentions, replies, and autonomous targeting\n * - timeline: processing timeline for actions (likes, retweets, replies)\n * - discovery: autonomous content discovery and engagement\n */\nexport class TwitterClientInstance implements ITwitterClient {\n client: ClientBase;\n post: TwitterPostClient;\n interaction: TwitterInteractionClient;\n timeline?: TwitterTimelineClient;\n discovery?: TwitterDiscoveryClient;\n service: TwitterService;\n\n constructor(runtime: IAgentRuntime, state: any) {\n // Pass twitterConfig to the base client\n this.client = new ClientBase(runtime, state);\n\n // Posting logic\n const postEnabledSetting = runtime.getSetting(\"TWITTER_ENABLE_POST\") ?? process.env.TWITTER_ENABLE_POST;\n logger.debug(`TWITTER_ENABLE_POST setting value: ${JSON.stringify(postEnabledSetting)}, type: ${typeof postEnabledSetting}`);\n \n const postEnabled = postEnabledSetting === \"true\" || postEnabledSetting === true;\n \n if (postEnabled) {\n logger.info(\"Twitter posting is ENABLED - creating post client\");\n this.post = new TwitterPostClient(this.client, runtime, state);\n } else {\n logger.info(\"Twitter posting is DISABLED - set TWITTER_ENABLE_POST=true to enable automatic posting\");\n }\n\n // Mentions and interactions\n const repliesEnabled = (runtime.getSetting(\"TWITTER_ENABLE_REPLIES\") ?? process.env.TWITTER_ENABLE_REPLIES) !== \"false\";\n \n if (repliesEnabled) {\n logger.info(\"Twitter replies/interactions are ENABLED\");\n this.interaction = new TwitterInteractionClient(\n this.client,\n runtime,\n state,\n );\n } else {\n logger.info(\"Twitter replies/interactions are DISABLED\");\n }\n\n // Timeline actions (likes, retweets, replies)\n const actionsEnabled = (runtime.getSetting(\"TWITTER_ENABLE_ACTIONS\") ?? process.env.TWITTER_ENABLE_ACTIONS) === \"true\";\n \n if (actionsEnabled) {\n logger.info(\"Twitter timeline actions are ENABLED\");\n this.timeline = new TwitterTimelineClient(this.client, runtime, state);\n } else {\n logger.info(\"Twitter timeline actions are DISABLED\");\n }\n\n // Discovery service for autonomous content discovery\n const discoveryEnabled = (runtime.getSetting(\"TWITTER_ENABLE_DISCOVERY\") ?? process.env.TWITTER_ENABLE_DISCOVERY) === \"true\" ||\n (actionsEnabled && (runtime.getSetting(\"TWITTER_ENABLE_DISCOVERY\") ?? process.env.TWITTER_ENABLE_DISCOVERY) !== \"false\");\n \n if (discoveryEnabled) {\n logger.info(\"Twitter discovery service is ENABLED\");\n this.discovery = new TwitterDiscoveryClient(this.client, runtime, state);\n } else {\n logger.info(\"Twitter discovery service is DISABLED - set TWITTER_ENABLE_DISCOVERY=true to enable\");\n }\n\n this.service = TwitterService.getInstance();\n }\n}\n\nasync function startTwitterClient(runtime: IAgentRuntime): Promise<void> {\n try {\n logger.log(\"🔧 Initializing Twitter plugin...\");\n\n await validateTwitterConfig(runtime);\n\n logger.log(\"✅ Twitter configuration validated successfully\");\n\n const twitterClient = new TwitterClientInstance(runtime, {});\n\n await twitterClient.client.init();\n\n // Add to service map\n runtime.registerService(TwitterService);\n\n // Start appropriate services based on configuration\n if (twitterClient.post) {\n logger.log(\"📮 Starting Twitter post client...\");\n await twitterClient.post.start();\n }\n\n if (twitterClient.interaction) {\n logger.log(\"💬 Starting Twitter interaction client...\");\n await twitterClient.interaction.start();\n }\n\n if (twitterClient.timeline) {\n logger.log(\"📊 Starting Twitter timeline client...\");\n await twitterClient.timeline.start();\n }\n\n if (twitterClient.discovery) {\n logger.log(\"🔍 Starting Twitter discovery client...\");\n await twitterClient.discovery.start();\n }\n\n logger.log(\"✅ Twitter plugin started successfully\");\n } catch (error) {\n logger.error(\"🚨 Failed to start Twitter plugin:\", error);\n throw error;\n }\n}\n\nexport const TwitterPlugin = {\n name: \"twitter\",\n description: \"Twitter client with posting, interactions, and timeline actions\",\n actions: [postTweetAction],\n services: [TwitterService],\n init: startTwitterClient,\n};\n\nexport default TwitterPlugin;\n","import {\n ChannelType,\n type Content,\n ContentType,\n EventType,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type MessagePayload,\n ModelType,\n createUniqueUuid,\n logger,\n} from \"@elizaos/core\";\nimport type { ClientBase } from \"./base\";\nimport { SearchMode } from \"./client/index\";\nimport type { Tweet as ClientTweet } from \"./client/tweets\";\nimport type {\n Tweet as CoreTweet,\n TwitterInteractionMemory,\n TwitterInteractionPayload,\n TwitterLikeReceivedPayload,\n TwitterMemory,\n TwitterQuoteReceivedPayload,\n TwitterRetweetReceivedPayload,\n} from \"./types\";\nimport { TwitterEventTypes } from \"./types\";\nimport { sendTweet } from \"./utils\";\nimport { shouldTargetUser, getTargetUsers } from \"./environment\";\n\n/**\n * Template for generating dialog and actions for a Twitter message handler.\n *\n * @type {string}\n */\nexport const twitterMessageHandlerTemplate = `# Task: Generate dialog and actions for {{agentName}}.\n{{providers}}\nHere is the current post text again. Remember to include an action if the current post text includes a prompt that asks for one of the available actions mentioned above (does not need to be exact)\n{{currentPost}}\n{{imageDescriptions}}\n\n# Instructions: Write the next message for {{agentName}}. Include the appropriate action from the list: {{actionNames}}\nResponse format should be formatted in a valid JSON block like this:\n\\`\\`\\`json\n{ \"thought\": \"<string>\", \"name\": \"{{agentName}}\", \"text\": \"<string>\", \"action\": \"<string>\" }\n\\`\\`\\`\n\nThe \"action\" field should be one of the options in [Available Actions] and the \"text\" field should be the response you want to send. Do not including any thinking or internal reflection in the \"text\" field. \"thought\" should be a short description of what the agent is thinking about before responding, inlcuding a brief justification for the response.`;\n\n/**\n * Template for generating dialog and actions for a message handler.\n * @type {string}\n */\nexport const messageHandlerTemplate = `\n{{agentName}} is replying to you:\n{{senderName}}: {{userMessage}}\n\n# Task: Generate a reply for {{agentName}}.\n{{providers}}\n\n# Instructions: Write a thoughtful response to {{senderName}} that is appropriate and relevant to their message. Do not including any thinking, self-reflection or internal dialog in your response.`;\n\n/**\n * The TwitterInteractionClient class manages Twitter interactions,\n * including handling mentions, managing timelines, and engaging with other users.\n * It extends the base Twitter client functionality to provide mention handling,\n * user interaction, and follow change detection capabilities.\n *\n * @extends ClientBase\n */\nexport class TwitterInteractionClient {\n client: ClientBase;\n runtime: IAgentRuntime;\n twitterUsername: string;\n private twitterUserId: string;\n private isDryRun: boolean;\n private state: any;\n private isRunning: boolean = false;\n private lastProcessedTimestamp: number = Date.now();\n\n /**\n * Constructor to initialize the Twitter interaction client with runtime and state management.\n *\n * @param {ClientBase} client - The client instance.\n * @param {IAgentRuntime} runtime - The runtime instance for agent operations.\n * @param {any} state - The state object containing configuration settings.\n */\n constructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n this.client = client;\n this.runtime = runtime;\n this.state = state;\n\n // Set dry run mode - checks both state and runtime settings\n const dryRunSetting = this.state?.TWITTER_DRY_RUN ?? this.runtime.getSetting(\"TWITTER_DRY_RUN\") ?? process.env.TWITTER_DRY_RUN;\n this.isDryRun = dryRunSetting === true || dryRunSetting === \"true\" || \n (typeof dryRunSetting === \"string\" && dryRunSetting.toLowerCase() === \"true\");\n }\n\n /**\n * Asynchronously starts the process of handling Twitter interactions on a loop.\n * Uses the unified TWITTER_ENGAGEMENT_INTERVAL setting.\n */\n async start() {\n this.isRunning = true;\n \n const handleTwitterInteractionsLoop = () => {\n if (!this.isRunning) {\n logger.info(\"Twitter interaction client stopped, exiting loop\");\n return;\n }\n \n // Get interval in minutes and convert to milliseconds\n const engagementIntervalMinutes = parseInt(\n this.state?.TWITTER_ENGAGEMENT_INTERVAL ||\n this.runtime.getSetting(\"TWITTER_ENGAGEMENT_INTERVAL\") as string ||\n process.env.TWITTER_ENGAGEMENT_INTERVAL ||\n \"30\"\n );\n \n const interactionInterval = engagementIntervalMinutes * 60 * 1000;\n \n logger.info(`Twitter interaction client will check every ${engagementIntervalMinutes} minutes`);\n\n this.handleTwitterInteractions();\n \n if (this.isRunning) {\n setTimeout(handleTwitterInteractionsLoop, interactionInterval);\n }\n };\n handleTwitterInteractionsLoop();\n }\n\n /**\n * Stops the Twitter interaction client\n */\n async stop() {\n logger.log(\"Stopping Twitter interaction client...\");\n this.isRunning = false;\n }\n\n /**\n * Asynchronously handles Twitter interactions by checking for mentions and target user posts.\n */\n async handleTwitterInteractions() {\n logger.log(\"Checking Twitter interactions\");\n\n const twitterUsername = this.client.profile?.username;\n \n try {\n // Check for mentions first (replies enabled by default)\n const repliesEnabled = (this.runtime.getSetting(\"TWITTER_ENABLE_REPLIES\") ?? process.env.TWITTER_ENABLE_REPLIES) !== \"false\";\n \n if (repliesEnabled) {\n await this.handleMentions(twitterUsername);\n }\n \n // Check target users' posts for autonomous engagement\n const targetUsersConfig = (this.runtime.getSetting(\"TWITTER_TARGET_USERS\") ?? process.env.TWITTER_TARGET_USERS) as string || \"\";\n \n if (targetUsersConfig?.trim()) {\n await this.handleTargetUserPosts(targetUsersConfig);\n }\n\n // Save the latest checked tweet ID to the file\n await this.client.cacheLatestCheckedTweetId();\n\n logger.log(\"Finished checking Twitter interactions\");\n } catch (error) {\n logger.error(\"Error handling Twitter interactions:\", error);\n }\n }\n\n /**\n * Handle mentions and replies\n */\n private async handleMentions(twitterUsername: string) {\n try {\n // Check for mentions\n const cursorKey = `twitter/${twitterUsername}/mention_cursor`;\n const cachedCursor: String = await this.runtime.getCache<string>(cursorKey);\n\n const searchResult = await this.client.fetchSearchTweets(\n `@${twitterUsername}`,\n 20,\n SearchMode.Latest,\n String(cachedCursor),\n );\n\n const mentionCandidates = searchResult.tweets;\n\n // If we got tweets and there's a valid cursor, cache it\n if (mentionCandidates.length > 0 && searchResult.previous) {\n await this.runtime.setCache(cursorKey, searchResult.previous);\n } else if (!searchResult.previous && !searchResult.next) {\n // If both previous and next are missing, clear the outdated cursor\n await this.runtime.setCache(cursorKey, \"\");\n }\n\n await this.processMentionTweets(mentionCandidates);\n } catch (error) {\n logger.error(\"Error handling mentions:\", error);\n }\n }\n\n /**\n * Handle autonomous engagement with target users' posts\n */\n private async handleTargetUserPosts(targetUsersConfig: string) {\n try {\n const targetUsers = getTargetUsers(targetUsersConfig);\n \n if (targetUsers.length === 0 && !targetUsersConfig.includes(\"*\")) {\n return; // No target users configured\n }\n \n logger.info(`Checking posts from target users: ${targetUsers.join(\", \") || \"everyone (*)\"}`);\n \n // For each target user, search their recent posts\n for (const targetUser of targetUsers) {\n try {\n const normalizedUsername = targetUser.replace(/^@/, \"\");\n \n // Search for recent posts from this user\n const searchQuery = `from:${normalizedUsername} -is:reply -is:retweet`;\n const searchResult = await this.client.fetchSearchTweets(\n searchQuery,\n 10, // Get up to 10 recent posts per user\n SearchMode.Latest\n );\n \n if (searchResult.tweets.length > 0) {\n logger.info(`Found ${searchResult.tweets.length} posts from @${normalizedUsername}`);\n \n // Process these tweets for potential engagement\n await this.processTargetUserTweets(searchResult.tweets, normalizedUsername);\n }\n } catch (error) {\n logger.error(`Error searching posts from @${targetUser}:`, error);\n }\n }\n \n // If wildcard is configured, also check timeline for any interesting posts\n if (targetUsersConfig.includes(\"*\")) {\n await this.processTimelineForEngagement();\n }\n } catch (error) {\n logger.error(\"Error handling target user posts:\", error);\n }\n }\n\n /**\n * Process tweets from target users for potential engagement\n */\n private async processTargetUserTweets(tweets: ClientTweet[], username: string) {\n const maxEngagementsPerRun = parseInt(\n this.runtime.getSetting(\"TWITTER_MAX_ENGAGEMENTS_PER_RUN\") as string || \n process.env.TWITTER_MAX_ENGAGEMENTS_PER_RUN || \n \"10\"\n );\n \n let engagementCount = 0;\n \n for (const tweet of tweets) {\n if (engagementCount >= maxEngagementsPerRun) {\n logger.info(`Reached max engagements limit (${maxEngagementsPerRun})`);\n break;\n }\n \n // Skip if already processed\n const tweetId = createUniqueUuid(this.runtime, tweet.id);\n const existingMemory = await this.runtime.getMemoryById(tweetId);\n \n if (existingMemory) {\n continue; // Already processed\n }\n \n // Skip if tweet is too old (older than 24 hours)\n const tweetAge = Date.now() - (tweet.timestamp * 1000);\n const maxAge = 24 * 60 * 60 * 1000; // 24 hours\n \n if (tweetAge > maxAge) {\n continue;\n }\n \n // Decide whether to engage with this tweet\n const shouldEngage = await this.shouldEngageWithTweet(tweet);\n \n if (shouldEngage) {\n logger.info(`Engaging with tweet from @${username}: ${tweet.text.substring(0, 50)}...`);\n \n // Create necessary context for the tweet\n await this.ensureTweetContext(tweet);\n \n // Handle the tweet (generate and send reply)\n const engaged = await this.engageWithTweet(tweet);\n \n if (engaged) {\n engagementCount++;\n }\n }\n }\n }\n\n /**\n * Process timeline for engagement when wildcard is configured\n */\n private async processTimelineForEngagement() {\n try {\n // This would use the timeline client if available, but for now\n // we'll do a general search for recent popular tweets\n const searchResult = await this.client.fetchSearchTweets(\n \"min_retweets:10 min_faves:20 -is:reply -is:retweet lang:en\",\n 20,\n SearchMode.Latest\n );\n \n const relevantTweets = searchResult.tweets.filter(tweet => {\n // Filter for tweets from the last 12 hours\n const tweetAge = Date.now() - (tweet.timestamp * 1000);\n return tweetAge < 12 * 60 * 60 * 1000;\n });\n \n if (relevantTweets.length > 0) {\n logger.info(`Found ${relevantTweets.length} relevant tweets from timeline`);\n await this.processTargetUserTweets(relevantTweets, \"timeline\");\n }\n } catch (error) {\n logger.error(\"Error processing timeline for engagement:\", error);\n }\n }\n\n /**\n * Determine if the bot should engage with a specific tweet\n */\n private async shouldEngageWithTweet(tweet: ClientTweet): Promise<boolean> {\n try {\n // Create a simple evaluation prompt\n const evaluationContext = {\n tweet: tweet.text,\n author: tweet.username,\n metrics: {\n likes: tweet.likes || 0,\n retweets: tweet.retweets || 0,\n replies: tweet.replies || 0,\n },\n };\n \n const shouldEngageMemory: Memory = {\n id: createUniqueUuid(this.runtime, `eval-${tweet.id}`),\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId: createUniqueUuid(this.runtime, tweet.conversationId),\n content: {\n text: `Should I engage with this tweet? Tweet: \"${tweet.text}\" by @${tweet.username}`,\n evaluationContext,\n },\n createdAt: Date.now(),\n };\n \n const state = await this.runtime.composeState(shouldEngageMemory);\n const context = `You are ${this.runtime.character.name}. Should you reply to this tweet based on your interests and expertise?\n \nTweet by @${tweet.username}: \"${tweet.text}\"\n\nReply with YES if:\n- The topic relates to your interests or expertise\n- You can add valuable insights or perspective\n- The conversation seems constructive\n\nReply with NO if:\n- The topic is outside your knowledge\n- The tweet is inflammatory or controversial\n- You have nothing meaningful to add\n\nResponse (YES/NO):`;\n\n const response = await this.runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: context,\n temperature: 0.3,\n maxTokens: 10,\n stop: [\"\\n\"],\n });\n \n return response.trim().toUpperCase().includes(\"YES\");\n } catch (error) {\n logger.error(\"Error determining engagement:\", error);\n return false;\n }\n }\n\n /**\n * Ensure tweet context exists (world, room, entity)\n */\n private async ensureTweetContext(tweet: ClientTweet) {\n const userId = tweet.userId;\n const conversationId = tweet.conversationId || tweet.id;\n const username = tweet.username;\n \n // Create world for user\n const worldId = createUniqueUuid(this.runtime, userId);\n await this.runtime.ensureWorldExists({\n id: worldId,\n name: `${username}'s Twitter`,\n agentId: this.runtime.agentId,\n serverId: userId,\n metadata: {\n ownership: { ownerId: userId },\n twitter: {\n username: username,\n id: userId,\n },\n },\n });\n \n // Create room for conversation\n const roomId = createUniqueUuid(this.runtime, conversationId);\n \n // Ensure entity/connection\n const entityId = createUniqueUuid(this.runtime, userId);\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: username,\n name: tweet.name,\n source: \"twitter\",\n type: ChannelType.FEED,\n worldId: worldId,\n });\n \n // Save tweet as memory\n const tweetMemory: Memory = {\n id: createUniqueUuid(this.runtime, tweet.id),\n entityId,\n content: {\n text: tweet.text,\n url: tweet.permanentUrl,\n source: \"twitter\",\n tweet,\n },\n agentId: this.runtime.agentId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n };\n \n await this.runtime.createMemory(tweetMemory, \"messages\");\n }\n\n /**\n * Engage with a tweet by generating and sending a reply\n */\n private async engageWithTweet(tweet: ClientTweet): Promise<boolean> {\n try {\n const message: Memory = {\n id: createUniqueUuid(this.runtime, tweet.id),\n entityId: createUniqueUuid(this.runtime, tweet.userId),\n content: {\n text: tweet.text,\n source: \"twitter\",\n tweet,\n },\n agentId: this.runtime.agentId,\n roomId: createUniqueUuid(this.runtime, tweet.conversationId),\n createdAt: tweet.timestamp * 1000,\n };\n \n const result = await this.handleTweet({\n tweet,\n message,\n thread: tweet.thread || [tweet],\n });\n \n return result.text && result.text.length > 0;\n } catch (error) {\n logger.error(\"Error engaging with tweet:\", error);\n return false;\n }\n }\n\n /**\n * Processes all incoming tweets that mention the bot.\n * For each new tweet:\n * - Ensures world, room, and connection exist\n * - Saves the tweet as memory\n * - Emits thread-related events (THREAD_CREATED / THREAD_UPDATED)\n * - Delegates tweet content to `handleTweet` for reply generation\n *\n * Note: MENTION_RECEIVED is currently disabled (see TODO below)\n */\n async processMentionTweets(mentionCandidates: ClientTweet[]) {\n logger.log(\n \"Completed checking mentioned tweets:\",\n mentionCandidates.length,\n );\n let uniqueTweetCandidates = [...mentionCandidates];\n\n // Sort tweet candidates by ID in ascending order\n uniqueTweetCandidates = uniqueTweetCandidates\n .sort((a, b) => a.id.localeCompare(b.id))\n .filter((tweet) => tweet.userId !== this.client.profile.id);\n\n // Get TWITTER_TARGET_USERS configuration\n const targetUsersConfig =\n (this.runtime.getSetting(\"TWITTER_TARGET_USERS\") ?? process.env.TWITTER_TARGET_USERS) as string || \"\";\n\n // Filter tweets based on TWITTER_TARGET_USERS if configured\n if (targetUsersConfig?.trim()) {\n uniqueTweetCandidates = uniqueTweetCandidates.filter((tweet) => {\n const shouldTarget = shouldTargetUser(\n tweet.username || \"\",\n targetUsersConfig,\n );\n if (!shouldTarget) {\n logger.log(\n `Skipping tweet from @${tweet.username} - not in target users list`,\n );\n }\n return shouldTarget;\n });\n }\n\n // Get max interactions per run setting\n const maxInteractionsPerRun = parseInt(\n this.runtime.getSetting(\"TWITTER_MAX_ENGAGEMENTS_PER_RUN\") as string || \n process.env.TWITTER_MAX_ENGAGEMENTS_PER_RUN || \n \"10\"\n );\n \n // Limit the number of interactions per run\n const tweetsToProcess = uniqueTweetCandidates.slice(0, maxInteractionsPerRun);\n logger.info(`Processing ${tweetsToProcess.length} of ${uniqueTweetCandidates.length} mention tweets (max: ${maxInteractionsPerRun})`);\n\n // for each tweet candidate, handle the tweet\n for (const tweet of tweetsToProcess) {\n if (\n !this.client.lastCheckedTweetId ||\n BigInt(tweet.id) > this.client.lastCheckedTweetId\n ) {\n // Generate the tweetId UUID the same way it's done in handleTweet\n const tweetId = createUniqueUuid(this.runtime, tweet.id);\n\n // Check if we've already processed this tweet\n const existingResponse = await this.runtime.getMemoryById(tweetId);\n\n if (existingResponse) {\n logger.log(`Already responded to tweet ${tweet.id}, skipping`);\n continue;\n }\n\n // Also check if we've already responded to this tweet (for chunked responses)\n // by looking for any memory with inReplyTo pointing to this tweet\n const conversationRoomId = createUniqueUuid(\n this.runtime,\n tweet.conversationId,\n );\n const existingReplies = await this.runtime.getMemories({\n tableName: \"messages\",\n roomId: conversationRoomId,\n count: 10, // Check recent messages in this room\n });\n\n // Check if any of the found memories is a reply to this specific tweet\n const hasExistingReply = existingReplies.some(\n (memory) =>\n memory.content.inReplyTo === tweetId ||\n memory.content.inReplyTo === tweet.id,\n );\n\n if (hasExistingReply) {\n logger.log(\n `Already responded to tweet ${tweet.id} (found in conversation history), skipping`,\n );\n continue;\n }\n\n logger.log(\"New Tweet found\", tweet.id);\n\n const userId = tweet.userId;\n const conversationId = tweet.conversationId || tweet.id;\n const roomId = createUniqueUuid(this.runtime, conversationId);\n const username = tweet.username;\n\n logger.log(\"----\");\n logger.log(`User: ${username} (${userId})`);\n logger.log(`Tweet: ${tweet.id}`);\n logger.log(`Conversation: ${conversationId}`);\n logger.log(`Room: ${roomId}`);\n logger.log(\"----\");\n\n // 1. Ensure world exists for the user\n const worldId = createUniqueUuid(this.runtime, userId);\n await this.runtime.ensureWorldExists({\n id: worldId,\n name: `${username}'s Twitter`,\n agentId: this.runtime.agentId,\n serverId: userId,\n metadata: {\n ownership: { ownerId: userId },\n twitter: {\n username: username,\n id: userId,\n },\n },\n });\n\n // 2. Ensure entity connection\n const entityId = createUniqueUuid(this.runtime, userId);\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: username,\n name: tweet.name,\n source: \"twitter\",\n type: ChannelType.FEED,\n worldId: worldId,\n });\n\n // 3. Create a memory for the tweet\n const memory: Memory = {\n id: tweetId,\n entityId,\n content: {\n text: tweet.text,\n url: tweet.permanentUrl,\n source: \"twitter\",\n tweet,\n },\n agentId: this.runtime.agentId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n };\n\n logger.log(\"Saving tweet memory...\");\n await this.runtime.createMemory(memory, \"messages\");\n\n // TODO: This doesn't work as intended - thread events are mixed with other events\n // and need a better implementation strategy\n // this.runtime.emitEvent(TwitterEventTypes.MENTION_RECEIVED, {\n // entityId,\n // memory: {...memory, id: createUniqueUuid(this.runtime)},\n // world: {id: worldId, ...},\n // isThread: !!tweet.thread,\n // });\n\n // 4. Handle thread-specific events\n if (tweet.thread && tweet.thread.length > 0) {\n const threadStartId = tweet.thread[0].id;\n const threadMemoryId = createUniqueUuid(\n this.runtime,\n `thread-${threadStartId}`,\n );\n\n const threadPayload = {\n runtime: this.runtime,\n entityId,\n conversationId: threadStartId,\n roomId: roomId,\n memory: memory,\n tweet: tweet,\n threadId: threadStartId,\n threadMemoryId: threadMemoryId,\n };\n\n // Check if this is a reply to an existing thread\n const previousThreadMemory =\n await this.runtime.getMemoryById(threadMemoryId);\n if (previousThreadMemory) {\n // This is a reply to an existing thread\n this.runtime.emitEvent(\n TwitterEventTypes.THREAD_UPDATED,\n threadPayload,\n );\n } else if (tweet.thread[0].id === tweet.id) {\n // This is the start of a new thread\n this.runtime.emitEvent(\n TwitterEventTypes.THREAD_CREATED,\n threadPayload,\n );\n }\n }\n\n await this.handleTweet({\n tweet,\n message: memory,\n thread: tweet.thread,\n });\n\n // Update the last checked tweet ID after processing each tweet\n this.client.lastCheckedTweetId = BigInt(tweet.id);\n }\n }\n }\n\n /**\n * Handles Twitter interactions such as likes, retweets, and quotes.\n * For each interaction:\n * - Creates a memory object\n * - Emits platform-specific events (LIKE_RECEIVED, RETWEET_RECEIVED, QUOTE_RECEIVED)\n * - Emits a generic REACTION_RECEIVED event with metadata\n */\n async handleInteraction(interaction: TwitterInteractionPayload) {\n if (interaction?.targetTweet?.conversationId) {\n const memory = this.createMemoryObject(\n interaction.type,\n `${interaction.id}-${interaction.type}`,\n interaction.userId,\n interaction.targetTweet.conversationId,\n );\n\n await this.runtime.createMemory(memory, \"messages\");\n\n // Create message for reaction\n const reactionMessage: TwitterMemory = {\n id: createUniqueUuid(this.runtime, interaction.targetTweetId),\n content: {\n text: interaction.targetTweet.text,\n source: \"twitter\",\n },\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n roomId: createUniqueUuid(\n this.runtime,\n interaction.targetTweet.conversationId,\n ),\n agentId: this.runtime.agentId,\n createdAt: Date.now(),\n };\n\n // Emit specific event for each type of interaction\n switch (interaction.type) {\n case \"like\": {\n const payload: TwitterLikeReceivedPayload = {\n runtime: this.runtime,\n tweet: interaction.targetTweet,\n user: {\n id: interaction.userId,\n username: interaction.username,\n name: interaction.name,\n },\n source: \"twitter\",\n };\n this.runtime.emitEvent(TwitterEventTypes.LIKE_RECEIVED, payload);\n break;\n }\n case \"retweet\": {\n const payload: TwitterRetweetReceivedPayload = {\n runtime: this.runtime,\n tweet: interaction.targetTweet,\n retweetId: interaction.retweetId || interaction.id,\n user: {\n id: interaction.userId,\n username: interaction.username,\n name: interaction.name,\n },\n source: \"twitter\",\n };\n this.runtime.emitEvent(TwitterEventTypes.RETWEET_RECEIVED, payload);\n break;\n }\n case \"quote\": {\n const payload: TwitterQuoteReceivedPayload = {\n runtime: this.runtime,\n quotedTweet: interaction.targetTweet,\n quoteTweet: interaction.quoteTweet || interaction.targetTweet,\n user: {\n id: interaction.userId,\n username: interaction.username,\n name: interaction.name,\n },\n message: reactionMessage,\n callback: async () => [],\n reaction: {\n type: \"quote\",\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n },\n source: \"twitter\",\n };\n this.runtime.emitEvent(TwitterEventTypes.QUOTE_RECEIVED, payload);\n break;\n }\n }\n\n // Also emit generic REACTION_RECEIVED event\n this.runtime.emitEvent(EventType.REACTION_RECEIVED, {\n runtime: this.runtime,\n entityId: createUniqueUuid(this.runtime, interaction.userId),\n roomId: createUniqueUuid(\n this.runtime,\n interaction.targetTweet.conversationId,\n ),\n world: createUniqueUuid(this.runtime, interaction.userId),\n message: reactionMessage,\n source: \"twitter\",\n metadata: {\n type: interaction.type,\n targetTweetId: interaction.targetTweetId,\n username: interaction.username,\n userId: interaction.userId,\n timestamp: Date.now(),\n quoteText: interaction.type === \"quote\" ? (interaction.quoteTweet?.text || \"\") : undefined,\n },\n callback: async () => [],\n } as MessagePayload);\n }\n }\n\n /**\n * Creates a memory object for a given Twitter interaction.\n *\n * @param {string} type - The type of interaction (e.g., 'like', 'retweet', 'quote').\n * @param {string} id - The unique identifier for the interaction.\n * @param {string} userId - The ID of the user who initiated the interaction.\n * @param {string} conversationId - The ID of the conversation context.\n * @returns {TwitterInteractionMemory} The constructed memory object.\n */\n createMemoryObject(\n type: string,\n id: string,\n userId: string,\n conversationId: string,\n ): TwitterInteractionMemory {\n return {\n id: createUniqueUuid(this.runtime, id),\n agentId: this.runtime.agentId,\n entityId: createUniqueUuid(this.runtime, userId),\n roomId: createUniqueUuid(this.runtime, conversationId),\n content: {\n type,\n source: \"twitter\",\n },\n createdAt: Date.now(),\n };\n }\n\n /**\n * Asynchronously handles a tweet by generating a response and sending it.\n * This method processes the tweet content, determines if a response is needed,\n * generates appropriate response text, and sends the tweet reply.\n *\n * @param {object} params - The parameters object containing the tweet, message, and thread.\n * @param {Tweet} params.tweet - The tweet object to handle.\n * @param {Memory} params.message - The memory object associated with the tweet.\n * @param {Tweet[]} params.thread - The array of tweets in the thread.\n * @returns {object} - An object containing the text of the response and any relevant actions.\n */\n async handleTweet({\n tweet,\n message,\n thread,\n }: {\n tweet: ClientTweet;\n message: Memory;\n thread: ClientTweet[];\n }) {\n if (!message.content.text) {\n logger.log(\"Skipping Tweet with no text\", tweet.id);\n return { text: \"\", actions: [\"IGNORE\"] };\n }\n\n // Create a callback for handling the response\n const callback: HandlerCallback = async (\n response: Content,\n tweetId?: string,\n ) => {\n try {\n if (!response.text) {\n logger.warn(\"No text content in response, skipping tweet reply\");\n return [];\n }\n\n const tweetToReplyTo = tweetId || tweet.id;\n\n if (this.isDryRun) {\n logger.info(\n `[DRY RUN] Would have replied to ${tweet.username} with: ${response.text}`,\n );\n return [];\n }\n\n logger.info(`Replying to tweet ${tweetToReplyTo}`);\n\n // Create the actual tweet using the Twitter API through the client\n const tweetResult = await sendTweet(\n this.client,\n response.text,\n [],\n tweetToReplyTo,\n );\n\n if (!tweetResult) {\n throw new Error(\"Failed to get tweet result from response\");\n }\n\n // Create memory for our response\n const responseId = createUniqueUuid(this.runtime, tweetResult.id);\n const responseMemory: Memory = {\n id: responseId,\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId: message.roomId,\n content: {\n ...response,\n source: \"twitter\",\n inReplyTo: message.id,\n },\n createdAt: Date.now(),\n };\n\n await this.runtime.createMemory(responseMemory, \"messages\");\n\n // Return the created memory\n return [responseMemory];\n } catch (error) {\n logger.error(\"Error in tweet reply callback:\", error);\n return [];\n }\n };\n\n const twitterUserId = tweet.userId;\n const entityId = createUniqueUuid(this.runtime, twitterUserId);\n const twitterUsername = tweet.username;\n\n // Emit MESSAGE_RECEIVED event\n this.runtime.emitEvent(\n [TwitterEventTypes.MESSAGE_RECEIVED, EventType.MESSAGE_RECEIVED],\n {\n runtime: this.runtime,\n world: createUniqueUuid(this.runtime, twitterUserId),\n entityId: entityId,\n roomId: message.roomId,\n userId: twitterUserId,\n message: message,\n thread: thread,\n source: \"twitter\",\n callback,\n entityName: twitterUsername,\n },\n );\n\n // For synchronous response generation\n const response = await callback(message.content, tweet.id);\n\n // Check if response is an array of memories and extract the text\n let responseText = \"\";\n if (Array.isArray(response) && response.length > 0) {\n const firstResponse = response[0];\n if (firstResponse?.content?.text) {\n responseText = firstResponse.content.text;\n }\n }\n\n return {\n text: responseText,\n actions: responseText ? [\"REPLY\"] : [\"IGNORE\"],\n };\n }\n}\n","import { TwitterApi } from \"twitter-api-v2\";\nimport { Profile } from \"./profile\";\n\n/**\n * Twitter API v2 authentication using developer credentials\n */\nexport class TwitterAuth {\n private v2Client: TwitterApi | null = null;\n private authenticated = false;\n private profile?: Profile;\n\n constructor(\n private appKey: string,\n private appSecret: string,\n private accessToken: string,\n private accessSecret: string,\n ) {\n this.initializeClient();\n }\n\n private initializeClient(): void {\n this.v2Client = new TwitterApi({\n appKey: this.appKey,\n appSecret: this.appSecret,\n accessToken: this.accessToken,\n accessSecret: this.accessSecret,\n });\n this.authenticated = true;\n }\n\n /**\n * Get the Twitter API v2 client\n */\n getV2Client(): TwitterApi {\n if (!this.v2Client) {\n throw new Error(\"Twitter API client not initialized\");\n }\n return this.v2Client;\n }\n\n /**\n * Check if authenticated\n */\n async isLoggedIn(): Promise<boolean> {\n if (!this.authenticated || !this.v2Client) {\n return false;\n }\n\n try {\n // Verify credentials by getting current user\n const me = await this.v2Client.v2.me();\n return !!me.data;\n } catch (error) {\n console.error(\"Failed to verify authentication:\", error);\n return false;\n }\n }\n\n /**\n * Get current user profile\n */\n async me(): Promise<Profile | undefined> {\n if (this.profile) {\n return this.profile;\n }\n\n if (!this.v2Client) {\n throw new Error(\"Not authenticated\");\n }\n\n try {\n const { data: user } = await this.v2Client.v2.me({\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"description\",\n \"profile_image_url\",\n \"public_metrics\",\n \"verified\",\n \"location\",\n \"created_at\",\n ],\n });\n\n this.profile = {\n userId: user.id,\n username: user.username,\n name: user.name,\n biography: user.description,\n avatar: user.profile_image_url,\n followersCount: user.public_metrics?.followers_count,\n followingCount: user.public_metrics?.following_count,\n isVerified: user.verified,\n location: user.location || \"\",\n joined: user.created_at ? new Date(user.created_at) : undefined,\n };\n\n return this.profile;\n } catch (error) {\n console.error(\"Failed to get user profile:\", error);\n return undefined;\n }\n }\n\n /**\n * Logout (clear credentials)\n */\n async logout(): Promise<void> {\n this.v2Client = null;\n this.authenticated = false;\n this.profile = undefined;\n }\n\n /**\n * For compatibility - always returns true since we use API keys\n */\n hasToken(): boolean {\n return this.authenticated;\n }\n}\n","import stringify from \"json-stable-stringify\";\nimport { type RequestApiResult } from \"./api-types\";\nimport type { TwitterAuth } from \"./auth\";\nimport type { TwitterApiErrorRaw } from \"./errors\";\n\n/**\n * Interface representing a raw user object from a legacy system.\n * @typedef {Object} LegacyUserRaw\n * @property {string} [created_at] - The date the user was created.\n * @property {string} [description] - The user's description.\n * @property {Object} [entities] - Additional entities associated with the user.\n * @property {Object} [url] - The URL associated with the user.\n * @property {Object[]} [urls] - Array of URLs associated with the user.\n * @property {string} [expanded_url] - The expanded URL.\n * @property {number} [favourites_count] - The number of favorited items.\n * @property {number} [followers_count] - The number of followers.\n * @property {number} [friends_count] - The number of friends.\n * @property {number} [media_count] - The number of media items.\n * @property {number} [statuses_count] - The number of statuses.\n * @property {string} [id_str] - The user ID as a string.\n * @property {number} [listed_count] - The number of lists the user is listed in.\n * @property {string} [name] - The user's name.\n * @property {string} location - The user's location.\n * @property {boolean} [geo_enabled] - Indicates if geo locations are enabled.\n * @property {string[]} [pinned_tweet_ids_str] - Array of pinned tweet IDs as strings.\n * @property {string} [profile_background_color] - The background color of the user's profile.\n * @property {string} [profile_banner_url] - The URL of the user's profile banner.\n * @property {string} [profile_image_url_https] - The URL of the user's profile image (HTTPS).\n * @property {boolean} [protected] - Indicates if the user's account is protected.\n * @property {string} [screen_name] - The user's screen name.\n * @property {boolean} [verified] - Indicates if the user is verified.\n * @property {boolean} [has_custom_timelines] - Indicates if the user has custom timelines.\n * @property {boolean} [has_extended_profile] - Indicates if the user has an extended profile.\n * @property {string} [url] - The user's URL.\n * @property {boolean} [can_dm] - Indicates if direct messages are enabled for the user.\n */\nexport interface LegacyUserRaw {\n created_at?: string;\n description?: string;\n entities?: {\n url?: {\n urls?: {\n expanded_url?: string;\n }[];\n };\n };\n favourites_count?: number;\n followers_count?: number;\n friends_count?: number;\n media_count?: number;\n statuses_count?: number;\n id_str?: string;\n listed_count?: number;\n name?: string;\n location: string;\n geo_enabled?: boolean;\n pinned_tweet_ids_str?: string[];\n profile_background_color?: string;\n profile_banner_url?: string;\n profile_image_url_https?: string;\n protected?: boolean;\n screen_name?: string;\n verified?: boolean;\n has_custom_timelines?: boolean;\n has_extended_profile?: boolean;\n url?: string;\n can_dm?: boolean;\n}\n\n/**\n * A parsed profile object.\n */\n/**\n * Interface representing a user profile.\n * @typedef {Object} Profile\n * @property {string} [avatar] - The URL to the user's avatar.\n * @property {string} [banner] - The URL to the user's banner image.\n * @property {string} [biography] - The user's biography.\n * @property {string} [birthday] - The user's birthday.\n * @property {number} [followersCount] - The number of followers the user has.\n * @property {number} [followingCount] - The number of users the user is following.\n * @property {number} [friendsCount] - The number of friends the user has.\n * @property {number} [mediaCount] - The number of media items the user has posted.\n * @property {number} [statusesCount] - The number of statuses the user has posted.\n * @property {boolean} [isPrivate] - Indicates if the user's profile is private.\n * @property {boolean} [isVerified] - Indicates if the user account is verified.\n * @property {boolean} [isBlueVerified] - Indicates if the user account has blue verification badge.\n * @property {Date} [joined] - The date the user joined the platform.\n * @property {number} [likesCount] - The number of likes the user has received.\n * @property {number} [listedCount] - The number of times the user has been listed.\n * @property {string} location - The user's location.\n * @property {string} [name] - The user's name.\n * @property {string[]} [pinnedTweetIds] - The IDs of the user's pinned tweets.\n * @property {number} [tweetsCount] - The number of tweets the user has posted.\n * @property {string} [url] - The user's website URL.\n * @property {string} [userId] - The unique user ID.\n * @property {string} [username] - The user's username.\n * @property {string} [website] - The user's website.\n * @property {boolean} [canDm] - Indicates if the user can receive direct messages.\n */\nexport interface Profile {\n avatar?: string;\n banner?: string;\n biography?: string;\n birthday?: string;\n followersCount?: number;\n followingCount?: number;\n friendsCount?: number;\n mediaCount?: number;\n statusesCount?: number;\n isPrivate?: boolean;\n isVerified?: boolean;\n isBlueVerified?: boolean;\n joined?: Date;\n likesCount?: number;\n listedCount?: number;\n location: string;\n name?: string;\n pinnedTweetIds?: string[];\n tweetsCount?: number;\n url?: string;\n userId?: string;\n username?: string;\n website?: string;\n canDm?: boolean;\n}\n\nexport interface UserRaw {\n data: {\n user: {\n result: {\n rest_id?: string;\n is_blue_verified?: boolean;\n legacy: LegacyUserRaw;\n };\n };\n };\n errors?: TwitterApiErrorRaw[];\n}\n\nfunction getAvatarOriginalSizeUrl(avatarUrl: string | undefined) {\n return avatarUrl ? avatarUrl.replace(\"_normal\", \"\") : undefined;\n}\n\nexport function parseProfile(\n user: LegacyUserRaw,\n isBlueVerified?: boolean,\n): Profile {\n const profile: Profile = {\n avatar: getAvatarOriginalSizeUrl(user.profile_image_url_https),\n banner: user.profile_banner_url,\n biography: user.description,\n followersCount: user.followers_count,\n followingCount: user.friends_count,\n friendsCount: user.friends_count,\n mediaCount: user.media_count,\n isPrivate: user.protected ?? false,\n isVerified: user.verified,\n likesCount: user.favourites_count,\n listedCount: user.listed_count,\n location: user.location,\n name: user.name,\n pinnedTweetIds: user.pinned_tweet_ids_str,\n tweetsCount: user.statuses_count,\n url: `https://twitter.com/${user.screen_name}`,\n userId: user.id_str,\n username: user.screen_name,\n isBlueVerified: isBlueVerified ?? false,\n canDm: user.can_dm,\n };\n\n if (user.created_at != null) {\n profile.joined = new Date(Date.parse(user.created_at));\n }\n\n const urls = user.entities?.url?.urls;\n if (urls?.length != null && urls?.length > 0) {\n profile.website = urls[0].expanded_url;\n }\n\n return profile;\n}\n\n/**\n * Convert Twitter API v2 user data to Profile format\n */\nfunction parseV2Profile(user: any): Profile {\n const profile: Profile = {\n avatar: getAvatarOriginalSizeUrl(user.profile_image_url),\n biography: user.description,\n followersCount: user.public_metrics?.followers_count,\n followingCount: user.public_metrics?.following_count,\n friendsCount: user.public_metrics?.following_count,\n tweetsCount: user.public_metrics?.tweet_count,\n isPrivate: user.protected ?? false,\n isVerified: user.verified ?? false,\n likesCount: user.public_metrics?.like_count,\n listedCount: user.public_metrics?.listed_count,\n location: user.location || \"\",\n name: user.name,\n pinnedTweetIds: user.pinned_tweet_id ? [user.pinned_tweet_id] : [],\n url: `https://twitter.com/${user.username}`,\n userId: user.id,\n username: user.username,\n isBlueVerified: user.verified_type === \"blue\",\n };\n\n if (user.created_at) {\n profile.joined = new Date(user.created_at);\n }\n\n if (user.entities?.url?.urls?.length > 0) {\n profile.website = user.entities.url.urls[0].expanded_url;\n }\n\n return profile;\n}\n\nexport async function getProfile(\n username: string,\n auth: TwitterAuth,\n): Promise<RequestApiResult<Profile>> {\n if (!auth) {\n return {\n success: false,\n err: new Error(\"Not authenticated\"),\n };\n }\n\n try {\n const client = auth.getV2Client();\n const user = await client.v2.userByUsername(username, {\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"created_at\",\n \"description\",\n \"entities\",\n \"location\",\n \"pinned_tweet_id\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"verified\",\n \"verified_type\",\n ],\n });\n\n if (!user.data) {\n return {\n success: false,\n err: new Error(`User ${username} not found`),\n };\n }\n\n return {\n success: true,\n value: parseV2Profile(user.data),\n };\n } catch (error: any) {\n return {\n success: false,\n err: new Error(error.message || \"Failed to fetch profile\"),\n };\n }\n}\n\nconst idCache = new Map<string, string>();\n\nexport async function getScreenNameByUserId(\n userId: string,\n auth: TwitterAuth,\n): Promise<RequestApiResult<string>> {\n if (!auth) {\n return {\n success: false,\n err: new Error(\"Not authenticated\"),\n };\n }\n\n try {\n const client = auth.getV2Client();\n const user = await client.v2.user(userId, {\n \"user.fields\": [\"username\"],\n });\n\n if (!user.data || !user.data.username) {\n return {\n success: false,\n err: new Error(`User with ID ${userId} not found`),\n };\n }\n\n return {\n success: true,\n value: user.data.username,\n };\n } catch (error: any) {\n return {\n success: false,\n err: new Error(error.message || \"Failed to fetch user\"),\n };\n }\n}\n\nexport async function getEntityIdByScreenName(\n screenName: string,\n auth: TwitterAuth,\n): Promise<RequestApiResult<string>> {\n const cached = idCache.get(screenName);\n if (cached != null) {\n return { success: true, value: cached };\n }\n\n const profileRes = await getProfile(screenName, auth);\n if (!profileRes.success) {\n return profileRes as any;\n }\n\n const profile = profileRes.value;\n if (profile.userId != null) {\n idCache.set(screenName, profile.userId);\n\n return {\n success: true,\n value: profile.userId,\n };\n }\n\n return {\n success: false,\n err: new Error(\"User ID is undefined.\"),\n };\n}\n","import { Headers } from \"headers-polyfill\";\nimport type { TwitterAuth } from \"./auth\";\nimport { type Profile } from \"./profile\";\nimport type { QueryProfilesResponse } from \"./api-types\";\n\n/**\n * Convert Twitter API v2 user data to Profile format\n */\nfunction parseV2UserToProfile(user: any): Profile {\n return {\n avatar: user.profile_image_url?.replace(\"_normal\", \"\"),\n biography: user.description,\n followersCount: user.public_metrics?.followers_count,\n followingCount: user.public_metrics?.following_count,\n friendsCount: user.public_metrics?.following_count,\n tweetsCount: user.public_metrics?.tweet_count,\n isPrivate: user.protected ?? false,\n isVerified: user.verified ?? false,\n likesCount: user.public_metrics?.like_count,\n listedCount: user.public_metrics?.listed_count,\n location: user.location || \"\",\n name: user.name,\n pinnedTweetIds: user.pinned_tweet_id ? [user.pinned_tweet_id] : [],\n url: `https://twitter.com/${user.username}`,\n userId: user.id,\n username: user.username,\n isBlueVerified: user.verified_type === \"blue\",\n joined: user.created_at ? new Date(user.created_at) : undefined,\n website: user.entities?.url?.urls?.[0]?.expanded_url,\n };\n}\n\n/**\n * Function to get the following profiles of a user.\n * @param {string} userId - The ID of the user to get the following profiles for.\n * @param {number} maxProfiles - The maximum number of profiles to retrieve.\n * @param {TwitterAuth} auth - The Twitter authentication credentials.\n * @returns {AsyncGenerator<Profile, void>} An async generator that yields Profile objects.\n */\nexport async function* getFollowing(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n if (!auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = auth.getV2Client();\n let count = 0;\n let paginationToken: string | undefined;\n\n try {\n while (count < maxProfiles) {\n const response = await client.v2.following(userId, {\n max_results: Math.min(maxProfiles - count, 100),\n pagination_token: paginationToken,\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"created_at\",\n \"description\",\n \"entities\",\n \"location\",\n \"pinned_tweet_id\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"verified\",\n \"verified_type\",\n ],\n });\n\n if (!response.data || response.data.length === 0) {\n break;\n }\n\n for (const user of response.data) {\n if (count >= maxProfiles) break;\n yield parseV2UserToProfile(user);\n count++;\n }\n\n paginationToken = response.meta?.next_token;\n if (!paginationToken) break;\n }\n } catch (error) {\n console.error(\"Error fetching following:\", error);\n throw error;\n }\n}\n\n/**\n * Get followers for a specific user.\n * @param {string} userId - The user ID for which to retrieve followers.\n * @param {number} maxProfiles - The maximum number of profiles to retrieve.\n * @param {TwitterAuth} auth - The authentication credentials for the Twitter API.\n * @returns {AsyncGenerator<Profile, void>} - An async generator that yields Profile objects representing followers.\n */\nexport async function* getFollowers(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n if (!auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = auth.getV2Client();\n let count = 0;\n let paginationToken: string | undefined;\n\n try {\n while (count < maxProfiles) {\n const response = await client.v2.followers(userId, {\n max_results: Math.min(maxProfiles - count, 100),\n pagination_token: paginationToken,\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"created_at\",\n \"description\",\n \"entities\",\n \"location\",\n \"pinned_tweet_id\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"verified\",\n \"verified_type\",\n ],\n });\n\n if (!response.data || response.data.length === 0) {\n break;\n }\n\n for (const user of response.data) {\n if (count >= maxProfiles) break;\n yield parseV2UserToProfile(user);\n count++;\n }\n\n paginationToken = response.meta?.next_token;\n if (!paginationToken) break;\n }\n } catch (error) {\n console.error(\"Error fetching followers:\", error);\n throw error;\n }\n}\n\n/**\n * Fetches the profiles that a user is following.\n * @param {string} userId - The ID of the user whose following profiles are to be fetched.\n * @param {number} maxProfiles - The maximum number of profiles to fetch.\n * @param {TwitterAuth} auth - The Twitter authentication details.\n * @param {string} [cursor] - Optional cursor for pagination.\n * @returns {Promise<QueryProfilesResponse>} A Promise that resolves with the response containing profiles the user is following.\n */\nexport async function fetchProfileFollowing(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth,\n cursor?: string,\n): Promise<QueryProfilesResponse> {\n if (!auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.following(userId, {\n max_results: Math.min(maxProfiles, 100),\n pagination_token: cursor,\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"created_at\",\n \"description\",\n \"entities\",\n \"location\",\n \"pinned_tweet_id\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"verified\",\n \"verified_type\",\n ],\n });\n\n const profiles = response.data?.map(parseV2UserToProfile) || [];\n\n return {\n profiles,\n next: response.meta?.next_token,\n };\n } catch (error) {\n console.error(\"Error fetching following profiles:\", error);\n throw error;\n }\n}\n\n/**\n * Fetches the profile followers for a given user ID.\n *\n * @param {string} userId - The user ID for which to fetch profile followers.\n * @param {number} maxProfiles - The maximum number of profiles to fetch.\n * @param {TwitterAuth} auth - The Twitter authentication credentials.\n * @param {string} [cursor] - Optional cursor for paginating results.\n * @returns {Promise<QueryProfilesResponse>} A promise that resolves with the parsed profile followers timeline.\n */\nexport async function fetchProfileFollowers(\n userId: string,\n maxProfiles: number,\n auth: TwitterAuth,\n cursor?: string,\n): Promise<QueryProfilesResponse> {\n if (!auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.followers(userId, {\n max_results: Math.min(maxProfiles, 100),\n pagination_token: cursor,\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"created_at\",\n \"description\",\n \"entities\",\n \"location\",\n \"pinned_tweet_id\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"verified\",\n \"verified_type\",\n ],\n });\n\n const profiles = response.data?.map(parseV2UserToProfile) || [];\n\n return {\n profiles,\n next: response.meta?.next_token,\n };\n } catch (error) {\n console.error(\"Error fetching follower profiles:\", error);\n throw error;\n }\n}\n\n/**\n * Follow a user using Twitter API v2\n *\n * @param {string} username - The username to follow\n * @param {TwitterAuth} auth - The authentication credentials\n * @returns {Promise<Response>} Response from the API\n */\nexport async function followUser(\n username: string,\n auth: TwitterAuth,\n): Promise<Response> {\n if (!auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = auth.getV2Client();\n\n try {\n // First get the user ID from username\n const userResponse = await client.v2.userByUsername(username);\n if (!userResponse.data) {\n throw new Error(`User ${username} not found`);\n }\n\n // Get the authenticated user's ID\n const meResponse = await client.v2.me();\n if (!meResponse.data) {\n throw new Error(\"Failed to get authenticated user\");\n }\n\n // Follow the user\n const result = await client.v2.follow(meResponse.data.id, userResponse.data.id);\n\n // Return a Response-like object for compatibility\n return new Response(JSON.stringify(result), {\n status: result.data?.following ? 200 : 400,\n headers: new Headers({ \"Content-Type\": \"application/json\" }),\n });\n } catch (error) {\n console.error(\"Error following user:\", error);\n throw error;\n }\n}\n","import type { TwitterAuth } from \"./auth\";\nimport type { Profile } from \"./profile\";\nimport type { Tweet } from \"./tweets\";\n\n/**\n * The categories that can be used in Twitter searches.\n */\n/**\n * Enum representing different search modes.\n * @enum {number}\n */\n\nexport enum SearchMode {\n Top = 0,\n Latest = 1,\n Photos = 2,\n Videos = 3,\n Users = 4,\n}\n\n/**\n * Search for tweets using Twitter API v2\n *\n * @param query Search query\n * @param maxTweets Maximum number of tweets to return\n * @param searchMode Search mode (not all modes are supported in v2)\n * @param auth Authentication\n * @returns Async generator of tweets\n */\nexport async function* searchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n const client = auth.getV2Client();\n\n // Build query based on search mode\n let finalQuery = query;\n switch (searchMode) {\n case SearchMode.Photos:\n finalQuery = `${query} has:media has:images`;\n break;\n case SearchMode.Videos:\n finalQuery = `${query} has:media has:videos`;\n break;\n }\n\n try {\n const searchIterator = await client.v2.search(finalQuery, {\n max_results: Math.min(maxTweets, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n });\n\n let count = 0;\n for await (const tweet of searchIterator) {\n if (count >= maxTweets) break;\n\n // Convert to Tweet format\n const convertedTweet: Tweet = {\n id: tweet.id,\n text: tweet.text || \"\",\n timestamp: tweet.created_at\n ? new Date(tweet.created_at).getTime()\n : Date.now(),\n timeParsed: tweet.created_at ? new Date(tweet.created_at) : new Date(),\n userId: tweet.author_id || \"\",\n name:\n searchIterator.includes?.users?.find((u) => u.id === tweet.author_id)\n ?.name || \"\",\n username:\n searchIterator.includes?.users?.find((u) => u.id === tweet.author_id)\n ?.username || \"\",\n conversationId: tweet.id,\n hashtags: tweet.entities?.hashtags?.map((h) => h.tag) || [],\n mentions:\n tweet.entities?.mentions?.map((m) => ({\n id: m.id || \"\",\n username: m.username || \"\",\n name: \"\",\n })) || [],\n photos: [],\n thread: [],\n urls: tweet.entities?.urls?.map((u) => u.expanded_url || u.url) || [],\n videos: [],\n isRetweet:\n tweet.referenced_tweets?.some((rt) => rt.type === \"retweeted\") ||\n false,\n isReply:\n tweet.referenced_tweets?.some((rt) => rt.type === \"replied_to\") ||\n false,\n isQuoted:\n tweet.referenced_tweets?.some((rt) => rt.type === \"quoted\") || false,\n isPin: false,\n sensitiveContent: false,\n likes: tweet.public_metrics?.like_count || undefined,\n replies: tweet.public_metrics?.reply_count || undefined,\n retweets: tweet.public_metrics?.retweet_count || undefined,\n views: tweet.public_metrics?.impression_count || undefined,\n quotes: tweet.public_metrics?.quote_count || undefined,\n };\n\n yield convertedTweet;\n count++;\n }\n } catch (error) {\n console.error(\"Search error:\", error);\n throw error;\n }\n}\n\n/**\n * Search for users using Twitter API v2\n *\n * Note: User search is limited in the standard Twitter API v2.\n * This searches for users mentioned in tweets matching the query.\n *\n * @param query Search query\n * @param maxProfiles Maximum number of profiles to return\n * @param auth Authentication\n * @returns Async generator of profiles\n */\nexport async function* searchProfiles(\n query: string,\n maxProfiles: number,\n auth: TwitterAuth,\n): AsyncGenerator<Profile, void> {\n const client = auth.getV2Client();\n const userIds = new Set<string>();\n const profiles: Profile[] = [];\n\n try {\n // Search for tweets and extract unique user IDs\n const searchIterator = await client.v2.search(query, {\n max_results: Math.min(maxProfiles * 2, 100), // Get more tweets to find more users\n \"tweet.fields\": [\"author_id\"],\n \"user.fields\": [\n \"id\",\n \"name\",\n \"username\",\n \"description\",\n \"profile_image_url\",\n \"public_metrics\",\n \"verified\",\n \"location\",\n \"created_at\",\n ],\n expansions: [\"author_id\"],\n });\n\n for await (const tweet of searchIterator) {\n if (tweet.author_id) {\n userIds.add(tweet.author_id);\n }\n\n // Also get users from includes\n if (searchIterator.includes?.users) {\n for (const user of searchIterator.includes.users) {\n if (profiles.length < maxProfiles && user.id) {\n const profile: Profile = {\n userId: user.id,\n username: user.username || \"\",\n name: user.name || \"\",\n biography: user.description || \"\",\n avatar: user.profile_image_url || \"\",\n followersCount: user.public_metrics?.followers_count,\n followingCount: user.public_metrics?.following_count,\n isVerified: user.verified || false,\n location: user.location || \"\",\n joined: user.created_at ? new Date(user.created_at) : undefined,\n };\n profiles.push(profile);\n }\n }\n }\n\n if (profiles.length >= maxProfiles) break;\n }\n\n // Yield the profiles we found\n for (const profile of profiles) {\n yield profile;\n }\n } catch (error) {\n console.error(\"Profile search error:\", error);\n throw error;\n }\n}\n\n/**\n * Fetch tweets quoting a specific tweet\n *\n * @param quotedTweetId The ID of the quoted tweet\n * @param maxTweets Maximum number of tweets to return\n * @param auth Authentication\n * @returns Async generator of tweets\n */\nexport async function* searchQuotedTweets(\n quotedTweetId: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n // Twitter API v2 doesn't have a direct endpoint for quote tweets\n // We need to search for tweets that reference this tweet\n const query = `url:\"twitter.com/*/status/${quotedTweetId}\"`;\n\n yield* searchTweets(query, maxTweets, SearchMode.Latest, auth);\n}\n\n// Compatibility exports\nexport const fetchSearchTweets = async (\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n auth: TwitterAuth,\n cursor?: string,\n) => {\n throw new Error(\n \"fetchSearchTweets is deprecated. Use searchTweets generator instead.\",\n );\n};\n\nexport const fetchSearchProfiles = async (\n query: string,\n maxProfiles: number,\n auth: TwitterAuth,\n cursor?: string,\n) => {\n throw new Error(\n \"fetchSearchProfiles is deprecated. Use searchProfiles generator instead.\",\n );\n};\n","import type {\n ApiV2Includes,\n MediaObjectV2,\n PlaceV2,\n PollV2,\n TTweetv2Expansion,\n TTweetv2MediaField,\n TTweetv2PlaceField,\n TTweetv2PollField,\n TTweetv2TweetField,\n TTweetv2UserField,\n TweetV2,\n UserV2,\n} from \"twitter-api-v2\";\nimport type { TwitterAuth } from \"./auth\";\nimport { getEntityIdByScreenName } from \"./profile\";\nimport type { QueryTweetsResponse } from \"./api-types\";\n\n/**\n * Default options for Twitter API v2 request parameters.\n * @typedef {Object} defaultOptions\n * @property {TTweetv2Expansion[]} expansions - List of expansions to include in the request.\n * @property {TTweetv2TweetField[]} tweetFields - List of tweet fields to include in the request.\n * @property {TTweetv2PollField[]} pollFields - List of poll fields to include in the request.\n * @property {TTweetv2MediaField[]} mediaFields - List of media fields to include in the request.\n * @property {TTweetv2UserField[]} userFields - List of user fields to include in the request.\n * @property {TTweetv2PlaceField[]} placeFields - List of place fields to include in the request.\n */\nexport const defaultOptions = {\n expansions: [\n \"attachments.poll_ids\",\n \"attachments.media_keys\",\n \"author_id\",\n \"referenced_tweets.id\",\n \"in_reply_to_user_id\",\n \"edit_history_tweet_ids\",\n \"geo.place_id\",\n \"entities.mentions.username\",\n \"referenced_tweets.id.author_id\",\n ] as TTweetv2Expansion[],\n tweetFields: [\n \"attachments\",\n \"author_id\",\n \"context_annotations\",\n \"conversation_id\",\n \"created_at\",\n \"entities\",\n \"geo\",\n \"id\",\n \"in_reply_to_user_id\",\n \"lang\",\n \"public_metrics\",\n \"edit_controls\",\n \"possibly_sensitive\",\n \"referenced_tweets\",\n \"reply_settings\",\n \"source\",\n \"text\",\n \"withheld\",\n \"note_tweet\",\n ] as TTweetv2TweetField[],\n pollFields: [\n \"duration_minutes\",\n \"end_datetime\",\n \"id\",\n \"options\",\n \"voting_status\",\n ] as TTweetv2PollField[],\n mediaFields: [\n \"duration_ms\",\n \"height\",\n \"media_key\",\n \"preview_image_url\",\n \"type\",\n \"url\",\n \"width\",\n \"public_metrics\",\n \"alt_text\",\n \"variants\",\n ] as TTweetv2MediaField[],\n userFields: [\n \"created_at\",\n \"description\",\n \"entities\",\n \"id\",\n \"location\",\n \"name\",\n \"profile_image_url\",\n \"protected\",\n \"public_metrics\",\n \"url\",\n \"username\",\n \"verified\",\n \"withheld\",\n ] as TTweetv2UserField[],\n placeFields: [\n \"contained_within\",\n \"country\",\n \"country_code\",\n \"full_name\",\n \"geo\",\n \"id\",\n \"name\",\n \"place_type\",\n ] as TTweetv2PlaceField[],\n};\n/**\n * Interface representing a mention.\n * @typedef {Object} Mention\n * @property {string} id - The unique identifier for the mention.\n * @property {string} [username] - The username associated with the mention.\n * @property {string} [name] - The name associated with the mention.\n */\nexport interface Mention {\n id: string;\n username?: string;\n name?: string;\n}\n\n/**\n * Interface representing a photo object.\n * @interface\n * @property {string} id - The unique identifier for the photo.\n * @property {string} url - The URL for the photo image.\n * @property {string} [alt_text] - The alternative text for the photo image. Optional.\n */\nexport interface Photo {\n id: string;\n url: string;\n alt_text: string | undefined;\n}\n\n/**\n * Interface representing a video object.\n * @typedef {Object} Video\n * @property {string} id - The unique identifier for the video.\n * @property {string} preview - The URL for the preview image of the video.\n * @property {string} [url] - The optional URL for the video.\n */\n\nexport interface Video {\n id: string;\n preview: string;\n url?: string;\n}\n\n/**\n * Interface representing a raw place object.\n * @typedef {Object} PlaceRaw\n * @property {string} [id] - The unique identifier of the place.\n * @property {string} [place_type] - The type of the place.\n * @property {string} [name] - The name of the place.\n * @property {string} [full_name] - The full name of the place.\n * @property {string} [country_code] - The country code of the place.\n * @property {string} [country] - The country name of the place.\n * @property {Object} [bounding_box] - The bounding box coordinates of the place.\n * @property {string} [bounding_box.type] - The type of the bounding box.\n * @property {number[][][]} [bounding_box.coordinates] - The coordinates of the bounding box in an array format.\n */\nexport interface PlaceRaw {\n id?: string;\n place_type?: string;\n name?: string;\n full_name?: string;\n country_code?: string;\n country?: string;\n bounding_box?: {\n type?: string;\n coordinates?: number[][][];\n };\n}\n\n/**\n * Interface representing poll data.\n *\n * @property {string} [id] - The unique identifier for the poll.\n * @property {string} [end_datetime] - The end date and time for the poll.\n * @property {string} [voting_status] - The status of the voting process.\n * @property {number} duration_minutes - The duration of the poll in minutes.\n * @property {PollOption[]} options - An array of poll options.\n */\nexport interface PollData {\n id?: string;\n end_datetime?: string;\n voting_status?: string;\n duration_minutes: number;\n options: PollOption[];\n}\n\n/**\n * Interface representing a poll option.\n * @typedef {Object} PollOption\n * @property {number} [position] - The position of the option.\n * @property {string} label - The label of the option.\n * @property {number} [votes] - The number of votes for the option.\n */\nexport interface PollOption {\n position?: number;\n label: string;\n votes?: number;\n}\n\n/**\n * A parsed Tweet object.\n */\n/**\n * Represents a Tweet on Twitter.\n * @typedef { Object } Tweet\n * @property { number } [bookmarkCount] - The number of times this Tweet has been bookmarked.\n * @property { string } [conversationId] - The ID of the conversation this Tweet is a part of.\n * @property {string[]} hashtags - An array of hashtags mentioned in the Tweet.\n * @property { string } [html] - The HTML content of the Tweet.\n * @property { string } [id] - The unique ID of the Tweet.\n * @property { Tweet } [inReplyToStatus] - The Tweet that this Tweet is in reply to.\n * @property { string } [inReplyToStatusId] - The ID of the Tweet that this Tweet is in reply to.\n * @property { boolean } [isQuoted] - Indicates if this Tweet is a quote of another Tweet.\n * @property { boolean } [isPin] - Indicates if this Tweet is pinned.\n * @property { boolean } [isReply] - Indicates if this Tweet is a reply to another Tweet.\n * @property { boolean } [isRetweet] - Indicates if this Tweet is a retweet.\n * @property { boolean } [isSelfThread] - Indicates if this Tweet is part of a self thread.\n * @property { string } [language] - The language of the Tweet.\n * @property { number } [likes] - The number of likes on the Tweet.\n * @property { string } [name] - The name associated with the Tweet.\n * @property {Mention[]} mentions - An array of mentions in the Tweet.\n * @property { string } [permanentUrl] - The permanent URL of the Tweet.\n * @property {Photo[]} photos - An array of photos attached to the Tweet.\n * @property { PlaceRaw } [place] - The place associated with the Tweet.\n * @property { Tweet } [quotedStatus] - The quoted Tweet.\n * @property { string } [quotedStatusId] - The ID of the quoted Tweet.\n * @property { number } [quotes] - The number of times this Tweet has been quoted.\n * @property { number } [replies] - The number of replies to the Tweet.\n * @property { number } [retweets] - The number of retweets on the Tweet.\n * @property { Tweet } [retweetedStatus] - The status that was retweeted.\n * @property { string } [retweetedStatusId] - The ID of the retweeted status.\n * @property { string } [text] - The text content of the Tweet.\n * @property {Tweet[]} thread - An array representing a Twitter thread.\n * @property { Date } [timeParsed] - The parsed timestamp of the Tweet.\n * @property { number } [timestamp] - The timestamp of the Tweet.\n * @property {string[]} urls - An array of URLs mentioned in the Tweet.\n * @property { string } [userId] - The ID of the user who posted the Tweet.\n * @property { string } [username] - The username of the user who posted the Tweet.\n * @property {Video[]} videos - An array of videos attached to the Tweet.\n * @property { number } [views] - The number of views on the Tweet.\n * @property { boolean } [sensitiveContent] - Indicates if the Tweet contains sensitive content.\n * @property {PollV2 | null} [poll] - The poll attached to the Tweet, if any.\n */\nexport interface Tweet {\n bookmarkCount?: number;\n conversationId?: string;\n hashtags: string[];\n html?: string;\n id?: string;\n inReplyToStatus?: Tweet;\n inReplyToStatusId?: string;\n isQuoted?: boolean;\n isPin?: boolean;\n isReply?: boolean;\n isRetweet?: boolean;\n isSelfThread?: boolean;\n language?: string;\n likes?: number;\n name?: string;\n mentions: Mention[];\n permanentUrl?: string;\n photos: Photo[];\n place?: PlaceRaw;\n quotedStatus?: Tweet;\n quotedStatusId?: string;\n quotes?: number;\n replies?: number;\n retweets?: number;\n retweetedStatus?: Tweet;\n retweetedStatusId?: string;\n text?: string;\n thread: Tweet[];\n timeParsed?: Date;\n timestamp?: number;\n urls: string[];\n userId?: string;\n username?: string;\n videos: Video[];\n views?: number;\n sensitiveContent?: boolean;\n poll?: PollV2 | null;\n}\n\nexport interface Retweeter {\n rest_id: string;\n screen_name: string;\n name: string;\n description?: string;\n}\n\nexport type TweetQuery =\n | Partial<Tweet>\n | ((tweet: Tweet) => boolean | Promise<boolean>);\n\nexport async function fetchTweets(\n userId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.userTimeline(userId, {\n max_results: Math.min(maxTweets, 100),\n exclude: [\"retweets\", \"replies\"],\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n pagination_token: cursor,\n });\n\n const convertedTweets: Tweet[] = [];\n\n // Use the paginator's built-in methods to access data\n for await (const tweet of response) {\n convertedTweets.push(parseTweetV2ToV1(tweet, response.includes));\n if (convertedTweets.length >= maxTweets) break;\n }\n\n return {\n tweets: convertedTweets,\n next: response.meta.next_token,\n };\n } catch (error) {\n throw new Error(`Failed to fetch tweets: ${error?.message || error}`);\n }\n}\n\nexport async function fetchTweetsAndReplies(\n userId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.userTimeline(userId, {\n max_results: Math.min(maxTweets, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n pagination_token: cursor,\n });\n\n const convertedTweets: Tweet[] = [];\n\n // Use the paginator's built-in methods to access data\n for await (const tweet of response) {\n convertedTweets.push(parseTweetV2ToV1(tweet, response.includes));\n if (convertedTweets.length >= maxTweets) break;\n }\n\n return {\n tweets: convertedTweets,\n next: response.meta.next_token,\n };\n } catch (error) {\n throw new Error(`Failed to fetch tweets and replies: ${error?.message || error}`);\n }\n}\n\nexport async function createCreateTweetRequestV2(\n text: string,\n auth: TwitterAuth,\n tweetId?: string,\n options?: {\n poll?: PollData;\n },\n) {\n const v2client = auth.getV2Client();\n if (v2client == null) {\n throw new Error(\"V2 client is not initialized\");\n }\n const { poll } = options || {};\n let tweetConfig;\n if (poll) {\n tweetConfig = {\n text,\n poll: {\n options: poll?.options.map((option) => option.label) ?? [],\n duration_minutes: poll?.duration_minutes ?? 60,\n },\n };\n } else if (tweetId) {\n tweetConfig = {\n text,\n reply: {\n in_reply_to_tweet_id: tweetId,\n },\n };\n } else {\n tweetConfig = {\n text,\n };\n }\n const tweetResponse = await v2client.v2.tweet(tweetConfig);\n let optionsConfig = {};\n if (options?.poll) {\n optionsConfig = {\n expansions: [\"attachments.poll_ids\"],\n pollFields: [\n \"options\",\n \"duration_minutes\",\n \"end_datetime\",\n \"voting_status\",\n ],\n };\n }\n return await getTweetV2(tweetResponse.data.id, auth, optionsConfig);\n}\n\nexport function parseTweetV2ToV1(\n tweetV2: TweetV2,\n includes?: ApiV2Includes,\n): Tweet {\n const parsedTweet: Tweet = {\n id: tweetV2.id,\n text: tweetV2.text ?? \"\",\n hashtags: tweetV2.entities?.hashtags?.map((tag) => tag.tag) ?? [],\n mentions: tweetV2.entities?.mentions?.map((mention) => ({\n id: mention.id,\n username: mention.username,\n })) ?? [],\n urls: tweetV2.entities?.urls?.map((url) => url.url) ?? [],\n likes: tweetV2.public_metrics?.like_count ?? 0,\n retweets: tweetV2.public_metrics?.retweet_count ?? 0,\n replies: tweetV2.public_metrics?.reply_count ?? 0,\n quotes: tweetV2.public_metrics?.quote_count ?? 0,\n views: tweetV2.public_metrics?.impression_count ?? 0,\n userId: tweetV2.author_id,\n conversationId: tweetV2.conversation_id,\n photos: [],\n videos: [],\n poll: null,\n username: \"\",\n name: \"\",\n thread: [],\n timestamp: tweetV2.created_at ? new Date(tweetV2.created_at).getTime() / 1000 : Date.now() / 1000,\n permanentUrl: `https://twitter.com/i/status/${tweetV2.id}`,\n // Check for referenced tweets\n isReply: tweetV2.referenced_tweets?.some(ref => ref.type === \"replied_to\") ?? false,\n isRetweet: tweetV2.referenced_tweets?.some(ref => ref.type === \"retweeted\") ?? false,\n isQuoted: tweetV2.referenced_tweets?.some(ref => ref.type === \"quoted\") ?? false,\n inReplyToStatusId: tweetV2.referenced_tweets?.find(ref => ref.type === \"replied_to\")?.id,\n quotedStatusId: tweetV2.referenced_tweets?.find(ref => ref.type === \"quoted\")?.id,\n retweetedStatusId: tweetV2.referenced_tweets?.find(ref => ref.type === \"retweeted\")?.id,\n };\n\n // Process Polls\n if (includes?.polls?.length) {\n const poll = includes.polls[0];\n parsedTweet.poll = {\n id: poll.id,\n end_datetime: poll.end_datetime,\n options: poll.options.map((option) => ({\n position: option.position,\n label: option.label,\n votes: option.votes,\n })),\n voting_status: poll.voting_status,\n };\n }\n\n // Process Media (photos and videos)\n if (includes?.media?.length) {\n includes.media.forEach((media: MediaObjectV2) => {\n if (media.type === \"photo\") {\n parsedTweet.photos.push({\n id: media.media_key,\n url: media.url ?? \"\",\n alt_text: media.alt_text ?? \"\",\n });\n } else if (media.type === \"video\" || media.type === \"animated_gif\") {\n parsedTweet.videos.push({\n id: media.media_key,\n preview: media.preview_image_url ?? \"\",\n url:\n media.variants?.find(\n (variant) => variant.content_type === \"video/mp4\",\n )?.url ?? \"\",\n });\n }\n });\n }\n\n // Process User (for author info)\n if (includes?.users?.length) {\n const user = includes.users.find(\n (user: UserV2) => user.id === tweetV2.author_id,\n );\n if (user) {\n parsedTweet.username = user.username ?? \"\";\n parsedTweet.name = user.name ?? \"\";\n }\n }\n\n // Process Place (if any)\n if (tweetV2?.geo?.place_id && includes?.places?.length) {\n const place = includes.places.find(\n (place: PlaceV2) => place.id === tweetV2?.geo?.place_id,\n );\n if (place) {\n parsedTweet.place = {\n id: place.id,\n full_name: place.full_name ?? \"\",\n country: place.country ?? \"\",\n country_code: place.country_code ?? \"\",\n name: place.name ?? \"\",\n place_type: place.place_type,\n };\n }\n }\n\n // TODO: Process Thread (referenced tweets) and remove reference to v1\n return parsedTweet;\n}\n\nexport async function createCreateTweetRequest(\n text: string,\n auth: TwitterAuth,\n tweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n hideLinkPreview = false,\n) {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n let tweetConfig: any = {\n text,\n };\n\n // Handle media uploads if provided\n if (mediaData && mediaData.length > 0) {\n // Note: Twitter API v2 media upload requires separate endpoint\n // For now, we'll skip media upload as it requires additional implementation\n console.warn(\"Media upload not yet implemented for Twitter API v2\");\n }\n\n // Handle reply\n if (tweetId) {\n tweetConfig.reply = {\n in_reply_to_tweet_id: tweetId,\n };\n }\n\n const result = await v2client.v2.tweet(tweetConfig);\n\n return {\n ok: true,\n json: async () => result,\n data: result,\n };\n } catch (error) {\n throw new Error(`Failed to create tweet: ${error?.message || error}`);\n }\n}\n\nexport async function createCreateNoteTweetRequest(\n text: string,\n auth: TwitterAuth,\n tweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n) {\n // Twitter API v2 doesn't have a separate endpoint for \"note tweets\"\n // Long tweets are handled automatically by the v2 tweet endpoint\n return createCreateTweetRequest(text, auth, tweetId, mediaData);\n}\n\nexport async function fetchListTweets(\n listId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.listTweets(listId, {\n max_results: Math.min(maxTweets, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n pagination_token: cursor,\n });\n\n const convertedTweets: Tweet[] = [];\n\n // Use the paginator's built-in methods to access data\n for await (const tweet of response) {\n convertedTweets.push(parseTweetV2ToV1(tweet, response.includes));\n if (convertedTweets.length >= maxTweets) break;\n }\n\n return {\n tweets: convertedTweets,\n next: response.meta.next_token,\n };\n } catch (error) {\n throw new Error(`Failed to fetch list tweets: ${error.message}`);\n }\n}\n\nexport async function deleteTweet(tweetId: string, auth: TwitterAuth) {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n const result = await v2client.v2.deleteTweet(tweetId);\n return {\n ok: true,\n json: async () => result,\n data: result,\n };\n } catch (error) {\n throw new Error(`Failed to delete tweet: ${error.message}`);\n }\n}\n\nexport async function* getTweets(\n user: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n const userIdRes = await getEntityIdByScreenName(user, auth);\n\n if (!userIdRes.success) {\n throw (userIdRes as any).err;\n }\n\n const { value: userId } = userIdRes;\n\n let cursor: string | undefined;\n let totalFetched = 0;\n\n while (totalFetched < maxTweets) {\n const response = await fetchTweets(userId, maxTweets - totalFetched, cursor, auth);\n \n for (const tweet of response.tweets) {\n yield tweet;\n totalFetched++;\n if (totalFetched >= maxTweets) break;\n }\n \n cursor = response.next;\n if (!cursor) break;\n }\n}\n\nexport async function* getTweetsByUserId(\n userId: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n let cursor: string | undefined;\n let totalFetched = 0;\n\n while (totalFetched < maxTweets) {\n const response = await fetchTweets(userId, maxTweets - totalFetched, cursor, auth);\n \n for (const tweet of response.tweets) {\n yield tweet;\n totalFetched++;\n if (totalFetched >= maxTweets) break;\n }\n \n cursor = response.next;\n if (!cursor) break;\n }\n}\n\nexport async function* getTweetsAndReplies(\n user: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n const userIdRes = await getEntityIdByScreenName(user, auth);\n\n if (!userIdRes.success) {\n throw (userIdRes as any).err;\n }\n\n const { value: userId } = userIdRes;\n\n let cursor: string | undefined;\n let totalFetched = 0;\n\n while (totalFetched < maxTweets) {\n const response = await fetchTweetsAndReplies(userId, maxTweets - totalFetched, cursor, auth);\n \n for (const tweet of response.tweets) {\n yield tweet;\n totalFetched++;\n if (totalFetched >= maxTweets) break;\n }\n \n cursor = response.next;\n if (!cursor) break;\n }\n}\n\nexport async function* getTweetsAndRepliesByUserId(\n userId: string,\n maxTweets: number,\n auth: TwitterAuth,\n): AsyncGenerator<Tweet, void> {\n let cursor: string | undefined;\n let totalFetched = 0;\n\n while (totalFetched < maxTweets) {\n const response = await fetchTweetsAndReplies(userId, maxTweets - totalFetched, cursor, auth);\n \n for (const tweet of response.tweets) {\n yield tweet;\n totalFetched++;\n if (totalFetched >= maxTweets) break;\n }\n \n cursor = response.next;\n if (!cursor) break;\n }\n}\n\nexport async function fetchLikedTweets(\n userId: string,\n maxTweets: number,\n cursor: string | undefined,\n auth: TwitterAuth,\n): Promise<QueryTweetsResponse> {\n const client = auth.getV2Client();\n\n try {\n const response = await client.v2.userLikedTweets(userId, {\n max_results: Math.min(maxTweets, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n pagination_token: cursor,\n });\n\n const convertedTweets: Tweet[] = [];\n\n // Use the paginator's built-in methods to access data\n for await (const tweet of response) {\n convertedTweets.push(parseTweetV2ToV1(tweet, response.includes));\n if (convertedTweets.length >= maxTweets) break;\n }\n\n return {\n tweets: convertedTweets,\n next: response.meta.next_token,\n };\n } catch (error) {\n throw new Error(`Failed to fetch liked tweets: ${error.message}`);\n }\n}\n\nexport async function getTweetWhere(\n tweets: AsyncIterable<Tweet>,\n query: TweetQuery,\n): Promise<Tweet | null> {\n const isCallback = typeof query === \"function\";\n\n for await (const tweet of tweets) {\n const matches = isCallback\n ? await query(tweet)\n : checkTweetMatches(tweet, query);\n\n if (matches) {\n return tweet;\n }\n }\n\n return null;\n}\n\nexport async function getTweetsWhere(\n tweets: AsyncIterable<Tweet>,\n query: TweetQuery,\n): Promise<Tweet[]> {\n const isCallback = typeof query === \"function\";\n const filtered = [];\n\n for await (const tweet of tweets) {\n const matches = isCallback ? query(tweet) : checkTweetMatches(tweet, query);\n\n if (!matches) continue;\n filtered.push(tweet);\n }\n\n return filtered;\n}\n\nfunction checkTweetMatches(tweet: Tweet, options: Partial<Tweet>): boolean {\n return Object.keys(options).every((k) => {\n const key = k as keyof Tweet;\n return tweet[key] === options[key];\n });\n}\n\nexport async function getLatestTweet(\n user: string,\n includeRetweets: boolean,\n max: number,\n auth: TwitterAuth,\n): Promise<Tweet | null | undefined> {\n const timeline = getTweets(user, max, auth);\n\n // No point looping if max is 1, just use first entry.\n return max === 1\n ? ((await timeline.next()).value as Tweet)\n : await getTweetWhere(timeline, { isRetweet: includeRetweets });\n}\n\n// TweetResultByRestId interface removed - no longer used with v2 API\n\nexport async function getTweet(\n id: string,\n auth: TwitterAuth,\n): Promise<Tweet | null> {\n const client = auth.getV2Client();\n\n try {\n const tweet = await client.v2.singleTweet(id, {\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n \"conversation_id\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n \"poll.fields\": [\"id\", \"options\", \"end_datetime\", \"voting_status\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"attachments.poll_ids\",\n \"referenced_tweets.id\",\n ],\n });\n\n if (!tweet.data) {\n return null;\n }\n\n return parseTweetV2ToV1(tweet.data, tweet.includes);\n } catch (error) {\n console.error(`Failed to get tweet: ${error.message}`);\n return null;\n }\n}\n\nexport async function getTweetV2(\n id: string,\n auth: TwitterAuth,\n options: {\n expansions?: TTweetv2Expansion[];\n tweetFields?: TTweetv2TweetField[];\n pollFields?: TTweetv2PollField[];\n mediaFields?: TTweetv2MediaField[];\n userFields?: TTweetv2UserField[];\n placeFields?: TTweetv2PlaceField[];\n } = defaultOptions,\n): Promise<Tweet | null> {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n const tweetData = await v2client.v2.singleTweet(id, {\n expansions: options?.expansions,\n \"tweet.fields\": options?.tweetFields,\n \"poll.fields\": options?.pollFields,\n \"media.fields\": options?.mediaFields,\n \"user.fields\": options?.userFields,\n \"place.fields\": options?.placeFields,\n });\n\n if (!tweetData?.data) {\n console.warn(`Tweet data not found for ID: ${id}`);\n return null;\n }\n\n // Extract primary tweet data\n const parsedTweet = parseTweetV2ToV1(\n tweetData.data,\n tweetData?.includes,\n );\n\n return parsedTweet;\n } catch (error) {\n console.error(`Error fetching tweet ${id}:`, error);\n return null;\n }\n}\n\nexport async function getTweetsV2(\n ids: string[],\n auth: TwitterAuth,\n options: {\n expansions?: TTweetv2Expansion[];\n tweetFields?: TTweetv2TweetField[];\n pollFields?: TTweetv2PollField[];\n mediaFields?: TTweetv2MediaField[];\n userFields?: TTweetv2UserField[];\n placeFields?: TTweetv2PlaceField[];\n } = defaultOptions,\n): Promise<Tweet[]> {\n const v2client = auth.getV2Client();\n if (!v2client) {\n return [];\n }\n\n try {\n const tweetData = await v2client.v2.tweets(ids, {\n expansions: options?.expansions,\n \"tweet.fields\": options?.tweetFields,\n \"poll.fields\": options?.pollFields,\n \"media.fields\": options?.mediaFields,\n \"user.fields\": options?.userFields,\n \"place.fields\": options?.placeFields,\n });\n const tweetsV2 = tweetData.data;\n if (tweetsV2.length === 0) {\n console.warn(`No tweet data found for IDs: ${ids.join(\", \")}`);\n return [];\n }\n return (\n await Promise.all(\n tweetsV2.map(\n async (tweet) => await getTweetV2(tweet.id, auth, options),\n ),\n )\n ).filter((tweet): tweet is Tweet => tweet !== null);\n } catch (error) {\n console.error(`Error fetching tweets for IDs: ${ids.join(\", \")}`, error);\n return [];\n }\n}\n\nexport async function getTweetAnonymous(\n id: string,\n auth: TwitterAuth,\n): Promise<Tweet | null> {\n // Twitter API v2 doesn't support anonymous access\n // Use the regular getTweet method\n return getTweet(id, auth);\n}\n\ninterface MediaUploadResponse {\n media_id_string: string;\n size: number;\n expires_after_secs: number;\n image: {\n image_type: string;\n w: number;\n h: number;\n };\n}\n\nasync function uploadMedia(\n mediaData: Buffer,\n auth: TwitterAuth,\n mediaType: string,\n): Promise<string> {\n // Twitter API v2 media upload is not yet fully implemented in twitter-api-v2 library\n // This would require using the v1.1 media upload endpoint with proper OAuth\n console.warn(\"Media upload not yet implemented for Twitter API v2\");\n throw new Error(\"Media upload not yet implemented for Twitter API v2\");\n}\n\n// Function to create a quote tweet\nexport async function createQuoteTweetRequest(\n text: string,\n quotedTweetId: string,\n auth: TwitterAuth,\n mediaData?: { data: Buffer; mediaType: string }[],\n) {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n // Quote tweets in v2 are created by including the tweet URL in the text\n const quotedTweetUrl = `https://twitter.com/i/status/${quotedTweetId}`;\n const fullText = `${text} ${quotedTweetUrl}`;\n\n const result = await v2client.v2.tweet({\n text: fullText,\n });\n\n return {\n ok: true,\n json: async () => result,\n data: result,\n };\n } catch (error) {\n throw new Error(`Failed to create quote tweet: ${error.message}`);\n }\n}\n\n/**\n * Likes a tweet with the given tweet ID.\n * @param tweetId The ID of the tweet to like.\n * @param auth The authentication object.\n * @returns A promise that resolves when the tweet is liked.\n */\nexport async function likeTweet(\n tweetId: string,\n auth: TwitterAuth,\n): Promise<void> {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n await v2client.v2.like(\n (await v2client.v2.me()).data.id, // Current user ID\n tweetId,\n );\n } catch (error) {\n throw new Error(`Failed to like tweet: ${error.message}`);\n }\n}\n\n/**\n * Retweets a tweet with the given tweet ID.\n * @param tweetId The ID of the tweet to retweet.\n * @param auth The authentication object.\n * @returns A promise that resolves when the tweet is retweeted.\n */\nexport async function retweet(\n tweetId: string,\n auth: TwitterAuth,\n): Promise<void> {\n const v2client = auth.getV2Client();\n if (!v2client) {\n throw new Error(\"V2 client is not initialized\");\n }\n\n try {\n await v2client.v2.retweet(\n (await v2client.v2.me()).data.id, // Current user ID\n tweetId,\n );\n } catch (error) {\n throw new Error(`Failed to retweet: ${error.message}`);\n }\n}\n\nexport async function createCreateLongTweetRequest(\n text: string,\n auth: TwitterAuth,\n tweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n) {\n // Twitter API v2 handles long tweets automatically\n // Just use the regular tweet creation endpoint\n return createCreateTweetRequest(text, auth, tweetId, mediaData);\n}\n\n// getArticle function removed - Twitter API v2 doesn't have a separate article endpoint\n\n/**\n * Fetches a single page of retweeters for a given tweet, collecting both bottom and top cursors.\n * Logs each user's description in the process.\n * All comments must remain in English.\n */\nexport async function fetchRetweetersPage(\n tweetId: string,\n auth: TwitterAuth,\n cursor?: string,\n count = 40,\n): Promise<{\n retweeters: Retweeter[];\n bottomCursor?: string;\n topCursor?: string;\n}> {\n // Twitter API v2 does not provide an endpoint to fetch retweeters\n // This functionality would require the API v2 retweeted_by endpoint\n console.warn(\"Fetching retweeters not implemented for Twitter API v2\");\n return {\n retweeters: [],\n bottomCursor: undefined,\n topCursor: undefined,\n };\n}\n\n/**\n * Retrieves *all* retweeters by chaining requests until no next cursor is found.\n * @param tweetId The ID of the tweet.\n * @param auth The TwitterAuth object for authentication.\n * @returns A list of all users that retweeted the tweet.\n */\nexport async function getAllRetweeters(\n tweetId: string,\n auth: TwitterAuth,\n): Promise<Retweeter[]> {\n let allRetweeters: Retweeter[] = [];\n let cursor: string | undefined;\n\n while (true) {\n // Destructure bottomCursor / topCursor\n const { retweeters, bottomCursor, topCursor } = await fetchRetweetersPage(\n tweetId,\n auth,\n cursor,\n 40,\n );\n allRetweeters = allRetweeters.concat(retweeters);\n\n const newCursor = bottomCursor || topCursor;\n\n // Stop if there is no new cursor or if it's the same as the old one\n if (!newCursor || newCursor === cursor) {\n break;\n }\n\n cursor = newCursor;\n }\n\n return allRetweeters;\n}\n","import type {\n TTweetv2Expansion,\n TTweetv2MediaField,\n TTweetv2PlaceField,\n TTweetv2PollField,\n TTweetv2TweetField,\n TTweetv2UserField,\n} from \"twitter-api-v2\";\nimport {\n type FetchTransformOptions,\n type QueryProfilesResponse,\n type QueryTweetsResponse,\n type RequestApiResult,\n} from \"./api-types\";\nimport { TwitterAuth } from \"./auth\";\n// Removed messages imports - using Twitter API v2 instead\nimport {\n type Profile,\n getEntityIdByScreenName,\n getProfile,\n getScreenNameByUserId,\n} from \"./profile\";\nimport {\n fetchProfileFollowers,\n fetchProfileFollowing,\n followUser,\n getFollowers,\n getFollowing,\n} from \"./relationships\";\nimport {\n SearchMode,\n searchProfiles,\n searchTweets,\n searchQuotedTweets,\n} from \"./search\";\n\nimport {\n type PollData,\n type Retweeter,\n type Tweet,\n type TweetQuery,\n createCreateLongTweetRequest,\n createCreateNoteTweetRequest,\n createCreateTweetRequest,\n createCreateTweetRequestV2,\n createQuoteTweetRequest,\n defaultOptions,\n deleteTweet,\n fetchListTweets,\n getAllRetweeters,\n getLatestTweet,\n getTweet,\n getTweetV2,\n getTweets,\n getTweetsAndReplies,\n getTweetsAndRepliesByUserId,\n getTweetsByUserId,\n getTweetsV2,\n getTweetsWhere,\n likeTweet,\n retweet,\n getTweetWhere,\n parseTweetV2ToV1,\n} from \"./tweets\";\n\nconst twUrl = \"https://twitter.com\";\n\n/**\n * An alternative fetch function to use instead of the default fetch function. This may be useful\n * in nonstandard runtime environments, such as edge workers.\n *\n * @param {typeof fetch} fetch - The fetch function to use.\n *\n * @param {Partial<FetchTransformOptions>} transform - Additional options that control how requests\n * and responses are processed. This can be used to proxy requests through other hosts, for example.\n */\nexport interface ClientOptions {\n /**\n * An alternative fetch function to use instead of the default fetch function. This may be useful\n * in nonstandard runtime environments, such as edge workers.\n */\n fetch: typeof fetch;\n\n /**\n * Additional options that control how requests and responses are processed. This can be used to\n * proxy requests through other hosts, for example.\n */\n transform: Partial<FetchTransformOptions>;\n}\n\n/**\n * An interface to Twitter's API v2.\n * - Reusing Client objects is recommended to minimize the time spent authenticating unnecessarily.\n */\nexport class Client {\n private auth?: TwitterAuth;\n\n /**\n * Creates a new Client object.\n * - Reusing Client objects is recommended to minimize the time spent authenticating unnecessarily.\n */\n constructor(private readonly options?: Partial<ClientOptions>) {}\n\n /**\n * Fetches a Twitter profile.\n * @param username The Twitter username of the profile to fetch, without an `@` at the beginning.\n * @returns The requested {@link Profile}.\n */\n public async getProfile(username: string): Promise<Profile> {\n const res = await getProfile(username, this.auth);\n return this.handleResponse(res);\n }\n\n /**\n * Fetches the user ID corresponding to the provided screen name.\n * @param screenName The Twitter screen name of the profile to fetch.\n * @returns The ID of the corresponding account.\n */\n public async getEntityIdByScreenName(screenName: string): Promise<string> {\n const res = await getEntityIdByScreenName(screenName, this.auth);\n return this.handleResponse(res);\n }\n\n /**\n *\n * @param userId The user ID of the profile to fetch.\n * @returns The screen name of the corresponding account.\n */\n public async getScreenNameByUserId(userId: string): Promise<string> {\n const response = await getScreenNameByUserId(userId, this.auth);\n return this.handleResponse(response);\n }\n\n /**\n * Fetches tweets from Twitter.\n * @param query The search query. Any Twitter-compatible query format can be used.\n * @param maxTweets The maximum number of tweets to return.\n * @param includeReplies Whether or not replies should be included in the response.\n * @param searchMode The category filter to apply to the search. Defaults to `Top`.\n * @returns An {@link AsyncGenerator} of tweets matching the provided filters.\n */\n public searchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode = SearchMode.Top,\n ): AsyncGenerator<Tweet, void> {\n return searchTweets(query, maxTweets, searchMode, this.auth);\n }\n\n /**\n * Fetches profiles from Twitter.\n * @param query The search query. Any Twitter-compatible query format can be used.\n * @param maxProfiles The maximum number of profiles to return.\n * @returns An {@link AsyncGenerator} of tweets matching the provided filter(s).\n */\n public searchProfiles(\n query: string,\n maxProfiles: number,\n ): AsyncGenerator<Profile, void> {\n return searchProfiles(query, maxProfiles, this.auth);\n }\n\n /**\n * Fetches tweets from Twitter.\n * @param query The search query. Any Twitter-compatible query format can be used.\n * @param maxTweets The maximum number of tweets to return.\n * @param includeReplies Whether or not replies should be included in the response.\n * @param searchMode The category filter to apply to the search. Defaults to `Top`.\n * @param cursor The search cursor, which can be passed into further requests for more results.\n * @returns A page of results, containing a cursor that can be used in further requests.\n */\n public async fetchSearchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n cursor?: string,\n ): Promise<QueryTweetsResponse> {\n // Use the generator and collect results\n const tweets: Tweet[] = [];\n const generator = searchTweets(query, maxTweets, searchMode, this.auth);\n \n for await (const tweet of generator) {\n tweets.push(tweet);\n }\n \n return {\n tweets,\n // v2 API doesn't provide cursor-based pagination for search\n next: undefined,\n };\n }\n\n /**\n * Fetches profiles from Twitter.\n * @param query The search query. Any Twitter-compatible query format can be used.\n * @param maxProfiles The maximum number of profiles to return.\n * @param cursor The search cursor, which can be passed into further requests for more results.\n * @returns A page of results, containing a cursor that can be used in further requests.\n */\n public async fetchSearchProfiles(\n query: string,\n maxProfiles: number,\n cursor?: string,\n ): Promise<QueryProfilesResponse> {\n // Use the generator and collect results\n const profiles: Profile[] = [];\n const generator = searchProfiles(query, maxProfiles, this.auth);\n \n for await (const profile of generator) {\n profiles.push(profile);\n }\n \n return {\n profiles,\n // v2 API doesn't provide cursor-based pagination for search\n next: undefined,\n };\n }\n\n /**\n * Fetches list tweets from Twitter.\n * @param listId The list id\n * @param maxTweets The maximum number of tweets to return.\n * @param cursor The search cursor, which can be passed into further requests for more results.\n * @returns A page of results, containing a cursor that can be used in further requests.\n */\n public fetchListTweets(\n listId: string,\n maxTweets: number,\n cursor?: string,\n ): Promise<QueryTweetsResponse> {\n return fetchListTweets(listId, maxTweets, cursor, this.auth);\n }\n\n /**\n * Fetch the profiles a user is following\n * @param userId The user whose following should be returned\n * @param maxProfiles The maximum number of profiles to return.\n * @returns An {@link AsyncGenerator} of following profiles for the provided user.\n */\n public getFollowing(\n userId: string,\n maxProfiles: number,\n ): AsyncGenerator<Profile, void> {\n return getFollowing(userId, maxProfiles, this.auth);\n }\n\n /**\n * Fetch the profiles that follow a user\n * @param userId The user whose followers should be returned\n * @param maxProfiles The maximum number of profiles to return.\n * @returns An {@link AsyncGenerator} of profiles following the provided user.\n */\n public getFollowers(\n userId: string,\n maxProfiles: number,\n ): AsyncGenerator<Profile, void> {\n return getFollowers(userId, maxProfiles, this.auth);\n }\n\n /**\n * Fetches following profiles from Twitter.\n * @param userId The user whose following should be returned\n * @param maxProfiles The maximum number of profiles to return.\n * @param cursor The search cursor, which can be passed into further requests for more results.\n * @returns A page of results, containing a cursor that can be used in further requests.\n */\n public fetchProfileFollowing(\n userId: string,\n maxProfiles: number,\n cursor?: string,\n ): Promise<QueryProfilesResponse> {\n return fetchProfileFollowing(userId, maxProfiles, this.auth, cursor);\n }\n\n /**\n * Fetches profile followers from Twitter.\n * @param userId The user whose following should be returned\n * @param maxProfiles The maximum number of profiles to return.\n * @param cursor The search cursor, which can be passed into further requests for more results.\n * @returns A page of results, containing a cursor that can be used in further requests.\n */\n public fetchProfileFollowers(\n userId: string,\n maxProfiles: number,\n cursor?: string,\n ): Promise<QueryProfilesResponse> {\n return fetchProfileFollowers(userId, maxProfiles, this.auth, cursor);\n }\n\n /**\n * Fetches the home timeline for the current user using Twitter API v2.\n * Note: Twitter API v2 doesn't distinguish between \"For You\" and \"Following\" feeds.\n * @param count The number of tweets to fetch.\n * @param seenTweetIds An array of tweet IDs that have already been seen (not used in v2).\n * @returns A promise that resolves to an array of tweets.\n */\n public async fetchHomeTimeline(\n count: number,\n seenTweetIds: string[],\n ): Promise<Tweet[]> {\n if (!this.auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = this.auth.getV2Client();\n\n try {\n const timeline = await client.v2.homeTimeline({\n max_results: Math.min(count, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n \"conversation_id\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n });\n\n const tweets: Tweet[] = [];\n for await (const tweet of timeline) {\n tweets.push(parseTweetV2ToV1(tweet, timeline.includes));\n if (tweets.length >= count) break;\n }\n\n return tweets;\n } catch (error) {\n console.error(\"Failed to fetch home timeline:\", error);\n throw error;\n }\n }\n\n /**\n * Fetches the home timeline for the current user (same as fetchHomeTimeline in v2).\n * Twitter API v2 doesn't provide separate \"Following\" timeline endpoint.\n * @param count The number of tweets to fetch.\n * @param seenTweetIds An array of tweet IDs that have already been seen (not used in v2).\n * @returns A promise that resolves to an array of tweets.\n */\n public async fetchFollowingTimeline(\n count: number,\n seenTweetIds: string[],\n ): Promise<Tweet[]> {\n // In v2 API, there's no separate following timeline endpoint\n // Use the same home timeline endpoint\n return this.fetchHomeTimeline(count, seenTweetIds);\n }\n\n async getUserTweets(\n userId: string,\n maxTweets = 200,\n cursor?: string,\n ): Promise<{ tweets: Tweet[]; next?: string }> {\n if (!this.auth) {\n throw new Error(\"Not authenticated\");\n }\n\n const client = this.auth.getV2Client();\n\n try {\n const response = await client.v2.userTimeline(userId, {\n max_results: Math.min(maxTweets, 100),\n \"tweet.fields\": [\n \"id\",\n \"text\",\n \"created_at\",\n \"author_id\",\n \"referenced_tweets\",\n \"entities\",\n \"public_metrics\",\n \"attachments\",\n \"conversation_id\",\n ],\n \"user.fields\": [\"id\", \"name\", \"username\", \"profile_image_url\"],\n \"media.fields\": [\"url\", \"preview_image_url\", \"type\"],\n expansions: [\n \"author_id\",\n \"attachments.media_keys\",\n \"referenced_tweets.id\",\n ],\n pagination_token: cursor,\n });\n\n const tweets: Tweet[] = [];\n for await (const tweet of response) {\n tweets.push(parseTweetV2ToV1(tweet, response.includes));\n if (tweets.length >= maxTweets) break;\n }\n\n return {\n tweets,\n next: response.meta?.next_token,\n };\n } catch (error) {\n console.error(\"Failed to fetch user tweets:\", error);\n throw error;\n }\n }\n\n async *getUserTweetsIterator(\n userId: string,\n maxTweets = 200,\n ): AsyncGenerator<Tweet, void> {\n let cursor: string | undefined;\n let retrievedTweets = 0;\n\n while (retrievedTweets < maxTweets) {\n const response = await this.getUserTweets(\n userId,\n maxTweets - retrievedTweets,\n cursor,\n );\n\n for (const tweet of response.tweets) {\n yield tweet;\n retrievedTweets++;\n if (retrievedTweets >= maxTweets) {\n break;\n }\n }\n\n cursor = response.next;\n\n if (!cursor) {\n break;\n }\n }\n }\n\n /**\n * Fetches the current trends from Twitter.\n * @returns The current list of trends.\n */\n public getTrends(): Promise<string[]> {\n // Trends API not available in Twitter API v2 with current implementation\n console.warn(\"Trends API not available in Twitter API v2\");\n return Promise.resolve([]);\n }\n\n /**\n * Fetches tweets from a Twitter user.\n * @param user The user whose tweets should be returned.\n * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n * @returns An {@link AsyncGenerator} of tweets from the provided user.\n */\n public getTweets(user: string, maxTweets = 200): AsyncGenerator<Tweet> {\n return getTweets(user, maxTweets, this.auth);\n }\n\n /**\n * Fetches tweets from a Twitter user using their ID.\n * @param userId The user whose tweets should be returned.\n * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n * @returns An {@link AsyncGenerator} of tweets from the provided user.\n */\n public getTweetsByUserId(\n userId: string,\n maxTweets = 200,\n ): AsyncGenerator<Tweet, void> {\n return getTweetsByUserId(userId, maxTweets, this.auth);\n }\n\n /**\n * Send a tweet\n * @param text The text of the tweet\n * @param tweetId The id of the tweet to reply to\n * @param mediaData Optional media data\n * @returns\n */\n\n async sendTweet(\n text: string,\n replyToTweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n hideLinkPreview?: boolean,\n ) {\n if (!text || text.trim().length === 0) {\n throw new Error(\"Text is required\");\n }\n if (text.toLowerCase().startsWith(\"error:\")) {\n throw new Error(\"Error sending tweet: \" + text);\n }\n return await createCreateTweetRequest(\n text,\n this.auth,\n replyToTweetId,\n mediaData,\n hideLinkPreview,\n );\n }\n\n async sendNoteTweet(\n text: string,\n replyToTweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n ) {\n if (!text || text.trim().length === 0) {\n throw new Error(\"Text is required\");\n }\n if (text.toLowerCase().startsWith(\"error:\")) {\n throw new Error(\"Error sending note tweet: \" + text);\n }\n return await createCreateNoteTweetRequest(\n text,\n this.auth,\n replyToTweetId,\n mediaData,\n );\n }\n\n /**\n * Send a long tweet (Note Tweet)\n * @param text The text of the tweet\n * @param tweetId The id of the tweet to reply to\n * @param mediaData Optional media data\n * @returns\n */\n async sendLongTweet(\n text: string,\n replyToTweetId?: string,\n mediaData?: { data: Buffer; mediaType: string }[],\n ) {\n return await createCreateLongTweetRequest(\n text,\n this.auth,\n replyToTweetId,\n mediaData,\n );\n }\n\n /**\n * Send a tweet\n * @param text The text of the tweet\n * @param tweetId The id of the tweet to reply to\n * @param options The options for the tweet\n * @returns\n */\n\n async sendTweetV2(\n text: string,\n replyToTweetId?: string,\n options?: {\n poll?: PollData;\n },\n ) {\n return await createCreateTweetRequestV2(\n text,\n this.auth,\n replyToTweetId,\n options,\n );\n }\n\n /**\n * Fetches tweets and replies from a Twitter user.\n * @param user The user whose tweets should be returned.\n * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n * @returns An {@link AsyncGenerator} of tweets from the provided user.\n */\n public getTweetsAndReplies(\n user: string,\n maxTweets = 200,\n ): AsyncGenerator<Tweet> {\n return getTweetsAndReplies(user, maxTweets, this.auth);\n }\n\n /**\n * Fetches tweets and replies from a Twitter user using their ID.\n * @param userId The user whose tweets should be returned.\n * @param maxTweets The maximum number of tweets to return. Defaults to `200`.\n * @returns An {@link AsyncGenerator} of tweets from the provided user.\n */\n public getTweetsAndRepliesByUserId(\n userId: string,\n maxTweets = 200,\n ): AsyncGenerator<Tweet, void> {\n return getTweetsAndRepliesByUserId(userId, maxTweets, this.auth);\n }\n\n /**\n * Fetches the first tweet matching the given query.\n *\n * Example:\n * ```js\n * const timeline = client.getTweets('user', 200);\n * const retweet = await client.getTweetWhere(timeline, { isRetweet: true });\n * ```\n * @param tweets The {@link AsyncIterable} of tweets to search through.\n * @param query A query to test **all** tweets against. This may be either an\n * object of key/value pairs or a predicate. If this query is an object, all\n * key/value pairs must match a {@link Tweet} for it to be returned. If this query\n * is a predicate, it must resolve to `true` for a {@link Tweet} to be returned.\n * - All keys are optional.\n * - If specified, the key must be implemented by that of {@link Tweet}.\n */\n public getTweetWhere(\n tweets: AsyncIterable<Tweet>,\n query: TweetQuery,\n ): Promise<Tweet | null> {\n return getTweetWhere(tweets, query);\n }\n\n /**\n * Fetches all tweets matching the given query.\n *\n * Example:\n * ```js\n * const timeline = client.getTweets('user', 200);\n * const retweets = await client.getTweetsWhere(timeline, { isRetweet: true });\n * ```\n * @param tweets The {@link AsyncIterable} of tweets to search through.\n * @param query A query to test **all** tweets against. This may be either an\n * object of key/value pairs or a predicate. If this query is an object, all\n * key/value pairs must match a {@link Tweet} for it to be returned. If this query\n * is a predicate, it must resolve to `true` for a {@link Tweet} to be returned.\n * - All keys are optional.\n * - If specified, the key must be implemented by that of {@link Tweet}.\n */\n public getTweetsWhere(\n tweets: AsyncIterable<Tweet>,\n query: TweetQuery,\n ): Promise<Tweet[]> {\n return getTweetsWhere(tweets, query);\n }\n\n /**\n * Fetches the most recent tweet from a Twitter user.\n * @param user The user whose latest tweet should be returned.\n * @param includeRetweets Whether or not to include retweets. Defaults to `false`.\n * @returns The {@link Tweet} object or `null`/`undefined` if it couldn't be fetched.\n */\n public getLatestTweet(\n user: string,\n includeRetweets = false,\n max = 200,\n ): Promise<Tweet | null | undefined> {\n return getLatestTweet(user, includeRetweets, max, this.auth);\n }\n\n /**\n * Fetches a single tweet.\n * @param id The ID of the tweet to fetch.\n * @returns The {@link Tweet} object, or `null` if it couldn't be fetched.\n */\n public getTweet(id: string): Promise<Tweet | null> {\n return getTweet(id, this.auth);\n }\n\n /**\n * Fetches a single tweet by ID using the Twitter API v2.\n * Allows specifying optional expansions and fields for more detailed data.\n *\n * @param {string} id - The ID of the tweet to fetch.\n * @param {Object} [options] - Optional parameters to customize the tweet data.\n * @param {string[]} [options.expansions] - Array of expansions to include, e.g., 'attachments.poll_ids'.\n * @param {string[]} [options.tweetFields] - Array of tweet fields to include, e.g., 'created_at', 'public_metrics'.\n * @param {string[]} [options.pollFields] - Array of poll fields to include, if the tweet has a poll, e.g., 'options', 'end_datetime'.\n * @param {string[]} [options.mediaFields] - Array of media fields to include, if the tweet includes media, e.g., 'url', 'preview_image_url'.\n * @param {string[]} [options.userFields] - Array of user fields to include, if user information is requested, e.g., 'username', 'verified'.\n * @param {string[]} [options.placeFields] - Array of place fields to include, if the tweet includes location data, e.g., 'full_name', 'country'.\n * @returns {Promise<TweetV2 | null>} - The tweet data, including requested expansions and fields.\n */\n async getTweetV2(\n id: string,\n options: {\n expansions?: TTweetv2Expansion[];\n tweetFields?: TTweetv2TweetField[];\n pollFields?: TTweetv2PollField[];\n mediaFields?: TTweetv2MediaField[];\n userFields?: TTweetv2UserField[];\n placeFields?: TTweetv2PlaceField[];\n } = defaultOptions,\n ): Promise<Tweet | null> {\n return await getTweetV2(id, this.auth, options);\n }\n\n /**\n * Fetches multiple tweets by IDs using the Twitter API v2.\n * Allows specifying optional expansions and fields for more detailed data.\n *\n * @param {string[]} ids - Array of tweet IDs to fetch.\n * @param {Object} [options] - Optional parameters to customize the tweet data.\n * @param {string[]} [options.expansions] - Array of expansions to include, e.g., 'attachments.poll_ids'.\n * @param {string[]} [options.tweetFields] - Array of tweet fields to include, e.g., 'created_at', 'public_metrics'.\n * @param {string[]} [options.pollFields] - Array of poll fields to include, if tweets contain polls, e.g., 'options', 'end_datetime'.\n * @param {string[]} [options.mediaFields] - Array of media fields to include, if tweets contain media, e.g., 'url', 'preview_image_url'.\n * @param {string[]} [options.userFields] - Array of user fields to include, if user information is requested, e.g., 'username', 'verified'.\n * @param {string[]} [options.placeFields] - Array of place fields to include, if tweets contain location data, e.g., 'full_name', 'country'.\n * @returns {Promise<TweetV2[]> } - Array of tweet data, including requested expansions and fields.\n */\n async getTweetsV2(\n ids: string[],\n options: {\n expansions?: TTweetv2Expansion[];\n tweetFields?: TTweetv2TweetField[];\n pollFields?: TTweetv2PollField[];\n mediaFields?: TTweetv2MediaField[];\n userFields?: TTweetv2UserField[];\n placeFields?: TTweetv2PlaceField[];\n } = defaultOptions,\n ): Promise<Tweet[]> {\n return await getTweetsV2(ids, this.auth, options);\n }\n\n /**\n * Updates the authentication state for the client.\n * @param auth The new authentication.\n */\n public updateAuth(auth: TwitterAuth) {\n this.auth = auth;\n }\n\n /**\n * Get current authentication credentials\n * @returns {TwitterAuth | null} Current authentication or null if not authenticated\n */\n public getAuth(): TwitterAuth | null {\n return this.auth;\n }\n\n /**\n * Check if client is properly authenticated with Twitter API v2 credentials\n * @returns {boolean} True if authenticated\n */\n public isAuthenticated(): boolean {\n if (!this.auth) return false;\n return this.auth.hasToken();\n }\n\n /**\n * Returns if the client is logged in as a real user.\n * @returns `true` if the client is logged in with a real user account; otherwise `false`.\n */\n public async isLoggedIn(): Promise<boolean> {\n return await this.auth.isLoggedIn();\n }\n\n /**\n * Returns the currently logged in user\n * @returns The currently logged in user\n */\n public async me(): Promise<Profile | undefined> {\n return this.auth.me();\n }\n\n /**\n * Login to Twitter using API v2 credentials only.\n * @param appKey The API key\n * @param appSecret The API secret key\n * @param accessToken The access token\n * @param accessSecret The access token secret\n */\n public async login(\n username: string,\n password: string,\n email?: string,\n twoFactorSecret?: string,\n appKey?: string,\n appSecret?: string,\n accessToken?: string,\n accessSecret?: string,\n ): Promise<void> {\n // Only use API credentials for v2 authentication\n if (!appKey || !appSecret || !accessToken || !accessSecret) {\n throw new Error(\n \"Twitter API v2 credentials are required for authentication\",\n );\n }\n\n this.auth = new TwitterAuth(appKey, appSecret, accessToken, accessSecret);\n }\n\n /**\n * Log out of Twitter.\n * Note: With API v2, logout is not applicable as we use API credentials.\n */\n public async logout(): Promise<void> {\n // With API v2 credentials, there's no logout process\n console.warn(\n \"Logout is not applicable when using Twitter API v2 credentials\",\n );\n }\n\n\n\n /**\n * Sends a quote tweet.\n * @param text The text of the tweet.\n * @param quotedTweetId The ID of the tweet to quote.\n * @param options Optional parameters, such as media data.\n * @returns The response from the Twitter API.\n */\n public async sendQuoteTweet(\n text: string,\n quotedTweetId: string,\n options?: {\n mediaData: { data: Buffer; mediaType: string }[];\n },\n ) {\n return await createQuoteTweetRequest(\n text,\n quotedTweetId,\n this.auth,\n options?.mediaData,\n );\n }\n\n /**\n * Delete a tweet with the given ID.\n * @param tweetId The ID of the tweet to delete.\n * @returns A promise that resolves when the tweet is deleted.\n */\n public async deleteTweet(tweetId: string): Promise<any> {\n // Call the deleteTweet function from tweets.ts\n return await deleteTweet(tweetId, this.auth);\n }\n\n /**\n * Likes a tweet with the given tweet ID.\n * @param tweetId The ID of the tweet to like.\n * @returns A promise that resolves when the tweet is liked.\n */\n public async likeTweet(tweetId: string): Promise<void> {\n // Call the likeTweet function from tweets.ts\n await likeTweet(tweetId, this.auth);\n }\n\n /**\n * Retweets a tweet with the given tweet ID.\n * @param tweetId The ID of the tweet to retweet.\n * @returns A promise that resolves when the tweet is retweeted.\n */\n public async retweet(tweetId: string): Promise<void> {\n // Call the retweet function from tweets.ts\n await retweet(tweetId, this.auth);\n }\n\n /**\n * Follows a user with the given user ID.\n * @param userId The user ID of the user to follow.\n * @returns A promise that resolves when the user is followed.\n */\n public async followUser(userName: string): Promise<void> {\n // Call the followUser function from relationships.ts\n await followUser(userName, this.auth);\n }\n\n /**\n * Fetches direct message conversations\n * Note: This functionality requires additional permissions and is not implemented in the current Twitter API v2 wrapper\n * @param userId User ID\n * @param cursor Pagination cursor\n * @returns Array of DM conversations\n */\n public async getDirectMessageConversations(\n userId: string,\n cursor?: string,\n ): Promise<any> {\n console.warn(\n \"Direct message conversations not implemented for Twitter API v2\",\n );\n return { conversations: [] };\n }\n\n /**\n * Sends a direct message to a user.\n * Note: This functionality requires additional permissions and is not implemented in the current Twitter API v2 wrapper\n * @param conversationId The ID of the conversation\n * @param text The text of the message\n * @returns The response from the Twitter API\n */\n public async sendDirectMessage(\n conversationId: string,\n text: string,\n ): Promise<any> {\n console.warn(\"Sending direct messages not implemented for Twitter API v2\");\n throw new Error(\"Direct message sending not implemented\");\n }\n\n private getAuthOptions(): Partial<{ fetch?: typeof fetch; transform?: any }> {\n return {\n fetch: this.options?.fetch,\n transform: this.options?.transform,\n };\n }\n\n private handleResponse<T>(res: RequestApiResult<T>): T {\n if (!res.success) {\n throw (res as any).err;\n }\n\n return res.value;\n }\n\n\n\n /**\n * Retrieves all users who retweeted the given tweet.\n * @param tweetId The ID of the tweet.\n * @returns An array of users (retweeters).\n */\n public async getRetweetersOfTweet(tweetId: string): Promise<Retweeter[]> {\n return await getAllRetweeters(tweetId, this.auth);\n }\n\n /**\n * Fetches all quoted tweets for a given tweet ID, handling pagination automatically.\n * @param tweetId The ID of the tweet to fetch quotes for.\n * @param maxQuotes Maximum number of quotes to return (default: 100).\n * @returns An array of all quoted tweets.\n */\n public async fetchAllQuotedTweets(\n tweetId: string,\n maxQuotes: number = 100,\n ): Promise<Tweet[]> {\n const allQuotes: Tweet[] = [];\n\n try {\n let cursor: string | undefined;\n let totalFetched = 0;\n\n while (totalFetched < maxQuotes) {\n const batchSize = Math.min(40, maxQuotes - totalFetched);\n const page = await this.fetchQuotedTweetsPage(\n tweetId,\n batchSize,\n cursor,\n );\n\n if (!page.tweets || page.tweets.length === 0) {\n break;\n }\n\n allQuotes.push(...page.tweets);\n totalFetched += page.tweets.length;\n\n // Check if there's a next page\n if (!page.next) {\n break;\n }\n\n cursor = page.next;\n }\n\n return allQuotes.slice(0, maxQuotes);\n } catch (error) {\n console.error(\"Error fetching quoted tweets:\", error);\n throw error;\n }\n }\n\n /**\n * Fetches quoted tweets for a given tweet ID.\n * This method now uses a generator function internally but maintains backward compatibility.\n * @param tweetId The ID of the tweet to fetch quotes for.\n * @param maxQuotes Maximum number of quotes to return.\n * @param cursor Optional cursor for pagination.\n * @returns A promise that resolves to a QueryTweetsResponse containing tweets and the next cursor.\n */\n public async fetchQuotedTweetsPage(\n tweetId: string,\n maxQuotes: number = 40,\n cursor?: string,\n ): Promise<QueryTweetsResponse> {\n // For backward compatibility, collect quotes from the generator\n const quotes: Tweet[] = [];\n let count = 0;\n\n // searchQuotedTweets doesn't support cursor, so we'll collect all quotes up to maxQuotes\n for await (const quote of searchQuotedTweets(\n tweetId,\n maxQuotes,\n this.auth,\n )) {\n quotes.push(quote);\n count++;\n if (count >= maxQuotes) break;\n }\n\n return {\n tweets: quotes,\n next: undefined, // Twitter API v2 doesn't provide cursor for quote search\n };\n }\n}\n","import fs from \"node:fs\";\nimport path from \"node:path\";\nimport type { Media } from \"@elizaos/core\";\nimport {\n type Content,\n type Memory,\n type UUID,\n createUniqueUuid,\n logger,\n truncateToCompleteSentence,\n} from \"@elizaos/core\";\nimport type { ClientBase } from \"./base\";\nimport type { Tweet } from \"./client\";\n\nimport type { ActionResponse, MediaData } from \"./types\";\nimport { TWEET_MAX_LENGTH } from \"./constants\";\n\nexport const wait = (minTime = 1000, maxTime = 3000) => {\n const waitTime =\n Math.floor(Math.random() * (maxTime - minTime + 1)) + minTime;\n return new Promise((resolve) => setTimeout(resolve, waitTime));\n};\n\nexport const isValidTweet = (tweet: Tweet): boolean => {\n // Filter out tweets with too many hashtags, @s, or $ signs, probably spam or garbage\n const hashtagCount = (tweet.text?.match(/#/g) || []).length;\n const atCount = (tweet.text?.match(/@/g) || []).length;\n const dollarSignCount = (tweet.text?.match(/\\$/g) || []).length;\n const totalCount = hashtagCount + atCount + dollarSignCount;\n\n return (\n hashtagCount <= 1 && atCount <= 2 && dollarSignCount <= 1 && totalCount <= 3\n );\n};\n\n/**\n * Fetches media data from a list of attachments, supporting both HTTP URLs and local file paths.\n *\n * @param attachments Array of Media objects containing URLs or file paths to fetch media from\n * @returns Promise that resolves with an array of MediaData objects containing the fetched media data and content type\n */\nexport async function fetchMediaData(\n attachments: Media[],\n): Promise<MediaData[]> {\n return Promise.all(\n attachments.map(async (attachment: Media) => {\n if (/^(http|https):\\/\\//.test(attachment.url)) {\n // Handle HTTP URLs\n const response = await fetch(attachment.url);\n if (!response.ok) {\n throw new Error(`Failed to fetch file: ${attachment.url}`);\n }\n const mediaBuffer = Buffer.from(await response.arrayBuffer());\n const mediaType = attachment.contentType || \"image/png\";\n return { data: mediaBuffer, mediaType };\n }\n if (fs.existsSync(attachment.url)) {\n // Handle local file paths\n const mediaBuffer = await fs.promises.readFile(\n path.resolve(attachment.url),\n );\n const mediaType = attachment.contentType || \"image/png\";\n return { data: mediaBuffer, mediaType };\n }\n throw new Error(\n `File not found: ${attachment.url}. Make sure the path is correct.`,\n );\n }),\n );\n}\n\n/**\n * Handles sending a note tweet with optional media data.\n *\n * @param {ClientBase} client - The client object used for sending the note tweet.\n * @param {string} content - The content of the note tweet.\n * @param {string} [tweetId] - Optional Tweet ID to reply to.\n * @param {MediaData[]} [mediaData] - Optional media data to attach to the note tweet.\n * @returns {Promise<Object>} - The result of the note tweet operation.\n * @throws {Error} - If the note tweet operation fails.\n */\nasync function handleNoteTweet(\n client: ClientBase,\n content: string,\n tweetId?: string,\n mediaData?: MediaData[],\n) {\n // Twitter API v2 handles long tweets automatically\n // Just use the regular sendTweet method\n const result = await client.twitterClient.sendTweet(\n content,\n tweetId,\n mediaData,\n );\n\n // Check if the result was successful\n if (!result || !result.ok) {\n // Tweet failed. Falling back to truncated Tweet.\n const truncateContent = truncateToCompleteSentence(\n content,\n TWEET_MAX_LENGTH,\n );\n return await sendStandardTweet(client, truncateContent, tweetId);\n }\n\n // Return the result directly\n return result;\n}\n\n/**\n * Send a standard tweet through the client\n */\nexport async function sendStandardTweet(\n client: ClientBase,\n content: string,\n tweetId?: string,\n mediaData?: MediaData[],\n) {\n const standardTweetResult = await client.twitterClient.sendTweet(\n content,\n tweetId,\n mediaData,\n );\n\n // The result is already the response object\n return standardTweetResult;\n}\n\nexport async function sendTweet(\n client: ClientBase,\n text: string,\n mediaData: MediaData[] = [],\n tweetToReplyTo?: string,\n): Promise<any> {\n const isNoteTweet = text.length > TWEET_MAX_LENGTH;\n const postText = isNoteTweet\n ? truncateToCompleteSentence(text, TWEET_MAX_LENGTH)\n : text;\n\n let result;\n\n try {\n result = await client.twitterClient.sendTweet(\n postText,\n tweetToReplyTo,\n mediaData,\n );\n logger.log(\"Successfully posted Tweet\");\n } catch (error) {\n logger.error(\"Error posting Tweet:\", error);\n throw error;\n }\n\n try {\n // The result from sendTweet should have the tweet data\n const tweetData = result?.data || result;\n\n // Extract the tweet ID and other data\n const tweetResult = tweetData?.data || tweetData;\n\n // if we have a response\n if (tweetResult && tweetResult.id) {\n if (client.lastCheckedTweetId < BigInt(tweetResult.id)) {\n client.lastCheckedTweetId = BigInt(tweetResult.id);\n }\n await client.cacheLatestCheckedTweetId();\n\n // Cache the tweet\n await client.cacheTweet(tweetResult);\n\n logger.log(\"Successfully posted a tweet\", tweetResult.id);\n\n return tweetResult;\n }\n } catch (error) {\n logger.error(\"Error parsing tweet response:\", error);\n throw error;\n }\n\n logger.error(\"No valid response from Twitter API\");\n throw new Error(\"Failed to send tweet - no valid response\");\n}\n\n/**\n * Sends a tweet on Twitter using the given client.\n *\n * @param {ClientBase} client The client used to send the tweet.\n * @param {Content} content The content of the tweet.\n * @param {UUID} roomId The ID of the room where the tweet will be sent.\n * @param {string} twitterUsername The Twitter username of the sender.\n * @param {string} inReplyTo The ID of the tweet to which the new tweet will reply.\n * @returns {Promise<Memory[]>} An array of memories representing the sent tweets.\n */\nexport async function sendChunkedTweet(\n client: ClientBase,\n content: Content,\n roomId: UUID,\n twitterUsername: string,\n inReplyTo: string,\n): Promise<Memory[]> {\n const messages: Memory[] = [];\n const chunks = splitTweetContent(content.text, TWEET_MAX_LENGTH);\n\n let previousTweetId = inReplyTo;\n\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n const isLastChunk = i === chunks.length - 1;\n\n // Add the tweet number to the beginning of each chunk\n const tweetContent = `${chunk}`;\n\n logger.debug(`Sending tweet ${i + 1}/${chunks.length}: ${tweetContent}`);\n\n try {\n // Convert Media[] to MediaData[] if needed\n let mediaData: MediaData[] = [];\n if (content.attachments && content.attachments.length > 0) {\n mediaData = await fetchMediaData(content.attachments);\n }\n\n const result = await sendTweet(\n client,\n tweetContent,\n mediaData,\n previousTweetId,\n );\n\n const body = typeof result === \"object\" ? result : await result.json();\n\n // Twitter API v2 response format\n const tweetResult = body?.data || body;\n\n // if we have a response\n if (tweetResult && tweetResult.id) {\n const tweetId = tweetResult.id;\n const permanentUrl = `https://x.com/${twitterUsername}/status/${tweetId}`;\n\n const memory: Memory = {\n id: createUniqueUuid(client.runtime, tweetId),\n entityId: client.runtime.agentId,\n content: {\n text: chunk,\n url: permanentUrl,\n source: \"twitter\",\n },\n agentId: client.runtime.agentId,\n roomId,\n createdAt: Date.now(),\n };\n\n messages.push(memory);\n previousTweetId = tweetId;\n }\n } catch (error) {\n logger.error(`Error sending chunk ${i + 1}:`, error);\n throw error;\n }\n }\n\n return messages;\n}\n\n/**\n * Splits the given content into individual tweets based on the maximum length allowed for a tweet.\n * @param {string} content - The content to split into tweets.\n * @param {number} maxLength - The maximum length allowed for a single tweet.\n * @returns {string[]} An array of strings representing individual tweets.\n */\nfunction splitTweetContent(content: string, maxLength: number): string[] {\n const paragraphs = content.split(\"\\n\\n\").map((p) => p.trim());\n const tweets: string[] = [];\n let currentTweet = \"\";\n\n for (const paragraph of paragraphs) {\n if (!paragraph) continue;\n\n if (`${currentTweet}\\n\\n${paragraph}`.trim().length <= maxLength) {\n if (currentTweet) {\n currentTweet += `\\n\\n${paragraph}`;\n } else {\n currentTweet = paragraph;\n }\n } else {\n if (currentTweet) {\n tweets.push(currentTweet.trim());\n }\n if (paragraph.length <= maxLength) {\n currentTweet = paragraph;\n } else {\n // Split long paragraph into smaller chunks\n const chunks = splitParagraph(paragraph, maxLength);\n tweets.push(...chunks.slice(0, -1));\n currentTweet = chunks[chunks.length - 1];\n }\n }\n }\n\n if (currentTweet) {\n tweets.push(currentTweet.trim());\n }\n\n return tweets;\n}\n\n/**\n * Extracts URLs from a given paragraph and replaces them with placeholders.\n *\n * @param {string} paragraph - The paragraph containing URLs that need to be replaced\n * @returns {Object} An object containing the updated text with placeholders and a map of placeholders to original URLs\n */\nfunction extractUrls(paragraph: string): {\n textWithPlaceholders: string;\n placeholderMap: Map<string, string>;\n} {\n // replace https urls with placeholder\n const urlRegex = /https?:\\/\\/[^\\s]+/g;\n const placeholderMap = new Map<string, string>();\n\n let urlIndex = 0;\n const textWithPlaceholders = paragraph.replace(urlRegex, (match) => {\n // twitter url would be considered as 23 characters\n // <<URL_CONSIDERER_23_1>> is also 23 characters\n const placeholder = `<<URL_CONSIDERER_23_${urlIndex}>>`; // Placeholder without . ? ! etc\n placeholderMap.set(placeholder, match);\n urlIndex++;\n return placeholder;\n });\n\n return { textWithPlaceholders, placeholderMap };\n}\n\n/**\n * Splits a given text into chunks based on the specified maximum length while preserving sentence boundaries.\n *\n * @param {string} text - The text to be split into chunks\n * @param {number} maxLength - The maximum length each chunk should not exceed\n *\n * @returns {string[]} An array of chunks where each chunk is within the specified maximum length\n */\nfunction splitSentencesAndWords(text: string, maxLength: number): string[] {\n // Split by periods, question marks and exclamation marks\n // Note that URLs in text have been replaced with `<<URL_xxx>>` and won't be split by dots\n const sentences = text.match(/[^.!?]+[.!?]+|[^.!?]+$/g) || [text];\n const chunks: string[] = [];\n let currentChunk = \"\";\n\n for (const sentence of sentences) {\n if (`${currentChunk} ${sentence}`.trim().length <= maxLength) {\n if (currentChunk) {\n currentChunk += ` ${sentence}`;\n } else {\n currentChunk = sentence;\n }\n } else {\n // Can't fit more, push currentChunk to results\n if (currentChunk) {\n chunks.push(currentChunk.trim());\n }\n\n // If current sentence itself is less than or equal to maxLength\n if (sentence.length <= maxLength) {\n currentChunk = sentence;\n } else {\n // Need to split sentence by spaces\n const words = sentence.split(\" \");\n currentChunk = \"\";\n for (const word of words) {\n if (`${currentChunk} ${word}`.trim().length <= maxLength) {\n if (currentChunk) {\n currentChunk += ` ${word}`;\n } else {\n currentChunk = word;\n }\n } else {\n if (currentChunk) {\n chunks.push(currentChunk.trim());\n }\n currentChunk = word;\n }\n }\n }\n }\n }\n\n // Handle remaining content\n if (currentChunk) {\n chunks.push(currentChunk.trim());\n }\n\n return chunks;\n}\n\n/**\n * Deduplicates mentions at the beginning of a paragraph.\n *\n * @param {string} paragraph - The input paragraph containing mentions.\n * @returns {string} - The paragraph with deduplicated mentions.\n */\nfunction deduplicateMentions(paragraph: string) {\n // Regex to match mentions at the beginning of the string\n const mentionRegex = /^@(\\w+)(?:\\s+@(\\w+))*(\\s+|$)/;\n\n // Find all matches\n const matches = paragraph.match(mentionRegex);\n\n if (!matches) {\n return paragraph; // If no matches, return the original string\n }\n\n // Extract mentions from the match groups\n let mentions = matches.slice(0, 1)[0].trim().split(\" \");\n\n // Deduplicate mentions\n mentions = Array.from(new Set(mentions));\n\n // Reconstruct the string with deduplicated mentions\n const uniqueMentionsString = mentions.join(\" \");\n\n // Find where the mentions end in the original string\n const endOfMentions = paragraph.indexOf(matches[0]) + matches[0].length;\n\n // Construct the result by combining unique mentions with the rest of the string\n return `${uniqueMentionsString} ${paragraph.slice(endOfMentions)}`;\n}\n\n/**\n * Restores the original URLs in the chunks by replacing placeholder URLs.\n *\n * @param {string[]} chunks - Array of strings representing chunks of text containing placeholder URLs.\n * @param {Map<string, string>} placeholderMap - Map with placeholder URLs as keys and original URLs as values.\n * @returns {string[]} - Array of strings with original URLs restored in each chunk.\n */\nfunction restoreUrls(\n chunks: string[],\n placeholderMap: Map<string, string>,\n): string[] {\n return chunks.map((chunk) => {\n // Replace all <<URL_CONSIDERER_23_>> in chunk back to original URLs using regex\n return chunk.replace(/<<URL_CONSIDERER_23_(\\d+)>>/g, (match) => {\n const original = placeholderMap.get(match);\n return original || match; // Return placeholder if not found (theoretically won't happen)\n });\n });\n}\n\n/**\n * Splits a paragraph into chunks of text with a maximum length, while preserving URLs.\n *\n * @param {string} paragraph - The paragraph to split.\n * @param {number} maxLength - The maximum length of each chunk.\n * @returns {string[]} An array of strings representing the splitted chunks of text.\n */\nfunction splitParagraph(paragraph: string, maxLength: number): string[] {\n // 1) Extract URLs and replace with placeholders\n const { textWithPlaceholders, placeholderMap } = extractUrls(paragraph);\n\n // 2) Use first section's logic to split by sentences first, then do secondary split\n const splittedChunks = splitSentencesAndWords(\n textWithPlaceholders,\n maxLength,\n );\n\n // 3) Replace placeholders back to original URLs\n const restoredChunks = restoreUrls(splittedChunks, placeholderMap);\n\n return restoredChunks;\n}\n\n/**\n * Parses the action response from the given text.\n *\n * @param {string} text - The text to parse actions from.\n * @returns {{ actions: ActionResponse }} The parsed actions with boolean values indicating if each action is present in the text.\n */\nexport const parseActionResponseFromText = (\n text: string,\n): { actions: ActionResponse } => {\n const actions: ActionResponse = {\n like: false,\n retweet: false,\n quote: false,\n reply: false,\n };\n\n // Regex patterns\n const likePattern = /\\[LIKE\\]/i;\n const retweetPattern = /\\[RETWEET\\]/i;\n const quotePattern = /\\[QUOTE\\]/i;\n const replyPattern = /\\[REPLY\\]/i;\n\n // Check with regex\n actions.like = likePattern.test(text);\n actions.retweet = retweetPattern.test(text);\n actions.quote = quotePattern.test(text);\n actions.reply = replyPattern.test(text);\n\n // Also do line by line parsing as backup\n const lines = text.split(\"\\n\");\n for (const line of lines) {\n const trimmed = line.trim();\n if (trimmed === \"[LIKE]\") actions.like = true;\n if (trimmed === \"[RETWEET]\") actions.retweet = true;\n if (trimmed === \"[QUOTE]\") actions.quote = true;\n if (trimmed === \"[REPLY]\") actions.reply = true;\n }\n\n return { actions };\n};\n\n// Export error handler utilities\nexport * from \"./utils/error-handler\";\n","export const TWITTER_SERVICE_NAME = \"twitter\";\nexport const TWEET_CHAR_LIMIT = 280;\nexport const TWEET_MAX_LENGTH = 4000; // Twitter API v2 supports longer tweets\n","import { logger } from \"@elizaos/core\";\n\nexport enum TwitterErrorType {\n AUTH = \"AUTH\",\n RATE_LIMIT = \"RATE_LIMIT\",\n API = \"API\",\n NETWORK = \"NETWORK\",\n MEDIA = \"MEDIA\",\n VALIDATION = \"VALIDATION\",\n UNKNOWN = \"UNKNOWN\",\n}\n\nexport class TwitterError extends Error {\n constructor(\n public type: TwitterErrorType,\n message: string,\n public originalError?: any,\n public details?: Record<string, any>\n ) {\n super(message);\n this.name = \"TwitterError\";\n }\n}\n\nexport function getErrorType(error: any): TwitterErrorType {\n const message = error?.message?.toLowerCase() || \"\";\n const code = error?.code || error?.response?.status;\n\n if (code === 401 || message.includes(\"unauthorized\") || message.includes(\"authentication\")) {\n return TwitterErrorType.AUTH;\n }\n\n if (code === 429 || message.includes(\"rate limit\") || message.includes(\"too many requests\")) {\n return TwitterErrorType.RATE_LIMIT;\n }\n\n if (message.includes(\"network\") || message.includes(\"timeout\") || message.includes(\"econnrefused\")) {\n return TwitterErrorType.NETWORK;\n }\n\n if (message.includes(\"media\") || message.includes(\"upload\")) {\n return TwitterErrorType.MEDIA;\n }\n\n if (message.includes(\"invalid\") || message.includes(\"missing\") || message.includes(\"required\")) {\n return TwitterErrorType.VALIDATION;\n }\n\n if (code >= 400 && code < 500) {\n return TwitterErrorType.API;\n }\n\n return TwitterErrorType.UNKNOWN;\n}\n\nexport function handleTwitterError(\n context: string,\n error: any,\n throwError = false\n): TwitterError | null {\n const errorType = getErrorType(error);\n const errorMessage = error?.message || String(error);\n \n const twitterError = new TwitterError(\n errorType,\n `${context}: ${errorMessage}`,\n error,\n {\n context,\n timestamp: new Date().toISOString(),\n ...(error?.response && { response: error.response }),\n }\n );\n\n // Log based on error type\n switch (errorType) {\n case TwitterErrorType.AUTH:\n logger.error(`[Twitter Auth Error] ${context}:`, errorMessage);\n break;\n case TwitterErrorType.RATE_LIMIT:\n logger.warn(`[Twitter Rate Limit] ${context}:`, errorMessage);\n break;\n case TwitterErrorType.NETWORK:\n logger.warn(`[Twitter Network Error] ${context}:`, errorMessage);\n break;\n default:\n logger.error(`[Twitter Error] ${context}:`, errorMessage);\n }\n\n if (throwError) {\n throw twitterError;\n }\n\n return twitterError;\n}\n\nexport function isRetryableError(error: TwitterError | any): boolean {\n if (error instanceof TwitterError) {\n return [\n TwitterErrorType.RATE_LIMIT,\n TwitterErrorType.NETWORK,\n ].includes(error.type);\n }\n\n const errorType = getErrorType(error);\n return [\n TwitterErrorType.RATE_LIMIT,\n TwitterErrorType.NETWORK,\n ].includes(errorType);\n}\n\nexport function getRetryDelay(error: TwitterError | any, attempt: number): number {\n const baseDelay = 1000; // 1 second\n const maxDelay = 60000; // 60 seconds\n\n if (error instanceof TwitterError || getErrorType(error) === TwitterErrorType.RATE_LIMIT) {\n // For rate limits, use longer delays\n return Math.min(baseDelay * Math.pow(2, attempt) * 5, maxDelay);\n }\n\n // Exponential backoff for other errors\n return Math.min(baseDelay * Math.pow(2, attempt), maxDelay);\n} ","export * from \"./errors.js\";\nexport * from \"./helpers/parseUtil.js\";\nexport * from \"./helpers/typeAliases.js\";\nexport * from \"./helpers/util.js\";\nexport * from \"./types.js\";\nexport * from \"./ZodError.js\";\n","export var util;\n(function (util) {\n util.assertEqual = (_) => { };\n function assertIs(_arg) { }\n util.assertIs = assertIs;\n function assertNever(_x) {\n throw new Error();\n }\n util.assertNever = assertNever;\n util.arrayToEnum = (items) => {\n const obj = {};\n for (const item of items) {\n obj[item] = item;\n }\n return obj;\n };\n util.getValidEnumValues = (obj) => {\n const validKeys = util.objectKeys(obj).filter((k) => typeof obj[obj[k]] !== \"number\");\n const filtered = {};\n for (const k of validKeys) {\n filtered[k] = obj[k];\n }\n return util.objectValues(filtered);\n };\n util.objectValues = (obj) => {\n return util.objectKeys(obj).map(function (e) {\n return obj[e];\n });\n };\n util.objectKeys = typeof Object.keys === \"function\" // eslint-disable-line ban/ban\n ? (obj) => Object.keys(obj) // eslint-disable-line ban/ban\n : (object) => {\n const keys = [];\n for (const key in object) {\n if (Object.prototype.hasOwnProperty.call(object, key)) {\n keys.push(key);\n }\n }\n return keys;\n };\n util.find = (arr, checker) => {\n for (const item of arr) {\n if (checker(item))\n return item;\n }\n return undefined;\n };\n util.isInteger = typeof Number.isInteger === \"function\"\n ? (val) => Number.isInteger(val) // eslint-disable-line ban/ban\n : (val) => typeof val === \"number\" && Number.isFinite(val) && Math.floor(val) === val;\n function joinValues(array, separator = \" | \") {\n return array.map((val) => (typeof val === \"string\" ? `'${val}'` : val)).join(separator);\n }\n util.joinValues = joinValues;\n util.jsonStringifyReplacer = (_, value) => {\n if (typeof value === \"bigint\") {\n return value.toString();\n }\n return value;\n };\n})(util || (util = {}));\nexport var objectUtil;\n(function (objectUtil) {\n objectUtil.mergeShapes = (first, second) => {\n return {\n ...first,\n ...second, // second overwrites first\n };\n };\n})(objectUtil || (objectUtil = {}));\nexport const ZodParsedType = util.arrayToEnum([\n \"string\",\n \"nan\",\n \"number\",\n \"integer\",\n \"float\",\n \"boolean\",\n \"date\",\n \"bigint\",\n \"symbol\",\n \"function\",\n \"undefined\",\n \"null\",\n \"array\",\n \"object\",\n \"unknown\",\n \"promise\",\n \"void\",\n \"never\",\n \"map\",\n \"set\",\n]);\nexport const getParsedType = (data) => {\n const t = typeof data;\n switch (t) {\n case \"undefined\":\n return ZodParsedType.undefined;\n case \"string\":\n return ZodParsedType.string;\n case \"number\":\n return Number.isNaN(data) ? ZodParsedType.nan : ZodParsedType.number;\n case \"boolean\":\n return ZodParsedType.boolean;\n case \"function\":\n return ZodParsedType.function;\n case \"bigint\":\n return ZodParsedType.bigint;\n case \"symbol\":\n return ZodParsedType.symbol;\n case \"object\":\n if (Array.isArray(data)) {\n return ZodParsedType.array;\n }\n if (data === null) {\n return ZodParsedType.null;\n }\n if (data.then && typeof data.then === \"function\" && data.catch && typeof data.catch === \"function\") {\n return ZodParsedType.promise;\n }\n if (typeof Map !== \"undefined\" && data instanceof Map) {\n return ZodParsedType.map;\n }\n if (typeof Set !== \"undefined\" && data instanceof Set) {\n return ZodParsedType.set;\n }\n if (typeof Date !== \"undefined\" && data instanceof Date) {\n return ZodParsedType.date;\n }\n return ZodParsedType.object;\n default:\n return ZodParsedType.unknown;\n }\n};\n","import { util } from \"./helpers/util.js\";\nexport const ZodIssueCode = util.arrayToEnum([\n \"invalid_type\",\n \"invalid_literal\",\n \"custom\",\n \"invalid_union\",\n \"invalid_union_discriminator\",\n \"invalid_enum_value\",\n \"unrecognized_keys\",\n \"invalid_arguments\",\n \"invalid_return_type\",\n \"invalid_date\",\n \"invalid_string\",\n \"too_small\",\n \"too_big\",\n \"invalid_intersection_types\",\n \"not_multiple_of\",\n \"not_finite\",\n]);\nexport const quotelessJson = (obj) => {\n const json = JSON.stringify(obj, null, 2);\n return json.replace(/\"([^\"]+)\":/g, \"$1:\");\n};\nexport class ZodError extends Error {\n get errors() {\n return this.issues;\n }\n constructor(issues) {\n super();\n this.issues = [];\n this.addIssue = (sub) => {\n this.issues = [...this.issues, sub];\n };\n this.addIssues = (subs = []) => {\n this.issues = [...this.issues, ...subs];\n };\n const actualProto = new.target.prototype;\n if (Object.setPrototypeOf) {\n // eslint-disable-next-line ban/ban\n Object.setPrototypeOf(this, actualProto);\n }\n else {\n this.__proto__ = actualProto;\n }\n this.name = \"ZodError\";\n this.issues = issues;\n }\n format(_mapper) {\n const mapper = _mapper ||\n function (issue) {\n return issue.message;\n };\n const fieldErrors = { _errors: [] };\n const processError = (error) => {\n for (const issue of error.issues) {\n if (issue.code === \"invalid_union\") {\n issue.unionErrors.map(processError);\n }\n else if (issue.code === \"invalid_return_type\") {\n processError(issue.returnTypeError);\n }\n else if (issue.code === \"invalid_arguments\") {\n processError(issue.argumentsError);\n }\n else if (issue.path.length === 0) {\n fieldErrors._errors.push(mapper(issue));\n }\n else {\n let curr = fieldErrors;\n let i = 0;\n while (i < issue.path.length) {\n const el = issue.path[i];\n const terminal = i === issue.path.length - 1;\n if (!terminal) {\n curr[el] = curr[el] || { _errors: [] };\n // if (typeof el === \"string\") {\n // curr[el] = curr[el] || { _errors: [] };\n // } else if (typeof el === \"number\") {\n // const errorArray: any = [];\n // errorArray._errors = [];\n // curr[el] = curr[el] || errorArray;\n // }\n }\n else {\n curr[el] = curr[el] || { _errors: [] };\n curr[el]._errors.push(mapper(issue));\n }\n curr = curr[el];\n i++;\n }\n }\n }\n };\n processError(this);\n return fieldErrors;\n }\n static assert(value) {\n if (!(value instanceof ZodError)) {\n throw new Error(`Not a ZodError: ${value}`);\n }\n }\n toString() {\n return this.message;\n }\n get message() {\n return JSON.stringify(this.issues, util.jsonStringifyReplacer, 2);\n }\n get isEmpty() {\n return this.issues.length === 0;\n }\n flatten(mapper = (issue) => issue.message) {\n const fieldErrors = {};\n const formErrors = [];\n for (const sub of this.issues) {\n if (sub.path.length > 0) {\n fieldErrors[sub.path[0]] = fieldErrors[sub.path[0]] || [];\n fieldErrors[sub.path[0]].push(mapper(sub));\n }\n else {\n formErrors.push(mapper(sub));\n }\n }\n return { formErrors, fieldErrors };\n }\n get formErrors() {\n return this.flatten();\n }\n}\nZodError.create = (issues) => {\n const error = new ZodError(issues);\n return error;\n};\n","import { ZodIssueCode } from \"../ZodError.js\";\nimport { util, ZodParsedType } from \"../helpers/util.js\";\nconst errorMap = (issue, _ctx) => {\n let message;\n switch (issue.code) {\n case ZodIssueCode.invalid_type:\n if (issue.received === ZodParsedType.undefined) {\n message = \"Required\";\n }\n else {\n message = `Expected ${issue.expected}, received ${issue.received}`;\n }\n break;\n case ZodIssueCode.invalid_literal:\n message = `Invalid literal value, expected ${JSON.stringify(issue.expected, util.jsonStringifyReplacer)}`;\n break;\n case ZodIssueCode.unrecognized_keys:\n message = `Unrecognized key(s) in object: ${util.joinValues(issue.keys, \", \")}`;\n break;\n case ZodIssueCode.invalid_union:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_union_discriminator:\n message = `Invalid discriminator value. Expected ${util.joinValues(issue.options)}`;\n break;\n case ZodIssueCode.invalid_enum_value:\n message = `Invalid enum value. Expected ${util.joinValues(issue.options)}, received '${issue.received}'`;\n break;\n case ZodIssueCode.invalid_arguments:\n message = `Invalid function arguments`;\n break;\n case ZodIssueCode.invalid_return_type:\n message = `Invalid function return type`;\n break;\n case ZodIssueCode.invalid_date:\n message = `Invalid date`;\n break;\n case ZodIssueCode.invalid_string:\n if (typeof issue.validation === \"object\") {\n if (\"includes\" in issue.validation) {\n message = `Invalid input: must include \"${issue.validation.includes}\"`;\n if (typeof issue.validation.position === \"number\") {\n message = `${message} at one or more positions greater than or equal to ${issue.validation.position}`;\n }\n }\n else if (\"startsWith\" in issue.validation) {\n message = `Invalid input: must start with \"${issue.validation.startsWith}\"`;\n }\n else if (\"endsWith\" in issue.validation) {\n message = `Invalid input: must end with \"${issue.validation.endsWith}\"`;\n }\n else {\n util.assertNever(issue.validation);\n }\n }\n else if (issue.validation !== \"regex\") {\n message = `Invalid ${issue.validation}`;\n }\n else {\n message = \"Invalid\";\n }\n break;\n case ZodIssueCode.too_small:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `more than`} ${issue.minimum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? \"exactly\" : issue.inclusive ? `at least` : `over`} ${issue.minimum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${issue.minimum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly equal to ` : issue.inclusive ? `greater than or equal to ` : `greater than `}${new Date(Number(issue.minimum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.too_big:\n if (issue.type === \"array\")\n message = `Array must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `less than`} ${issue.maximum} element(s)`;\n else if (issue.type === \"string\")\n message = `String must contain ${issue.exact ? `exactly` : issue.inclusive ? `at most` : `under`} ${issue.maximum} character(s)`;\n else if (issue.type === \"number\")\n message = `Number must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"bigint\")\n message = `BigInt must be ${issue.exact ? `exactly` : issue.inclusive ? `less than or equal to` : `less than`} ${issue.maximum}`;\n else if (issue.type === \"date\")\n message = `Date must be ${issue.exact ? `exactly` : issue.inclusive ? `smaller than or equal to` : `smaller than`} ${new Date(Number(issue.maximum))}`;\n else\n message = \"Invalid input\";\n break;\n case ZodIssueCode.custom:\n message = `Invalid input`;\n break;\n case ZodIssueCode.invalid_intersection_types:\n message = `Intersection results could not be merged`;\n break;\n case ZodIssueCode.not_multiple_of:\n message = `Number must be a multiple of ${issue.multipleOf}`;\n break;\n case ZodIssueCode.not_finite:\n message = \"Number must be finite\";\n break;\n default:\n message = _ctx.defaultError;\n util.assertNever(issue);\n }\n return { message };\n};\nexport default errorMap;\n","import defaultErrorMap from \"./locales/en.js\";\nlet overrideErrorMap = defaultErrorMap;\nexport { defaultErrorMap };\nexport function setErrorMap(map) {\n overrideErrorMap = map;\n}\nexport function getErrorMap() {\n return overrideErrorMap;\n}\n","import { getErrorMap } from \"../errors.js\";\nimport defaultErrorMap from \"../locales/en.js\";\nexport const makeIssue = (params) => {\n const { data, path, errorMaps, issueData } = params;\n const fullPath = [...path, ...(issueData.path || [])];\n const fullIssue = {\n ...issueData,\n path: fullPath,\n };\n if (issueData.message !== undefined) {\n return {\n ...issueData,\n path: fullPath,\n message: issueData.message,\n };\n }\n let errorMessage = \"\";\n const maps = errorMaps\n .filter((m) => !!m)\n .slice()\n .reverse();\n for (const map of maps) {\n errorMessage = map(fullIssue, { data, defaultError: errorMessage }).message;\n }\n return {\n ...issueData,\n path: fullPath,\n message: errorMessage,\n };\n};\nexport const EMPTY_PATH = [];\nexport function addIssueToContext(ctx, issueData) {\n const overrideMap = getErrorMap();\n const issue = makeIssue({\n issueData: issueData,\n data: ctx.data,\n path: ctx.path,\n errorMaps: [\n ctx.common.contextualErrorMap, // contextual error map is first priority\n ctx.schemaErrorMap, // then schema-bound map if available\n overrideMap, // then global override map\n overrideMap === defaultErrorMap ? undefined : defaultErrorMap, // then global default map\n ].filter((x) => !!x),\n });\n ctx.common.issues.push(issue);\n}\nexport class ParseStatus {\n constructor() {\n this.value = \"valid\";\n }\n dirty() {\n if (this.value === \"valid\")\n this.value = \"dirty\";\n }\n abort() {\n if (this.value !== \"aborted\")\n this.value = \"aborted\";\n }\n static mergeArray(status, results) {\n const arrayValue = [];\n for (const s of results) {\n if (s.status === \"aborted\")\n return INVALID;\n if (s.status === \"dirty\")\n status.dirty();\n arrayValue.push(s.value);\n }\n return { status: status.value, value: arrayValue };\n }\n static async mergeObjectAsync(status, pairs) {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n });\n }\n return ParseStatus.mergeObjectSync(status, syncPairs);\n }\n static mergeObjectSync(status, pairs) {\n const finalObject = {};\n for (const pair of pairs) {\n const { key, value } = pair;\n if (key.status === \"aborted\")\n return INVALID;\n if (value.status === \"aborted\")\n return INVALID;\n if (key.status === \"dirty\")\n status.dirty();\n if (value.status === \"dirty\")\n status.dirty();\n if (key.value !== \"__proto__\" && (typeof value.value !== \"undefined\" || pair.alwaysSet)) {\n finalObject[key.value] = value.value;\n }\n }\n return { status: status.value, value: finalObject };\n }\n}\nexport const INVALID = Object.freeze({\n status: \"aborted\",\n});\nexport const DIRTY = (value) => ({ status: \"dirty\", value });\nexport const OK = (value) => ({ status: \"valid\", value });\nexport const isAborted = (x) => x.status === \"aborted\";\nexport const isDirty = (x) => x.status === \"dirty\";\nexport const isValid = (x) => x.status === \"valid\";\nexport const isAsync = (x) => typeof Promise !== \"undefined\" && x instanceof Promise;\n","export var errorUtil;\n(function (errorUtil) {\n errorUtil.errToObj = (message) => typeof message === \"string\" ? { message } : message || {};\n // biome-ignore lint:\n errorUtil.toString = (message) => typeof message === \"string\" ? message : message?.message;\n})(errorUtil || (errorUtil = {}));\n","import { ZodError, ZodIssueCode, } from \"./ZodError.js\";\nimport { defaultErrorMap, getErrorMap } from \"./errors.js\";\nimport { errorUtil } from \"./helpers/errorUtil.js\";\nimport { DIRTY, INVALID, OK, ParseStatus, addIssueToContext, isAborted, isAsync, isDirty, isValid, makeIssue, } from \"./helpers/parseUtil.js\";\nimport { util, ZodParsedType, getParsedType } from \"./helpers/util.js\";\nclass ParseInputLazyPath {\n constructor(parent, value, path, key) {\n this._cachedPath = [];\n this.parent = parent;\n this.data = value;\n this._path = path;\n this._key = key;\n }\n get path() {\n if (!this._cachedPath.length) {\n if (Array.isArray(this._key)) {\n this._cachedPath.push(...this._path, ...this._key);\n }\n else {\n this._cachedPath.push(...this._path, this._key);\n }\n }\n return this._cachedPath;\n }\n}\nconst handleResult = (ctx, result) => {\n if (isValid(result)) {\n return { success: true, data: result.value };\n }\n else {\n if (!ctx.common.issues.length) {\n throw new Error(\"Validation failed but no issues detected.\");\n }\n return {\n success: false,\n get error() {\n if (this._error)\n return this._error;\n const error = new ZodError(ctx.common.issues);\n this._error = error;\n return this._error;\n },\n };\n }\n};\nfunction processCreateParams(params) {\n if (!params)\n return {};\n const { errorMap, invalid_type_error, required_error, description } = params;\n if (errorMap && (invalid_type_error || required_error)) {\n throw new Error(`Can't use \"invalid_type_error\" or \"required_error\" in conjunction with custom error map.`);\n }\n if (errorMap)\n return { errorMap: errorMap, description };\n const customMap = (iss, ctx) => {\n const { message } = params;\n if (iss.code === \"invalid_enum_value\") {\n return { message: message ?? ctx.defaultError };\n }\n if (typeof ctx.data === \"undefined\") {\n return { message: message ?? required_error ?? ctx.defaultError };\n }\n if (iss.code !== \"invalid_type\")\n return { message: ctx.defaultError };\n return { message: message ?? invalid_type_error ?? ctx.defaultError };\n };\n return { errorMap: customMap, description };\n}\nexport class ZodType {\n get description() {\n return this._def.description;\n }\n _getType(input) {\n return getParsedType(input.data);\n }\n _getOrReturnCtx(input, ctx) {\n return (ctx || {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n });\n }\n _processInputParams(input) {\n return {\n status: new ParseStatus(),\n ctx: {\n common: input.parent.common,\n data: input.data,\n parsedType: getParsedType(input.data),\n schemaErrorMap: this._def.errorMap,\n path: input.path,\n parent: input.parent,\n },\n };\n }\n _parseSync(input) {\n const result = this._parse(input);\n if (isAsync(result)) {\n throw new Error(\"Synchronous parse encountered promise.\");\n }\n return result;\n }\n _parseAsync(input) {\n const result = this._parse(input);\n return Promise.resolve(result);\n }\n parse(data, params) {\n const result = this.safeParse(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n safeParse(data, params) {\n const ctx = {\n common: {\n issues: [],\n async: params?.async ?? false,\n contextualErrorMap: params?.errorMap,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const result = this._parseSync({ data, path: ctx.path, parent: ctx });\n return handleResult(ctx, result);\n }\n \"~validate\"(data) {\n const ctx = {\n common: {\n issues: [],\n async: !!this[\"~standard\"].async,\n },\n path: [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n if (!this[\"~standard\"].async) {\n try {\n const result = this._parseSync({ data, path: [], parent: ctx });\n return isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n };\n }\n catch (err) {\n if (err?.message?.toLowerCase()?.includes(\"encountered\")) {\n this[\"~standard\"].async = true;\n }\n ctx.common = {\n issues: [],\n async: true,\n };\n }\n }\n return this._parseAsync({ data, path: [], parent: ctx }).then((result) => isValid(result)\n ? {\n value: result.value,\n }\n : {\n issues: ctx.common.issues,\n });\n }\n async parseAsync(data, params) {\n const result = await this.safeParseAsync(data, params);\n if (result.success)\n return result.data;\n throw result.error;\n }\n async safeParseAsync(data, params) {\n const ctx = {\n common: {\n issues: [],\n contextualErrorMap: params?.errorMap,\n async: true,\n },\n path: params?.path || [],\n schemaErrorMap: this._def.errorMap,\n parent: null,\n data,\n parsedType: getParsedType(data),\n };\n const maybeAsyncResult = this._parse({ data, path: ctx.path, parent: ctx });\n const result = await (isAsync(maybeAsyncResult) ? maybeAsyncResult : Promise.resolve(maybeAsyncResult));\n return handleResult(ctx, result);\n }\n refine(check, message) {\n const getIssueProperties = (val) => {\n if (typeof message === \"string\" || typeof message === \"undefined\") {\n return { message };\n }\n else if (typeof message === \"function\") {\n return message(val);\n }\n else {\n return message;\n }\n };\n return this._refinement((val, ctx) => {\n const result = check(val);\n const setError = () => ctx.addIssue({\n code: ZodIssueCode.custom,\n ...getIssueProperties(val),\n });\n if (typeof Promise !== \"undefined\" && result instanceof Promise) {\n return result.then((data) => {\n if (!data) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n if (!result) {\n setError();\n return false;\n }\n else {\n return true;\n }\n });\n }\n refinement(check, refinementData) {\n return this._refinement((val, ctx) => {\n if (!check(val)) {\n ctx.addIssue(typeof refinementData === \"function\" ? refinementData(val, ctx) : refinementData);\n return false;\n }\n else {\n return true;\n }\n });\n }\n _refinement(refinement) {\n return new ZodEffects({\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"refinement\", refinement },\n });\n }\n superRefine(refinement) {\n return this._refinement(refinement);\n }\n constructor(def) {\n /** Alias of safeParseAsync */\n this.spa = this.safeParseAsync;\n this._def = def;\n this.parse = this.parse.bind(this);\n this.safeParse = this.safeParse.bind(this);\n this.parseAsync = this.parseAsync.bind(this);\n this.safeParseAsync = this.safeParseAsync.bind(this);\n this.spa = this.spa.bind(this);\n this.refine = this.refine.bind(this);\n this.refinement = this.refinement.bind(this);\n this.superRefine = this.superRefine.bind(this);\n this.optional = this.optional.bind(this);\n this.nullable = this.nullable.bind(this);\n this.nullish = this.nullish.bind(this);\n this.array = this.array.bind(this);\n this.promise = this.promise.bind(this);\n this.or = this.or.bind(this);\n this.and = this.and.bind(this);\n this.transform = this.transform.bind(this);\n this.brand = this.brand.bind(this);\n this.default = this.default.bind(this);\n this.catch = this.catch.bind(this);\n this.describe = this.describe.bind(this);\n this.pipe = this.pipe.bind(this);\n this.readonly = this.readonly.bind(this);\n this.isNullable = this.isNullable.bind(this);\n this.isOptional = this.isOptional.bind(this);\n this[\"~standard\"] = {\n version: 1,\n vendor: \"zod\",\n validate: (data) => this[\"~validate\"](data),\n };\n }\n optional() {\n return ZodOptional.create(this, this._def);\n }\n nullable() {\n return ZodNullable.create(this, this._def);\n }\n nullish() {\n return this.nullable().optional();\n }\n array() {\n return ZodArray.create(this);\n }\n promise() {\n return ZodPromise.create(this, this._def);\n }\n or(option) {\n return ZodUnion.create([this, option], this._def);\n }\n and(incoming) {\n return ZodIntersection.create(this, incoming, this._def);\n }\n transform(transform) {\n return new ZodEffects({\n ...processCreateParams(this._def),\n schema: this,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect: { type: \"transform\", transform },\n });\n }\n default(def) {\n const defaultValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodDefault({\n ...processCreateParams(this._def),\n innerType: this,\n defaultValue: defaultValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n });\n }\n brand() {\n return new ZodBranded({\n typeName: ZodFirstPartyTypeKind.ZodBranded,\n type: this,\n ...processCreateParams(this._def),\n });\n }\n catch(def) {\n const catchValueFunc = typeof def === \"function\" ? def : () => def;\n return new ZodCatch({\n ...processCreateParams(this._def),\n innerType: this,\n catchValue: catchValueFunc,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n });\n }\n describe(description) {\n const This = this.constructor;\n return new This({\n ...this._def,\n description,\n });\n }\n pipe(target) {\n return ZodPipeline.create(this, target);\n }\n readonly() {\n return ZodReadonly.create(this);\n }\n isOptional() {\n return this.safeParse(undefined).success;\n }\n isNullable() {\n return this.safeParse(null).success;\n }\n}\nconst cuidRegex = /^c[^\\s-]{8,}$/i;\nconst cuid2Regex = /^[0-9a-z]+$/;\nconst ulidRegex = /^[0-9A-HJKMNP-TV-Z]{26}$/i;\n// const uuidRegex =\n// /^([a-f0-9]{8}-[a-f0-9]{4}-[1-5][a-f0-9]{3}-[a-f0-9]{4}-[a-f0-9]{12}|00000000-0000-0000-0000-000000000000)$/i;\nconst uuidRegex = /^[0-9a-fA-F]{8}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{4}\\b-[0-9a-fA-F]{12}$/i;\nconst nanoidRegex = /^[a-z0-9_-]{21}$/i;\nconst jwtRegex = /^[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]+\\.[A-Za-z0-9-_]*$/;\nconst durationRegex = /^[-+]?P(?!$)(?:(?:[-+]?\\d+Y)|(?:[-+]?\\d+[.,]\\d+Y$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:(?:[-+]?\\d+W)|(?:[-+]?\\d+[.,]\\d+W$))?(?:(?:[-+]?\\d+D)|(?:[-+]?\\d+[.,]\\d+D$))?(?:T(?=[\\d+-])(?:(?:[-+]?\\d+H)|(?:[-+]?\\d+[.,]\\d+H$))?(?:(?:[-+]?\\d+M)|(?:[-+]?\\d+[.,]\\d+M$))?(?:[-+]?\\d+(?:[.,]\\d+)?S)?)??$/;\n// from https://stackoverflow.com/a/46181/1550155\n// old version: too slow, didn't support unicode\n// const emailRegex = /^((([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+(\\.([a-z]|\\d|[!#\\$%&'\\*\\+\\-\\/=\\?\\^_`{\\|}~]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])+)*)|((\\x22)((((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(([\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x7f]|\\x21|[\\x23-\\x5b]|[\\x5d-\\x7e]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(\\\\([\\x01-\\x09\\x0b\\x0c\\x0d-\\x7f]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]))))*(((\\x20|\\x09)*(\\x0d\\x0a))?(\\x20|\\x09)+)?(\\x22)))@((([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|\\d|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))\\.)+(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])|(([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])([a-z]|\\d|-|\\.|_|~|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])*([a-z]|[\\u00A0-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF])))$/i;\n//old email regex\n// const emailRegex = /^(([^<>()[\\].,;:\\s@\"]+(\\.[^<>()[\\].,;:\\s@\"]+)*)|(\".+\"))@((?!-)([^<>()[\\].,;:\\s@\"]+\\.)+[^<>()[\\].,;:\\s@\"]{1,})[^-<>()[\\].,;:\\s@\"]$/i;\n// eslint-disable-next-line\n// const emailRegex =\n// /^(([^<>()[\\]\\\\.,;:\\s@\\\"]+(\\.[^<>()[\\]\\\\.,;:\\s@\\\"]+)*)|(\\\".+\\\"))@((\\[(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\])|(\\[IPv6:(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))\\])|([A-Za-z0-9]([A-Za-z0-9-]*[A-Za-z0-9])*(\\.[A-Za-z]{2,})+))$/;\n// const emailRegex =\n// /^[a-zA-Z0-9\\.\\!\\#\\$\\%\\&\\'\\*\\+\\/\\=\\?\\^\\_\\`\\{\\|\\}\\~\\-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(?:\\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;\n// const emailRegex =\n// /^(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|\"(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21\\x23-\\x5b\\x5d-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])*\")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\\x01-\\x08\\x0b\\x0c\\x0e-\\x1f\\x21-\\x5a\\x53-\\x7f]|\\\\[\\x01-\\x09\\x0b\\x0c\\x0e-\\x7f])+)\\])$/i;\nconst emailRegex = /^(?!\\.)(?!.*\\.\\.)([A-Z0-9_'+\\-\\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\\-]*\\.)+[A-Z]{2,}$/i;\n// const emailRegex =\n// /^[a-z0-9.!#$%&’*+/=?^_`{|}~-]+@[a-z0-9-]+(?:\\.[a-z0-9\\-]+)*$/i;\n// from https://thekevinscott.com/emojis-in-javascript/#writing-a-regular-expression\nconst _emojiRegex = `^(\\\\p{Extended_Pictographic}|\\\\p{Emoji_Component})+$`;\nlet emojiRegex;\n// faster, simpler, safer\nconst ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/;\nconst ipv4CidrRegex = /^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\\/(3[0-2]|[12]?[0-9])$/;\n// const ipv6Regex =\n// /^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/;\nconst ipv6Regex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/;\nconst ipv6CidrRegex = /^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/;\n// https://stackoverflow.com/questions/7860392/determine-if-string-is-in-base64-using-javascript\nconst base64Regex = /^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/;\n// https://base64.guru/standards/base64url\nconst base64urlRegex = /^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/;\n// simple\n// const dateRegexSource = `\\\\d{4}-\\\\d{2}-\\\\d{2}`;\n// no leap year validation\n// const dateRegexSource = `\\\\d{4}-((0[13578]|10|12)-31|(0[13-9]|1[0-2])-30|(0[1-9]|1[0-2])-(0[1-9]|1\\\\d|2\\\\d))`;\n// with leap year validation\nconst dateRegexSource = `((\\\\d\\\\d[2468][048]|\\\\d\\\\d[13579][26]|\\\\d\\\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\\\d|30)|(02)-(0[1-9]|1\\\\d|2[0-8])))`;\nconst dateRegex = new RegExp(`^${dateRegexSource}$`);\nfunction timeRegexSource(args) {\n let secondsRegexSource = `[0-5]\\\\d`;\n if (args.precision) {\n secondsRegexSource = `${secondsRegexSource}\\\\.\\\\d{${args.precision}}`;\n }\n else if (args.precision == null) {\n secondsRegexSource = `${secondsRegexSource}(\\\\.\\\\d+)?`;\n }\n const secondsQuantifier = args.precision ? \"+\" : \"?\"; // require seconds if precision is nonzero\n return `([01]\\\\d|2[0-3]):[0-5]\\\\d(:${secondsRegexSource})${secondsQuantifier}`;\n}\nfunction timeRegex(args) {\n return new RegExp(`^${timeRegexSource(args)}$`);\n}\n// Adapted from https://stackoverflow.com/a/3143231\nexport function datetimeRegex(args) {\n let regex = `${dateRegexSource}T${timeRegexSource(args)}`;\n const opts = [];\n opts.push(args.local ? `Z?` : `Z`);\n if (args.offset)\n opts.push(`([+-]\\\\d{2}:?\\\\d{2})`);\n regex = `${regex}(${opts.join(\"|\")})`;\n return new RegExp(`^${regex}$`);\n}\nfunction isValidIP(ip, version) {\n if ((version === \"v4\" || !version) && ipv4Regex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6Regex.test(ip)) {\n return true;\n }\n return false;\n}\nfunction isValidJWT(jwt, alg) {\n if (!jwtRegex.test(jwt))\n return false;\n try {\n const [header] = jwt.split(\".\");\n // Convert base64url to base64\n const base64 = header\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(header.length + ((4 - (header.length % 4)) % 4), \"=\");\n const decoded = JSON.parse(atob(base64));\n if (typeof decoded !== \"object\" || decoded === null)\n return false;\n if (\"typ\" in decoded && decoded?.typ !== \"JWT\")\n return false;\n if (!decoded.alg)\n return false;\n if (alg && decoded.alg !== alg)\n return false;\n return true;\n }\n catch {\n return false;\n }\n}\nfunction isValidCidr(ip, version) {\n if ((version === \"v4\" || !version) && ipv4CidrRegex.test(ip)) {\n return true;\n }\n if ((version === \"v6\" || !version) && ipv6CidrRegex.test(ip)) {\n return true;\n }\n return false;\n}\nexport class ZodString extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = String(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.string) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.string,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.length < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.length > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"length\") {\n const tooBig = input.data.length > check.value;\n const tooSmall = input.data.length < check.value;\n if (tooBig || tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n if (tooBig) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n else if (tooSmall) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"string\",\n inclusive: true,\n exact: true,\n message: check.message,\n });\n }\n status.dirty();\n }\n }\n else if (check.kind === \"email\") {\n if (!emailRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"email\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"emoji\") {\n if (!emojiRegex) {\n emojiRegex = new RegExp(_emojiRegex, \"u\");\n }\n if (!emojiRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"emoji\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"uuid\") {\n if (!uuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"uuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"nanoid\") {\n if (!nanoidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"nanoid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid\") {\n if (!cuidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cuid2\") {\n if (!cuid2Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cuid2\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ulid\") {\n if (!ulidRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ulid\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"url\") {\n try {\n new URL(input.data);\n }\n catch {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"regex\") {\n check.regex.lastIndex = 0;\n const testResult = check.regex.test(input.data);\n if (!testResult) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"regex\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"trim\") {\n input.data = input.data.trim();\n }\n else if (check.kind === \"includes\") {\n if (!input.data.includes(check.value, check.position)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { includes: check.value, position: check.position },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"toLowerCase\") {\n input.data = input.data.toLowerCase();\n }\n else if (check.kind === \"toUpperCase\") {\n input.data = input.data.toUpperCase();\n }\n else if (check.kind === \"startsWith\") {\n if (!input.data.startsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { startsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"endsWith\") {\n if (!input.data.endsWith(check.value)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: { endsWith: check.value },\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"datetime\") {\n const regex = datetimeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"datetime\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"date\") {\n const regex = dateRegex;\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"date\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"time\") {\n const regex = timeRegex(check);\n if (!regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_string,\n validation: \"time\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"duration\") {\n if (!durationRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"duration\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"ip\") {\n if (!isValidIP(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"ip\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"jwt\") {\n if (!isValidJWT(input.data, check.alg)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"jwt\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"cidr\") {\n if (!isValidCidr(input.data, check.version)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"cidr\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64\") {\n if (!base64Regex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"base64url\") {\n if (!base64urlRegex.test(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n validation: \"base64url\",\n code: ZodIssueCode.invalid_string,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _regex(regex, validation, message) {\n return this.refinement((data) => regex.test(data), {\n validation,\n code: ZodIssueCode.invalid_string,\n ...errorUtil.errToObj(message),\n });\n }\n _addCheck(check) {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n email(message) {\n return this._addCheck({ kind: \"email\", ...errorUtil.errToObj(message) });\n }\n url(message) {\n return this._addCheck({ kind: \"url\", ...errorUtil.errToObj(message) });\n }\n emoji(message) {\n return this._addCheck({ kind: \"emoji\", ...errorUtil.errToObj(message) });\n }\n uuid(message) {\n return this._addCheck({ kind: \"uuid\", ...errorUtil.errToObj(message) });\n }\n nanoid(message) {\n return this._addCheck({ kind: \"nanoid\", ...errorUtil.errToObj(message) });\n }\n cuid(message) {\n return this._addCheck({ kind: \"cuid\", ...errorUtil.errToObj(message) });\n }\n cuid2(message) {\n return this._addCheck({ kind: \"cuid2\", ...errorUtil.errToObj(message) });\n }\n ulid(message) {\n return this._addCheck({ kind: \"ulid\", ...errorUtil.errToObj(message) });\n }\n base64(message) {\n return this._addCheck({ kind: \"base64\", ...errorUtil.errToObj(message) });\n }\n base64url(message) {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return this._addCheck({\n kind: \"base64url\",\n ...errorUtil.errToObj(message),\n });\n }\n jwt(options) {\n return this._addCheck({ kind: \"jwt\", ...errorUtil.errToObj(options) });\n }\n ip(options) {\n return this._addCheck({ kind: \"ip\", ...errorUtil.errToObj(options) });\n }\n cidr(options) {\n return this._addCheck({ kind: \"cidr\", ...errorUtil.errToObj(options) });\n }\n datetime(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"datetime\",\n precision: null,\n offset: false,\n local: false,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"datetime\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n offset: options?.offset ?? false,\n local: options?.local ?? false,\n ...errorUtil.errToObj(options?.message),\n });\n }\n date(message) {\n return this._addCheck({ kind: \"date\", message });\n }\n time(options) {\n if (typeof options === \"string\") {\n return this._addCheck({\n kind: \"time\",\n precision: null,\n message: options,\n });\n }\n return this._addCheck({\n kind: \"time\",\n precision: typeof options?.precision === \"undefined\" ? null : options?.precision,\n ...errorUtil.errToObj(options?.message),\n });\n }\n duration(message) {\n return this._addCheck({ kind: \"duration\", ...errorUtil.errToObj(message) });\n }\n regex(regex, message) {\n return this._addCheck({\n kind: \"regex\",\n regex: regex,\n ...errorUtil.errToObj(message),\n });\n }\n includes(value, options) {\n return this._addCheck({\n kind: \"includes\",\n value: value,\n position: options?.position,\n ...errorUtil.errToObj(options?.message),\n });\n }\n startsWith(value, message) {\n return this._addCheck({\n kind: \"startsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n endsWith(value, message) {\n return this._addCheck({\n kind: \"endsWith\",\n value: value,\n ...errorUtil.errToObj(message),\n });\n }\n min(minLength, message) {\n return this._addCheck({\n kind: \"min\",\n value: minLength,\n ...errorUtil.errToObj(message),\n });\n }\n max(maxLength, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxLength,\n ...errorUtil.errToObj(message),\n });\n }\n length(len, message) {\n return this._addCheck({\n kind: \"length\",\n value: len,\n ...errorUtil.errToObj(message),\n });\n }\n /**\n * Equivalent to `.min(1)`\n */\n nonempty(message) {\n return this.min(1, errorUtil.errToObj(message));\n }\n trim() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"trim\" }],\n });\n }\n toLowerCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toLowerCase\" }],\n });\n }\n toUpperCase() {\n return new ZodString({\n ...this._def,\n checks: [...this._def.checks, { kind: \"toUpperCase\" }],\n });\n }\n get isDatetime() {\n return !!this._def.checks.find((ch) => ch.kind === \"datetime\");\n }\n get isDate() {\n return !!this._def.checks.find((ch) => ch.kind === \"date\");\n }\n get isTime() {\n return !!this._def.checks.find((ch) => ch.kind === \"time\");\n }\n get isDuration() {\n return !!this._def.checks.find((ch) => ch.kind === \"duration\");\n }\n get isEmail() {\n return !!this._def.checks.find((ch) => ch.kind === \"email\");\n }\n get isURL() {\n return !!this._def.checks.find((ch) => ch.kind === \"url\");\n }\n get isEmoji() {\n return !!this._def.checks.find((ch) => ch.kind === \"emoji\");\n }\n get isUUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"uuid\");\n }\n get isNANOID() {\n return !!this._def.checks.find((ch) => ch.kind === \"nanoid\");\n }\n get isCUID() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid\");\n }\n get isCUID2() {\n return !!this._def.checks.find((ch) => ch.kind === \"cuid2\");\n }\n get isULID() {\n return !!this._def.checks.find((ch) => ch.kind === \"ulid\");\n }\n get isIP() {\n return !!this._def.checks.find((ch) => ch.kind === \"ip\");\n }\n get isCIDR() {\n return !!this._def.checks.find((ch) => ch.kind === \"cidr\");\n }\n get isBase64() {\n return !!this._def.checks.find((ch) => ch.kind === \"base64\");\n }\n get isBase64url() {\n // base64url encoding is a modification of base64 that can safely be used in URLs and filenames\n return !!this._def.checks.find((ch) => ch.kind === \"base64url\");\n }\n get minLength() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxLength() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodString.create = (params) => {\n return new ZodString({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodString,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\n// https://stackoverflow.com/questions/3966484/why-does-modulus-operator-return-fractional-number-in-javascript/31711034#31711034\nfunction floatSafeRemainder(val, step) {\n const valDecCount = (val.toString().split(\".\")[1] || \"\").length;\n const stepDecCount = (step.toString().split(\".\")[1] || \"\").length;\n const decCount = valDecCount > stepDecCount ? valDecCount : stepDecCount;\n const valInt = Number.parseInt(val.toFixed(decCount).replace(\".\", \"\"));\n const stepInt = Number.parseInt(step.toFixed(decCount).replace(\".\", \"\"));\n return (valInt % stepInt) / 10 ** decCount;\n}\nexport class ZodNumber extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n this.step = this.multipleOf;\n }\n _parse(input) {\n if (this._def.coerce) {\n input.data = Number(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.number) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.number,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"int\") {\n if (!util.isInteger(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: \"integer\",\n received: \"float\",\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: check.value,\n type: \"number\",\n inclusive: check.inclusive,\n exact: false,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (floatSafeRemainder(input.data, check.value) !== 0) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"finite\") {\n if (!Number.isFinite(input.data)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_finite,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodNumber({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodNumber({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n int(message) {\n return this._addCheck({\n kind: \"int\",\n message: errorUtil.toString(message),\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: 0,\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value: value,\n message: errorUtil.toString(message),\n });\n }\n finite(message) {\n return this._addCheck({\n kind: \"finite\",\n message: errorUtil.toString(message),\n });\n }\n safe(message) {\n return this._addCheck({\n kind: \"min\",\n inclusive: true,\n value: Number.MIN_SAFE_INTEGER,\n message: errorUtil.toString(message),\n })._addCheck({\n kind: \"max\",\n inclusive: true,\n value: Number.MAX_SAFE_INTEGER,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n get isInt() {\n return !!this._def.checks.find((ch) => ch.kind === \"int\" || (ch.kind === \"multipleOf\" && util.isInteger(ch.value)));\n }\n get isFinite() {\n let max = null;\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"finite\" || ch.kind === \"int\" || ch.kind === \"multipleOf\") {\n return true;\n }\n else if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n else if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return Number.isFinite(min) && Number.isFinite(max);\n }\n}\nZodNumber.create = (params) => {\n return new ZodNumber({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodNumber,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBigInt extends ZodType {\n constructor() {\n super(...arguments);\n this.min = this.gte;\n this.max = this.lte;\n }\n _parse(input) {\n if (this._def.coerce) {\n try {\n input.data = BigInt(input.data);\n }\n catch {\n return this._getInvalidInput(input);\n }\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.bigint) {\n return this._getInvalidInput(input);\n }\n let ctx = undefined;\n const status = new ParseStatus();\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n const tooSmall = check.inclusive ? input.data < check.value : input.data <= check.value;\n if (tooSmall) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n type: \"bigint\",\n minimum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n const tooBig = check.inclusive ? input.data > check.value : input.data >= check.value;\n if (tooBig) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n type: \"bigint\",\n maximum: check.value,\n inclusive: check.inclusive,\n message: check.message,\n });\n status.dirty();\n }\n }\n else if (check.kind === \"multipleOf\") {\n if (input.data % check.value !== BigInt(0)) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.not_multiple_of,\n multipleOf: check.value,\n message: check.message,\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return { status: status.value, value: input.data };\n }\n _getInvalidInput(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.bigint,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n gte(value, message) {\n return this.setLimit(\"min\", value, true, errorUtil.toString(message));\n }\n gt(value, message) {\n return this.setLimit(\"min\", value, false, errorUtil.toString(message));\n }\n lte(value, message) {\n return this.setLimit(\"max\", value, true, errorUtil.toString(message));\n }\n lt(value, message) {\n return this.setLimit(\"max\", value, false, errorUtil.toString(message));\n }\n setLimit(kind, value, inclusive, message) {\n return new ZodBigInt({\n ...this._def,\n checks: [\n ...this._def.checks,\n {\n kind,\n value,\n inclusive,\n message: errorUtil.toString(message),\n },\n ],\n });\n }\n _addCheck(check) {\n return new ZodBigInt({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n positive(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n negative(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: false,\n message: errorUtil.toString(message),\n });\n }\n nonpositive(message) {\n return this._addCheck({\n kind: \"max\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n nonnegative(message) {\n return this._addCheck({\n kind: \"min\",\n value: BigInt(0),\n inclusive: true,\n message: errorUtil.toString(message),\n });\n }\n multipleOf(value, message) {\n return this._addCheck({\n kind: \"multipleOf\",\n value,\n message: errorUtil.toString(message),\n });\n }\n get minValue() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min;\n }\n get maxValue() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max;\n }\n}\nZodBigInt.create = (params) => {\n return new ZodBigInt({\n checks: [],\n typeName: ZodFirstPartyTypeKind.ZodBigInt,\n coerce: params?.coerce ?? false,\n ...processCreateParams(params),\n });\n};\nexport class ZodBoolean extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = Boolean(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.boolean) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.boolean,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodBoolean.create = (params) => {\n return new ZodBoolean({\n typeName: ZodFirstPartyTypeKind.ZodBoolean,\n coerce: params?.coerce || false,\n ...processCreateParams(params),\n });\n};\nexport class ZodDate extends ZodType {\n _parse(input) {\n if (this._def.coerce) {\n input.data = new Date(input.data);\n }\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.date) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.date,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (Number.isNaN(input.data.getTime())) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_date,\n });\n return INVALID;\n }\n const status = new ParseStatus();\n let ctx = undefined;\n for (const check of this._def.checks) {\n if (check.kind === \"min\") {\n if (input.data.getTime() < check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n message: check.message,\n inclusive: true,\n exact: false,\n minimum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else if (check.kind === \"max\") {\n if (input.data.getTime() > check.value) {\n ctx = this._getOrReturnCtx(input, ctx);\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n message: check.message,\n inclusive: true,\n exact: false,\n maximum: check.value,\n type: \"date\",\n });\n status.dirty();\n }\n }\n else {\n util.assertNever(check);\n }\n }\n return {\n status: status.value,\n value: new Date(input.data.getTime()),\n };\n }\n _addCheck(check) {\n return new ZodDate({\n ...this._def,\n checks: [...this._def.checks, check],\n });\n }\n min(minDate, message) {\n return this._addCheck({\n kind: \"min\",\n value: minDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n max(maxDate, message) {\n return this._addCheck({\n kind: \"max\",\n value: maxDate.getTime(),\n message: errorUtil.toString(message),\n });\n }\n get minDate() {\n let min = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"min\") {\n if (min === null || ch.value > min)\n min = ch.value;\n }\n }\n return min != null ? new Date(min) : null;\n }\n get maxDate() {\n let max = null;\n for (const ch of this._def.checks) {\n if (ch.kind === \"max\") {\n if (max === null || ch.value < max)\n max = ch.value;\n }\n }\n return max != null ? new Date(max) : null;\n }\n}\nZodDate.create = (params) => {\n return new ZodDate({\n checks: [],\n coerce: params?.coerce || false,\n typeName: ZodFirstPartyTypeKind.ZodDate,\n ...processCreateParams(params),\n });\n};\nexport class ZodSymbol extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.symbol) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.symbol,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodSymbol.create = (params) => {\n return new ZodSymbol({\n typeName: ZodFirstPartyTypeKind.ZodSymbol,\n ...processCreateParams(params),\n });\n};\nexport class ZodUndefined extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.undefined,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodUndefined.create = (params) => {\n return new ZodUndefined({\n typeName: ZodFirstPartyTypeKind.ZodUndefined,\n ...processCreateParams(params),\n });\n};\nexport class ZodNull extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.null) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.null,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodNull.create = (params) => {\n return new ZodNull({\n typeName: ZodFirstPartyTypeKind.ZodNull,\n ...processCreateParams(params),\n });\n};\nexport class ZodAny extends ZodType {\n constructor() {\n super(...arguments);\n // to prevent instances of other classes from extending ZodAny. this causes issues with catchall in ZodObject.\n this._any = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodAny.create = (params) => {\n return new ZodAny({\n typeName: ZodFirstPartyTypeKind.ZodAny,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnknown extends ZodType {\n constructor() {\n super(...arguments);\n // required\n this._unknown = true;\n }\n _parse(input) {\n return OK(input.data);\n }\n}\nZodUnknown.create = (params) => {\n return new ZodUnknown({\n typeName: ZodFirstPartyTypeKind.ZodUnknown,\n ...processCreateParams(params),\n });\n};\nexport class ZodNever extends ZodType {\n _parse(input) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.never,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n}\nZodNever.create = (params) => {\n return new ZodNever({\n typeName: ZodFirstPartyTypeKind.ZodNever,\n ...processCreateParams(params),\n });\n};\nexport class ZodVoid extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.undefined) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.void,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n}\nZodVoid.create = (params) => {\n return new ZodVoid({\n typeName: ZodFirstPartyTypeKind.ZodVoid,\n ...processCreateParams(params),\n });\n};\nexport class ZodArray extends ZodType {\n _parse(input) {\n const { ctx, status } = this._processInputParams(input);\n const def = this._def;\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (def.exactLength !== null) {\n const tooBig = ctx.data.length > def.exactLength.value;\n const tooSmall = ctx.data.length < def.exactLength.value;\n if (tooBig || tooSmall) {\n addIssueToContext(ctx, {\n code: tooBig ? ZodIssueCode.too_big : ZodIssueCode.too_small,\n minimum: (tooSmall ? def.exactLength.value : undefined),\n maximum: (tooBig ? def.exactLength.value : undefined),\n type: \"array\",\n inclusive: true,\n exact: true,\n message: def.exactLength.message,\n });\n status.dirty();\n }\n }\n if (def.minLength !== null) {\n if (ctx.data.length < def.minLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.minLength.message,\n });\n status.dirty();\n }\n }\n if (def.maxLength !== null) {\n if (ctx.data.length > def.maxLength.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxLength.value,\n type: \"array\",\n inclusive: true,\n exact: false,\n message: def.maxLength.message,\n });\n status.dirty();\n }\n }\n if (ctx.common.async) {\n return Promise.all([...ctx.data].map((item, i) => {\n return def.type._parseAsync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n })).then((result) => {\n return ParseStatus.mergeArray(status, result);\n });\n }\n const result = [...ctx.data].map((item, i) => {\n return def.type._parseSync(new ParseInputLazyPath(ctx, item, ctx.path, i));\n });\n return ParseStatus.mergeArray(status, result);\n }\n get element() {\n return this._def.type;\n }\n min(minLength, message) {\n return new ZodArray({\n ...this._def,\n minLength: { value: minLength, message: errorUtil.toString(message) },\n });\n }\n max(maxLength, message) {\n return new ZodArray({\n ...this._def,\n maxLength: { value: maxLength, message: errorUtil.toString(message) },\n });\n }\n length(len, message) {\n return new ZodArray({\n ...this._def,\n exactLength: { value: len, message: errorUtil.toString(message) },\n });\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodArray.create = (schema, params) => {\n return new ZodArray({\n type: schema,\n minLength: null,\n maxLength: null,\n exactLength: null,\n typeName: ZodFirstPartyTypeKind.ZodArray,\n ...processCreateParams(params),\n });\n};\nfunction deepPartialify(schema) {\n if (schema instanceof ZodObject) {\n const newShape = {};\n for (const key in schema.shape) {\n const fieldSchema = schema.shape[key];\n newShape[key] = ZodOptional.create(deepPartialify(fieldSchema));\n }\n return new ZodObject({\n ...schema._def,\n shape: () => newShape,\n });\n }\n else if (schema instanceof ZodArray) {\n return new ZodArray({\n ...schema._def,\n type: deepPartialify(schema.element),\n });\n }\n else if (schema instanceof ZodOptional) {\n return ZodOptional.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodNullable) {\n return ZodNullable.create(deepPartialify(schema.unwrap()));\n }\n else if (schema instanceof ZodTuple) {\n return ZodTuple.create(schema.items.map((item) => deepPartialify(item)));\n }\n else {\n return schema;\n }\n}\nexport class ZodObject extends ZodType {\n constructor() {\n super(...arguments);\n this._cached = null;\n /**\n * @deprecated In most cases, this is no longer needed - unknown properties are now silently stripped.\n * If you want to pass through unknown properties, use `.passthrough()` instead.\n */\n this.nonstrict = this.passthrough;\n // extend<\n // Augmentation extends ZodRawShape,\n // NewOutput extends util.flatten<{\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // }>,\n // NewInput extends util.flatten<{\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }>\n // >(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<T, Augmentation>,\n // UnknownKeys,\n // Catchall,\n // NewOutput,\n // NewInput\n // > {\n // return new ZodObject({\n // ...this._def,\n // shape: () => ({\n // ...this._def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // }\n /**\n * @deprecated Use `.extend` instead\n * */\n this.augment = this.extend;\n }\n _getCached() {\n if (this._cached !== null)\n return this._cached;\n const shape = this._def.shape();\n const keys = util.objectKeys(shape);\n this._cached = { shape, keys };\n return this._cached;\n }\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.object) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const { status, ctx } = this._processInputParams(input);\n const { shape, keys: shapeKeys } = this._getCached();\n const extraKeys = [];\n if (!(this._def.catchall instanceof ZodNever && this._def.unknownKeys === \"strip\")) {\n for (const key in ctx.data) {\n if (!shapeKeys.includes(key)) {\n extraKeys.push(key);\n }\n }\n }\n const pairs = [];\n for (const key of shapeKeys) {\n const keyValidator = shape[key];\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: keyValidator._parse(new ParseInputLazyPath(ctx, value, ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (this._def.catchall instanceof ZodNever) {\n const unknownKeys = this._def.unknownKeys;\n if (unknownKeys === \"passthrough\") {\n for (const key of extraKeys) {\n pairs.push({\n key: { status: \"valid\", value: key },\n value: { status: \"valid\", value: ctx.data[key] },\n });\n }\n }\n else if (unknownKeys === \"strict\") {\n if (extraKeys.length > 0) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.unrecognized_keys,\n keys: extraKeys,\n });\n status.dirty();\n }\n }\n else if (unknownKeys === \"strip\") {\n }\n else {\n throw new Error(`Internal ZodObject error: invalid unknownKeys value.`);\n }\n }\n else {\n // run catchall validation\n const catchall = this._def.catchall;\n for (const key of extraKeys) {\n const value = ctx.data[key];\n pairs.push({\n key: { status: \"valid\", value: key },\n value: catchall._parse(new ParseInputLazyPath(ctx, value, ctx.path, key) //, ctx.child(key), value, getParsedType(value)\n ),\n alwaysSet: key in ctx.data,\n });\n }\n }\n if (ctx.common.async) {\n return Promise.resolve()\n .then(async () => {\n const syncPairs = [];\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n syncPairs.push({\n key,\n value,\n alwaysSet: pair.alwaysSet,\n });\n }\n return syncPairs;\n })\n .then((syncPairs) => {\n return ParseStatus.mergeObjectSync(status, syncPairs);\n });\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get shape() {\n return this._def.shape();\n }\n strict(message) {\n errorUtil.errToObj;\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strict\",\n ...(message !== undefined\n ? {\n errorMap: (issue, ctx) => {\n const defaultError = this._def.errorMap?.(issue, ctx).message ?? ctx.defaultError;\n if (issue.code === \"unrecognized_keys\")\n return {\n message: errorUtil.errToObj(message).message ?? defaultError,\n };\n return {\n message: defaultError,\n };\n },\n }\n : {}),\n });\n }\n strip() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"strip\",\n });\n }\n passthrough() {\n return new ZodObject({\n ...this._def,\n unknownKeys: \"passthrough\",\n });\n }\n // const AugmentFactory =\n // <Def extends ZodObjectDef>(def: Def) =>\n // <Augmentation extends ZodRawShape>(\n // augmentation: Augmentation\n // ): ZodObject<\n // extendShape<ReturnType<Def[\"shape\"]>, Augmentation>,\n // Def[\"unknownKeys\"],\n // Def[\"catchall\"]\n // > => {\n // return new ZodObject({\n // ...def,\n // shape: () => ({\n // ...def.shape(),\n // ...augmentation,\n // }),\n // }) as any;\n // };\n extend(augmentation) {\n return new ZodObject({\n ...this._def,\n shape: () => ({\n ...this._def.shape(),\n ...augmentation,\n }),\n });\n }\n /**\n * Prior to zod@1.0.12 there was a bug in the\n * inferred type of merged objects. Please\n * upgrade if you are experiencing issues.\n */\n merge(merging) {\n const merged = new ZodObject({\n unknownKeys: merging._def.unknownKeys,\n catchall: merging._def.catchall,\n shape: () => ({\n ...this._def.shape(),\n ...merging._def.shape(),\n }),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n });\n return merged;\n }\n // merge<\n // Incoming extends AnyZodObject,\n // Augmentation extends Incoming[\"shape\"],\n // NewOutput extends {\n // [k in keyof Augmentation | keyof Output]: k extends keyof Augmentation\n // ? Augmentation[k][\"_output\"]\n // : k extends keyof Output\n // ? Output[k]\n // : never;\n // },\n // NewInput extends {\n // [k in keyof Augmentation | keyof Input]: k extends keyof Augmentation\n // ? Augmentation[k][\"_input\"]\n // : k extends keyof Input\n // ? Input[k]\n // : never;\n // }\n // >(\n // merging: Incoming\n // ): ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"],\n // NewOutput,\n // NewInput\n // > {\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n setKey(key, schema) {\n return this.augment({ [key]: schema });\n }\n // merge<Incoming extends AnyZodObject>(\n // merging: Incoming\n // ): //ZodObject<T & Incoming[\"_shape\"], UnknownKeys, Catchall> = (merging) => {\n // ZodObject<\n // extendShape<T, ReturnType<Incoming[\"_def\"][\"shape\"]>>,\n // Incoming[\"_def\"][\"unknownKeys\"],\n // Incoming[\"_def\"][\"catchall\"]\n // > {\n // // const mergedShape = objectUtil.mergeShapes(\n // // this._def.shape(),\n // // merging._def.shape()\n // // );\n // const merged: any = new ZodObject({\n // unknownKeys: merging._def.unknownKeys,\n // catchall: merging._def.catchall,\n // shape: () =>\n // objectUtil.mergeShapes(this._def.shape(), merging._def.shape()),\n // typeName: ZodFirstPartyTypeKind.ZodObject,\n // }) as any;\n // return merged;\n // }\n catchall(index) {\n return new ZodObject({\n ...this._def,\n catchall: index,\n });\n }\n pick(mask) {\n const shape = {};\n for (const key of util.objectKeys(mask)) {\n if (mask[key] && this.shape[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n omit(mask) {\n const shape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (!mask[key]) {\n shape[key] = this.shape[key];\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => shape,\n });\n }\n /**\n * @deprecated\n */\n deepPartial() {\n return deepPartialify(this);\n }\n partial(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n const fieldSchema = this.shape[key];\n if (mask && !mask[key]) {\n newShape[key] = fieldSchema;\n }\n else {\n newShape[key] = fieldSchema.optional();\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n required(mask) {\n const newShape = {};\n for (const key of util.objectKeys(this.shape)) {\n if (mask && !mask[key]) {\n newShape[key] = this.shape[key];\n }\n else {\n const fieldSchema = this.shape[key];\n let newField = fieldSchema;\n while (newField instanceof ZodOptional) {\n newField = newField._def.innerType;\n }\n newShape[key] = newField;\n }\n }\n return new ZodObject({\n ...this._def,\n shape: () => newShape,\n });\n }\n keyof() {\n return createZodEnum(util.objectKeys(this.shape));\n }\n}\nZodObject.create = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.strictCreate = (shape, params) => {\n return new ZodObject({\n shape: () => shape,\n unknownKeys: \"strict\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nZodObject.lazycreate = (shape, params) => {\n return new ZodObject({\n shape,\n unknownKeys: \"strip\",\n catchall: ZodNever.create(),\n typeName: ZodFirstPartyTypeKind.ZodObject,\n ...processCreateParams(params),\n });\n};\nexport class ZodUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const options = this._def.options;\n function handleResults(results) {\n // return first issue-free validation if it exists\n for (const result of results) {\n if (result.result.status === \"valid\") {\n return result.result;\n }\n }\n for (const result of results) {\n if (result.result.status === \"dirty\") {\n // add issues from dirty option\n ctx.common.issues.push(...result.ctx.common.issues);\n return result.result;\n }\n }\n // return invalid\n const unionErrors = results.map((result) => new ZodError(result.ctx.common.issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return Promise.all(options.map(async (option) => {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n return {\n result: await option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n }),\n ctx: childCtx,\n };\n })).then(handleResults);\n }\n else {\n let dirty = undefined;\n const issues = [];\n for (const option of options) {\n const childCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n parent: null,\n };\n const result = option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: childCtx,\n });\n if (result.status === \"valid\") {\n return result;\n }\n else if (result.status === \"dirty\" && !dirty) {\n dirty = { result, ctx: childCtx };\n }\n if (childCtx.common.issues.length) {\n issues.push(childCtx.common.issues);\n }\n }\n if (dirty) {\n ctx.common.issues.push(...dirty.ctx.common.issues);\n return dirty.result;\n }\n const unionErrors = issues.map((issues) => new ZodError(issues));\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union,\n unionErrors,\n });\n return INVALID;\n }\n }\n get options() {\n return this._def.options;\n }\n}\nZodUnion.create = (types, params) => {\n return new ZodUnion({\n options: types,\n typeName: ZodFirstPartyTypeKind.ZodUnion,\n ...processCreateParams(params),\n });\n};\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\n////////// //////////\n////////// ZodDiscriminatedUnion //////////\n////////// //////////\n/////////////////////////////////////////////////////\n/////////////////////////////////////////////////////\nconst getDiscriminator = (type) => {\n if (type instanceof ZodLazy) {\n return getDiscriminator(type.schema);\n }\n else if (type instanceof ZodEffects) {\n return getDiscriminator(type.innerType());\n }\n else if (type instanceof ZodLiteral) {\n return [type.value];\n }\n else if (type instanceof ZodEnum) {\n return type.options;\n }\n else if (type instanceof ZodNativeEnum) {\n // eslint-disable-next-line ban/ban\n return util.objectValues(type.enum);\n }\n else if (type instanceof ZodDefault) {\n return getDiscriminator(type._def.innerType);\n }\n else if (type instanceof ZodUndefined) {\n return [undefined];\n }\n else if (type instanceof ZodNull) {\n return [null];\n }\n else if (type instanceof ZodOptional) {\n return [undefined, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodNullable) {\n return [null, ...getDiscriminator(type.unwrap())];\n }\n else if (type instanceof ZodBranded) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodReadonly) {\n return getDiscriminator(type.unwrap());\n }\n else if (type instanceof ZodCatch) {\n return getDiscriminator(type._def.innerType);\n }\n else {\n return [];\n }\n};\nexport class ZodDiscriminatedUnion extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const discriminator = this.discriminator;\n const discriminatorValue = ctx.data[discriminator];\n const option = this.optionsMap.get(discriminatorValue);\n if (!option) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_union_discriminator,\n options: Array.from(this.optionsMap.keys()),\n path: [discriminator],\n });\n return INVALID;\n }\n if (ctx.common.async) {\n return option._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n else {\n return option._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n get discriminator() {\n return this._def.discriminator;\n }\n get options() {\n return this._def.options;\n }\n get optionsMap() {\n return this._def.optionsMap;\n }\n /**\n * The constructor of the discriminated union schema. Its behaviour is very similar to that of the normal z.union() constructor.\n * However, it only allows a union of objects, all of which need to share a discriminator property. This property must\n * have a different value for each object in the union.\n * @param discriminator the name of the discriminator property\n * @param types an array of object schemas\n * @param params\n */\n static create(discriminator, options, params) {\n // Get all the valid discriminator values\n const optionsMap = new Map();\n // try {\n for (const type of options) {\n const discriminatorValues = getDiscriminator(type.shape[discriminator]);\n if (!discriminatorValues.length) {\n throw new Error(`A discriminator value for key \\`${discriminator}\\` could not be extracted from all schema options`);\n }\n for (const value of discriminatorValues) {\n if (optionsMap.has(value)) {\n throw new Error(`Discriminator property ${String(discriminator)} has duplicate value ${String(value)}`);\n }\n optionsMap.set(value, type);\n }\n }\n return new ZodDiscriminatedUnion({\n typeName: ZodFirstPartyTypeKind.ZodDiscriminatedUnion,\n discriminator,\n options,\n optionsMap,\n ...processCreateParams(params),\n });\n }\n}\nfunction mergeValues(a, b) {\n const aType = getParsedType(a);\n const bType = getParsedType(b);\n if (a === b) {\n return { valid: true, data: a };\n }\n else if (aType === ZodParsedType.object && bType === ZodParsedType.object) {\n const bKeys = util.objectKeys(b);\n const sharedKeys = util.objectKeys(a).filter((key) => bKeys.indexOf(key) !== -1);\n const newObj = { ...a, ...b };\n for (const key of sharedKeys) {\n const sharedValue = mergeValues(a[key], b[key]);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newObj[key] = sharedValue.data;\n }\n return { valid: true, data: newObj };\n }\n else if (aType === ZodParsedType.array && bType === ZodParsedType.array) {\n if (a.length !== b.length) {\n return { valid: false };\n }\n const newArray = [];\n for (let index = 0; index < a.length; index++) {\n const itemA = a[index];\n const itemB = b[index];\n const sharedValue = mergeValues(itemA, itemB);\n if (!sharedValue.valid) {\n return { valid: false };\n }\n newArray.push(sharedValue.data);\n }\n return { valid: true, data: newArray };\n }\n else if (aType === ZodParsedType.date && bType === ZodParsedType.date && +a === +b) {\n return { valid: true, data: a };\n }\n else {\n return { valid: false };\n }\n}\nexport class ZodIntersection extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const handleParsed = (parsedLeft, parsedRight) => {\n if (isAborted(parsedLeft) || isAborted(parsedRight)) {\n return INVALID;\n }\n const merged = mergeValues(parsedLeft.value, parsedRight.value);\n if (!merged.valid) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_intersection_types,\n });\n return INVALID;\n }\n if (isDirty(parsedLeft) || isDirty(parsedRight)) {\n status.dirty();\n }\n return { status: status.value, value: merged.data };\n };\n if (ctx.common.async) {\n return Promise.all([\n this._def.left._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n this._def.right._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }),\n ]).then(([left, right]) => handleParsed(left, right));\n }\n else {\n return handleParsed(this._def.left._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }), this._def.right._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n }));\n }\n }\n}\nZodIntersection.create = (left, right, params) => {\n return new ZodIntersection({\n left: left,\n right: right,\n typeName: ZodFirstPartyTypeKind.ZodIntersection,\n ...processCreateParams(params),\n });\n};\n// type ZodTupleItems = [ZodTypeAny, ...ZodTypeAny[]];\nexport class ZodTuple extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.array) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.array,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n if (ctx.data.length < this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n return INVALID;\n }\n const rest = this._def.rest;\n if (!rest && ctx.data.length > this._def.items.length) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: this._def.items.length,\n inclusive: true,\n exact: false,\n type: \"array\",\n });\n status.dirty();\n }\n const items = [...ctx.data]\n .map((item, itemIndex) => {\n const schema = this._def.items[itemIndex] || this._def.rest;\n if (!schema)\n return null;\n return schema._parse(new ParseInputLazyPath(ctx, item, ctx.path, itemIndex));\n })\n .filter((x) => !!x); // filter nulls\n if (ctx.common.async) {\n return Promise.all(items).then((results) => {\n return ParseStatus.mergeArray(status, results);\n });\n }\n else {\n return ParseStatus.mergeArray(status, items);\n }\n }\n get items() {\n return this._def.items;\n }\n rest(rest) {\n return new ZodTuple({\n ...this._def,\n rest,\n });\n }\n}\nZodTuple.create = (schemas, params) => {\n if (!Array.isArray(schemas)) {\n throw new Error(\"You must pass an array of schemas to z.tuple([ ... ])\");\n }\n return new ZodTuple({\n items: schemas,\n typeName: ZodFirstPartyTypeKind.ZodTuple,\n rest: null,\n ...processCreateParams(params),\n });\n};\nexport class ZodRecord extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.object) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.object,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const pairs = [];\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n for (const key in ctx.data) {\n pairs.push({\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, key)),\n value: valueType._parse(new ParseInputLazyPath(ctx, ctx.data[key], ctx.path, key)),\n alwaysSet: key in ctx.data,\n });\n }\n if (ctx.common.async) {\n return ParseStatus.mergeObjectAsync(status, pairs);\n }\n else {\n return ParseStatus.mergeObjectSync(status, pairs);\n }\n }\n get element() {\n return this._def.valueType;\n }\n static create(first, second, third) {\n if (second instanceof ZodType) {\n return new ZodRecord({\n keyType: first,\n valueType: second,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(third),\n });\n }\n return new ZodRecord({\n keyType: ZodString.create(),\n valueType: first,\n typeName: ZodFirstPartyTypeKind.ZodRecord,\n ...processCreateParams(second),\n });\n }\n}\nexport class ZodMap extends ZodType {\n get keySchema() {\n return this._def.keyType;\n }\n get valueSchema() {\n return this._def.valueType;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.map) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.map,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const keyType = this._def.keyType;\n const valueType = this._def.valueType;\n const pairs = [...ctx.data.entries()].map(([key, value], index) => {\n return {\n key: keyType._parse(new ParseInputLazyPath(ctx, key, ctx.path, [index, \"key\"])),\n value: valueType._parse(new ParseInputLazyPath(ctx, value, ctx.path, [index, \"value\"])),\n };\n });\n if (ctx.common.async) {\n const finalMap = new Map();\n return Promise.resolve().then(async () => {\n for (const pair of pairs) {\n const key = await pair.key;\n const value = await pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n });\n }\n else {\n const finalMap = new Map();\n for (const pair of pairs) {\n const key = pair.key;\n const value = pair.value;\n if (key.status === \"aborted\" || value.status === \"aborted\") {\n return INVALID;\n }\n if (key.status === \"dirty\" || value.status === \"dirty\") {\n status.dirty();\n }\n finalMap.set(key.value, value.value);\n }\n return { status: status.value, value: finalMap };\n }\n }\n}\nZodMap.create = (keyType, valueType, params) => {\n return new ZodMap({\n valueType,\n keyType,\n typeName: ZodFirstPartyTypeKind.ZodMap,\n ...processCreateParams(params),\n });\n};\nexport class ZodSet extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.set) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.set,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const def = this._def;\n if (def.minSize !== null) {\n if (ctx.data.size < def.minSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_small,\n minimum: def.minSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.minSize.message,\n });\n status.dirty();\n }\n }\n if (def.maxSize !== null) {\n if (ctx.data.size > def.maxSize.value) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.too_big,\n maximum: def.maxSize.value,\n type: \"set\",\n inclusive: true,\n exact: false,\n message: def.maxSize.message,\n });\n status.dirty();\n }\n }\n const valueType = this._def.valueType;\n function finalizeSet(elements) {\n const parsedSet = new Set();\n for (const element of elements) {\n if (element.status === \"aborted\")\n return INVALID;\n if (element.status === \"dirty\")\n status.dirty();\n parsedSet.add(element.value);\n }\n return { status: status.value, value: parsedSet };\n }\n const elements = [...ctx.data.values()].map((item, i) => valueType._parse(new ParseInputLazyPath(ctx, item, ctx.path, i)));\n if (ctx.common.async) {\n return Promise.all(elements).then((elements) => finalizeSet(elements));\n }\n else {\n return finalizeSet(elements);\n }\n }\n min(minSize, message) {\n return new ZodSet({\n ...this._def,\n minSize: { value: minSize, message: errorUtil.toString(message) },\n });\n }\n max(maxSize, message) {\n return new ZodSet({\n ...this._def,\n maxSize: { value: maxSize, message: errorUtil.toString(message) },\n });\n }\n size(size, message) {\n return this.min(size, message).max(size, message);\n }\n nonempty(message) {\n return this.min(1, message);\n }\n}\nZodSet.create = (valueType, params) => {\n return new ZodSet({\n valueType,\n minSize: null,\n maxSize: null,\n typeName: ZodFirstPartyTypeKind.ZodSet,\n ...processCreateParams(params),\n });\n};\nexport class ZodFunction extends ZodType {\n constructor() {\n super(...arguments);\n this.validate = this.implement;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.function) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.function,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n function makeArgsIssue(args, error) {\n return makeIssue({\n data: args,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_arguments,\n argumentsError: error,\n },\n });\n }\n function makeReturnsIssue(returns, error) {\n return makeIssue({\n data: returns,\n path: ctx.path,\n errorMaps: [ctx.common.contextualErrorMap, ctx.schemaErrorMap, getErrorMap(), defaultErrorMap].filter((x) => !!x),\n issueData: {\n code: ZodIssueCode.invalid_return_type,\n returnTypeError: error,\n },\n });\n }\n const params = { errorMap: ctx.common.contextualErrorMap };\n const fn = ctx.data;\n if (this._def.returns instanceof ZodPromise) {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(async function (...args) {\n const error = new ZodError([]);\n const parsedArgs = await me._def.args.parseAsync(args, params).catch((e) => {\n error.addIssue(makeArgsIssue(args, e));\n throw error;\n });\n const result = await Reflect.apply(fn, this, parsedArgs);\n const parsedReturns = await me._def.returns._def.type\n .parseAsync(result, params)\n .catch((e) => {\n error.addIssue(makeReturnsIssue(result, e));\n throw error;\n });\n return parsedReturns;\n });\n }\n else {\n // Would love a way to avoid disabling this rule, but we need\n // an alias (using an arrow function was what caused 2651).\n // eslint-disable-next-line @typescript-eslint/no-this-alias\n const me = this;\n return OK(function (...args) {\n const parsedArgs = me._def.args.safeParse(args, params);\n if (!parsedArgs.success) {\n throw new ZodError([makeArgsIssue(args, parsedArgs.error)]);\n }\n const result = Reflect.apply(fn, this, parsedArgs.data);\n const parsedReturns = me._def.returns.safeParse(result, params);\n if (!parsedReturns.success) {\n throw new ZodError([makeReturnsIssue(result, parsedReturns.error)]);\n }\n return parsedReturns.data;\n });\n }\n }\n parameters() {\n return this._def.args;\n }\n returnType() {\n return this._def.returns;\n }\n args(...items) {\n return new ZodFunction({\n ...this._def,\n args: ZodTuple.create(items).rest(ZodUnknown.create()),\n });\n }\n returns(returnType) {\n return new ZodFunction({\n ...this._def,\n returns: returnType,\n });\n }\n implement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n strictImplement(func) {\n const validatedFunc = this.parse(func);\n return validatedFunc;\n }\n static create(args, returns, params) {\n return new ZodFunction({\n args: (args ? args : ZodTuple.create([]).rest(ZodUnknown.create())),\n returns: returns || ZodUnknown.create(),\n typeName: ZodFirstPartyTypeKind.ZodFunction,\n ...processCreateParams(params),\n });\n }\n}\nexport class ZodLazy extends ZodType {\n get schema() {\n return this._def.getter();\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const lazySchema = this._def.getter();\n return lazySchema._parse({ data: ctx.data, path: ctx.path, parent: ctx });\n }\n}\nZodLazy.create = (getter, params) => {\n return new ZodLazy({\n getter: getter,\n typeName: ZodFirstPartyTypeKind.ZodLazy,\n ...processCreateParams(params),\n });\n};\nexport class ZodLiteral extends ZodType {\n _parse(input) {\n if (input.data !== this._def.value) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_literal,\n expected: this._def.value,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n get value() {\n return this._def.value;\n }\n}\nZodLiteral.create = (value, params) => {\n return new ZodLiteral({\n value: value,\n typeName: ZodFirstPartyTypeKind.ZodLiteral,\n ...processCreateParams(params),\n });\n};\nfunction createZodEnum(values, params) {\n return new ZodEnum({\n values,\n typeName: ZodFirstPartyTypeKind.ZodEnum,\n ...processCreateParams(params),\n });\n}\nexport class ZodEnum extends ZodType {\n _parse(input) {\n if (typeof input.data !== \"string\") {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(this._def.values);\n }\n if (!this._cache.has(input.data)) {\n const ctx = this._getOrReturnCtx(input);\n const expectedValues = this._def.values;\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get options() {\n return this._def.values;\n }\n get enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Values() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n get Enum() {\n const enumValues = {};\n for (const val of this._def.values) {\n enumValues[val] = val;\n }\n return enumValues;\n }\n extract(values, newDef = this._def) {\n return ZodEnum.create(values, {\n ...this._def,\n ...newDef,\n });\n }\n exclude(values, newDef = this._def) {\n return ZodEnum.create(this.options.filter((opt) => !values.includes(opt)), {\n ...this._def,\n ...newDef,\n });\n }\n}\nZodEnum.create = createZodEnum;\nexport class ZodNativeEnum extends ZodType {\n _parse(input) {\n const nativeEnumValues = util.getValidEnumValues(this._def.values);\n const ctx = this._getOrReturnCtx(input);\n if (ctx.parsedType !== ZodParsedType.string && ctx.parsedType !== ZodParsedType.number) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n expected: util.joinValues(expectedValues),\n received: ctx.parsedType,\n code: ZodIssueCode.invalid_type,\n });\n return INVALID;\n }\n if (!this._cache) {\n this._cache = new Set(util.getValidEnumValues(this._def.values));\n }\n if (!this._cache.has(input.data)) {\n const expectedValues = util.objectValues(nativeEnumValues);\n addIssueToContext(ctx, {\n received: ctx.data,\n code: ZodIssueCode.invalid_enum_value,\n options: expectedValues,\n });\n return INVALID;\n }\n return OK(input.data);\n }\n get enum() {\n return this._def.values;\n }\n}\nZodNativeEnum.create = (values, params) => {\n return new ZodNativeEnum({\n values: values,\n typeName: ZodFirstPartyTypeKind.ZodNativeEnum,\n ...processCreateParams(params),\n });\n};\nexport class ZodPromise extends ZodType {\n unwrap() {\n return this._def.type;\n }\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n if (ctx.parsedType !== ZodParsedType.promise && ctx.common.async === false) {\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.promise,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n const promisified = ctx.parsedType === ZodParsedType.promise ? ctx.data : Promise.resolve(ctx.data);\n return OK(promisified.then((data) => {\n return this._def.type.parseAsync(data, {\n path: ctx.path,\n errorMap: ctx.common.contextualErrorMap,\n });\n }));\n }\n}\nZodPromise.create = (schema, params) => {\n return new ZodPromise({\n type: schema,\n typeName: ZodFirstPartyTypeKind.ZodPromise,\n ...processCreateParams(params),\n });\n};\nexport class ZodEffects extends ZodType {\n innerType() {\n return this._def.schema;\n }\n sourceType() {\n return this._def.schema._def.typeName === ZodFirstPartyTypeKind.ZodEffects\n ? this._def.schema.sourceType()\n : this._def.schema;\n }\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n const effect = this._def.effect || null;\n const checkCtx = {\n addIssue: (arg) => {\n addIssueToContext(ctx, arg);\n if (arg.fatal) {\n status.abort();\n }\n else {\n status.dirty();\n }\n },\n get path() {\n return ctx.path;\n },\n };\n checkCtx.addIssue = checkCtx.addIssue.bind(checkCtx);\n if (effect.type === \"preprocess\") {\n const processed = effect.transform(ctx.data, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(processed).then(async (processed) => {\n if (status.value === \"aborted\")\n return INVALID;\n const result = await this._def.schema._parseAsync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n });\n }\n else {\n if (status.value === \"aborted\")\n return INVALID;\n const result = this._def.schema._parseSync({\n data: processed,\n path: ctx.path,\n parent: ctx,\n });\n if (result.status === \"aborted\")\n return INVALID;\n if (result.status === \"dirty\")\n return DIRTY(result.value);\n if (status.value === \"dirty\")\n return DIRTY(result.value);\n return result;\n }\n }\n if (effect.type === \"refinement\") {\n const executeRefinement = (acc) => {\n const result = effect.refinement(acc, checkCtx);\n if (ctx.common.async) {\n return Promise.resolve(result);\n }\n if (result instanceof Promise) {\n throw new Error(\"Async refinement encountered during synchronous parse operation. Use .parseAsync instead.\");\n }\n return acc;\n };\n if (ctx.common.async === false) {\n const inner = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n // return value is ignored\n executeRefinement(inner.value);\n return { status: status.value, value: inner.value };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((inner) => {\n if (inner.status === \"aborted\")\n return INVALID;\n if (inner.status === \"dirty\")\n status.dirty();\n return executeRefinement(inner.value).then(() => {\n return { status: status.value, value: inner.value };\n });\n });\n }\n }\n if (effect.type === \"transform\") {\n if (ctx.common.async === false) {\n const base = this._def.schema._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (!isValid(base))\n return INVALID;\n const result = effect.transform(base.value, checkCtx);\n if (result instanceof Promise) {\n throw new Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);\n }\n return { status: status.value, value: result };\n }\n else {\n return this._def.schema._parseAsync({ data: ctx.data, path: ctx.path, parent: ctx }).then((base) => {\n if (!isValid(base))\n return INVALID;\n return Promise.resolve(effect.transform(base.value, checkCtx)).then((result) => ({\n status: status.value,\n value: result,\n }));\n });\n }\n }\n util.assertNever(effect);\n }\n}\nZodEffects.create = (schema, effect, params) => {\n return new ZodEffects({\n schema,\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n effect,\n ...processCreateParams(params),\n });\n};\nZodEffects.createWithPreprocess = (preprocess, schema, params) => {\n return new ZodEffects({\n schema,\n effect: { type: \"preprocess\", transform: preprocess },\n typeName: ZodFirstPartyTypeKind.ZodEffects,\n ...processCreateParams(params),\n });\n};\nexport { ZodEffects as ZodTransformer };\nexport class ZodOptional extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.undefined) {\n return OK(undefined);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodOptional.create = (type, params) => {\n return new ZodOptional({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodOptional,\n ...processCreateParams(params),\n });\n};\nexport class ZodNullable extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType === ZodParsedType.null) {\n return OK(null);\n }\n return this._def.innerType._parse(input);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodNullable.create = (type, params) => {\n return new ZodNullable({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodNullable,\n ...processCreateParams(params),\n });\n};\nexport class ZodDefault extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n let data = ctx.data;\n if (ctx.parsedType === ZodParsedType.undefined) {\n data = this._def.defaultValue();\n }\n return this._def.innerType._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n removeDefault() {\n return this._def.innerType;\n }\n}\nZodDefault.create = (type, params) => {\n return new ZodDefault({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodDefault,\n defaultValue: typeof params.default === \"function\" ? params.default : () => params.default,\n ...processCreateParams(params),\n });\n};\nexport class ZodCatch extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n // newCtx is used to not collect issues from inner types in ctx\n const newCtx = {\n ...ctx,\n common: {\n ...ctx.common,\n issues: [],\n },\n };\n const result = this._def.innerType._parse({\n data: newCtx.data,\n path: newCtx.path,\n parent: {\n ...newCtx,\n },\n });\n if (isAsync(result)) {\n return result.then((result) => {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n });\n }\n else {\n return {\n status: \"valid\",\n value: result.status === \"valid\"\n ? result.value\n : this._def.catchValue({\n get error() {\n return new ZodError(newCtx.common.issues);\n },\n input: newCtx.data,\n }),\n };\n }\n }\n removeCatch() {\n return this._def.innerType;\n }\n}\nZodCatch.create = (type, params) => {\n return new ZodCatch({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodCatch,\n catchValue: typeof params.catch === \"function\" ? params.catch : () => params.catch,\n ...processCreateParams(params),\n });\n};\nexport class ZodNaN extends ZodType {\n _parse(input) {\n const parsedType = this._getType(input);\n if (parsedType !== ZodParsedType.nan) {\n const ctx = this._getOrReturnCtx(input);\n addIssueToContext(ctx, {\n code: ZodIssueCode.invalid_type,\n expected: ZodParsedType.nan,\n received: ctx.parsedType,\n });\n return INVALID;\n }\n return { status: \"valid\", value: input.data };\n }\n}\nZodNaN.create = (params) => {\n return new ZodNaN({\n typeName: ZodFirstPartyTypeKind.ZodNaN,\n ...processCreateParams(params),\n });\n};\nexport const BRAND = Symbol(\"zod_brand\");\nexport class ZodBranded extends ZodType {\n _parse(input) {\n const { ctx } = this._processInputParams(input);\n const data = ctx.data;\n return this._def.type._parse({\n data,\n path: ctx.path,\n parent: ctx,\n });\n }\n unwrap() {\n return this._def.type;\n }\n}\nexport class ZodPipeline extends ZodType {\n _parse(input) {\n const { status, ctx } = this._processInputParams(input);\n if (ctx.common.async) {\n const handleAsync = async () => {\n const inResult = await this._def.in._parseAsync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return DIRTY(inResult.value);\n }\n else {\n return this._def.out._parseAsync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n };\n return handleAsync();\n }\n else {\n const inResult = this._def.in._parseSync({\n data: ctx.data,\n path: ctx.path,\n parent: ctx,\n });\n if (inResult.status === \"aborted\")\n return INVALID;\n if (inResult.status === \"dirty\") {\n status.dirty();\n return {\n status: \"dirty\",\n value: inResult.value,\n };\n }\n else {\n return this._def.out._parseSync({\n data: inResult.value,\n path: ctx.path,\n parent: ctx,\n });\n }\n }\n }\n static create(a, b) {\n return new ZodPipeline({\n in: a,\n out: b,\n typeName: ZodFirstPartyTypeKind.ZodPipeline,\n });\n }\n}\nexport class ZodReadonly extends ZodType {\n _parse(input) {\n const result = this._def.innerType._parse(input);\n const freeze = (data) => {\n if (isValid(data)) {\n data.value = Object.freeze(data.value);\n }\n return data;\n };\n return isAsync(result) ? result.then((data) => freeze(data)) : freeze(result);\n }\n unwrap() {\n return this._def.innerType;\n }\n}\nZodReadonly.create = (type, params) => {\n return new ZodReadonly({\n innerType: type,\n typeName: ZodFirstPartyTypeKind.ZodReadonly,\n ...processCreateParams(params),\n });\n};\n////////////////////////////////////////\n////////////////////////////////////////\n////////// //////////\n////////// z.custom //////////\n////////// //////////\n////////////////////////////////////////\n////////////////////////////////////////\nfunction cleanParams(params, data) {\n const p = typeof params === \"function\" ? params(data) : typeof params === \"string\" ? { message: params } : params;\n const p2 = typeof p === \"string\" ? { message: p } : p;\n return p2;\n}\nexport function custom(check, _params = {}, \n/**\n * @deprecated\n *\n * Pass `fatal` into the params object instead:\n *\n * ```ts\n * z.string().custom((val) => val.length > 5, { fatal: false })\n * ```\n *\n */\nfatal) {\n if (check)\n return ZodAny.create().superRefine((data, ctx) => {\n const r = check(data);\n if (r instanceof Promise) {\n return r.then((r) => {\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n });\n }\n if (!r) {\n const params = cleanParams(_params, data);\n const _fatal = params.fatal ?? fatal ?? true;\n ctx.addIssue({ code: \"custom\", ...params, fatal: _fatal });\n }\n return;\n });\n return ZodAny.create();\n}\nexport { ZodType as Schema, ZodType as ZodSchema };\nexport const late = {\n object: ZodObject.lazycreate,\n};\nexport var ZodFirstPartyTypeKind;\n(function (ZodFirstPartyTypeKind) {\n ZodFirstPartyTypeKind[\"ZodString\"] = \"ZodString\";\n ZodFirstPartyTypeKind[\"ZodNumber\"] = \"ZodNumber\";\n ZodFirstPartyTypeKind[\"ZodNaN\"] = \"ZodNaN\";\n ZodFirstPartyTypeKind[\"ZodBigInt\"] = \"ZodBigInt\";\n ZodFirstPartyTypeKind[\"ZodBoolean\"] = \"ZodBoolean\";\n ZodFirstPartyTypeKind[\"ZodDate\"] = \"ZodDate\";\n ZodFirstPartyTypeKind[\"ZodSymbol\"] = \"ZodSymbol\";\n ZodFirstPartyTypeKind[\"ZodUndefined\"] = \"ZodUndefined\";\n ZodFirstPartyTypeKind[\"ZodNull\"] = \"ZodNull\";\n ZodFirstPartyTypeKind[\"ZodAny\"] = \"ZodAny\";\n ZodFirstPartyTypeKind[\"ZodUnknown\"] = \"ZodUnknown\";\n ZodFirstPartyTypeKind[\"ZodNever\"] = \"ZodNever\";\n ZodFirstPartyTypeKind[\"ZodVoid\"] = \"ZodVoid\";\n ZodFirstPartyTypeKind[\"ZodArray\"] = \"ZodArray\";\n ZodFirstPartyTypeKind[\"ZodObject\"] = \"ZodObject\";\n ZodFirstPartyTypeKind[\"ZodUnion\"] = \"ZodUnion\";\n ZodFirstPartyTypeKind[\"ZodDiscriminatedUnion\"] = \"ZodDiscriminatedUnion\";\n ZodFirstPartyTypeKind[\"ZodIntersection\"] = \"ZodIntersection\";\n ZodFirstPartyTypeKind[\"ZodTuple\"] = \"ZodTuple\";\n ZodFirstPartyTypeKind[\"ZodRecord\"] = \"ZodRecord\";\n ZodFirstPartyTypeKind[\"ZodMap\"] = \"ZodMap\";\n ZodFirstPartyTypeKind[\"ZodSet\"] = \"ZodSet\";\n ZodFirstPartyTypeKind[\"ZodFunction\"] = \"ZodFunction\";\n ZodFirstPartyTypeKind[\"ZodLazy\"] = \"ZodLazy\";\n ZodFirstPartyTypeKind[\"ZodLiteral\"] = \"ZodLiteral\";\n ZodFirstPartyTypeKind[\"ZodEnum\"] = \"ZodEnum\";\n ZodFirstPartyTypeKind[\"ZodEffects\"] = \"ZodEffects\";\n ZodFirstPartyTypeKind[\"ZodNativeEnum\"] = \"ZodNativeEnum\";\n ZodFirstPartyTypeKind[\"ZodOptional\"] = \"ZodOptional\";\n ZodFirstPartyTypeKind[\"ZodNullable\"] = \"ZodNullable\";\n ZodFirstPartyTypeKind[\"ZodDefault\"] = \"ZodDefault\";\n ZodFirstPartyTypeKind[\"ZodCatch\"] = \"ZodCatch\";\n ZodFirstPartyTypeKind[\"ZodPromise\"] = \"ZodPromise\";\n ZodFirstPartyTypeKind[\"ZodBranded\"] = \"ZodBranded\";\n ZodFirstPartyTypeKind[\"ZodPipeline\"] = \"ZodPipeline\";\n ZodFirstPartyTypeKind[\"ZodReadonly\"] = \"ZodReadonly\";\n})(ZodFirstPartyTypeKind || (ZodFirstPartyTypeKind = {}));\n// requires TS 4.4+\nclass Class {\n constructor(..._) { }\n}\nconst instanceOfType = (\n// const instanceOfType = <T extends new (...args: any[]) => any>(\ncls, params = {\n message: `Input not instance of ${cls.name}`,\n}) => custom((data) => data instanceof cls, params);\nconst stringType = ZodString.create;\nconst numberType = ZodNumber.create;\nconst nanType = ZodNaN.create;\nconst bigIntType = ZodBigInt.create;\nconst booleanType = ZodBoolean.create;\nconst dateType = ZodDate.create;\nconst symbolType = ZodSymbol.create;\nconst undefinedType = ZodUndefined.create;\nconst nullType = ZodNull.create;\nconst anyType = ZodAny.create;\nconst unknownType = ZodUnknown.create;\nconst neverType = ZodNever.create;\nconst voidType = ZodVoid.create;\nconst arrayType = ZodArray.create;\nconst objectType = ZodObject.create;\nconst strictObjectType = ZodObject.strictCreate;\nconst unionType = ZodUnion.create;\nconst discriminatedUnionType = ZodDiscriminatedUnion.create;\nconst intersectionType = ZodIntersection.create;\nconst tupleType = ZodTuple.create;\nconst recordType = ZodRecord.create;\nconst mapType = ZodMap.create;\nconst setType = ZodSet.create;\nconst functionType = ZodFunction.create;\nconst lazyType = ZodLazy.create;\nconst literalType = ZodLiteral.create;\nconst enumType = ZodEnum.create;\nconst nativeEnumType = ZodNativeEnum.create;\nconst promiseType = ZodPromise.create;\nconst effectsType = ZodEffects.create;\nconst optionalType = ZodOptional.create;\nconst nullableType = ZodNullable.create;\nconst preprocessType = ZodEffects.createWithPreprocess;\nconst pipelineType = ZodPipeline.create;\nconst ostring = () => stringType().optional();\nconst onumber = () => numberType().optional();\nconst oboolean = () => booleanType().optional();\nexport const coerce = {\n string: ((arg) => ZodString.create({ ...arg, coerce: true })),\n number: ((arg) => ZodNumber.create({ ...arg, coerce: true })),\n boolean: ((arg) => ZodBoolean.create({\n ...arg,\n coerce: true,\n })),\n bigint: ((arg) => ZodBigInt.create({ ...arg, coerce: true })),\n date: ((arg) => ZodDate.create({ ...arg, coerce: true })),\n};\nexport { anyType as any, arrayType as array, bigIntType as bigint, booleanType as boolean, dateType as date, discriminatedUnionType as discriminatedUnion, effectsType as effect, enumType as enum, functionType as function, instanceOfType as instanceof, intersectionType as intersection, lazyType as lazy, literalType as literal, mapType as map, nanType as nan, nativeEnumType as nativeEnum, neverType as never, nullType as null, nullableType as nullable, numberType as number, objectType as object, oboolean, onumber, optionalType as optional, ostring, pipelineType as pipeline, preprocessType as preprocess, promiseType as promise, recordType as record, setType as set, strictObjectType as strictObject, stringType as string, symbolType as symbol, effectsType as transformer, tupleType as tuple, undefinedType as undefined, unionType as union, unknownType as unknown, voidType as void, };\nexport const NEVER = INVALID;\n","import { type IAgentRuntime } from \"@elizaos/core\";\nimport { z } from \"zod\";\n\n/**\n * Simplified Twitter environment schema\n * All time intervals are in minutes for consistency\n */\nexport const twitterEnvSchema = z.object({\n // Required API credentials\n TWITTER_API_KEY: z.string(),\n TWITTER_API_SECRET_KEY: z.string(),\n TWITTER_ACCESS_TOKEN: z.string(),\n TWITTER_ACCESS_TOKEN_SECRET: z.string(),\n \n // Core configuration\n TWITTER_DRY_RUN: z.string().default(\"false\"),\n TWITTER_TARGET_USERS: z.string().default(\"\"), // comma-separated list, empty = all\n \n // Feature toggles\n TWITTER_ENABLE_POST: z.string().default(\"false\"),\n TWITTER_ENABLE_REPLIES: z.string().default(\"true\"),\n TWITTER_ENABLE_ACTIONS: z.string().default(\"false\"), // likes, retweets, quotes\n \n // Timing configuration (all in minutes)\n TWITTER_POST_INTERVAL: z.string().default(\"120\"), // minutes between posts\n TWITTER_ENGAGEMENT_INTERVAL: z.string().default(\"30\"), // minutes between all interactions\n \n // Limits\n TWITTER_MAX_ENGAGEMENTS_PER_RUN: z.string().default(\"10\"),\n TWITTER_MAX_TWEET_LENGTH: z.string().default(\"280\"), // standard tweet length\n \n // Advanced\n TWITTER_RETRY_LIMIT: z.string().default(\"5\"),\n});\n\n// Remove deprecated\ndelete process.env.TWITTER_SEARCH_ENABLE;\ndelete process.env.TWITTER_POST_ENABLE;\n\nexport type TwitterConfig = z.infer<typeof twitterEnvSchema>;\n\n/**\n * Parse safe integer with fallback\n */\nfunction safeParseInt(value: string | undefined, defaultValue: number): number {\n if (!value) return defaultValue;\n const parsed = parseInt(value, 10);\n return isNaN(parsed) ? defaultValue : parsed;\n}\n\n/**\n * Helper to parse a comma-separated list of Twitter usernames\n */\nfunction parseTargetUsers(targetUsersStr?: string | null): string[] {\n if (!targetUsersStr?.trim()) {\n return [];\n }\n return targetUsersStr\n .split(\",\")\n .map((user) => user.trim())\n .filter(Boolean);\n}\n\n/**\n * Check if a user should be targeted for interactions\n * Empty list means target everyone\n * \"*\" wildcard means target everyone explicitly\n */\nexport function shouldTargetUser(\n username: string,\n targetUsersConfig: string,\n): boolean {\n if (!targetUsersConfig?.trim()) {\n return true; // Empty = interact with everyone\n }\n\n const targetUsers = parseTargetUsers(targetUsersConfig);\n \n if (targetUsers.includes(\"*\")) {\n return true; // Wildcard = everyone\n }\n\n // Check if the username (without @) is in the target list\n const normalizedUsername = username.toLowerCase().replace(/^@/, \"\");\n return targetUsers.some(\n (target) => target.toLowerCase().replace(/^@/, \"\") === normalizedUsername,\n );\n}\n\n/**\n * Get parsed target users list\n */\nexport function getTargetUsers(targetUsersConfig: string): string[] {\n const users = parseTargetUsers(targetUsersConfig);\n // Filter out wildcard since it's a special case\n return users.filter(u => u !== \"*\");\n}\n\n/**\n * Helper function to get a setting from runtime or environment\n */\nfunction getSetting(\n runtime: IAgentRuntime,\n key: string,\n defaultValue?: string\n): string | undefined {\n return runtime.getSetting(key) ?? process.env[key] ?? defaultValue;\n}\n\n/**\n * Validates Twitter configuration using simplified schema\n */\nexport async function validateTwitterConfig(\n runtime: IAgentRuntime,\n config: Partial<TwitterConfig> = {},\n): Promise<TwitterConfig> {\n try {\n const validatedConfig: TwitterConfig = {\n TWITTER_API_KEY: config.TWITTER_API_KEY ?? getSetting(runtime, \"TWITTER_API_KEY\") ?? \"\",\n TWITTER_API_SECRET_KEY: config.TWITTER_API_SECRET_KEY ?? getSetting(runtime, \"TWITTER_API_SECRET_KEY\") ?? \"\",\n TWITTER_ACCESS_TOKEN: config.TWITTER_ACCESS_TOKEN ?? getSetting(runtime, \"TWITTER_ACCESS_TOKEN\") ?? \"\",\n TWITTER_ACCESS_TOKEN_SECRET: config.TWITTER_ACCESS_TOKEN_SECRET ?? getSetting(runtime, \"TWITTER_ACCESS_TOKEN_SECRET\") ?? \"\",\n TWITTER_DRY_RUN: String((config.TWITTER_DRY_RUN ?? getSetting(runtime, \"TWITTER_DRY_RUN\") ?? \"false\").toLowerCase() === \"true\"),\n TWITTER_TARGET_USERS: config.TWITTER_TARGET_USERS ?? getSetting(runtime, \"TWITTER_TARGET_USERS\") ?? \"\",\n TWITTER_ENABLE_POST: String((config.TWITTER_ENABLE_POST ?? getSetting(runtime, \"TWITTER_ENABLE_POST\") ?? \"false\").toLowerCase() === \"true\"),\n TWITTER_ENABLE_REPLIES: String(\n config.TWITTER_ENABLE_REPLIES !== undefined\n ? config.TWITTER_ENABLE_REPLIES.toLowerCase() === \"true\"\n : (getSetting(runtime, \"TWITTER_ENABLE_REPLIES\") ?? \"true\").toLowerCase() === \"true\"\n ),\n TWITTER_ENABLE_ACTIONS: String((config.TWITTER_ENABLE_ACTIONS ?? getSetting(runtime, \"TWITTER_ENABLE_ACTIONS\") ?? \"false\").toLowerCase() === \"true\"),\n TWITTER_POST_INTERVAL: String(safeParseInt(config.TWITTER_POST_INTERVAL ?? getSetting(runtime, \"TWITTER_POST_INTERVAL\"), 120)),\n TWITTER_ENGAGEMENT_INTERVAL: String(safeParseInt(config.TWITTER_ENGAGEMENT_INTERVAL ?? getSetting(runtime, \"TWITTER_ENGAGEMENT_INTERVAL\"), 30)),\n TWITTER_MAX_ENGAGEMENTS_PER_RUN: String(safeParseInt(config.TWITTER_MAX_ENGAGEMENTS_PER_RUN ?? getSetting(runtime, \"TWITTER_MAX_ENGAGEMENTS_PER_RUN\"), 10)),\n TWITTER_MAX_TWEET_LENGTH: String(safeParseInt(config.TWITTER_MAX_TWEET_LENGTH ?? getSetting(runtime, \"TWITTER_MAX_TWEET_LENGTH\"), 280)),\n TWITTER_RETRY_LIMIT: String(safeParseInt(config.TWITTER_RETRY_LIMIT ?? getSetting(runtime, \"TWITTER_RETRY_LIMIT\"), 5)),\n };\n\n // Validate required credentials\n if (\n !validatedConfig.TWITTER_API_KEY ||\n !validatedConfig.TWITTER_API_SECRET_KEY ||\n !validatedConfig.TWITTER_ACCESS_TOKEN ||\n !validatedConfig.TWITTER_ACCESS_TOKEN_SECRET\n ) {\n throw new Error(\n \"Twitter API credentials are required. Please set TWITTER_API_KEY, TWITTER_API_SECRET_KEY, TWITTER_ACCESS_TOKEN, and TWITTER_ACCESS_TOKEN_SECRET\",\n );\n }\n\n return twitterEnvSchema.parse(validatedConfig);\n } catch (error) {\n if (error instanceof z.ZodError) {\n const errorMessages = error.errors\n .map((err) => `${err.path.join(\".\")}: ${err.message}`)\n .join(\", \");\n throw new Error(\n `Twitter configuration validation failed: ${errorMessages}`,\n );\n }\n throw error;\n }\n}\n\n/**\n * Get configuration from environment variables\n * @returns Partial<TwitterConfig>\n */\nfunction getEnvConfig(): Partial<TwitterConfig> {\n const config: Partial<TwitterConfig> = {};\n\n const getConfig = (key: keyof TwitterConfig): string | undefined => {\n if (typeof process !== \"undefined\" && process.env) {\n return process.env[key];\n }\n return undefined;\n };\n\n // Map all environment variables\n Object.keys(twitterEnvSchema.shape).forEach((key) => {\n const value = getConfig(key as keyof TwitterConfig);\n if (value !== undefined) {\n config[key as keyof TwitterConfig] = value;\n }\n });\n\n return config;\n}\n\n/**\n * Get default configuration\n * @returns TwitterConfig with default values\n */\nfunction getDefaultConfig(): TwitterConfig {\n const getConfig = (key: keyof TwitterConfig): string | undefined => {\n if (typeof process !== \"undefined\" && process.env) {\n return process.env[key];\n }\n return undefined;\n };\n\n return {\n TWITTER_API_KEY: getConfig(\"TWITTER_API_KEY\") || \"\",\n TWITTER_API_SECRET_KEY: getConfig(\"TWITTER_API_SECRET_KEY\") || \"\",\n TWITTER_ACCESS_TOKEN: getConfig(\"TWITTER_ACCESS_TOKEN\") || \"\",\n TWITTER_ACCESS_TOKEN_SECRET: getConfig(\"TWITTER_ACCESS_TOKEN_SECRET\") || \"\",\n TWITTER_DRY_RUN: getConfig(\"TWITTER_DRY_RUN\") || \"false\",\n TWITTER_TARGET_USERS: getConfig(\"TWITTER_TARGET_USERS\") || \"\",\n TWITTER_ENABLE_POST: getConfig(\"TWITTER_ENABLE_POST\") || \"false\",\n TWITTER_ENABLE_REPLIES: getConfig(\"TWITTER_ENABLE_REPLIES\") || \"true\",\n TWITTER_ENABLE_ACTIONS: getConfig(\"TWITTER_ENABLE_ACTIONS\") || \"false\",\n TWITTER_POST_INTERVAL: getConfig(\"TWITTER_POST_INTERVAL\") || \"120\",\n TWITTER_ENGAGEMENT_INTERVAL: getConfig(\"TWITTER_ENGAGEMENT_INTERVAL\") || \"30\",\n TWITTER_MAX_ENGAGEMENTS_PER_RUN: getConfig(\"TWITTER_MAX_ENGAGEMENTS_PER_RUN\") || \"10\",\n TWITTER_MAX_TWEET_LENGTH: getConfig(\"TWITTER_MAX_TWEET_LENGTH\") || \"280\",\n TWITTER_RETRY_LIMIT: getConfig(\"TWITTER_RETRY_LIMIT\") || \"5\",\n };\n}\n\n/**\n * Load configuration from file (stub for future implementation)\n * @param configPath - Path to the configuration file (optional)\n * @returns Partial TwitterConfig object\n */\nexport function loadConfigFromFile(configPath?: string): Partial<TwitterConfig> {\n // For now, return empty config as file loading is not implemented\n return {};\n}\n\n/**\n * Load merged configuration from all sources\n * @param configPath - Path to the configuration file (optional)\n * @returns Complete TwitterConfig object\n */\nexport function loadConfig(configPath?: string): TwitterConfig {\n const fileConfig = loadConfigFromFile(configPath);\n\n return {\n ...getDefaultConfig(),\n ...fileConfig,\n ...getEnvConfig(),\n };\n}\n\n\n\n/**\n * Validate configuration\n * @param config - Configuration to validate\n * @throws Error if configuration is invalid\n */\nexport function validateConfig(config: unknown): TwitterConfig {\n return twitterEnvSchema.parse(config);\n}\n","import {\n ChannelType,\n type Content,\n EventType,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type UUID,\n createUniqueUuid,\n logger,\n} from \"@elizaos/core\";\nimport type { ClientBase } from \"./base\";\nimport type { MediaData } from \"./types\";\nimport { TwitterEventTypes } from \"./types\";\nimport { sendTweet } from \"./utils\";\n/**\n * Class representing a Twitter post client for generating and posting tweets.\n */\nexport class TwitterPostClient {\n client: ClientBase;\n runtime: IAgentRuntime;\n twitterUsername: string;\n private isDryRun: boolean;\n private state: any;\n private isRunning: boolean = false;\n\n /**\n * Constructor for initializing a new Twitter client with the provided client, runtime, and state\n * @param {ClientBase} client - The client used for interacting with Twitter API\n * @param {IAgentRuntime} runtime - The runtime environment for the agent\n * @param {any} state - The state object containing configuration settings\n */\n constructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n this.client = client;\n this.state = state;\n this.runtime = runtime;\n const dryRunSetting = this.state?.TWITTER_DRY_RUN ?? this.runtime.getSetting(\"TWITTER_DRY_RUN\") ?? process.env.TWITTER_DRY_RUN;\n this.isDryRun = dryRunSetting === true || dryRunSetting === \"true\" || \n (typeof dryRunSetting === \"string\" && dryRunSetting.toLowerCase() === \"true\");\n\n // Log configuration on initialization\n logger.log(\"Twitter Post Client Configuration:\");\n logger.log(`- Dry Run Mode: ${this.isDryRun ? \"Enabled\" : \"Disabled\"}`);\n\n const postInterval = parseInt(\n this.state?.TWITTER_POST_INTERVAL || \n this.runtime.getSetting(\"TWITTER_POST_INTERVAL\") as string || \n process.env.TWITTER_POST_INTERVAL ||\n \"120\"\n );\n logger.log(`- Post Interval: ${postInterval} minutes`);\n }\n \n /**\n * Stops the Twitter post client\n */\n async stop() {\n logger.log(\"Stopping Twitter post client...\");\n this.isRunning = false;\n }\n\n /**\n * Starts the Twitter post client, setting up a loop to periodically generate new tweets.\n */\n async start() {\n logger.log(\"Starting Twitter post client...\");\n this.isRunning = true;\n\n const generateNewTweetLoop = async () => {\n if (!this.isRunning) {\n logger.log(\"Twitter post client stopped, exiting loop\");\n return;\n }\n \n // Get post interval in minutes\n const postIntervalMinutes = parseInt(\n this.state?.TWITTER_POST_INTERVAL || \n this.runtime.getSetting(\"TWITTER_POST_INTERVAL\") as string || \n process.env.TWITTER_POST_INTERVAL ||\n \"120\"\n );\n \n // Convert to milliseconds\n const interval = postIntervalMinutes * 60 * 1000;\n \n logger.info(`Next tweet scheduled in ${postIntervalMinutes} minutes`);\n\n await this.generateNewTweet();\n \n if (this.isRunning) {\n setTimeout(generateNewTweetLoop, interval);\n }\n };\n\n // Start the loop after a 1 minute delay to allow other services to initialize\n // Always post immediately for better UX\n await new Promise((resolve) => setTimeout(resolve, 1000));\n \n // Check if we should generate a tweet immediately\n const postImmediately = parseInt(\n this.state?.TWITTER_POST_INTERVAL || \n this.runtime.getSetting(\"TWITTER_POST_INTERVAL\") as string || \n process.env.TWITTER_POST_INTERVAL ||\n \"120\"\n ) === 0;\n \n if (postImmediately) {\n logger.info(\"TWITTER_POST_IMMEDIATELY is true, generating initial tweet now\");\n await this.generateNewTweet();\n }\n \n // Start the regular generation loop\n generateNewTweetLoop();\n }\n\n /**\n * Handles the creation and posting of a tweet by emitting standardized events.\n * This approach aligns with our platform-independent architecture.\n */\n async generateNewTweet() {\n logger.info(\"Attempting to generate new tweet...\");\n \n try {\n // Create the timeline room ID for storing the post\n const userId = this.client.profile?.id;\n if (!userId) {\n logger.error(\"Cannot generate tweet: Twitter profile not available\");\n return;\n }\n\n logger.info(`Generating tweet for user: ${this.client.profile?.username} (${userId})`);\n\n // Create standardized world and room IDs\n const worldId = createUniqueUuid(this.runtime, userId) as UUID;\n const roomId = createUniqueUuid(this.runtime, `${userId}-home`) as UUID;\n \n // Create a callback for handling the actual posting\n const callback: HandlerCallback = async (content: Content) => {\n logger.info(\"Tweet generation callback triggered\");\n \n try {\n if (this.isDryRun) {\n logger.info(`[DRY RUN] Would post tweet: ${content.text}`);\n return [];\n }\n\n if (content.text.includes(\"Error: Missing\")) {\n logger.error(\"Error: Missing some context\", content);\n return [];\n }\n\n logger.info(`Posting tweet: ${content.text}`);\n\n // Post the tweet\n const result = await this.postToTwitter(\n content.text,\n content.mediaData as MediaData[],\n );\n\n // If result is null, it means we detected a duplicate tweet and skipped posting\n if (result === null) {\n logger.info(\"Skipped posting duplicate tweet\");\n return [];\n }\n\n const tweetId = (result as any).id;\n logger.info(`Tweet posted successfully! ID: ${tweetId}`);\n\n if (result) {\n const postedTweetId = createUniqueUuid(this.runtime, tweetId);\n\n // Create memory for the posted tweet\n const postedMemory: Memory = {\n id: postedTweetId,\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId,\n content: {\n ...content,\n source: \"twitter\",\n channelType: ChannelType.FEED,\n type: \"post\",\n metadata: {\n tweetId,\n postedAt: Date.now(),\n },\n },\n createdAt: Date.now(),\n };\n\n await this.runtime.createMemory(postedMemory, \"messages\");\n\n return [postedMemory];\n }\n\n return [];\n } catch (error) {\n logger.error(\"Error in tweet generation callback:\", error);\n return [];\n }\n };\n\n // Emit the event that will trigger the agent to generate content\n this.runtime.emitEvent(\n TwitterEventTypes.POST_GENERATED,\n {\n callback,\n entityId: this.runtime.agentId,\n userId,\n roomId,\n source: \"twitter\",\n },\n );\n \n logger.info(\"POST_GENERATED event emitted successfully\");\n } catch (error) {\n logger.error(\"Error generating tweet:\", error);\n }\n }\n\n /**\n * Posts content to Twitter\n * @param {string} text The tweet text to post\n * @param {MediaData[]} mediaData Optional media to attach to the tweet\n * @returns {Promise<any>} The result from the Twitter API\n */\n private async postToTwitter(\n text: string,\n mediaData: MediaData[] = [],\n ): Promise<any> {\n try {\n // Check if this tweet is a duplicate of the last one\n const lastPost = await this.runtime.getCache<any>(\n `twitter/${this.client.profile?.username}/lastPost`,\n );\n if (lastPost) {\n // Fetch the last tweet to compare content\n const lastTweet = await this.client.getTweet(lastPost.id);\n if (lastTweet && lastTweet.text === text) {\n logger.warn(\n \"Tweet is a duplicate of the last post. Skipping to avoid duplicate.\",\n );\n return null;\n }\n }\n\n // Handle media uploads if needed\n const mediaIds: string[] = [];\n\n if (mediaData && mediaData.length > 0) {\n for (const media of mediaData) {\n try {\n // TODO: Media upload will need to be updated to use the new API\n // For now, just log a warning that media upload is not supported\n logger.warn(\n \"Media upload not currently supported with the modern Twitter API\",\n );\n } catch (error) {\n logger.error(\"Error uploading media:\", error);\n }\n }\n }\n\n const result = await sendTweet(this.client, text, mediaData);\n\n // Cache the new post to prevent duplicates\n await this.runtime.setCache(\n `twitter/${this.client.profile?.username}/lastPost`,\n {\n id: (result as any).id,\n text: text,\n timestamp: Date.now(),\n },\n );\n\n return result;\n } catch (error) {\n logger.error(\"Error posting to Twitter:\", error);\n throw error;\n }\n }\n}\n","import type { ClientBase } from \"./base\";\nimport {\n ChannelType,\n composePromptFromState,\n createUniqueUuid,\n ModelType,\n type IAgentRuntime,\n UUID,\n State,\n Memory,\n parseKeyValueXml,\n} from \"@elizaos/core\";\nimport type { Client, Tweet } from \"./client/index\";\nimport { logger } from \"@elizaos/core\";\n\nimport {\n twitterActionTemplate,\n quoteTweetTemplate,\n replyTweetTemplate,\n} from \"./templates\";\nimport { sendTweet, parseActionResponseFromText } from \"./utils\";\nimport { ActionResponse } from \"./types\";\n\nenum TIMELINE_TYPE {\n ForYou = \"foryou\",\n Following = \"following\",\n}\n\nexport class TwitterTimelineClient {\n client: ClientBase;\n twitterClient: Client;\n runtime: IAgentRuntime;\n isDryRun: boolean;\n timelineType: TIMELINE_TYPE;\n private state: any;\n private isRunning: boolean = false;\n\n constructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n this.client = client;\n this.twitterClient = client.twitterClient;\n this.runtime = runtime;\n this.state = state;\n\n const dryRunSetting = this.state?.TWITTER_DRY_RUN ?? this.runtime.getSetting(\"TWITTER_DRY_RUN\") ?? process.env.TWITTER_DRY_RUN;\n this.isDryRun = dryRunSetting === true || dryRunSetting === \"true\" || \n (typeof dryRunSetting === \"string\" && dryRunSetting.toLowerCase() === \"true\");\n\n // Load timeline mode from runtime settings or use default\n this.timelineType =\n (this.runtime.getSetting(\"TWITTER_TIMELINE_MODE\") ?? process.env.TWITTER_TIMELINE_MODE) ||\n TIMELINE_TYPE.ForYou;\n }\n\n async start() {\n logger.info(\"Starting Twitter timeline client...\");\n this.isRunning = true;\n \n const handleTwitterTimelineLoop = () => {\n if (!this.isRunning) {\n logger.info(\"Twitter timeline client stopped, exiting loop\");\n return;\n }\n \n // Use unified engagement interval\n const engagementIntervalMinutes = parseInt(\n this.state?.TWITTER_ENGAGEMENT_INTERVAL ||\n this.runtime.getSetting(\"TWITTER_ENGAGEMENT_INTERVAL\") as string ||\n process.env.TWITTER_ENGAGEMENT_INTERVAL ||\n \"30\"\n );\n const actionInterval = engagementIntervalMinutes * 60 * 1000;\n \n logger.info(`Timeline client will check every ${engagementIntervalMinutes} minutes`);\n\n this.handleTimeline();\n \n if (this.isRunning) {\n setTimeout(handleTwitterTimelineLoop, actionInterval);\n }\n };\n handleTwitterTimelineLoop();\n }\n\n async stop() {\n logger.info(\"Stopping Twitter timeline client...\");\n this.isRunning = false;\n }\n\n async getTimeline(count: number): Promise<Tweet[]> {\n const twitterUsername = this.client.profile?.username;\n const homeTimeline =\n this.timelineType === TIMELINE_TYPE.Following\n ? await this.twitterClient.fetchFollowingTimeline(count, [])\n : await this.twitterClient.fetchHomeTimeline(count, []);\n\n // The timeline methods now return Tweet objects directly from v2 API\n return homeTimeline\n .filter((tweet) => tweet.username !== twitterUsername); // do not perform action on self-tweets\n }\n\n createTweetId(runtime: IAgentRuntime, tweet: Tweet) {\n return createUniqueUuid(runtime, tweet.id);\n }\n\n formMessage(runtime: IAgentRuntime, tweet: Tweet) {\n return {\n id: this.createTweetId(runtime, tweet),\n agentId: runtime.agentId,\n content: {\n text: tweet.text,\n url: tweet.permanentUrl,\n imageUrls: tweet.photos?.map((photo) => photo.url) || [],\n inReplyTo: tweet.inReplyToStatusId\n ? createUniqueUuid(runtime, tweet.inReplyToStatusId)\n : undefined,\n source: \"twitter\",\n channelType: ChannelType.GROUP,\n tweet,\n },\n entityId: createUniqueUuid(runtime, tweet.userId),\n roomId: createUniqueUuid(runtime, tweet.conversationId),\n createdAt: tweet.timestamp * 1000,\n };\n }\n\n async handleTimeline() {\n logger.info(\"Starting Twitter timeline processing...\");\n\n const tweets = await this.getTimeline(20);\n logger.info(`Fetched ${tweets.length} tweets from timeline`);\n \n // Use max engagements per run from environment\n const maxActionsPerCycle = parseInt(\n this.runtime.getSetting(\"TWITTER_MAX_ENGAGEMENTS_PER_RUN\") as string || \n process.env.TWITTER_MAX_ENGAGEMENTS_PER_RUN || \n \"10\"\n );\n \n const tweetDecisions = [];\n for (const tweet of tweets) {\n try {\n const tweetId = this.createTweetId(this.runtime, tweet);\n // Skip if we've already processed this tweet\n const memory = await this.runtime.getMemoryById(tweetId);\n if (memory) {\n logger.log(`Already processed tweet ID: ${tweet.id}`);\n continue;\n }\n\n const roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n\n const message = this.formMessage(this.runtime, tweet);\n\n let state = await this.runtime.composeState(message);\n\n const actionRespondPrompt =\n composePromptFromState({\n state,\n template:\n this.runtime.character.templates?.twitterActionTemplate ||\n twitterActionTemplate,\n }) +\n `\nTweet:\n${tweet.text}\n\n# Respond with qualifying action tags only.\n\nChoose any combination of [LIKE], [RETWEET], [QUOTE], and [REPLY] that are appropriate. Each action must be on its own line. Your response must only include the chosen actions.`;\n\n const actionResponse = await this.runtime.useModel(\n ModelType.TEXT_SMALL,\n {\n prompt: actionRespondPrompt,\n },\n );\n const parsedResponse = parseActionResponseFromText(actionResponse);\n\n // Ensure a valid action response was generated\n if (!parsedResponse) {\n logger.debug(`No action response generated for tweet ${tweet.id}`);\n continue;\n }\n\n tweetDecisions.push({\n tweet,\n actionResponse: parsedResponse,\n tweetState: state,\n roomId,\n });\n\n // Limit the number of actions per cycle\n if (tweetDecisions.length >= maxActionsPerCycle) break;\n } catch (error) {\n logger.error(`Error processing tweet ${tweet.id}:`, error);\n }\n }\n\n // Rank by the quality of the response\n const rankByActionRelevance = (arr) => {\n return arr.sort((a, b) => {\n const countTrue = (obj: typeof a.actionResponse) =>\n Object.values(obj).filter(Boolean).length;\n\n const countA = countTrue(a.actionResponse);\n const countB = countTrue(b.actionResponse);\n\n // Primary sort by number of true values\n if (countA !== countB) {\n return countB - countA;\n }\n\n // Secondary sort by the \"like\" property\n if (a.actionResponse.like !== b.actionResponse.like) {\n return a.actionResponse.like ? -1 : 1;\n }\n\n // Tertiary sort keeps the remaining objects with equal weight\n return 0;\n });\n };\n // Sort the timeline based on the action decision score,\n const prioritizedTweets = rankByActionRelevance(tweetDecisions);\n \n logger.info(`Processing ${prioritizedTweets.length} tweets with actions`);\n if (prioritizedTweets.length > 0) {\n const actionSummary = prioritizedTweets.map(td => {\n const actions = [];\n if (td.actionResponse.like) actions.push('LIKE');\n if (td.actionResponse.retweet) actions.push('RETWEET');\n if (td.actionResponse.quote) actions.push('QUOTE');\n if (td.actionResponse.reply) actions.push('REPLY');\n return `Tweet ${td.tweet.id}: ${actions.join(', ')}`;\n });\n logger.info(`Actions to execute:\\n${actionSummary.join('\\n')}`);\n }\n\n await this.processTimelineActions(prioritizedTweets);\n logger.info(\"Timeline processing complete\");\n }\n\n private async processTimelineActions(\n tweetDecisions: {\n tweet: Tweet;\n actionResponse: ActionResponse;\n tweetState: State;\n roomId: UUID;\n }[],\n ): Promise<\n {\n tweetId: string;\n actionResponse: ActionResponse;\n executedActions: string[];\n }[]\n > {\n const results = [];\n\n for (const { tweet, actionResponse, tweetState, roomId } of tweetDecisions) {\n const tweetId = this.createTweetId(this.runtime, tweet);\n const executedActions = [];\n\n // Update memory with processed tweet\n await this.runtime.createMemory(\n {\n id: tweetId,\n entityId: createUniqueUuid(this.runtime, tweet.userId),\n content: {\n text: tweet.text,\n url: tweet.permanentUrl,\n source: \"twitter\",\n channelType: ChannelType.GROUP,\n tweet: tweet,\n },\n agentId: this.runtime.agentId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n },\n \"messages\",\n );\n\n try {\n // ensure world and rooms, connections, and worlds are created\n const userId = tweet.userId;\n const worldId = createUniqueUuid(this.runtime, userId);\n const entityId = createUniqueUuid(this.runtime, userId);\n\n await this.ensureTweetWorldContext(tweet, roomId, worldId, entityId);\n\n if (actionResponse.like) {\n await this.handleLikeAction(tweet);\n executedActions.push(\"like\");\n }\n\n if (actionResponse.retweet) {\n await this.handleRetweetAction(tweet);\n executedActions.push(\"retweet\");\n }\n\n if (actionResponse.quote) {\n await this.handleQuoteAction(tweet);\n executedActions.push(\"quote\");\n }\n\n if (actionResponse.reply) {\n await this.handleReplyAction(tweet);\n executedActions.push(\"reply\");\n }\n\n results.push({ tweetId: tweet.id, actionResponse, executedActions });\n } catch (error) {\n logger.error(`Error processing actions for tweet ${tweet.id}:`, error);\n }\n }\n\n return results;\n }\n\n private async ensureTweetWorldContext(\n tweet: Tweet,\n roomId: UUID,\n worldId: UUID,\n entityId: UUID,\n ) {\n await this.runtime.ensureWorldExists({\n id: worldId,\n name: `${tweet.name}'s Twitter`,\n agentId: this.runtime.agentId,\n serverId: tweet.userId,\n metadata: {\n ownership: { ownerId: tweet.userId },\n twitter: {\n username: tweet.username,\n id: tweet.userId,\n name: tweet.name,\n },\n },\n });\n\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: tweet.username,\n name: tweet.name,\n worldName: `${tweet.name}'s Twitter`,\n source: \"twitter\",\n type: ChannelType.GROUP,\n channelId: tweet.conversationId,\n serverId: tweet.userId,\n worldId,\n metadata: {\n ownership: { ownerId: tweet.userId },\n twitter: {\n username: tweet.username,\n id: tweet.userId,\n name: tweet.name,\n },\n },\n });\n }\n\n async handleLikeAction(tweet: Tweet) {\n try {\n if (this.isDryRun) {\n logger.log(`[DRY RUN] Would have liked tweet ${tweet.id}`);\n return;\n }\n await this.twitterClient.likeTweet(tweet.id);\n logger.log(`Liked tweet ${tweet.id}`);\n } catch (error) {\n logger.error(`Error liking tweet ${tweet.id}:`, error);\n }\n }\n\n async handleRetweetAction(tweet: Tweet) {\n try {\n if (this.isDryRun) {\n logger.log(`[DRY RUN] Would have retweeted tweet ${tweet.id}`);\n return;\n }\n await this.twitterClient.retweet(tweet.id);\n logger.log(`Retweeted tweet ${tweet.id}`);\n } catch (error) {\n logger.error(`Error retweeting tweet ${tweet.id}:`, error);\n }\n }\n\n async handleQuoteAction(tweet: Tweet) {\n try {\n const message = this.formMessage(this.runtime, tweet);\n\n let state = await this.runtime.composeState(message);\n\n const quotePrompt =\n composePromptFromState({\n state,\n template:\n this.runtime.character.templates?.quoteTweetTemplate ||\n quoteTweetTemplate,\n }) +\n `\nYou are responding to this tweet:\n${tweet.text}`;\n\n const quoteResponse = await this.runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: quotePrompt,\n });\n const responseObject = parseKeyValueXml(quoteResponse);\n\n if (responseObject.post) {\n if (this.isDryRun) {\n logger.log(`[DRY RUN] Would have quoted tweet ${tweet.id} with: ${responseObject.post}`);\n return;\n }\n \n const result = await this.client.requestQueue.add(\n async () =>\n await this.twitterClient.sendQuoteTweet(\n responseObject.post,\n tweet.id,\n ),\n );\n\n const body: any = await result.json();\n\n const tweetResult =\n body?.data?.create_tweet?.tweet_results?.result || body?.data || body;\n if (tweetResult) {\n logger.log(\"Successfully posted quote tweet\");\n } else {\n logger.error(\"Quote tweet creation failed:\", body);\n }\n\n // Create memory for our response\n const tweetId =\n tweetResult?.id || Date.now().toString();\n const responseId = createUniqueUuid(this.runtime, tweetId);\n const responseMemory: Memory = {\n id: responseId,\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId: message.roomId,\n content: {\n ...responseObject,\n inReplyTo: message.id,\n },\n createdAt: Date.now(),\n };\n\n // Save the response to memory\n await this.runtime.createMemory(responseMemory, \"messages\");\n }\n } catch (error) {\n logger.error(\"Error in quote tweet generation:\", error);\n }\n }\n\n async handleReplyAction(tweet: Tweet) {\n try {\n const message = this.formMessage(this.runtime, tweet);\n\n let state = await this.runtime.composeState(message);\n\n const replyPrompt =\n composePromptFromState({\n state,\n template:\n this.runtime.character.templates?.replyTweetTemplate ||\n replyTweetTemplate,\n }) +\n `\nYou are replying to this tweet:\n${tweet.text}`;\n\n const replyResponse = await this.runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: replyPrompt,\n });\n const responseObject = parseKeyValueXml(replyResponse);\n\n if (responseObject.post) {\n if (this.isDryRun) {\n logger.log(`[DRY RUN] Would have replied to tweet ${tweet.id} with: ${responseObject.post}`);\n return;\n }\n \n const result = await sendTweet(\n this.client,\n responseObject.post,\n [],\n tweet.id,\n );\n\n if (result) {\n logger.log(\"Successfully posted reply tweet\");\n \n // Create memory for our response\n const responseId = createUniqueUuid(this.runtime, result.id);\n const responseMemory: Memory = {\n id: responseId,\n entityId: this.runtime.agentId,\n agentId: this.runtime.agentId,\n roomId: message.roomId,\n content: {\n ...responseObject,\n inReplyTo: message.id,\n },\n createdAt: Date.now(),\n };\n\n // Save the response to memory\n await this.runtime.createMemory(responseMemory, \"messages\");\n }\n }\n } catch (error) {\n logger.error(\"Error in reply tweet generation:\", error);\n }\n }\n}\n","export const twitterActionTemplate = `\n# INSTRUCTIONS: Determine actions for {{agentName}} (@{{twitterUserName}}) based on:\n{{bio}}\n{{postDirections}}\n\nGuidelines:\n- ONLY engage with content that DIRECTLY relates to character's core interests\n- Direct mentions are priority IF they are on-topic\n- Skip ALL content that is:\n - Off-topic or tangentially related\n - From high-profile accounts unless explicitly relevant\n - Generic/viral content without specific relevance\n - Political/controversial unless central to character\n - Promotional/marketing unless directly relevant\n\nActions (respond only with tags):\n[LIKE] - Perfect topic match AND aligns with character (9.8/10)\n[RETWEET] - Exceptional content that embodies character's expertise (9.5/10)\n[QUOTE] - Can add substantial domain expertise (9.5/10)\n[REPLY] - Can contribute meaningful, expert-level insight (9.5/10)\n`;\n\nexport const quoteTweetTemplate = `# Task: Write a quote tweet in the voice, style, and perspective of {{agentName}} @{{twitterUserName}}.\n\n{{bio}}\n{{postDirections}}\n\n<response>\n <thought>Your thought here, explaining why the quote tweet is meaningful or how it connects to what {{agentName}} cares about</thought>\n <post>The quote tweet content here, under 280 characters, without emojis, no questions</post>\n</response>\n\nYour quote tweet should be:\n- A reaction, agreement, disagreement, or expansion of the original tweet\n- Personal and unique to {{agentName}}’s style and point of view\n- 1 to 3 sentences long, chosen at random\n- No questions, no emojis, concise\n- Use \"\\\\n\\\\n\" (double spaces) between multiple sentences\n- Max 280 characters including line breaks\n\nYour output must ONLY contain the XML block.`;\n\nexport const replyTweetTemplate = `# Task: Write a reply tweet in the voice, style, and perspective of {{agentName}} @{{twitterUserName}}.\n\n{{bio}}\n{{postDirections}}\n\n<response>\n <thought>Your thought here, explaining why this reply is meaningful or how it connects to what {{agentName}} cares about</thought>\n <post>The reply tweet content here, under 280 characters, without emojis, no questions</post>\n</response>\n\nYour reply should be:\n- A direct response, agreement, disagreement, or personal take on the original tweet\n- Reflective of {{agentName}}’s unique voice and values\n- 1 to 2 sentences long, chosen at random\n- No questions, no emojis, concise\n- Use \"\\\\n\\\\n\" (double spaces) between multiple sentences if needed\n- Max 280 characters including line breaks\n\nYour output must ONLY contain the XML block.`;\n","import type { ClientBase } from \"./base\";\nimport type { Client, Tweet } from \"./client/index\";\nimport {\n type IAgentRuntime,\n createUniqueUuid,\n logger,\n ModelType,\n} from \"@elizaos/core\";\nimport { SearchMode } from \"./client/index\";\n\ninterface DiscoveryConfig {\n // Topics from character configuration\n topics: string[];\n // Minimum follower count for accounts to consider\n minFollowerCount: number;\n // Maximum accounts to follow per cycle\n maxFollowsPerCycle: number;\n // Maximum engagements per cycle\n maxEngagementsPerCycle: number;\n // Engagement probability thresholds\n likeThreshold: number;\n replyThreshold: number;\n quoteThreshold: number;\n}\n\ninterface ScoredTweet {\n tweet: Tweet;\n relevanceScore: number;\n engagementType: 'like' | 'reply' | 'quote' | 'skip';\n}\n\ninterface ScoredAccount {\n user: {\n id: string;\n username: string;\n name: string;\n followersCount: number;\n };\n qualityScore: number;\n relevanceScore: number;\n}\n\nexport class TwitterDiscoveryClient {\n private client: ClientBase;\n private twitterClient: Client;\n private runtime: IAgentRuntime;\n private config: DiscoveryConfig;\n private isRunning: boolean = false;\n private isDryRun: boolean;\n\n constructor(client: ClientBase, runtime: IAgentRuntime, state: any) {\n this.client = client;\n this.twitterClient = client.twitterClient;\n this.runtime = runtime;\n \n // Check dry run mode\n const dryRunSetting = state?.TWITTER_DRY_RUN ?? this.runtime.getSetting(\"TWITTER_DRY_RUN\") ?? process.env.TWITTER_DRY_RUN;\n this.isDryRun = dryRunSetting === true || dryRunSetting === \"true\" || \n (typeof dryRunSetting === \"string\" && dryRunSetting.toLowerCase() === \"true\");\n \n // Build config from character settings\n this.config = this.buildDiscoveryConfig();\n \n logger.info(\"Twitter Discovery Config:\", {\n topics: this.config.topics,\n isDryRun: this.isDryRun,\n minFollowerCount: this.config.minFollowerCount,\n maxFollowsPerCycle: this.config.maxFollowsPerCycle,\n maxEngagementsPerCycle: this.config.maxEngagementsPerCycle,\n });\n }\n\n private buildDiscoveryConfig(): DiscoveryConfig {\n const character = this.runtime.character;\n \n // Use character topics or extract from bio\n const topics = character.topics || this.extractTopicsFromBio(character.bio);\n \n return {\n topics,\n minFollowerCount: parseInt(\n this.runtime.getSetting(\"TWITTER_MIN_FOLLOWER_COUNT\") as string || \n process.env.TWITTER_MIN_FOLLOWER_COUNT || \n \"100\"\n ),\n maxFollowsPerCycle: parseInt(\n this.runtime.getSetting(\"TWITTER_MAX_FOLLOWS_PER_CYCLE\") as string || \n process.env.TWITTER_MAX_FOLLOWS_PER_CYCLE || \n \"5\"\n ),\n maxEngagementsPerCycle: parseInt(\n this.runtime.getSetting(\"TWITTER_MAX_ENGAGEMENTS_PER_RUN\") as string || \n process.env.TWITTER_MAX_ENGAGEMENTS_PER_RUN || \n \"10\"\n ),\n likeThreshold: 0.6,\n replyThreshold: 0.8,\n quoteThreshold: 0.85,\n };\n }\n\n private extractTopicsFromBio(bio: string | string[]): string[] {\n const bioText = Array.isArray(bio) ? bio.join(\" \") : bio;\n // Extract meaningful words as potential topics\n const words = bioText.toLowerCase()\n .split(/\\s+/)\n .filter(word => word.length > 4)\n .filter(word => !['about', 'helping', 'working', 'people', 'making', 'building'].includes(word));\n return [...new Set(words)].slice(0, 5); // Limit to 5 topics\n }\n\n async start() {\n logger.info(\"Starting Twitter Discovery Client...\");\n this.isRunning = true;\n \n const discoveryLoop = async () => {\n if (!this.isRunning) {\n logger.info(\"Discovery client stopped, exiting loop\");\n return;\n }\n \n try {\n await this.runDiscoveryCycle();\n } catch (error) {\n logger.error(\"Discovery cycle error:\", error);\n }\n \n // Run discovery every 20-40 minutes (with variance)\n const baseInterval = parseInt(\n this.runtime.getSetting(\"TWITTER_DISCOVERY_INTERVAL\") as string || \n process.env.TWITTER_DISCOVERY_INTERVAL || \n \"30\"\n );\n const variance = Math.random() * 20 - 10; // ±10 minutes\n const nextInterval = (baseInterval + variance) * 60 * 1000;\n \n logger.info(`Next discovery cycle in ${((baseInterval + variance)).toFixed(1)} minutes`);\n \n if (this.isRunning) {\n setTimeout(discoveryLoop, nextInterval);\n }\n };\n \n // Start after a short delay\n setTimeout(discoveryLoop, 5000);\n }\n\n async stop() {\n logger.info(\"Stopping Twitter Discovery Client...\");\n this.isRunning = false;\n }\n\n private async runDiscoveryCycle() {\n logger.info(\"Starting Twitter discovery cycle...\");\n \n const discoveries = await this.discoverContent();\n const { tweets, accounts } = discoveries;\n \n logger.info(`Discovered ${tweets.length} tweets and ${accounts.length} accounts`);\n \n // Process discovered accounts (follow high-quality ones)\n const followedCount = await this.processAccounts(accounts);\n \n // Process discovered tweets (engage with relevant ones)\n const engagementCount = await this.processTweets(tweets);\n \n logger.info(\n `Discovery cycle complete: ${followedCount} follows, ${engagementCount} engagements`\n );\n }\n\n private async discoverContent(): Promise<{\n tweets: ScoredTweet[];\n accounts: ScoredAccount[];\n }> {\n const allTweets: ScoredTweet[] = [];\n const allAccounts = new Map<string, ScoredAccount>();\n \n // Note: Twitter API v2 doesn't support trends, so we skip trend-based discovery\n \n // 1. Discover from topic searches (primary discovery method)\n try {\n const topicContent = await this.discoverFromTopics();\n allTweets.push(...topicContent.tweets);\n topicContent.accounts.forEach(acc => \n allAccounts.set(acc.user.id, acc)\n );\n } catch (error) {\n logger.error(\"Failed to discover from topics:\", error);\n }\n \n // 2. Discover from conversation threads\n try {\n const threadContent = await this.discoverFromThreads();\n allTweets.push(...threadContent.tweets);\n threadContent.accounts.forEach(acc => \n allAccounts.set(acc.user.id, acc)\n );\n } catch (error) {\n logger.error(\"Failed to discover from threads:\", error);\n }\n \n // 3. Discover from popular accounts in our topics\n try {\n const popularContent = await this.discoverFromPopularAccounts();\n allTweets.push(...popularContent.tweets);\n popularContent.accounts.forEach(acc => \n allAccounts.set(acc.user.id, acc)\n );\n } catch (error) {\n logger.error(\"Failed to discover from popular accounts:\", error);\n }\n \n // Sort by relevance score\n const sortedTweets = allTweets\n .sort((a, b) => b.relevanceScore - a.relevanceScore)\n .slice(0, 50); // Top 50 tweets\n \n const sortedAccounts = Array.from(allAccounts.values())\n .sort((a, b) => (b.qualityScore * b.relevanceScore) - (a.qualityScore * a.relevanceScore))\n .slice(0, 20); // Top 20 accounts\n \n return { tweets: sortedTweets, accounts: sortedAccounts };\n }\n\n private async discoverFromTopics(): Promise<{\n tweets: ScoredTweet[];\n accounts: ScoredAccount[];\n }> {\n logger.debug(\"Discovering from character topics...\");\n \n const tweets: ScoredTweet[] = [];\n const accounts = new Map<string, ScoredAccount>();\n \n // Search for each topic with different query strategies\n for (const topic of this.config.topics.slice(0, 5)) {\n try {\n // Strategy 1: Popular recent tweets\n const popularQuery = `${topic} -is:retweet -is:reply min_faves:10 lang:en`;\n \n logger.debug(`Searching popular tweets for topic: ${topic}`);\n const popularResults = await this.twitterClient.fetchSearchTweets(\n popularQuery,\n 20,\n SearchMode.Top\n );\n \n for (const tweet of popularResults.tweets) {\n const scored = this.scoreTweet(tweet, 'topic');\n tweets.push(scored);\n }\n \n // Strategy 2: Latest tweets from verified/notable accounts\n const verifiedQuery = `${topic} -is:retweet lang:en filter:verified`;\n \n logger.debug(`Searching verified accounts for topic: ${topic}`);\n const verifiedResults = await this.twitterClient.fetchSearchTweets(\n verifiedQuery,\n 10,\n SearchMode.Latest\n );\n \n for (const tweet of verifiedResults.tweets) {\n const scored = this.scoreTweet(tweet, 'topic');\n tweets.push(scored);\n \n // Extract account info from tweet author\n const authorUsername = tweet.username;\n const authorName = tweet.name || tweet.username;\n \n // For v2 API, we don't get follower count in tweet data\n // We'll need to make a separate call or estimate quality differently\n const account = this.scoreAccount({\n id: tweet.userId,\n username: authorUsername,\n name: authorName,\n followersCount: 1000, // Default estimate for verified accounts\n });\n \n if (account.qualityScore > 0.5) {\n accounts.set(tweet.userId, account);\n }\n }\n } catch (error) {\n logger.error(`Failed to search topic ${topic}:`, error);\n }\n }\n \n return { tweets, accounts: Array.from(accounts.values()) };\n }\n\n private async discoverFromThreads(): Promise<{\n tweets: ScoredTweet[];\n accounts: ScoredAccount[];\n }> {\n logger.debug(\"Discovering from conversation threads...\");\n \n const tweets: ScoredTweet[] = [];\n const accounts = new Map<string, ScoredAccount>();\n \n // Search for viral conversations in our topics\n const topicQuery = this.config.topics\n .slice(0, 3)\n .map(t => `\"${t}\"`)\n .join(\" OR \");\n \n try {\n const viralQuery = `${topicQuery} min_replies:20 min_faves:50 -is:retweet`;\n \n logger.debug(`Searching viral threads with query: ${viralQuery}`);\n const searchResults = await this.twitterClient.fetchSearchTweets(\n viralQuery,\n 15,\n SearchMode.Top\n );\n \n for (const tweet of searchResults.tweets) {\n const scored = this.scoreTweet(tweet, 'thread');\n tweets.push(scored);\n \n // Viral thread authors are likely high-quality accounts\n const account = this.scoreAccount({\n id: tweet.userId,\n username: tweet.username,\n name: tweet.name || tweet.username,\n followersCount: 5000, // Estimate for viral content creators\n });\n \n if (account.qualityScore > 0.6) {\n accounts.set(tweet.userId, account);\n }\n }\n } catch (error) {\n logger.error(\"Failed to discover threads:\", error);\n }\n \n return { tweets, accounts: Array.from(accounts.values()) };\n }\n\n private async discoverFromPopularAccounts(): Promise<{\n tweets: ScoredTweet[];\n accounts: ScoredAccount[];\n }> {\n logger.debug(\"Discovering from popular accounts in topics...\");\n \n const tweets: ScoredTweet[] = [];\n const accounts = new Map<string, ScoredAccount>();\n \n // Search for users who frequently tweet about our topics\n for (const topic of this.config.topics.slice(0, 3)) {\n try {\n // Find tweets from accounts with high engagement\n const influencerQuery = `${topic} -is:retweet min_faves:100 min_retweets:20`;\n \n logger.debug(`Searching for influencers in topic: ${topic}`);\n const results = await this.twitterClient.fetchSearchTweets(\n influencerQuery,\n 10,\n SearchMode.Top\n );\n \n for (const tweet of results.tweets) {\n const scored = this.scoreTweet(tweet, 'topic');\n tweets.push(scored);\n \n // High engagement suggests a quality account\n const estimatedFollowers = Math.max(\n (tweet.likes || 0) * 100,\n (tweet.retweets || 0) * 200,\n 10000\n );\n \n const account = this.scoreAccount({\n id: tweet.userId,\n username: tweet.username,\n name: tweet.name || tweet.username,\n followersCount: estimatedFollowers,\n });\n \n if (account.qualityScore > 0.7) {\n accounts.set(tweet.userId, account);\n }\n }\n } catch (error) {\n logger.error(`Failed to discover popular accounts for ${topic}:`, error);\n }\n }\n \n return { tweets, accounts: Array.from(accounts.values()) };\n }\n\n // Remove the discoverFromTrends method since API v2 doesn't support it\n // Remove the isTrendRelevant method since we're not using trends\n\n private scoreTweet(tweet: Tweet, source: 'topic' | 'thread'): ScoredTweet {\n let relevanceScore = 0;\n \n // Base score by source\n const sourceScores = {\n topic: 0.5,\n thread: 0.4,\n };\n relevanceScore += sourceScores[source];\n \n // Score by engagement metrics\n const engagementScore = Math.min(\n (tweet.likes || 0) / 1000 + \n (tweet.retweets || 0) / 500 + \n (tweet.replies || 0) / 100,\n 0.3\n );\n relevanceScore += engagementScore;\n \n // Score by content relevance to topics\n const textLower = tweet.text.toLowerCase();\n const topicMatches = this.config.topics.filter(topic => \n textLower.includes(topic.toLowerCase())\n ).length;\n relevanceScore += Math.min(topicMatches * 0.1, 0.3);\n \n // Bonus for verified accounts (if available in tweet data)\n // Note: isBlueVerified might not be available in all tweet responses\n \n // Normalize score\n relevanceScore = Math.min(relevanceScore, 1);\n \n // Determine engagement type based on score\n let engagementType: ScoredTweet['engagementType'] = 'skip';\n if (relevanceScore >= this.config.quoteThreshold) {\n engagementType = 'quote';\n } else if (relevanceScore >= this.config.replyThreshold) {\n engagementType = 'reply';\n } else if (relevanceScore >= this.config.likeThreshold) {\n engagementType = 'like';\n }\n \n return {\n tweet,\n relevanceScore,\n engagementType,\n };\n }\n\n private scoreAccount(user: ScoredAccount['user']): ScoredAccount {\n let qualityScore = 0;\n let relevanceScore = 0;\n \n // Quality based on follower count\n if (user.followersCount > 10000) qualityScore += 0.4;\n else if (user.followersCount > 1000) qualityScore += 0.3;\n else if (user.followersCount > 100) qualityScore += 0.2;\n \n // Relevance based on username/name matching topics\n const userText = `${user.username} ${user.name}`.toLowerCase();\n const topicMatches = this.config.topics.filter(topic => \n userText.includes(topic.toLowerCase())\n ).length;\n relevanceScore = Math.min(topicMatches * 0.3, 1);\n \n return {\n user,\n qualityScore: Math.min(qualityScore, 1),\n relevanceScore,\n };\n }\n\n private async processAccounts(accounts: ScoredAccount[]): Promise<number> {\n let followedCount = 0;\n \n for (const scoredAccount of accounts) {\n if (followedCount >= this.config.maxFollowsPerCycle) break;\n \n try {\n // Check if already following (via memory)\n const isFollowing = await this.checkIfFollowing(scoredAccount.user.id);\n if (isFollowing) continue;\n \n if (this.isDryRun) {\n logger.info(\n `[DRY RUN] Would follow @${scoredAccount.user.username} ` +\n `(quality: ${scoredAccount.qualityScore.toFixed(2)}, ` +\n `relevance: ${scoredAccount.relevanceScore.toFixed(2)})`\n );\n } else {\n // Follow the account\n await this.twitterClient.followUser(scoredAccount.user.id);\n \n logger.info(\n `Followed @${scoredAccount.user.username} ` +\n `(quality: ${scoredAccount.qualityScore.toFixed(2)}, ` +\n `relevance: ${scoredAccount.relevanceScore.toFixed(2)})`\n );\n \n // Save follow action to memory\n await this.saveFollowMemory(scoredAccount.user);\n }\n \n followedCount++;\n \n // Add a delay to avoid rate limits\n await this.delay(2000 + Math.random() * 3000);\n } catch (error) {\n logger.error(`Failed to follow @${scoredAccount.user.username}:`, error);\n }\n }\n \n return followedCount;\n }\n\n private async processTweets(tweets: ScoredTweet[]): Promise<number> {\n let engagementCount = 0;\n \n for (const scoredTweet of tweets) {\n if (engagementCount >= this.config.maxEngagementsPerCycle) break;\n if (scoredTweet.engagementType === 'skip') continue;\n \n try {\n // Check if already engaged\n const tweetMemoryId = createUniqueUuid(this.runtime, scoredTweet.tweet.id);\n const existingMemory = await this.runtime.getMemoryById(tweetMemoryId);\n if (existingMemory) {\n logger.debug(`Already engaged with tweet ${scoredTweet.tweet.id}, skipping`);\n continue;\n }\n \n // Perform engagement\n switch (scoredTweet.engagementType) {\n case 'like':\n if (this.isDryRun) {\n logger.info(`[DRY RUN] Would like tweet: ${scoredTweet.tweet.id} (score: ${scoredTweet.relevanceScore.toFixed(2)})`);\n } else {\n await this.twitterClient.likeTweet(scoredTweet.tweet.id);\n logger.info(`Liked tweet: ${scoredTweet.tweet.id} (score: ${scoredTweet.relevanceScore.toFixed(2)})`);\n }\n break;\n \n case 'reply':\n const replyText = await this.generateReply(scoredTweet.tweet);\n if (this.isDryRun) {\n logger.info(`[DRY RUN] Would reply to tweet ${scoredTweet.tweet.id} with: \"${replyText}\"`);\n } else {\n await this.twitterClient.sendTweet(replyText, scoredTweet.tweet.id);\n logger.info(`Replied to tweet: ${scoredTweet.tweet.id}`);\n }\n break;\n \n case 'quote':\n const quoteText = await this.generateQuote(scoredTweet.tweet);\n if (this.isDryRun) {\n logger.info(`[DRY RUN] Would quote tweet ${scoredTweet.tweet.id} with: \"${quoteText}\"`);\n } else {\n await this.twitterClient.sendQuoteTweet(quoteText, scoredTweet.tweet.id);\n logger.info(`Quoted tweet: ${scoredTweet.tweet.id}`);\n }\n break;\n }\n \n // Save engagement to memory (even in dry run for tracking)\n await this.saveEngagementMemory(scoredTweet.tweet, scoredTweet.engagementType);\n \n engagementCount++;\n \n // Add delay to avoid rate limits\n await this.delay(3000 + Math.random() * 5000);\n } catch (error) {\n logger.error(`Failed to engage with tweet ${scoredTweet.tweet.id}:`, error);\n }\n }\n \n return engagementCount;\n }\n\n private async checkIfFollowing(userId: string): Promise<boolean> {\n // Check our memory to see if we've followed them\n const embedding = await this.runtime.useModel(ModelType.TEXT_EMBEDDING, {\n text: `followed twitter user ${userId}`\n });\n \n const followMemories = await this.runtime.searchMemories({\n tableName: \"messages\",\n embedding,\n match_threshold: 0.8,\n count: 1,\n });\n return followMemories.length > 0;\n }\n\n private async generateReply(tweet: Tweet): Promise<string> {\n const prompt = `You are ${this.runtime.character.name}. Generate a thoughtful reply to this tweet:\n\nTweet by @${tweet.username}: \"${tweet.text}\"\n\nYour interests: ${this.config.topics.join(\", \")}\nCharacter bio: ${Array.isArray(this.runtime.character.bio) ? this.runtime.character.bio.join(\" \") : this.runtime.character.bio}\n\nKeep the reply:\n- Relevant and adding value to the conversation\n- Under 280 characters\n- Natural and conversational\n- Related to your expertise and interests\n- Respectful and constructive\n\nReply:`;\n \n const response = await this.runtime.useModel(ModelType.TEXT_SMALL, {\n prompt,\n max_tokens: 100,\n temperature: 0.8,\n });\n \n return response.trim();\n }\n\n private async generateQuote(tweet: Tweet): Promise<string> {\n const prompt = `You are ${this.runtime.character.name}. Add your perspective to this tweet with a quote tweet:\n\nOriginal tweet by @${tweet.username}: \"${tweet.text}\"\n\nYour interests: ${this.config.topics.join(\", \")}\nCharacter bio: ${Array.isArray(this.runtime.character.bio) ? this.runtime.character.bio.join(\" \") : this.runtime.character.bio}\n\nCreate a quote tweet that:\n- Adds unique insight or perspective\n- Is under 280 characters\n- Respectfully builds on the original idea\n- Showcases your expertise\n- Encourages further discussion\n\nQuote tweet:`;\n \n const response = await this.runtime.useModel(ModelType.TEXT_SMALL, {\n prompt,\n max_tokens: 100,\n temperature: 0.8,\n });\n \n return response.trim();\n }\n\n private async saveEngagementMemory(tweet: Tweet, engagementType: string) {\n const memoryId = await this.runtime.createMemory({\n id: createUniqueUuid(this.runtime, tweet.id),\n entityId: createUniqueUuid(this.runtime, tweet.userId),\n content: {\n text: `${engagementType} tweet from @${tweet.username}: ${tweet.text}`,\n metadata: {\n tweetId: tweet.id,\n engagementType,\n source: 'discovery',\n isDryRun: this.isDryRun,\n },\n },\n roomId: createUniqueUuid(this.runtime, tweet.conversationId),\n }, \"messages\");\n }\n\n private async saveFollowMemory(user: ScoredAccount['user']) {\n const memoryId = await this.runtime.createMemory({\n entityId: createUniqueUuid(this.runtime, user.id),\n content: {\n text: `followed twitter user ${user.id} @${user.username}`,\n metadata: {\n userId: user.id,\n username: user.username,\n name: user.name,\n followersCount: user.followersCount,\n source: 'discovery',\n isDryRun: this.isDryRun,\n },\n },\n roomId: createUniqueUuid(this.runtime, `twitter-follows`),\n }, \"messages\");\n }\n\n private delay(ms: number): Promise<void> {\n return new Promise(resolve => setTimeout(resolve, ms));\n }\n}","import {\n ChannelType,\n type Content,\n type IAgentRuntime,\n type Memory,\n type State,\n type UUID,\n createUniqueUuid,\n logger,\n} from \"@elizaos/core\";\nimport {\n Client,\n type QueryTweetsResponse,\n SearchMode,\n type Tweet,\n} from \"./client/index\";\nimport { TwitterInteractionPayload } from \"./types\";\n\ninterface TwitterUser {\n id_str: string;\n screen_name: string;\n name: string;\n}\n\ninterface TwitterFollowersResponse {\n users: TwitterUser[];\n}\n\n/**\n * Extracts the answer from the given text.\n *\n * @param {string} text - The text containing the answer\n * @returns {string} The extracted answer\n */\nexport function extractAnswer(text: string): string {\n const startIndex = text.indexOf(\"Answer: \") + 8;\n const endIndex = text.indexOf(\"<|endoftext|>\", 11);\n return text.slice(startIndex, endIndex);\n}\n\n/**\n * Represents a Twitter Profile.\n * @typedef {Object} TwitterProfile\n * @property {string} id - The unique identifier of the profile.\n * @property {string} username - The username of the profile.\n * @property {string} screenName - The screen name of the profile.\n * @property {string} bio - The biography of the profile.\n * @property {string[]} nicknames - An array of nicknames associated with the profile.\n */\ntype TwitterProfile = {\n id: string;\n username: string;\n screenName: string;\n bio: string;\n nicknames: string[];\n};\n\n/**\n * Class representing a request queue for handling asynchronous requests in a controlled manner.\n */\n\nclass RequestQueue {\n private queue: (() => Promise<any>)[] = [];\n private processing = false;\n private maxRetries = 3;\n private retryAttempts = new Map<() => Promise<any>, number>();\n\n /**\n * Asynchronously adds a request to the queue, then processes the queue.\n *\n * @template T\n * @param {() => Promise<T>} request - The request to be added to the queue\n * @returns {Promise<T>} - A promise that resolves with the result of the request or rejects with an error\n */\n async add<T>(request: () => Promise<T>): Promise<T> {\n return new Promise((resolve, reject) => {\n this.queue.push(async () => {\n try {\n const result = await request();\n resolve(result);\n } catch (error) {\n reject(error);\n }\n });\n this.processQueue();\n });\n }\n\n /**\n * Asynchronously processes the queue of requests.\n *\n * @returns A promise that resolves when the queue has been fully processed.\n */\n private async processQueue(): Promise<void> {\n if (this.processing || this.queue.length === 0) {\n return;\n }\n this.processing = true;\n\n while (this.queue.length > 0) {\n const request = this.queue.shift()!;\n try {\n await request();\n // Clear retry count on success\n this.retryAttempts.delete(request);\n } catch (error) {\n logger.error(\"Error processing request:\", error);\n \n const retryCount = (this.retryAttempts.get(request) || 0) + 1;\n \n if (retryCount < this.maxRetries) {\n this.retryAttempts.set(request, retryCount);\n this.queue.unshift(request);\n await this.exponentialBackoff(retryCount);\n // Break the loop to allow exponential backoff to take effect\n break;\n } else {\n logger.error(`Max retries (${this.maxRetries}) exceeded for request, skipping`);\n this.retryAttempts.delete(request);\n }\n }\n await this.randomDelay();\n }\n\n this.processing = false;\n \n // If there are still items in the queue, restart processing\n if (this.queue.length > 0) {\n this.processQueue();\n }\n }\n\n /**\n * Implements an exponential backoff strategy for retrying a task.\n * @param {number} retryCount - The number of retries attempted so far.\n * @returns {Promise<void>} - A promise that resolves after a delay based on the retry count.\n */\n private async exponentialBackoff(retryCount: number): Promise<void> {\n const delay = 2 ** retryCount * 1000;\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n\n /**\n * Asynchronous method that creates a random delay between 1500ms and 3500ms.\n *\n * @returns A Promise that resolves after the random delay has passed.\n */\n private async randomDelay(): Promise<void> {\n const delay = Math.floor(Math.random() * 2000) + 1500;\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n}\n\n/**\n * Class representing a base client for interacting with Twitter.\n * @extends EventEmitter\n */\nexport class ClientBase {\n static _twitterClients: { [accountIdentifier: string]: Client } = {};\n twitterClient: Client;\n runtime: IAgentRuntime;\n lastCheckedTweetId: bigint | null = null;\n temperature = 0.5;\n\n requestQueue: RequestQueue = new RequestQueue();\n\n profile: TwitterProfile | null;\n\n /**\n * Caches a tweet in the database.\n *\n * @param {Tweet} tweet - The tweet to cache.\n * @returns {Promise<void>} A promise that resolves once the tweet is cached.\n */\n async cacheTweet(tweet: Tweet): Promise<void> {\n if (!tweet) {\n logger.warn(\"Tweet is undefined, skipping cache\");\n return;\n }\n\n this.runtime.setCache<Tweet>(`twitter/tweets/${tweet.id}`, tweet);\n }\n\n /**\n * Retrieves a cached tweet by its ID.\n * @param {string} tweetId - The ID of the tweet to retrieve from the cache.\n * @returns {Promise<Tweet | undefined>} A Promise that resolves to the cached tweet, or undefined if the tweet is not found in the cache.\n */\n async getCachedTweet(tweetId: string): Promise<Tweet | undefined> {\n const cached = await this.runtime.getCache<Tweet>(\n `twitter/tweets/${tweetId}`,\n );\n\n if (!cached) {\n return undefined;\n }\n\n return cached;\n }\n\n /**\n * Asynchronously retrieves a tweet with the specified ID.\n * If the tweet is found in the cache, it is returned from the cache.\n * If not, a request is made to the Twitter API to get the tweet, which is then cached and returned.\n * @param {string} tweetId - The ID of the tweet to retrieve.\n * @returns {Promise<Tweet>} A Promise that resolves to the retrieved tweet.\n */\n async getTweet(tweetId: string): Promise<Tweet> {\n const cachedTweet = await this.getCachedTweet(tweetId);\n\n if (cachedTweet) {\n return cachedTweet;\n }\n\n const tweet = await this.requestQueue.add(() =>\n this.twitterClient.getTweet(tweetId),\n );\n\n await this.cacheTweet(tweet);\n return tweet;\n }\n\n callback: (self: ClientBase) => any = null;\n\n /**\n * This method is called when the application is ready.\n * It throws an error indicating that it is not implemented in the base class\n * and should be implemented in the subclass.\n */\n onReady() {\n throw new Error(\"Not implemented in base class, please call from subclass\");\n }\n\n /**\n * Parse the raw tweet data into a standardized Tweet object.\n */\n /**\n * Parses a raw tweet object into a structured Tweet object.\n *\n * @param {any} raw - The raw tweet object to parse.\n * @param {number} [depth=0] - The current depth of parsing nested quotes/retweets.\n * @param {number} [maxDepth=3] - The maximum depth allowed for parsing nested quotes/retweets.\n * @returns {Tweet} The parsed Tweet object.\n */\n\n\n state: any;\n\n constructor(runtime: IAgentRuntime, state: any) {\n this.runtime = runtime;\n this.state = state;\n \n // Use API key as the identifier for client reuse\n const apiKey =\n state?.TWITTER_API_KEY ||\n runtime.getSetting(\"TWITTER_API_KEY\") ||\n process.env.TWITTER_API_KEY;\n if (apiKey && ClientBase._twitterClients[apiKey]) {\n this.twitterClient = ClientBase._twitterClients[apiKey];\n } else {\n this.twitterClient = new Client();\n if (apiKey) {\n ClientBase._twitterClients[apiKey] = this.twitterClient;\n }\n }\n }\n\n async init() {\n // First ensure the agent exists in the database\n // await this.runtime.ensureAgentExists(this.runtime.character);\n\n const apiKey =\n this.state?.TWITTER_API_KEY || \n this.runtime.getSetting(\"TWITTER_API_KEY\") ||\n process.env.TWITTER_API_KEY;\n const apiSecretKey =\n this.state?.TWITTER_API_SECRET_KEY ||\n this.runtime.getSetting(\"TWITTER_API_SECRET_KEY\") ||\n process.env.TWITTER_API_SECRET_KEY;\n const accessToken =\n this.state?.TWITTER_ACCESS_TOKEN ||\n this.runtime.getSetting(\"TWITTER_ACCESS_TOKEN\") ||\n process.env.TWITTER_ACCESS_TOKEN;\n const accessTokenSecret =\n this.state?.TWITTER_ACCESS_TOKEN_SECRET ||\n this.runtime.getSetting(\"TWITTER_ACCESS_TOKEN_SECRET\") ||\n process.env.TWITTER_ACCESS_TOKEN_SECRET;\n\n // Validate required credentials\n if (!apiKey || !apiSecretKey || !accessToken || !accessTokenSecret) {\n const missing = [];\n if (!apiKey) missing.push(\"TWITTER_API_KEY\");\n if (!apiSecretKey) missing.push(\"TWITTER_API_SECRET_KEY\");\n if (!accessToken) missing.push(\"TWITTER_ACCESS_TOKEN\");\n if (!accessTokenSecret) missing.push(\"TWITTER_ACCESS_TOKEN_SECRET\");\n throw new Error(\n `Missing required Twitter API credentials: ${missing.join(\", \")}`,\n );\n }\n\n const maxRetries = process.env.MAX_RETRIES\n ? parseInt(process.env.MAX_RETRIES)\n : 3;\n let retryCount = 0;\n let lastError: Error | null = null;\n\n while (retryCount < maxRetries) {\n try {\n logger.log(\"Initializing Twitter API v2 client\");\n await this.twitterClient.login(\n \"\", // username not needed for API v2\n \"\", // password not needed for API v2\n \"\", // email not needed for API v2\n \"\", // 2FA not needed for API v2\n apiKey,\n apiSecretKey,\n accessToken,\n accessTokenSecret,\n );\n\n if (await this.twitterClient.isLoggedIn()) {\n logger.info(\"Successfully authenticated with Twitter API v2\");\n break;\n }\n } catch (error) {\n lastError = error instanceof Error ? error : new Error(String(error));\n logger.error(\n `Authentication attempt ${retryCount + 1} failed: ${lastError.message}`,\n );\n retryCount++;\n\n if (retryCount < maxRetries) {\n const delay = 2 ** retryCount * 1000; // Exponential backoff\n logger.info(`Retrying in ${delay / 1000} seconds...`);\n await new Promise((resolve) => setTimeout(resolve, delay));\n }\n }\n }\n\n if (retryCount >= maxRetries) {\n throw new Error(\n `Twitter authentication failed after ${maxRetries} attempts. Last error: ${lastError?.message}`,\n );\n }\n\n // Initialize Twitter profile from the authenticated user\n const profile = await this.twitterClient.me();\n if (profile) {\n logger.log(\"Twitter user ID:\", profile.userId);\n logger.log(\"Twitter loaded:\", JSON.stringify(profile, null, 10));\n\n const agentId = this.runtime.agentId;\n\n const entity = await this.runtime.getEntityById(agentId);\n const entityMetadata = entity?.metadata as any;\n if (entityMetadata?.twitter?.userName !== profile.username) {\n logger.log(\n \"Updating Agents known X/twitter handle\",\n profile.username,\n \"was\",\n entityMetadata?.twitter,\n );\n const names = [profile.name, profile.username];\n await this.runtime.updateEntity({\n id: agentId,\n names: [...new Set([...(entity.names || []), ...names])].filter(\n Boolean,\n ),\n metadata: {\n ...(entityMetadata || {}),\n twitter: {\n ...(entityMetadata?.twitter || {}),\n name: profile.name,\n userName: profile.username,\n },\n },\n agentId,\n });\n }\n\n // Store profile info for use in responses\n this.profile = {\n id: profile.userId,\n username: profile.username, // this is the at\n screenName: profile.name, // this is the human readable name\n bio: profile.biography || \"\",\n nicknames: [],\n };\n } else {\n throw new Error(\"Failed to load profile\");\n }\n\n await this.loadLatestCheckedTweetId();\n await this.populateTimeline();\n }\n\n async fetchOwnPosts(count: number): Promise<Tweet[]> {\n logger.debug(\"fetching own posts\");\n const homeTimeline = await this.twitterClient.getUserTweets(\n this.profile.id,\n count,\n );\n // homeTimeline.tweets already contains Tweet objects from v2 API, no parsing needed\n return homeTimeline.tweets;\n }\n\n /**\n * Fetch timeline for twitter account, optionally only from followed accounts\n */\n async fetchHomeTimeline(\n count: number,\n following?: boolean,\n ): Promise<Tweet[]> {\n logger.debug(\"fetching home timeline\");\n const homeTimeline = following\n ? await this.twitterClient.fetchFollowingTimeline(count, [])\n : await this.twitterClient.fetchHomeTimeline(count, []);\n\n // homeTimeline already contains Tweet objects from v2 API, no parsing needed\n return homeTimeline;\n }\n\n async fetchSearchTweets(\n query: string,\n maxTweets: number,\n searchMode: SearchMode,\n cursor?: string,\n ): Promise<QueryTweetsResponse> {\n try {\n // Sometimes this fails because we are rate limited. in this case, we just need to return an empty array\n // if we dont get a response in 5 seconds, something is wrong\n const timeoutPromise = new Promise((resolve) =>\n setTimeout(() => resolve({ tweets: [] }), 15000),\n );\n\n try {\n const result = await this.requestQueue.add(\n async () =>\n await Promise.race([\n this.twitterClient.fetchSearchTweets(\n query,\n maxTweets,\n searchMode,\n cursor,\n ),\n timeoutPromise,\n ]),\n );\n return (result ?? { tweets: [] }) as QueryTweetsResponse;\n } catch (error) {\n logger.error(\"Error fetching search tweets:\", error);\n return { tweets: [] };\n }\n } catch (error) {\n logger.error(\"Error fetching search tweets:\", error);\n return { tweets: [] };\n }\n }\n\n private async populateTimeline() {\n logger.debug(\"populating timeline...\");\n\n const cachedTimeline = await this.getCachedTimeline();\n\n // Check if the cache file exists\n if (cachedTimeline) {\n // Read the cached search results from the file\n\n // Get the existing memories from the database\n const existingMemories = await this.runtime.getMemoriesByRoomIds({\n tableName: \"messages\",\n roomIds: cachedTimeline.map((tweet) =>\n createUniqueUuid(this.runtime, tweet.conversationId),\n ),\n });\n\n //TODO: load tweets not in cache?\n\n // Create a Set to store the IDs of existing memories\n const existingMemoryIds = new Set(\n existingMemories.map((memory) => memory.id.toString()),\n );\n\n // Check if any of the cached tweets exist in the existing memories\n const someCachedTweetsExist = cachedTimeline.some((tweet) =>\n existingMemoryIds.has(createUniqueUuid(this.runtime, tweet.id)),\n );\n\n if (someCachedTweetsExist) {\n // Filter out the cached tweets that already exist in the database\n const tweetsToSave = cachedTimeline.filter(\n (tweet) =>\n tweet.userId !== this.profile.id &&\n !existingMemoryIds.has(createUniqueUuid(this.runtime, tweet.id)),\n );\n\n // Save the missing tweets as memories\n for (const tweet of tweetsToSave) {\n logger.log(\"Saving Tweet\", tweet.id);\n\n if (tweet.userId === this.profile.id) {\n continue;\n }\n\n // Create a world for this Twitter user if it doesn't exist\n const worldId = createUniqueUuid(this.runtime, tweet.userId) as UUID;\n await this.runtime.ensureWorldExists({\n id: worldId,\n name: `${tweet.username}'s Twitter`,\n agentId: this.runtime.agentId,\n serverId: tweet.userId,\n metadata: {\n ownership: { ownerId: tweet.userId },\n twitter: {\n username: tweet.username,\n id: tweet.userId,\n },\n },\n });\n\n const roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n const entityId =\n tweet.userId === this.profile.id\n ? this.runtime.agentId\n : createUniqueUuid(this.runtime, tweet.userId);\n\n // Ensure the entity exists with proper world association\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: tweet.username,\n name: tweet.name,\n source: \"twitter\",\n type: ChannelType.FEED,\n worldId: worldId,\n });\n\n const content = {\n text: tweet.text,\n url: tweet.permanentUrl,\n source: \"twitter\",\n inReplyTo: tweet.inReplyToStatusId\n ? createUniqueUuid(this.runtime, tweet.inReplyToStatusId)\n : undefined,\n } as Content;\n\n await this.runtime.createMemory(\n {\n id: createUniqueUuid(this.runtime, tweet.id),\n entityId,\n content: content,\n agentId: this.runtime.agentId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n },\n \"messages\",\n );\n\n await this.cacheTweet(tweet);\n }\n\n logger.log(\n `Populated ${tweetsToSave.length} missing tweets from the cache.`,\n );\n return;\n }\n }\n\n const timeline = await this.fetchHomeTimeline(cachedTimeline ? 10 : 50);\n\n // Get the most recent 20 mentions and interactions\n const mentionsAndInteractions = await this.fetchSearchTweets(\n `@${this.profile.username}`,\n 20,\n SearchMode.Latest,\n );\n\n // Combine the timeline tweets and mentions/interactions\n const allTweets = [...timeline, ...mentionsAndInteractions.tweets];\n\n // Create a Set to store unique tweet IDs\n const tweetIdsToCheck = new Set<string>();\n const roomIds = new Set<UUID>();\n\n // Add tweet IDs to the Set\n for (const tweet of allTweets) {\n tweetIdsToCheck.add(tweet.id);\n roomIds.add(createUniqueUuid(this.runtime, tweet.conversationId));\n }\n\n // Check the existing memories in the database\n const existingMemories = await this.runtime.getMemoriesByRoomIds({\n tableName: \"messages\",\n roomIds: Array.from(roomIds),\n });\n\n // Create a Set to store the existing memory IDs\n const existingMemoryIds = new Set<UUID>(\n existingMemories.map((memory) => memory.id),\n );\n\n // Filter out the tweets that already exist in the database\n const tweetsToSave = allTweets.filter(\n (tweet) =>\n tweet.userId !== this.profile.id &&\n !existingMemoryIds.has(createUniqueUuid(this.runtime, tweet.id)),\n );\n\n logger.debug({\n processingTweets: tweetsToSave.map((tweet) => tweet.id).join(\",\"),\n });\n\n // Save the new tweets as memories\n for (const tweet of tweetsToSave) {\n logger.log(\"Saving Tweet\", tweet.id);\n\n if (tweet.userId === this.profile.id) {\n continue;\n }\n\n // Create a world for this Twitter user if it doesn't exist\n const worldId = createUniqueUuid(this.runtime, tweet.userId) as UUID;\n await this.runtime.ensureWorldExists({\n id: worldId,\n name: `${tweet.username}'s Twitter`,\n agentId: this.runtime.agentId,\n serverId: tweet.userId,\n metadata: {\n ownership: { ownerId: tweet.userId },\n twitter: {\n username: tweet.username,\n id: tweet.userId,\n },\n },\n });\n\n const roomId = createUniqueUuid(this.runtime, tweet.conversationId);\n\n const entityId =\n tweet.userId === this.profile.id\n ? this.runtime.agentId\n : createUniqueUuid(this.runtime, tweet.userId);\n\n // Ensure the entity exists with proper world association\n await this.runtime.ensureConnection({\n entityId,\n roomId,\n userName: tweet.username,\n name: tweet.name,\n source: \"twitter\",\n type: ChannelType.FEED,\n worldId: worldId,\n });\n\n const content = {\n text: tweet.text,\n url: tweet.permanentUrl,\n source: \"twitter\",\n inReplyTo: tweet.inReplyToStatusId\n ? createUniqueUuid(this.runtime, tweet.inReplyToStatusId)\n : undefined,\n } as Content;\n\n await this.runtime.createMemory(\n {\n id: createUniqueUuid(this.runtime, tweet.id),\n entityId,\n content: content,\n agentId: this.runtime.agentId,\n roomId,\n createdAt: tweet.timestamp * 1000,\n },\n \"messages\",\n );\n\n await this.cacheTweet(tweet);\n }\n\n // Cache\n await this.cacheTimeline(timeline);\n await this.cacheMentions(mentionsAndInteractions.tweets);\n }\n\n async saveRequestMessage(message: Memory, state: State) {\n if (message.content.text) {\n const recentMessage = await this.runtime.getMemories({\n tableName: \"messages\",\n roomId: message.roomId,\n count: 1,\n unique: false,\n });\n\n if (\n recentMessage.length > 0 &&\n recentMessage[0].content === message.content\n ) {\n logger.debug(\"Message already saved\", recentMessage[0].id);\n } else {\n await this.runtime.createMemory(message, \"messages\");\n }\n\n await this.runtime.evaluate(message, {\n ...state,\n twitterClient: this.twitterClient,\n });\n }\n }\n\n async loadLatestCheckedTweetId(): Promise<void> {\n const latestCheckedTweetId = await this.runtime.getCache<string>(\n `twitter/${this.profile.username}/latest_checked_tweet_id`,\n );\n\n if (latestCheckedTweetId) {\n this.lastCheckedTweetId = BigInt(latestCheckedTweetId);\n }\n }\n\n async cacheLatestCheckedTweetId() {\n if (this.lastCheckedTweetId) {\n await this.runtime.setCache<string>(\n `twitter/${this.profile.username}/latest_checked_tweet_id`,\n this.lastCheckedTweetId.toString(),\n );\n }\n }\n\n async getCachedTimeline(): Promise<Tweet[] | undefined> {\n const cached = await this.runtime.getCache<Tweet[]>(\n `twitter/${this.profile.username}/timeline`,\n );\n\n if (!cached) {\n return undefined;\n }\n\n return cached;\n }\n\n async cacheTimeline(timeline: Tweet[]) {\n await this.runtime.setCache<Tweet[]>(\n `twitter/${this.profile.username}/timeline`,\n timeline,\n );\n }\n\n async cacheMentions(mentions: Tweet[]) {\n await this.runtime.setCache<Tweet[]>(\n `twitter/${this.profile.username}/mentions`,\n mentions,\n );\n }\n\n async fetchProfile(username: string): Promise<TwitterProfile> {\n try {\n const profile = await this.requestQueue.add(async () => {\n const profile = await this.twitterClient.getProfile(username);\n return {\n id: profile.userId,\n username,\n screenName: profile.name || this.runtime.character.name,\n bio:\n profile.biography || typeof this.runtime.character.bio === \"string\"\n ? (this.runtime.character.bio as string)\n : this.runtime.character.bio.length > 0\n ? this.runtime.character.bio[0]\n : \"\",\n nicknames: this.profile?.nicknames || [],\n } satisfies TwitterProfile;\n });\n\n return profile;\n } catch (error) {\n logger.error(\"Error fetching Twitter profile:\", error);\n throw error;\n }\n }\n\n /**\n * Fetches recent interactions (likes, retweets, quotes) for the authenticated user's tweets\n */\n async fetchInteractions() {\n try {\n const username = this.profile.username;\n // Use fetchSearchTweets to get mentions instead of the non-existent get method\n const mentionsResponse = await this.requestQueue.add(() =>\n this.twitterClient.fetchSearchTweets(\n `@${username}`,\n 100,\n SearchMode.Latest,\n ),\n );\n\n // Process tweets directly into the expected interaction format\n return mentionsResponse.tweets.map((tweet) =>\n this.formatTweetToInteraction(tweet),\n );\n } catch (error) {\n logger.error(\"Error fetching Twitter interactions:\", error);\n return [];\n }\n }\n\n formatTweetToInteraction(tweet): TwitterInteractionPayload | null {\n if (!tweet) return null;\n\n const isQuote = tweet.isQuoted;\n const isRetweet = !!tweet.retweetedStatus;\n const type = isQuote ? \"quote\" : isRetweet ? \"retweet\" : \"like\";\n\n return {\n id: tweet.id,\n type,\n userId: tweet.userId,\n username: tweet.username,\n name: tweet.name || tweet.username,\n targetTweetId: tweet.inReplyToStatusId || tweet.quotedStatusId,\n targetTweet: tweet.quotedStatus || tweet,\n quoteTweet: isQuote ? tweet : undefined,\n retweetId: tweet.retweetedStatus?.id,\n };\n }\n}\n","import { Service, type IAgentRuntime } from \"@elizaos/core\";\n\nexport class TwitterService extends Service {\n static serviceType = \"twitter\";\n \n // Add the required abstract property\n capabilityDescription = \"The agent is able to send and receive messages on Twitter\";\n \n private static instance: TwitterService;\n\n constructor(runtime?: IAgentRuntime) {\n super(runtime);\n }\n\n static getInstance(): TwitterService {\n if (!TwitterService.instance) {\n TwitterService.instance = new TwitterService();\n }\n return TwitterService.instance;\n }\n\n static async start(runtime: IAgentRuntime): Promise<TwitterService> {\n const instance = TwitterService.getInstance();\n instance.runtime = runtime;\n return instance;\n }\n\n async stop(): Promise<void> {\n // Clean up resources if needed\n }\n} ","import {\n Action,\n type ActionExample,\n type HandlerCallback,\n type IAgentRuntime,\n type Memory,\n type State,\n logger,\n createUniqueUuid,\n ModelType,\n} from \"@elizaos/core\";\nimport { ClientBase } from \"../base.js\";\n\nexport const postTweetAction: Action = {\n name: \"POST_TWEET\",\n similes: [\"TWEET\", \"SEND_TWEET\", \"TWITTER_POST\", \"POST_ON_TWITTER\", \"SHARE_ON_TWITTER\"],\n validate: async (runtime: IAgentRuntime, message: Memory): Promise<boolean> => {\n logger.debug(\"Validating POST_TWEET action\");\n \n // Basic validation - make sure we have content to tweet\n const text = message.content?.text?.trim();\n if (!text || text.length === 0) {\n logger.error(\"No text content for tweet\");\n return false;\n }\n \n // Check tweet length (280 characters)\n if (text.length > 280) {\n logger.warn(`Tweet too long: ${text.length} characters`);\n // Still valid, will be truncated or sent as thread\n }\n \n return true;\n },\n description: \"Post a tweet on Twitter\",\n handler: async (\n runtime: IAgentRuntime,\n message: Memory,\n state: State,\n _options: { [key: string]: unknown },\n callback?: HandlerCallback\n ): Promise<boolean> => {\n logger.info(\"Executing POST_TWEET action\");\n \n try {\n // Initialize a Twitter client directly\n const client = new ClientBase(runtime, {});\n \n // Check if client is initialized\n if (!client.twitterClient) {\n await client.init();\n }\n \n // Verify we have a profile\n if (!client.profile) {\n throw new Error(\"Twitter client not properly initialized - no profile found\");\n }\n \n // Get tweet content\n const tweetText = message.content?.text?.trim() || \"\";\n \n // Generate a more natural tweet if the input is too short or generic\n let finalTweetText = tweetText;\n if (tweetText.length < 50 || tweetText.toLowerCase().includes(\"post\") || tweetText.toLowerCase().includes(\"tweet\")) {\n const tweetPrompt = `You are ${runtime.character.name}. Create an interesting tweet based on this context:\n\nContext: ${tweetText}\n\nYour interests: ${runtime.character.topics?.join(\", \") || \"technology, AI, web3\"}\nYour style: ${runtime.character.style?.all?.join(\", \") || \"thoughtful, engaging\"}\n\nGenerate a tweet that:\n- Is under 280 characters\n- Reflects your personality and interests\n- Is engaging and conversational\n- Doesn't use hashtags unless truly relevant\n- Doesn't ask questions at the end\n- Is not generic or promotional\n\nTweet:`;\n \n const response = await runtime.useModel(ModelType.TEXT_SMALL, {\n prompt: tweetPrompt,\n max_tokens: 100,\n temperature: 0.8,\n });\n \n finalTweetText = response.trim();\n }\n \n // Post the tweet\n const result = await client.twitterClient.sendTweet(finalTweetText);\n \n if (result && result.data) {\n const tweetData = result.data.data || result.data;\n // Extract tweet ID from the response - handle different response formats\n let tweetId: string;\n if ('id' in tweetData) {\n tweetId = tweetData.id;\n } else if ((tweetData as any).data?.id) {\n tweetId = (tweetData as any).data.id;\n } else {\n tweetId = Date.now().toString();\n }\n const tweetUrl = `https://twitter.com/${client.profile.username}/status/${tweetId}`;\n \n logger.info(`Successfully posted tweet: ${tweetId}`);\n \n // Create memory of the posted tweet\n await runtime.createMemory({\n entityId: runtime.agentId,\n content: {\n text: finalTweetText,\n url: tweetUrl,\n source: \"twitter\",\n action: \"POST_TWEET\",\n },\n roomId: message.roomId,\n }, \"messages\");\n \n if (callback) {\n await callback({\n text: `I've posted a tweet: \"${finalTweetText}\"\\n\\nView it here: ${tweetUrl}`,\n metadata: {\n tweetId: tweetId,\n tweetUrl,\n }\n });\n }\n \n return true;\n } else {\n throw new Error(\"Failed to post tweet - no response data\");\n }\n } catch (error) {\n logger.error(\"Error posting tweet:\", error);\n \n if (callback) {\n await callback({\n text: `Sorry, I couldn't post the tweet. Error: ${error.message}`,\n metadata: { error: error.message }\n });\n }\n \n return false;\n }\n },\n examples: [\n [\n {\n name: \"{{user1}}\",\n content: {\n text: \"Post a tweet about the importance of open source AI\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"I'll post a tweet about open source AI for you.\",\n action: \"POST_TWEET\",\n },\n },\n ],\n [\n {\n name: \"{{user1}}\",\n content: {\n text: \"Tweet something interesting about web3\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"I'll share an interesting thought about web3 on Twitter.\",\n action: \"POST_TWEET\",\n },\n },\n ],\n [\n {\n name: \"{{user1}}\",\n content: {\n text: \"Share your thoughts on the future of technology on Twitter\",\n },\n },\n {\n name: \"{{agentName}}\",\n content: {\n text: \"I'll post my thoughts on the future of technology.\",\n action: \"POST_TWEET\",\n },\n },\n ],\n ],\n}; "],"mappings":";;;;;;;AAAA,SAA6B,UAAAA,eAAc;;;ACA3C;AAAA,EACE;AAAA,EAGA;AAAA,EAKA;AAAA,EACA,oBAAAC;AAAA,EACA,UAAAC;AAAA,OACK;;;ACZP,SAAS,kBAAkB;AAMpB,IAAM,cAAN,MAAkB;AAAA,EAKvB,YACU,QACA,WACA,aACA,cACR;AAJQ;AACA;AACA;AACA;AARV,SAAQ,WAA8B;AACtC,SAAQ,gBAAgB;AAStB,SAAK,iBAAiB;AAAA,EACxB;AAAA,EAEQ,mBAAyB;AAC/B,SAAK,WAAW,IAAI,WAAW;AAAA,MAC7B,QAAQ,KAAK;AAAA,MACb,WAAW,KAAK;AAAA,MAChB,aAAa,KAAK;AAAA,MAClB,cAAc,KAAK;AAAA,IACrB,CAAC;AACD,SAAK,gBAAgB;AAAA,EACvB;AAAA;AAAA;AAAA;AAAA,EAKA,cAA0B;AACxB,QAAI,CAAC,KAAK,UAAU;AAClB,YAAM,IAAI,MAAM,oCAAoC;AAAA,IACtD;AACA,WAAO,KAAK;AAAA,EACd;AAAA;AAAA;AAAA;AAAA,EAKA,MAAM,aAA+B;AACnC,QAAI,CAAC,KAAK,iBAAiB,CAAC,KAAK,UAAU;AACzC,aAAO;AAAA,IACT;AAEA,QAAI;AAEF,YAAM,KAAK,MAAM,KAAK,SAAS,GAAG,GAAG;AACrC,aAAO,CAAC,CAAC,GAAG;AAAA,IACd,SAAS,OAAO;AACd,cAAQ,MAAM,oCAAoC,KAAK;AACvD,aAAO;AAAA,IACT;AAAA,EACF;AAAA;AAAA;AAAA;AAAA,EAK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S,MAAM;AAAA,IACrC;AAEA,QAAI,cAAc,WAAW;AAC3B,MAAAA,QAAO,IAAI,gDAAyC;AACpD,YAAM,cAAc,UAAU,MAAM;AAAA,IACtC;AAEA,IAAAA,QAAO,IAAI,4CAAuC;AAAA,EACpD,SAAS,OAAO;AACd,IAAAA,QAAO,MAAM,6CAAsC,KAAK;AACxD,UAAM;AAAA,EACR;AACF;AAEO,IAAM,gBAAgB;AAAA,EAC3B,MAAM;AAAA,EACN,aAAa;AAAA,EACb,SAAS,CAAC,eAAe;AAAA,EACzB,UAAU,CAAC,cAAc;AAAA,EACzB,MAAM;AACR;AAEA,IAAO,gBAAQ;","names":["logger","createUniqueUuid","logger","user","place","logger","logger","util","objectUtil","path","errorUtil","path","errorMap","ctx","result","issues","elements","processed","result","r","ZodFirstPartyTypeKind","logger","createUniqueUuid","memory","response","ChannelType","createUniqueUuid","logger","logger","createUniqueUuid","ChannelType","ChannelType","createUniqueUuid","ModelType","logger","logger","createUniqueUuid","ChannelType","ModelType","createUniqueUuid","logger","ModelType","logger","createUniqueUuid","ModelType","ChannelType","createUniqueUuid","logger","logger","existingMemories","createUniqueUuid","existingMemoryIds","tweetsToSave","ChannelType","profile","logger","ModelType","logger","ModelType","logger"]}
|